Class: Low::ConnectionManager

Inherits:
Object
  • Object
show all
Defined in:
lib/connections/connection_manager.rb

Constant Summary collapse

DEFAULT_KEEP_ALIVE_TIMEOUT =
30
DEFAULT_REQUEST_TIMEOUT =
10

Instance Method Summary collapse

Constructor Details

#initialize(config:) ⇒ ConnectionManager

Returns a new instance of ConnectionManager.



13
14
15
# File 'lib/connections/connection_manager.rb', line 13

def initialize(config:)
  @config = config
end

Instance Method Details

#handle_connection(socket:) ⇒ Object



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
# File 'lib/connections/connection_manager.rb', line 17

def handle_connection(socket:)
  stream = RequestParser.create_stream(socket:)
  keep_alive = true
  version = nil

  while keep_alive
    break unless socket.wait_readable(keep_alive_timeout)

    socket.timeout = request_timeout
    begin
      request = RequestParser.parse(stream:, host: config.host, port: config.port, version:)
    rescue IO::TimeoutError
      break
    ensure
      socket.timeout = nil
    end
    break if request.nil?

    version ||= request.version
    keep_alive = keep_alive?(request)

    response_event = Events::RequestEvent.take(request:)
    response = response_event.response

    ResponseBuilder.respond(config:, socket:, response:, keep_alive:)
  end
end

#keep_alive?(request) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
53
54
55
# File 'lib/connections/connection_manager.rb', line 45

def keep_alive?(request)
  tokens = (request.headers['connection'] || []).flat_map do |value|
    value.split(',').map { |token| token.strip.downcase }
  end

  if request.version.to_s.downcase.include?('1.0')
    tokens.include?('keep-alive')
  else
    !tokens.include?('close')
  end
end

#keep_alive_timeout ⇒ Object



57
58
59
# File 'lib/connections/connection_manager.rb', line 57

def keep_alive_timeout
  config.keep_alive_timeout || DEFAULT_KEEP_ALIVE_TIMEOUT
end

#request_timeout ⇒ Object



61
62
63
# File 'lib/connections/connection_manager.rb', line 61

def request_timeout
  config.request_timeout || DEFAULT_REQUEST_TIMEOUT
end