rainbows.git  about / heads / tags
Unicorn for sleepy apps and slow clients
blob 3055b9d986984dec11e90b8be9e22d50ab432aeb 1911 bytes (raw)
$ git show v2.0.0:lib/rainbows/process_client.rb	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 
# -*- encoding: binary -*-
# :enddoc:
module Rainbows::ProcessClient
  G = Rainbows::G
  include Rainbows::Response
  HttpParser = Unicorn::HttpParser
  NULL_IO = Unicorn::HttpRequest::NULL_IO
  RACK_INPUT = Unicorn::HttpRequest::RACK_INPUT
  TeeInput = Unicorn::TeeInput
  include Rainbows::Const

  # once a client is accepted, it is processed in its entirety here
  # in 3 easy steps: read request, call app, write app response
  # this is used by synchronous concurrency models
  #   Base, ThreadSpawn, ThreadPool
  def process_client(client) # :nodoc:
    hp = HttpParser.new
    client.kgio_read!(16384, buf = hp.buf)
    remote_addr = client.kgio_addr
    alive = false

    begin # loop
      until env = hp.parse
        client.timed_read(buf2 ||= "") or return
        buf << buf2
      end

      env[CLIENT_IO] = client
      env[RACK_INPUT] = 0 == hp.content_length ?
                        NULL_IO : TeeInput.new(client, hp)
      env[REMOTE_ADDR] = remote_addr
      status, headers, body = APP.call(env.update(RACK_DEFAULTS))

      if 100 == status.to_i
        client.write(EXPECT_100_RESPONSE)
        env.delete(HTTP_EXPECT)
        status, headers, body = APP.call(env)
      end

      if hp.headers?
        headers = HH.new(headers)
        range = make_range!(env, status, headers) and status = range.shift
        alive = hp.next? && G.alive
        headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
        client.write(response_header(status, headers))
      end
      write_body(client, body, range)
    end while alive
  # if we get any error, try to write something back to the client
  # assuming we haven't closed the socket, but don't get hung up
  # if the socket is already closed or broken.  We'll always ensure
  # the socket is closed at the end of this function
  rescue => e
    Rainbows::Error.write(client, e)
  ensure
    client.close unless client.closed?
  end
end

git clone https://yhbt.net/rainbows.git