Class: Telecaster

Inherits:
Object
  • Object
show all
Defined in:
lib/telecaster/multi.rb,
lib/telecaster.rb

Overview

This is Telecaster::Multi, not a multitelecaster.

Defined Under Namespace

Classes: Multi

Constant Summary collapse

ASYNC_RESPONSE =
[-1, {}, []].freeze
DEFAULT_TIMEOUT =
10
EMHTTP_VERSION =
EM::HttpRequest::VERSION.split('.')[0].to_i
TYPE_JSON =
'application/json'
ROOT =
File.expand_path('..', __FILE__)

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Telecaster

Returns a new instance of Telecaster.



16
17
18
19
20
# File 'lib/telecaster.rb', line 16

def initialize(options)
  @backend_hosts = options[:backends]
  @logger        = options[:logger]
  @timeout       = options[:timeout] || DEFAULT_TIMEOUT
end

Instance Method Details

#call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/telecaster.rb', line 29

def call(env)
  ensure_reactor_running
  
  start     = Time.now.to_f
  method    = env['REQUEST_METHOD'].downcase
  multi     = Multi.new
  callback  = env['async.callback']
  args      = create_args(env)
  
  @backend_hosts.each do |host|
    uri     = File.join(host, env['REQUEST_URI'])
    request = create_request(uri)
    
    multi.add(host, request.__send__(method, args))
  end
  
  multi.callback do |response|
    duration = ((Time.now.to_f - start) * 1000).round
    summary = response.map { |r| '[' + [r['host'], r['status'] || '-', r['duration'] || '-'] * ' ' + ']' }
    @logger.info "#{env['REQUEST_METHOD']} #{env['REQUEST_URI']} backends:#{response.size} duration:#{duration} #{summary * ' '}"
    
    json = Yajl::Encoder.encode(response, :pretty => true, :indent => '  ')
    callback.call [200, {'Content-Type' => TYPE_JSON}, [json]]
  end
  
  ASYNC_RESPONSE
  
rescue => e
  [500, {'Content-Type' => 'text/plain'}, [e.message]]
end

#listen(port) ⇒ Object



22
23
24
25
26
27
# File 'lib/telecaster.rb', line 22

def listen(port)
  app = self
  server = Thin::Server.new('0.0.0.0', port) { run app }
  server.timeout = 1.5 * @timeout
  server.start
end