code shuffling for kgio
[rainbows.git] / lib / rainbows / process_client.rb
blob5e200e55ba123cbf0c1918617018fe811dc4bca1
1 # -*- encoding: binary -*-
2 # :enddoc:
3 module Rainbows::ProcessClient
4   G = Rainbows::G
5   include Rainbows::Response
6   HttpParser = Unicorn::HttpParser
7   NULL_IO = Unicorn::HttpRequest::NULL_IO
8   RACK_INPUT = Unicorn::HttpRequest::RACK_INPUT
9   TeeInput = Rainbows::TeeInput
10   include Rainbows::Const
12   def wait_headers_readable(client)
13     IO.select([client], nil, nil, G.kato)
14   end
16   # once a client is accepted, it is processed in its entirety here
17   # in 3 easy steps: read request, call app, write app response
18   # this is used by synchronous concurrency models
19   #   Base, ThreadSpawn, ThreadPool
20   def process_client(client) # :nodoc:
21     hp = HttpParser.new
22     client.readpartial(16384, buf = hp.buf)
23     remote_addr = client.kgio_addr
25     begin # loop
26       until env = hp.parse
27         wait_headers_readable(client) or return
28         buf << client.readpartial(16384)
29       end
31       env[CLIENT_IO] = client
32       env[RACK_INPUT] = 0 == hp.content_length ?
33                         NULL_IO : TeeInput.new(client, hp)
34       env[REMOTE_ADDR] = remote_addr
35       status, headers, body = APP.call(env.update(RACK_DEFAULTS))
37       if 100 == status.to_i
38         client.write(EXPECT_100_RESPONSE)
39         env.delete(HTTP_EXPECT)
40         status, headers, body = APP.call(env)
41       end
43       if hp.headers?
44         headers = HH.new(headers)
45         range = make_range!(env, status, headers) and status = range.shift
46         env = hp.keepalive? && G.alive
47         headers[CONNECTION] = env ? KEEP_ALIVE : CLOSE
48         client.write(response_header(status, headers))
49       end
50       write_body(client, body, range)
51     end while env && hp.reset.nil?
52   # if we get any error, try to write something back to the client
53   # assuming we haven't closed the socket, but don't get hung up
54   # if the socket is already closed or broken.  We'll always ensure
55   # the socket is closed at the end of this function
56   rescue => e
57     Rainbows::Error.write(client, e)
58   ensure
59     client.close unless client.closed?
60   end
61 end