Class: OpenAI::NetHTTPClient

Inherits:
HTTPClient
  • Object
show all
Defined in:
lib/openai/net_http_client.rb,
sig/openai/net_http_client.rbs

Overview

The SDK's pooled Net::HTTP implementation.

Network operations from a non-blocking fiber cooperate with its active Ruby Fiber scheduler, allowing concurrent requests and streams without occupying one thread per request.

Pass a block to configure each SDK-created connection before it is pooled and started.

Constant Summary collapse

KEEP_ALIVE_TIMEOUT =

Returns:

  • (30)
30
DEFAULT_MAX_CONNECTIONS =

Returns:

  • (Integer)
[Etc.nprocessors, 99].max
URI =

Returns:

  • (:Generic url,)
Net =

Returns:

  • (:HTTP connection,)

Instance Method Summary collapse

Constructor Details

#initialize(size: self.class::DEFAULT_MAX_CONNECTIONS, &connection_configurator) ⇒ NetHTTPClient

Returns a new instance of NetHTTPClient.

Parameters:

  • size (Integer) (defaults to: self.class::DEFAULT_MAX_CONNECTIONS)
  • connection_configurator (#call, nil)

    A block that configures every SDK-created Net::HTTP connection before it is pooled and started.

  • size: (Integer) (defaults to: self.class::DEFAULT_MAX_CONNECTIONS)


338
339
340
341
342
343
344
345
# File 'lib/openai/net_http_client.rb', line 338

def initialize(size: self.class::DEFAULT_MAX_CONNECTIONS, &connection_configurator)
  super()
  @mutex = Mutex.new
  @size = size
  @cert_store = OpenSSL::X509::Store.new.tap(&:set_default_paths)
  @connection_configurator = connection_configurator
  @pools = {}
end

Instance Method Details

#closevoid

This method returns an undefined value.

Closes current pooled connections. The client remains reusable and will create fresh pools on subsequent requests.

In-flight requests are allowed to finish before their connection closes.



222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/openai/net_http_client.rb', line 222

def close
  pools = @mutex.synchronize do
    current_pools = @pools
    @pools = {}
    current_pools
  end

  pools.each_value do |pool|
    pool.shutdown { |pooled_connection| close_connection(pooled_connection.connection) }
  end

  nil
end

#execute(request) {|connection| ... } ⇒ OpenAI::HTTPClient::Response

Executes a request using a pooled Net::HTTP connection.

Parameters:

Yield Parameters:

  • connection (Net::HTTP)

    configured connection, before any network I/O

Returns:



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/openai/net_http_client.rb', line 241

def execute(request, &connection_validator)
  url = request.url
  deadline = request.timeout&.then { OpenAI::Internal::Util.monotonic_secs + _1 }

  req = nil
  finished = false

  # rubocop:disable Metrics/BlockLength
  enum = Enumerator.new do |y|
    next if finished

    with_pool(url, deadline: deadline) do |conn, pooled_connection|
      previously_started = conn.started?
      validation_complete = false
      begin
        connection_validator&.call(conn)

        if !previously_started && conn.started?
          raise ArgumentError, "connection validation must leave the connection unstarted"
        end

        expected_ssl = %w[https wss].include?(url.scheme)
        unless conn.use_ssl? == expected_ssl
          raise ArgumentError, "connection validation must preserve TLS for the requested URL"
        end

        validation_complete = true
      ensure
        unless validation_complete
          close_connection(conn)
          pooled_connection.connection = nil
        end
      end

      eof = false
      closing = nil
      ::Thread.handle_interrupt(Object => :never) do
        ::Thread.handle_interrupt(Object => :immediate) do
          req, closing = build_request(request) do
            calibrate_socket_timeout(conn, deadline)
          end

          calibrate_socket_timeout(conn, deadline)
          conn.start unless conn.started?

          calibrate_socket_timeout(conn, deadline)
          ::Kernel.catch(:jump) do
            conn.request(req) do |rsp|
              y << [req, rsp]
              ::Kernel.throw(:jump) if finished

              rsp.read_body do |bytes|
                y << bytes.force_encoding(Encoding::BINARY)
                ::Kernel.throw(:jump) if finished

                calibrate_socket_timeout(conn, deadline)
              end

              eof = true
            end
          end
        end

      ensure
        begin
          conn.finish if !eof && conn&.started?
        ensure
          closing&.call
        end
      end
    end

  rescue ConnectionConfigurationError => e
    raise e.original, cause: e.original.cause
  rescue Timeout::Error
    raise OpenAI::Errors::APITimeoutError.new(url: url, request: req)
  rescue *NETWORK_ERRORS
    raise OpenAI::Errors::APIConnectionError.new(url: url, request: req)
  end
  # rubocop:enable Metrics/BlockLength

  _, response = enum.next
  body = OpenAI::Internal::Util.fused_enum(enum, external: true) do
    finished = true
    loop { enum.next }
  end

  OpenAI::HTTPClient::Response.new(
    status: Integer(response.code),
    headers: response.each_header.to_h,
    body: body
  )
end