1 # -*- encoding: binary -*-
3 EM::VERSION >= '0.12.10' or abort 'eventmachine 0.12.10 is required'
4 require 'rainbows/ev_core'
8 # Implements a basic single-threaded event model with
9 # {EventMachine}[http://rubyeventmachine.com/]. It is capable of
10 # handling thousands of simultaneous client connections, but with only
11 # a single-threaded app dispatch. It is suited for slow clients,
12 # and can work with slow applications via asynchronous libraries such as
13 # {async_sinatra}[http://github.com/raggi/async_sinatra],
14 # {Cramp}[http://m.onkey.org/2010/1/7/introducing-cramp],
15 # and {rack-fiber_pool}[http://github.com/mperham/rack-fiber_pool].
17 # It does not require your Rack application to be thread-safe,
18 # reentrancy is only required for the DevFdResponse body
21 # Compatibility: Whatever \EventMachine ~> 0.12.10 and Unicorn both
22 # support, currently Ruby 1.8/1.9.
24 # This model is compatible with users of "async.callback" in the Rack
26 # {async_sinatra}[http://github.com/raggi/async_sinatra].
28 # For a complete asynchronous framework,
29 # {Cramp}[http://m.onkey.org/2010/1/7/introducing-cramp] is fully
30 # supported when using this concurrency model.
32 # This model is fully-compatible with
33 # {rack-fiber_pool}[http://github.com/mperham/rack-fiber_pool]
34 # which allows each request to run inside its own \Fiber after
35 # all request processing is complete.
37 # Merb (and other frameworks/apps) supporting +deferred?+ execution as
38 # documented at http://brainspl.at/articles/2008/04/18/deferred-requests-with-merb-ebb-and-thin
39 # will also get the ability to conditionally defer request processing
40 # to a separate thread.
42 # This model does not implement as streaming "rack.input" which allows
43 # the Rack application to process data as it arrives. This means
44 # "rack.input" will be fully buffered in memory or to a temporary file
45 # before the application is entered.
50 autoload :ResponsePipe, 'rainbows/event_machine/response_pipe'
51 autoload :ResponseChunkPipe, 'rainbows/event_machine/response_chunk_pipe'
52 autoload :TryDefer, 'rainbows/event_machine/try_defer'
54 class Client < EM::Connection # :nodoc: all
56 include Rainbows::EvCore
65 alias receive_data on_read
69 close_connection_after_writing
73 # To avoid clobbering the current streaming response
74 # (often a static file), we do not attempt to process another
75 # request on the same connection until the first is complete
76 return EM.next_tick { app_call } if @body
78 set_comm_inactivity_timeout 0
79 @env[RACK_INPUT] = @input
80 @env[REMOTE_ADDR] = @remote_addr
81 @env[ASYNC_CALLBACK] = method(:em_write_response)
82 @env[ASYNC_CLOSE] = EM::DefaultDeferrable.new
84 response = catch(:async) { APP.call(@env.update(RACK_DEFAULTS)) }
86 # too tricky to support pipelining with :async since the
87 # second (pipelined) request could be a stuck behind a
88 # long-running async response
89 (response.nil? || -1 == response[0]) and return @state = :close
91 em_write_response(response, alive = @hp.keepalive? && G.alive)
96 if @body.nil? && @hp.headers(@env, @buf)
97 EM.next_tick { on_read('') }
99 set_comm_inactivity_timeout(G.kato)
104 def em_write_response(response, alive = false)
105 status, headers, body = response
107 headers = HH.new(headers)
108 headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
113 if body.respond_to?(:errback) && body.respond_to?(:callback)
115 body.callback { quit }
116 body.errback { quit }
117 # async response, this could be a trickle as is in comet-style apps
118 headers[CONNECTION] = CLOSE if headers
120 elsif body.respond_to?(:to_path)
121 st = File.stat(path = body.to_path)
124 write(response_header(status, headers)) if headers
125 @body = stream_file_data(path)
127 body.close if body.respond_to?(:close)
131 body.close if body.respond_to?(:close)
133 alive ? on_read('') : quit
136 elsif st.socket? || st.pipe?
137 @body = io = body_to_io(body)
138 chunk = stream_response_headers(status, headers) if headers
139 m = chunk ? ResponseChunkPipe : ResponsePipe
140 return EM.watch(io, m, self, alive, body).notify_readable = true
142 # char or block device... WTF? fall through to body.each
145 write(response_header(status, headers)) if headers
146 write_body_each(self, body)
151 async_close = @env[ASYNC_CLOSE] and async_close.succeed
152 @body.respond_to?(:fail) and @body.fail
153 @_io.close unless @_io.closed?
157 module Server # :nodoc: all
165 return if CUR.size >= MAX
166 io = Rainbows.accept(@io) or return
167 sig = EM.attach_fd(io.fileno, false)
168 CUR[sig] = CL.new(sig, io)
172 def init_worker_process(worker) # :nodoc:
173 Rainbows::Response.setup(Rainbows::EventMachine::Client)
177 # runs inside each forked worker, this sits around and waits
178 # for connections and doesn't die until the parent dies (or is
179 # given a INT, QUIT, or TERM signal)
180 def worker_loop(worker) # :nodoc:
181 init_worker_process(worker)
182 G.server.app.respond_to?(:deferred?) and
183 G.server.app = TryDefer[G.server.app]
185 # enable them both, should be non-fatal if not supported
188 logger.info "#@use: epoll=#{EM.epoll?} kqueue=#{EM.kqueue?}"
189 client_class = Rainbows.const_get(@use).const_get(:Client)
190 Server.const_set(:MAX, worker_connections + LISTENERS.size)
191 Server.const_set(:CL, client_class)
192 client_class.const_set(:APP, G.server.app)
194 conns = EM.instance_variable_get(:@conns) or
195 raise RuntimeError, "EM @conns instance variable not accessible!"
196 Server.const_set(:CUR, conns)
197 EM.add_periodic_timer(1) do
199 conns.each_value { |c| client_class === c and c.quit }
200 EM.stop if conns.empty? && EM.reactor_running?
203 LISTENERS.map! do |s|
204 EM.watch(s, Server) { |c| c.notify_readable = true }