Class: LeanPool::HTTPPool

Inherits:
Object
  • Object
show all
Defined in:
lib/lean_pool/http_pool.rb

Overview

Note:

Uses Ruby's standard Net::HTTP library. Connections are reused when possible but removed automatically if errors occur.

HTTP connection pool implementation using Net::HTTP.

HTTPPool provides a convenient wrapper around Pool for managing HTTP/1 connections. It automatically handles connection lifecycle, request/response processing, and connection reuse.

This is an example implementation demonstrating how to use LeanPool for HTTP connections. For production use with more advanced features (HTTP/2, connection keep-alive optimization, etc.), consider using libraries like HTTP.rb or Faraday with connection pooling.

Features:

  • Automatic connection management and reuse
  • Support for both HTTP and HTTPS (SSL)
  • GET and POST request methods
  • Custom headers and timeouts
  • Automatic connection removal on errors

Examples:

Basic HTTP requests

pool = LeanPool::HTTPPool.new("api.example.com", 443, size: 10, use_ssl: true)

response = pool.get("/users")
puts response[:status]  # => 200
puts response[:body]
puts response[:headers]

POST request with JSON

pool = LeanPool::HTTPPool.new("api.example.com", 443, use_ssl: true)

response = pool.post(
  "/users",
  body: '{"name":"John"}',
  headers: { "Content-Type" => "application/json" }
)

With custom timeout

pool = LeanPool::HTTPPool.new("api.example.com", 80, timeout: 10.0)
response = pool.get("/slow-endpoint", timeout: 15.0)

Since:

  • 0.1.0

Instance Method Summary collapse

Constructor Details

#initialize(host, port, size: 10, timeout: 5.0, use_ssl: false) ⇒ HTTPPool

Initialize a new HTTP connection pool.

Creates a new pool for managing HTTP connections to the specified host and port. Connections are created lazily on-demand and reused when possible.

Examples:

pool = LeanPool::HTTPPool.new("api.example.com", 443, size: 10, use_ssl: true)

Parameters:

  • host (String)

    The hostname or IP address to connect to

  • port (Integer)

    The port number to connect to

  • size (Integer) (defaults to: 10)

    Maximum number of connections in the pool (default: 10)

  • timeout (Float) (defaults to: 5.0)

    Default timeout in seconds for operations (default: 5.0)

  • use_ssl (Boolean) (defaults to: false)

    Whether to use SSL/TLS for connections (default: false)

Since:

  • 0.1.0



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/lean_pool/http_pool.rb', line 64

def initialize(host, port, size: 10, timeout: 5.0, use_ssl: false)
  @host = host
  @port = port
  @use_ssl = use_ssl

  @pool = Pool.new(
    size: size,
    timeout: timeout,
    pool_state: { host: host, port: port, use_ssl: use_ssl }
  ) do |state|
    http = Net::HTTP.new(state[:host], state[:port])
    http.use_ssl = state[:use_ssl] if state[:use_ssl]
    http
  end
end

Instance Method Details

#get(path, headers: {}, timeout: nil) ⇒ Hash

Perform a GET HTTP request.

Retrieves a connection from the pool, performs a GET request to the specified path, and returns the response. The connection is automatically returned to the pool unless an error occurs, in which case it's removed.

Examples:

Basic GET request

response = pool.get("/users")
puts response[:status]  # => 200
puts response[:body]

With custom headers

response = pool.get(
  "/api/data",
  headers: { "Authorization" => "Bearer token", "Accept" => "application/json" }
)

With custom timeout

response = pool.get("/slow-endpoint", timeout: 30.0)

Parameters:

  • path (String)

    The request path (e.g., "/users" or "/api/v1/data")

  • headers (Hash) (defaults to: {})

    Optional HTTP headers to include in the request

  • timeout (Float, nil) (defaults to: nil)

    Optional timeout override in seconds. If nil, uses the pool's default timeout.

Returns:

  • (Hash)

    Response hash with the following keys:

    • :status [Integer] HTTP status code (e.g., 200, 404, 500)
    • :body [String] Response body
    • :headers [Hash] Response headers
  • (Hash)

    If an error occurs, returns a hash with :error and :remove keys

Since:

  • 0.1.0



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/lean_pool/http_pool.rb', line 109

def get(path, headers: {}, timeout: nil)
  @pool.checkout(timeout: timeout) do |http|
    http.start unless http.started?

    request = Net::HTTP::Get.new(path)
    headers.each { |k, v| request[k] = v }

    response = http.request(request)

    {
      status: response.code.to_i,
      body: response.body,
      headers: response.to_hash
    }
  end
rescue => e
  # Remove connection if it's broken
  { error: e.message, remove: true }
end

#post(path, body: "", headers: {}, timeout: nil) ⇒ Hash

Perform a POST HTTP request.

Retrieves a connection from the pool, performs a POST request to the specified path with the given body, and returns the response. The connection is automatically returned to the pool unless an error occurs, in which case it's removed.

Examples:

Basic POST request

response = pool.post("/users", body: '{"name":"John"}')

POST with JSON

response = pool.post(
  "/api/users",
  body: '{"name":"John","email":"[email protected]"}',
  headers: { "Content-Type" => "application/json" }
)

POST with form data

response = pool.post(
  "/submit",
  body: "name=John&[email protected]",
  headers: { "Content-Type" => "application/x-www-form-urlencoded" }
)

Parameters:

  • path (String)

    The request path (e.g., "/users" or "/api/v1/create")

  • body (String) (defaults to: "")

    The request body to send (default: empty string)

  • headers (Hash) (defaults to: {})

    Optional HTTP headers to include in the request

  • timeout (Float, nil) (defaults to: nil)

    Optional timeout override in seconds. If nil, uses the pool's default timeout.

Returns:

  • (Hash)

    Response hash with the following keys:

    • :status [Integer] HTTP status code (e.g., 200, 201, 400, 500)
    • :body [String] Response body
    • :headers [Hash] Response headers
  • (Hash)

    If an error occurs, returns a hash with :error and :remove keys

Since:

  • 0.1.0



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/lean_pool/http_pool.rb', line 162

def post(path, body: "", headers: {}, timeout: nil)
  @pool.checkout(timeout: timeout) do |http|
    http.start unless http.started?

    request = Net::HTTP::Post.new(path)
    headers.each { |k, v| request[k] = v }
    request.body = body

    response = http.request(request)

    {
      status: response.code.to_i,
      body: response.body,
      headers: response.to_hash
    }
  end
rescue => e
  { error: e.message, remove: true }
end

#shutdownvoid

This method returns an undefined value.

Shutdown the HTTP pool gracefully.

Closes all HTTP connections in the pool and prevents new requests. All connections are properly finished before being removed from the pool.

See Also:

Since:

  • 0.1.0



200
201
202
203
204
# File 'lib/lean_pool/http_pool.rb', line 200

def shutdown
  @pool.shutdown do |http|
    http.finish if http.started?
  end
end

#statsHash

Get HTTP pool statistics.

Returns statistics about the underlying connection pool, including size, available connections, in-use connections, and total connections.

Returns:

  • (Hash)

    Pool statistics hash with :size, :available, :in_use, and :total keys

See Also:

Since:

  • 0.1.0



189
190
191
# File 'lib/lean_pool/http_pool.rb', line 189

def stats
  @pool.stats
end