writer_thread_*: split out classes into separate files
[rainbows.git] / lib / rainbows / process_client.rb
blob271185d454e3f25d4e235bc34185abe62cf2992f
1 # -*- encoding: binary -*-
2 # :enddoc:
3 require 'rainbows/rack_input'
4 module Rainbows::ProcessClient
5   G = Rainbows::G
6   include Rainbows::Response
7   HttpParser = Unicorn::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         alive = hp.next? && G.alive
41         headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
42         client.write(response_header(status, headers))
43       end
44       write_body(client, body, range)
45     end while alive
46   # if we get any error, try to write something back to the client
47   # assuming we haven't closed the socket, but don't get hung up
48   # if the socket is already closed or broken.  We'll always ensure
49   # the socket is closed at the end of this function
50   rescue => e
51     Rainbows::Error.write(client, e)
52   ensure
53     client.close unless client.closed?
54   end
55 end