simplify per-client keepalive state checks
[rainbows.git] / lib / rainbows / process_client.rb
blob54e59e8fa87f4bd8ee19de57e389431ac59e1b14
1 # -*- encoding: binary -*-
2 # :enddoc:
3 require 'rainbows/rack_input'
4 module Rainbows::ProcessClient
5   G = Rainbows::G
6   include Rainbows::Response
7   HttpParser = Rainbows::HttpParser
8   include Rainbows::RackInput
9   include Rainbows::Const
11   # once a client is accepted, it is processed in its entirety here
12   # in 3 easy steps: read request, call app, write app response
13   # this is used by synchronous concurrency models
14   #   Base, ThreadSpawn, ThreadPool
15   def process_client(client) # :nodoc:
16     hp = HttpParser.new
17     client.kgio_read!(16384, buf = hp.buf)
18     remote_addr = client.kgio_addr
19     alive = false
21     begin # loop
22       until env = hp.parse
23         client.timed_read(buf2 ||= "") or return
24         buf << buf2
25       end
27       set_input(env, hp, client)
28       env[REMOTE_ADDR] = remote_addr
29       status, headers, body = APP.call(env.update(RACK_DEFAULTS))
31       if 100 == status.to_i
32         client.write(EXPECT_100_RESPONSE)
33         env.delete(HTTP_EXPECT)
34         status, headers, body = APP.call(env)
35       end
37       if hp.headers?
38         headers = HH.new(headers)
39         range = make_range!(env, status, headers) and status = range.shift
40         headers[CONNECTION] = (alive = hp.next?) ? KEEP_ALIVE : CLOSE
41         client.write(response_header(status, headers))
42       end
43       write_body(client, body, range)
44     end while alive
45   # if we get any error, try to write something back to the client
46   # assuming we haven't closed the socket, but don't get hung up
47   # if the socket is already closed or broken.  We'll always ensure
48   # the socket is closed at the end of this function
49   rescue => e
50     Rainbows::Error.write(client, e)
51   ensure
52     client.close unless client.closed?
53   end
54 end