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 67477d6
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
6 changes: 6 additions & 0 deletions docs/adapters/patron.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ conn = Faraday.new(...) do |f|
end
```

## Multithreading

This adapter use a mutex around the patron session to be thread-safe.
A [connection_pool](https://rubygems.org/gems/connection_pool) can be
used to share multiple connections between threads.

## Links

* [Gem RDoc][rdoc]
Expand Down
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)
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 67477d6

Please sign in to comment.