1 # -*- encoding: binary -*-
3 class Rainbows::EventMachine::Client < EM::Connection
4 include Rainbows::EvCore
13 def receive_data(data)
14 # To avoid clobbering the current streaming response
15 # (often a static file), we do not attempt to process another
16 # request on the same connection until the first is complete
20 @_io.shutdown(Socket::SHUT_RD) if @buf.size > 0x1c000
22 EM.next_tick { receive_data(nil) } unless @buf.empty?
24 on_read(data || Z) if (@buf.size > 0) || data
30 close_connection_after_writing
34 set_comm_inactivity_timeout 0
35 @env[RACK_INPUT] = input
36 @env[REMOTE_ADDR] = @_io.kgio_addr
37 @env[ASYNC_CALLBACK] = method(:write_async_response)
38 @env[ASYNC_CLOSE] = EM::DefaultDeferrable.new
39 status, headers, body = catch(:async) {
40 APP.call(@env.merge!(RACK_DEFAULTS))
43 (nil == status || -1 == status) ? @deferred = true :
44 ev_write_response(status, headers, body, @hp.next?)
47 def deferred_errback(orig_body)
49 orig_body.close if orig_body.respond_to?(:close)
54 def deferred_callback(orig_body, alive)
56 orig_body.close if orig_body.respond_to?(:close)
58 alive ? receive_data(nil) : quit
62 def ev_write_response(status, headers, body, alive)
63 @state = :headers if alive
64 if body.respond_to?(:errback) && body.respond_to?(:callback)
66 deferred_errback(body)
67 deferred_callback(body, alive)
68 elsif body.respond_to?(:to_path)
69 st = File.stat(path = body.to_path)
72 write_headers(status, headers, alive)
73 @deferred = stream_file_data(path)
74 deferred_errback(body)
75 deferred_callback(body, alive)
77 elsif st.socket? || st.pipe?
78 io = body_to_io(@deferred = body)
79 chunk = stream_response_headers(status, headers, alive)
80 m = chunk ? Rainbows::EventMachine::ResponseChunkPipe :
81 Rainbows::EventMachine::ResponsePipe
82 return EM.watch(io, m, self).notify_readable = true
84 # char or block device... WTF? fall through to body.each
86 write_response(status, headers, body, alive)
90 set_comm_inactivity_timeout(Rainbows.keepalive_timeout)
92 EM.next_tick { receive_data(nil) }
101 @deferred.close if @deferred.respond_to?(:close)
102 @hp.keepalive? ? receive_data(@deferred = nil) : quit
106 async_close = @env[ASYNC_CLOSE] and async_close.succeed
107 @deferred.respond_to?(:fail) and @deferred.fail
111 # EventMachine's EventableDescriptor::Close() may close
112 # the underlying file descriptor without invalidating the
113 # associated IO object on errors, so @_io.closed? isn't