Skip to content

Commit

Permalink
Reuse Patron session with mutex
Browse files Browse the repository at this point in the history
Reuse Patron session to support keep-alive/connection reuse and make
them thread-safe using a mutex.

fixes #1001
  • Loading branch information
derSascha committed Jul 13, 2019
1 parent ac27ce5 commit 4a8e9c4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
24 changes: 21 additions & 3 deletions lib/faraday/adapter/patron.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,25 @@ class Adapter
class Patron < Faraday::Adapter
dependency 'patron'

def initialize(app = nil, opts = {}, &block)
@mutex = Mutex.new
super(app, opts, &block)
end

def call(env)
super
# Patron::Session is not thread-safe, use a mutex to be safe
@mutex.synchronize do
super
perform_request env
end
end

def perform_request(env)
# TODO: support streaming requests
env[:body] = env[:body].read if env[:body].respond_to? :read

session = ::Patron::Session.new
@config_block&.call(session)
session = @session ||= create_session

if (env[:url].scheme == 'https') && env[:ssl]
configure_ssl(session, env[:ssl])
end
Expand Down Expand Up @@ -83,6 +95,12 @@ def call(env)
end
end

def create_session
session = ::Patron::Session.new
@config_block.call(session) if @config_block
session
end

def configure_ssl(session, ssl)
if ssl.fetch(:verify, true)
session.cacert = ssl[:ca_file]
Expand Down
17 changes: 17 additions & 0 deletions spec/faraday/adapter/patron_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,21 @@

expect { conn.get('/') }.to raise_error(RuntimeError, 'Configuration block called')
end

it 'reuses the patron session for keep-alive' do
last_session = nil
conn = Faraday.new do |f|
f.adapter :patron do |session|
if last_session
expect(session).to eq last_session
else
last_session = session
end
end
end

stub_request(:get, 'http://example.com')
conn.get('http://example.com/')
conn.get('http://example.com/')
end
end

0 comments on commit 4a8e9c4

Please sign in to comment.