From fcd87530a5acc4351f05141ae9f34dc8bb9555d9 Mon Sep 17 00:00:00 2001 From: Tabby Cromarty Date: Mon, 12 Dec 2022 15:52:05 +0000 Subject: [PATCH] Store connection object in thread local --- lib/companies_house/client.rb | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/lib/companies_house/client.rb b/lib/companies_house/client.rb index a7deff0..478c10f 100644 --- a/lib/companies_house/client.rb +++ b/lib/companies_house/client.rb @@ -24,10 +24,18 @@ def initialize(config) @read_timeout = config[:read_timeout] || 60 @instrumentation = configure_instrumentation(config[:instrumentation]) raise ArgumentError, "HTTP is not supported" if @endpoint.scheme != "https" + + # Clear stale thread-local connection object if necessary - its lifetime should + # match the lifetime of the client object + Thread.current[:companies_house_client_connection] = nil end def end_connection - @connection.finish if @connection&.started? + return if Thread.current[:companies_house_client_connection].nil? + return unless Thread.current[:companies_house_client_connection].started? + + Thread.current[:companies_house_client_connection].finish + Thread.current[:companies_house_client_connection] = nil end def company(id) @@ -74,11 +82,12 @@ def company_search(query, items_per_page: nil, start_index: nil) end def connection - @connection ||= Net::HTTP.new(endpoint.host, endpoint.port).tap do |conn| - conn.use_ssl = true - conn.open_timeout = @open_timeout - conn.read_timeout = @read_timeout - end + Thread.current[:companies_house_client_connection] ||= + Net::HTTP.new(endpoint.host, endpoint.port).tap do |conn| + conn.use_ssl = true + conn.open_timeout = @open_timeout + conn.read_timeout = @read_timeout + end end private