Skip to content

Commit

Permalink
Revert "Revert "Merge pull request #300 from tbeauvais/httpclient_thr…
Browse files Browse the repository at this point in the history
…ead_safe""

This reverts commit 20d49b0.
  • Loading branch information
bblimke committed Feb 21, 2024
1 parent d209ee1 commit 3ed6b48
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions lib/webmock/http_lib_adapters/httpclient_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ def self.disable!
end

module WebMockHTTPClients
WEBMOCK_HTTPCLIENT_RESPONSES = :webmock_httpclient_responses
WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES = :webmock_httpclient_request_signatures

REQUEST_RESPONSE_LOCK = Mutex.new

Expand All @@ -57,6 +59,9 @@ def do_get_stream(req, proxy, conn, &block)
end

def do_get(req, proxy, conn, stream = false, &block)

clear_thread_variables unless conn.async_thread

request_signature = build_request_signature(req, :reuse_existing)

WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
Expand Down Expand Up @@ -103,12 +108,16 @@ def do_get(req, proxy, conn, stream = false, &block)
end

def do_request_async(method, uri, query, body, extheader)
clear_thread_variables
req = create_request(method, uri, query, body, extheader)
request_signature = build_request_signature(req)
synchronize_request_response { webmock_request_signatures << request_signature }

if webmock_responses[request_signature] || WebMock.net_connect_allowed?(request_signature.uri)
super
conn = super
conn.async_thread[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES] = Thread.current[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES]
conn.async_thread[WEBMOCK_HTTPCLIENT_RESPONSES] = Thread.current[WEBMOCK_HTTPCLIENT_RESPONSES]
conn
else
raise WebMock::NetConnectNotAllowedError.new(request_signature)
end
Expand Down Expand Up @@ -188,15 +197,15 @@ def build_request_signature(req, reuse_existing = false)
end

def webmock_responses
@webmock_responses ||= Hash.new do |hash, request_signature|
Thread.current[WEBMOCK_HTTPCLIENT_RESPONSES] ||= Hash.new do |hash, request_signature|
synchronize_request_response do
hash[request_signature] = WebMock::StubRegistry.instance.response_for_request(request_signature)
end
end
end

def webmock_request_signatures
@webmock_request_signatures ||= []
Thread.current[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES] ||= []
end

def previous_signature_for(signature)
Expand Down Expand Up @@ -228,6 +237,11 @@ def synchronize_request_response
end
end
end

def clear_thread_variables
Thread.current[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES] = nil
Thread.current[WEBMOCK_HTTPCLIENT_RESPONSES] = nil
end
end

class WebMockHTTPClient < HTTPClient
Expand Down

0 comments on commit 3ed6b48

Please sign in to comment.