remove unnecessary header munging for static file serving
[rainbows.git] / lib / rainbows / event_machine.rb
blob77fc962573526c764af6f06b01838181f119ce94
1 # -*- encoding: binary -*-
2 require 'eventmachine'
3 EM::VERSION >= '0.12.10' or abort 'eventmachine 0.12.10 is required'
4 require 'rainbows/ev_core'
6 module Rainbows
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].
16   #
17   # It does not require your Rack application to be thread-safe,
18   # reentrancy is only required for the DevFdResponse body
19   # generator.
20   #
21   # Compatibility: Whatever \EventMachine ~> 0.12.10 and Unicorn both
22   # support, currently Ruby 1.8/1.9.
23   #
24   # This model is compatible with users of "async.callback" in the Rack
25   # environment such as
26   # {async_sinatra}[http://github.com/raggi/async_sinatra].
27   #
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.
31   #
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.
36   #
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.
41   #
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.
47   module EventMachine
49     include Base
51     class Client < EM::Connection # :nodoc: all
52       include Rainbows::EvCore
53       include Rainbows::Response
54       G = Rainbows::G
56       def initialize(io)
57         @_io = io
58         @body = nil
59       end
61       alias write send_data
62       alias receive_data on_read
64       def quit
65         super
66         close_connection_after_writing
67       end
69       def app_call
70         set_comm_inactivity_timeout 0
71         begin
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)
87           if alive
88             @env.clear
89             @hp.reset
90             @state = :headers
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
94           end
95           return
96         end while true
97       end
99       # used for streaming sockets and pipes
100       def stream_response(status, headers, io)
101         if headers
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))
106         else
107           do_chunk = false
108         end
109         if do_chunk
110           EM.watch(io, ResponseChunkPipe, self).notify_readable = true
111         else
112           EM.enable_proxy(EM.attach(io, ResponsePipe, self), self, 16384)
113         end
114       end
116       def em_write_response(response, alive = false)
117         status, headers, body = response
118         headers = @hp.headers? ? HH.new(headers) : nil if headers
119         @body = body
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
125           if headers
126             headers[CONNECTION] = CLOSE
127             write(response_header(status, headers))
128           end
129           return write_body_each(self, body)
130         elsif body.respond_to?(:to_path)
131           io = body_to_io(body)
132           st = io.stat
134           if st.file?
135             if headers
136               headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
137               write(response_header(status, headers))
138             end
139             stream = stream_file_data(body.to_path)
140             stream.callback { quit } unless alive
141             return
142           elsif st.socket? || st.pipe?
143             return stream_response(status, headers, io)
144           end
145           # char or block device... WTF? fall through to body.each
146         end
148         if headers
149           headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
150           write(response_header(status, headers))
151         end
152         write_body_each(self, body)
153         quit unless alive
154       end
156       def unbind
157         async_close = @env[ASYNC_CLOSE] and async_close.succeed
158         @body.respond_to?(:fail) and @body.fail
159         @_io.close
160       end
161     end
163     module ResponsePipe # :nodoc: all
164       def initialize(client)
165         @client = client
166       end
168       def unbind
169         @io.close
170         @client.quit
171       end
172     end
174     module ResponseChunkPipe # :nodoc: all
175       include ResponsePipe
177       def unbind
178         @client.write("0\r\n\r\n")
179         super
180       end
182       def notify_readable
183         begin
184           data = begin
185             @io.read_nonblock(16384)
186           rescue Errno::EINTR
187             retry
188           rescue Errno::EAGAIN
189             return
190           rescue EOFError
191             detach
192             return
193           end
194           @client.send_data(sprintf("%x\r\n", data.size))
195           @client.send_data(data)
196           @client.send_data("\r\n")
197         end while true
198       end
199     end
201     module Server # :nodoc: all
203       def close
204         detach
205         @io.close
206       end
208       def notify_readable
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)
213       end
214     end
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
221       def initialize(app)
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
225         super
226       end
228       def call(env)
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 :<
233           nil
234         else
235           app.call(env)
236         end
237       end
238     end
240     def init_worker_process(worker) # :nodoc:
241       Rainbows::Response.setup(Rainbows::EventMachine::Client)
242       super
243     end
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
254       EM.epoll
255       EM.kqueue
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)
261       EM.run {
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
266           unless G.tick
267             conns.each_value { |c| client_class === c and c.quit }
268             EM.stop if conns.empty? && EM.reactor_running?
269           end
270         end
271         LISTENERS.map! do |s|
272           EM.watch(s, Server) { |c| c.notify_readable = true }
273         end
274       }
275     end
277   end