Skip to content

Commit

Permalink
Merge pull request #70 from gocardless/thread-safe-connection-object
Browse files Browse the repository at this point in the history
Make HTTP connection object thread-safe
  • Loading branch information
Tabby authored Dec 13, 2022
2 parents 17373f2 + e31f4b0 commit 9ee4fb3
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions lib/companies_house/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 9ee4fb3

Please sign in to comment.