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.
51 class Client < EM::Connection # :nodoc: all
52 include Rainbows::EvCore
53 include Rainbows::Response
62 alias receive_data on_read
66 close_connection_after_writing
70 set_comm_inactivity_timeout 0
72 @env[RACK_INPUT] = @input
73 @env[REMOTE_ADDR] = @remote_addr
74 @env[ASYNC_CALLBACK] = method(:em_write_response)
76 # we're not sure if anybody uses this, but Thin sets it, too
77 @env[ASYNC_CLOSE] = EM::DefaultDeferrable.new
79 response = catch(:async) { APP.call(@env.update(RACK_DEFAULTS)) }
81 # too tricky to support pipelining with :async since the
82 # second (pipelined) request could be a stuck behind a
83 # long-running async response
84 (response.nil? || -1 == response[0]) and return @state = :close
86 em_write_response(response, alive = @hp.keepalive? && G.alive)
91 # keepalive requests are always body-less, so @input is unchanged
92 @hp.headers(@env, @buf) and next
93 set_comm_inactivity_timeout G.kato
99 # used for streaming sockets and pipes
100 def stream_response(status, headers, io)
102 do_chunk = !!(headers['Transfer-Encoding'] =~ %r{\Achunked\z}i)
103 do_chunk = false if headers.delete('X-Rainbows-Autochunk') == 'no'
104 headers[CONNECTION] = CLOSE # TODO: allow keep-alive
105 write(response_header(status, headers))
110 EM.watch(io, ResponseChunkPipe, self).notify_readable = true
112 EM.enable_proxy(EM.attach(io, ResponsePipe, self), self, 16384)
116 def em_write_response(response, alive = false)
117 status, headers, body = response
118 headers = @hp.headers? ? HH.new(headers) : nil if headers
121 if body.respond_to?(:errback) && body.respond_to?(:callback)
122 body.callback { quit }
123 body.errback { quit }
124 # async response, this could be a trickle as is in comet-style apps
126 headers[CONNECTION] = CLOSE
127 write(response_header(status, headers))
129 return write_body_each(self, body)
130 elsif body.respond_to?(:to_path)
131 io = body_to_io(body)
136 headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
137 write(response_header(status, headers))
139 stream = stream_file_data(body.to_path)
140 stream.callback { quit } unless alive
142 elsif st.socket? || st.pipe?
143 return stream_response(status, headers, io)
145 # char or block device... WTF? fall through to body.each
149 headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
150 write(response_header(status, headers))
152 write_body_each(self, body)
157 async_close = @env[ASYNC_CLOSE] and async_close.succeed
158 @body.respond_to?(:fail) and @body.fail
163 module ResponsePipe # :nodoc: all
164 def initialize(client)
174 module ResponseChunkPipe # :nodoc: all
178 @client.write("0\r\n\r\n")
185 @io.read_nonblock(16384)
194 @client.send_data(sprintf("%x\r\n", data.size))
195 @client.send_data(data)
196 @client.send_data("\r\n")
201 module Server # :nodoc: all
209 return if CUR.size >= MAX
210 io = Rainbows.accept(@io) or return
211 sig = EM.attach_fd(io.fileno, false)
212 CUR[sig] = CL.new(sig, io)
216 # Middleware that will run the app dispatch in a separate thread.
217 # This middleware is automatically loaded by Rainbows! when using
218 # EventMachine and if the app responds to the +deferred?+ method.
219 class TryDefer < Struct.new(:app) # :nodoc: all
222 # the entire app becomes multithreaded, even the root (non-deferred)
223 # thread since any thread can share processes with others
224 Const::RACK_DEFAULTS['rack.multithread'] = true
229 if app.deferred?(env)
230 EM.defer(proc { catch(:async) { app.call(env) } },
231 env[EvCore::ASYNC_CALLBACK])
232 # all of the async/deferred stuff breaks Rack::Lint :<
240 def init_worker_process(worker) # :nodoc:
241 Rainbows::Response.setup(Rainbows::EventMachine::Client)
245 # runs inside each forked worker, this sits around and waits
246 # for connections and doesn't die until the parent dies (or is
247 # given a INT, QUIT, or TERM signal)
248 def worker_loop(worker) # :nodoc:
249 init_worker_process(worker)
250 G.server.app.respond_to?(:deferred?) and
251 G.server.app = TryDefer[G.server.app]
253 # enable them both, should be non-fatal if not supported
256 logger.info "#@use: epoll=#{EM.epoll?} kqueue=#{EM.kqueue?}"
257 client_class = Rainbows.const_get(@use).const_get(:Client)
258 Server.const_set(:MAX, worker_connections + LISTENERS.size)
259 Server.const_set(:CL, client_class)
260 client_class.const_set(:APP, G.server.app)
262 conns = EM.instance_variable_get(:@conns) or
263 raise RuntimeError, "EM @conns instance variable not accessible!"
264 Server.const_set(:CUR, conns)
265 EM.add_periodic_timer(1) do
267 conns.each_value { |c| client_class === c and c.quit }
268 EM.stop if conns.empty? && EM.reactor_running?
271 LISTENERS.map! do |s|
272 EM.watch(s, Server) { |c| c.notify_readable = true }