epoll*: favor shutdown(2) for keepalive timeout
[rainbows.git] / lib / rainbows / epoll / client.rb
blobf690d85af93fca2199ed13ec393cb71d00e1acb4
1 # -*- encoding: binary -*-
2 # :enddoc:
4 module Rainbows::Epoll::Client
6   include Rainbows::EvCore
7   APP = Rainbows.server.app
8   Server = Rainbows::Epoll::Server
9   IN = SleepyPenguin::Epoll::IN | SleepyPenguin::Epoll::ET
10   OUT = SleepyPenguin::Epoll::OUT | SleepyPenguin::Epoll::ET
11   KATO = {}
12   KATO.compare_by_identity if KATO.respond_to?(:compare_by_identity)
13   Rainbows.at_quit { KATO.each_key { |k| k.timeout! }.clear }
14   Rainbows.config!(self, :keepalive_timeout)
15   EP = Rainbows::EP
16   ReRun = []
17   @@last_expire = Time.now
19   def self.expire
20     return if ((now = Time.now) - @@last_expire) < 1.0
21     if (ot = KEEPALIVE_TIMEOUT) >= 0
22       ot = now - ot
23       KATO.delete_if { |client, time| time < ot and client.timeout! }
24     end
25     @@last_expire = now
26   end
28   def self.loop
29     begin
30       EP.wait(nil, 1000) { |_, obj| obj.epoll_run }
31       while obj = ReRun.shift
32         obj.epoll_run
33       end
34       expire
35     rescue Errno::EINTR
36     rescue => e
37       Rainbows::Error.listen_loop(e)
38     end while Rainbows.tick || Server.nr > 0
39   end
41   # only call this once
42   def epoll_once
43     @wr_queue = [] # may contain String, ResponsePipe, and StreamFile objects
44     post_init
45     on_readable
46     rescue => e
47       handle_error(e)
48   end
50   def on_readable
51     case rv = kgio_tryread(CLIENT_HEADER_BUFFER_SIZE, RBUF)
52     when String
53       on_read(rv)
54       return if @wr_queue[0] || closed?
55     when :wait_readable
56       KATO[self] = @@last_expire if :headers == @state
57       return EP.set(self, IN)
58     else
59       break
60     end until :close == @state
61     close unless closed?
62     rescue Errno::ECONNRESET
63       close
64     rescue IOError
65   end
67   def app_call input # called by on_read()
68     @env[RACK_INPUT] = input
69     @env[REMOTE_ADDR] = kgio_addr
70     status, headers, body = APP.call(@env.merge!(RACK_DEFAULTS))
71     ev_write_response(status, headers, body, @hp.next?)
72   end
74   def write_response_path(status, headers, body, alive)
75     io = body_to_io(body)
76     st = io.stat
78     if st.file?
79       defer_file(status, headers, body, alive, io, st)
80     elsif st.socket? || st.pipe?
81       chunk = stream_response_headers(status, headers, alive)
82       stream_response_body(body, io, chunk)
83     else
84       # char or block device... WTF?
85       write_response(status, headers, body, alive)
86     end
87   end
89   # used for streaming sockets and pipes
90   def stream_response_body(body, io, chunk)
91     pipe = (chunk ? Rainbows::Epoll::ResponseChunkPipe :
92                     Rainbows::Epoll::ResponsePipe).new(io, self, body)
93     return @wr_queue << pipe if @wr_queue[0]
94     stream_pipe(pipe) or return
95     @wr_queue[0] or @wr_queue << Z
96   end
98   def ev_write_response(status, headers, body, alive)
99     @state = alive ? :headers : :close
100     if body.respond_to?(:to_path)
101       write_response_path(status, headers, body, alive)
102     else
103       write_response(status, headers, body, alive)
104     end
105     on_read(Z) if alive && 0 == @wr_queue.size && 0 != @buf.size
106   end
108   def epoll_run
109     if @wr_queue[0]
110       on_writable
111     else
112       KATO.delete self
113       on_readable
114     end
115   end
117   def want_more
118     ReRun << self
119   end
121   def on_deferred_write_complete
122     :close == @state and return close
123     0 == @buf.size ? on_readable : on_read(Z)
124   end
126   def handle_error(e)
127     msg = Rainbows::Error.response(e) and kgio_trywrite(msg) rescue nil
128     ensure
129       close
130   end
132   def write_deferred(obj)
133     Rainbows::StreamFile === obj ? stream_file(obj) : stream_pipe(obj)
134   end
136   # writes until our write buffer is empty or we block
137   # returns true if we're done writing everything
138   def on_writable
139     obj = @wr_queue.shift
141     case rv = String === obj ? kgio_trywrite(obj) : write_deferred(obj)
142     when nil
143       obj = @wr_queue.shift or return on_deferred_write_complete
144     when String
145       obj = rv # retry
146     when :wait_writable # Strings and StreamFiles only
147       @wr_queue.unshift(obj)
148       EP.set(self, OUT)
149       return
150     when :deferred
151       return
152     end while true
153     rescue => e
154       handle_error(e)
155   end
157   def write(buf)
158     unless @wr_queue[0]
159       case rv = kgio_trywrite(buf)
160       when nil
161         return # all written
162       when String
163         buf = rv # retry
164       when :wait_writable
165         @wr_queue << buf.dup # >3-word 1.9 strings are copy-on-write
166         return EP.set(self, OUT)
167       end while true
168     end
169     @wr_queue << buf.dup # >3-word 1.9 strings are copy-on-write
170   end
172   def close
173     @wr_queue.each { |x| x.respond_to?(:close) and x.close rescue nil }
174     super
175     on_close
176   end
178   def on_close
179     KATO.delete(self)
180     Server.decr
181   end
183   def timeout!
184     shutdown
185     true
186   end
188   def defer_file(status, headers, body, alive, io, st)
189     if r = sendfile_range(status, headers)
190       status, headers, range = r
191       write_headers(status, headers, alive)
192       range and defer_file_stream(range[0], range[1], io, body)
193     else
194       write_headers(status, headers, alive)
195       defer_file_stream(0, st.size, io, body)
196     end
197   end
199   # returns +nil+ on EOF, :wait_writable if the client blocks
200   def stream_file(sf) # +sf+ is a Rainbows::StreamFile object
201     case n = trysendfile(sf, sf.offset, sf.count)
202     when Integer
203       sf.offset += n
204       0 == (sf.count -= n) and return sf.close
205     else
206       return n # :wait_writable or nil
207     end while true
208     rescue
209       sf.close
210       raise
211   end
213   def defer_file_stream(offset, count, io, body)
214     sf = Rainbows::StreamFile.new(offset, count, io, body)
215     unless @wr_queue[0]
216       stream_file(sf) or return
217     end
218     @wr_queue << sf
219     EP.set(self, OUT)
220   end
222   # this alternates between a push and pull model from the pipe -> client
223   # to avoid having too much data in userspace on either end.
224   def stream_pipe(pipe)
225     case buf = pipe.tryread
226     when String
227       write(buf)
228       if @wr_queue[0]
229         # client is blocked on write, client will pull from pipe later
230         EP.delete pipe
231         @wr_queue << pipe
232         EP.set(self, OUT)
233         return :deferred
234       end
235       # continue looping...
236     when :wait_readable
237       # pipe blocked on read, let the pipe push to the client in the future
238       EP.delete self
239       EP.set(pipe, IN)
240       return :deferred
241     else # nil => EOF
242       return pipe.close # nil
243     end while true
244     rescue
245       pipe.close
246       raise
247   end