Sha256: 5f642858a7fb31774a67e5848597b5499a566131634962c41a41a5a292da5e7a

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 KB

Contents

#!/usr/bin/env ruby

require 'rubygems'
require 'lab_bench'

require 'haml'
require 'eventmachine'
require 'em-websocket'
require 'sinatra/base'
require 'thin'
require 'yajl'

SOCKETS = []
MESSAGES = [] # TODO this is unbounded

class LabBenchServer < Sinatra::Base
  set :public, LabBench::ASSETS
  set :views, File.join(LabBench::ASSETS, 'views')

  helpers do
    def css(css)
      "/css/#{css}.css?" + File.mtime(File.join(LabBench::ASSETS, "css", "#{css}.css")).to_i.to_s
    end
    
    def js(js)
      "/js/#{js}.js?" + File.mtime(File.join(LabBench::ASSETS, "js", "#{js}.js")).to_i.to_s
    end
  end
  
  get '/' do
    haml :index
  end
  
  # lets the TestRunner ensure that we're up and running
  get '/ping' do
    'Pong!'
  end
  
  # give the TestRunner a chance to post events, which we cache and rebrooadcase
  post '/test_event' do
    message = Yajl::Encoder.encode(params.merge(:milliseconds => (Time.now.to_f * 1000).to_i))
    MESSAGES << message
    
    SOCKETS.each { |s| s.send message }
    
    # should vend back a UID for this test run or something
    # might also need to accept a UID that the client has already given us
    'Okay'
  end
end

EventMachine.run do
  # HACK - websockets and HTTP on different (adjacent) ports
  EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 9021) do |ws|
    ws.onopen do
      # backfill old messages to the client
      # TODO is this blocking? I would guess no...
      ws.send Yajl::Encoder.encode(['backfilling'])
      MESSAGES.each { |message| ws.send(message) }

      # put the client in the list of real-time recipients
      ws.send Yajl::Encoder.encode(['realtime'])
      SOCKETS << ws
    end
    
    ws.onclose do
      SOCKETS.delete(ws)
    end

    ws.onerror { |e| puts "Error: #{e.message}" }
  end
  
  LabBenchServer.run!(:host => '0.0.0.0', :port => 9020)
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lab_bench-0.3.1 bin/lab_bench_server
lab_bench-0.3.0 bin/lab_bench_server
lab_bench-0.2.1 bin/lab_bench_server