class Rmega::ConnPool::ConnectionManager

@see www.dmitry-ishkov.com/2021/05/turbocharge-http-requests-in-ruby.html

Constants

KEEP_ALIVE_TIMEOUT

Seconds to reuse the connection of the previous request. If the idle time is less than this Keep-Alive Timeout, Net::HTTP reuses the TCP/IP socket used by the previous communication. Source: Ruby docs

STALE_AFTER

if a client wasn’t used within this time range it gets removed from the cache and the connection closed. This helps to make sure there are no memory leaks.

Attributes

clients_store[RW]

KEEP_ALIVE_TIMEOUT vs STALE_AFTER STALE_AFTER - how long an Net::HTTP client object is cached in ruby KEEP_ALIVE_TIMEOUT - how long that client keeps TCP/IP socket open.

last_used[RW]

KEEP_ALIVE_TIMEOUT vs STALE_AFTER STALE_AFTER - how long an Net::HTTP client object is cached in ruby KEEP_ALIVE_TIMEOUT - how long that client keeps TCP/IP socket open.

Public Class Methods

new(*args) click to toggle source
Calls superclass method
# File lib/rmega/conn_pool.rb, line 49
def initialize(*args)
  super
  self.clients_store = {}
  self.last_used = Time.now
end

Public Instance Methods

close_connections!() click to toggle source

close connections for each client

# File lib/rmega/conn_pool.rb, line 86
def close_connections!
  synchronize do
    clients_store.values.each(&:finish)
    self.clients_store = {}
  end
end
get_client(uri, options) click to toggle source
# File lib/rmega/conn_pool.rb, line 55
def get_client(uri, options)
  synchronize do
    # refresh the last time a client was used,
    # this prevents the client from becoming stale
    self.last_used = Time.now
  
    # we use params as a cache key for clients.
    # 2 connections to the same host but with different
    # options are going to use different HTTP clients
    params = [uri.host, uri.port, options]
    client = clients_store[params]
  
    return client if client
  
    client = ::Net::HTTP.new(uri.host, uri.port)
    client.keep_alive_timeout = KEEP_ALIVE_TIMEOUT

    # set SSL to true if a scheme is https
    client.use_ssl = uri.scheme == "https"
  
    # open connection
    client.start
  
    # cache the client
    clients_store[params] = client
  
    client
  end
end
stale?() click to toggle source
# File lib/rmega/conn_pool.rb, line 93
def stale?
  Time.now - last_used > STALE_AFTER
end