event_machine: avoid redundant open() for static files
[rainbows.git] / lib / rainbows / event_machine.rb
blob4402c72505c1cfe09f44d430f6c05b02a5f6ca3f
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
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
55       include Rainbows::EvCore
56       G = Rainbows::G
58       def initialize(io)
59         @_io = io
60         @body = nil
61       end
63       alias write send_data
64       alias receive_data on_read
66       def quit
67         super
68         close_connection_after_writing
69       end
71       def app_call
72         set_comm_inactivity_timeout 0
73         begin
74           @env[RACK_INPUT] = @input
75           @env[REMOTE_ADDR] = @remote_addr
76           @env[ASYNC_CALLBACK] = method(:em_write_response)
78           # we're not sure if anybody uses this, but Thin sets it, too
79           @env[ASYNC_CLOSE] = EM::DefaultDeferrable.new
81           response = catch(:async) { APP.call(@env.update(RACK_DEFAULTS)) }
83           # too tricky to support pipelining with :async since the
84           # second (pipelined) request could be a stuck behind a
85           # long-running async response
86           (response.nil? || -1 == response[0]) and return @state = :close
88           em_write_response(response, alive = @hp.keepalive? && G.alive)
89           if alive
90             @env.clear
91             @hp.reset
92             @state = :headers
93             # keepalive requests are always body-less, so @input is unchanged
94             @hp.headers(@env, @buf) and next
95             set_comm_inactivity_timeout G.kato
96           end
97           return
98         end while true
99       end
101       def em_write_response(response, alive = false)
102         status, headers, body = response
103         if @hp.headers?
104           headers = HH.new(headers)
105           headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
106         else
107           headers = nil
108         end
110         if body.respond_to?(:errback) && body.respond_to?(:callback)
111           @body = body
112           body.callback { quit }
113           body.errback { quit }
114           # async response, this could be a trickle as is in comet-style apps
115           headers[CONNECTION] = CLOSE if headers
116           alive = true
117         elsif body.respond_to?(:to_path)
118           st = File.stat(path = body.to_path)
120           if st.file?
121             cb = lambda do
122               body.close if body.respond_to?(:close)
123               quit unless alive
124             end
125             write(response_header(status, headers)) if headers
126             @body = stream = stream_file_data(path)
127             stream.errback(&cb)
128             return stream.callback(&cb)
129           elsif st.socket? || st.pipe?
130             io = body_to_io(body)
131             chunk = stream_response_headers(status, headers) if headers
132             m = chunk ? ResponseChunkPipe : ResponsePipe
133             return EM.watch(io, m, self, alive, body).notify_readable = true
134           end
135           # char or block device... WTF? fall through to body.each
136         end
138         write(response_header(status, headers)) if headers
139         write_body_each(self, body)
140         quit unless alive
141       end
143       def unbind
144         async_close = @env[ASYNC_CLOSE] and async_close.succeed
145         @body.respond_to?(:fail) and @body.fail
146         @_io.close
147       end
148     end
150     module Server # :nodoc: all
152       def close
153         detach
154         @io.close
155       end
157       def notify_readable
158         return if CUR.size >= MAX
159         io = Rainbows.accept(@io) or return
160         sig = EM.attach_fd(io.fileno, false)
161         CUR[sig] = CL.new(sig, io)
162       end
163     end
165     def init_worker_process(worker) # :nodoc:
166       Rainbows::Response.setup(Rainbows::EventMachine::Client)
167       super
168     end
170     # runs inside each forked worker, this sits around and waits
171     # for connections and doesn't die until the parent dies (or is
172     # given a INT, QUIT, or TERM signal)
173     def worker_loop(worker) # :nodoc:
174       init_worker_process(worker)
175       G.server.app.respond_to?(:deferred?) and
176         G.server.app = TryDefer[G.server.app]
178       # enable them both, should be non-fatal if not supported
179       EM.epoll
180       EM.kqueue
181       logger.info "#@use: epoll=#{EM.epoll?} kqueue=#{EM.kqueue?}"
182       client_class = Rainbows.const_get(@use).const_get(:Client)
183       Server.const_set(:MAX, worker_connections + LISTENERS.size)
184       Server.const_set(:CL, client_class)
185       client_class.const_set(:APP, G.server.app)
186       EM.run {
187         conns = EM.instance_variable_get(:@conns) or
188           raise RuntimeError, "EM @conns instance variable not accessible!"
189         Server.const_set(:CUR, conns)
190         EM.add_periodic_timer(1) do
191           unless G.tick
192             conns.each_value { |c| client_class === c and c.quit }
193             EM.stop if conns.empty? && EM.reactor_running?
194           end
195         end
196         LISTENERS.map! do |s|
197           EM.watch(s, Server) { |c| c.notify_readable = true }
198         end
199       }
200     end
202   end