Skip to content

Commit e77ae81

Browse files
committed
Add support for persistent connections.
1 parent eafae43 commit e77ae81

File tree

3 files changed

+23
-14
lines changed

3 files changed

+23
-14
lines changed

Gemfile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
source 'https://rubygems.org'
22

33
gemspec
4+
5+
gem "faraday", git: "https://github.com/lostisland/faraday.git"

lib/async/http/faraday/adapter.rb

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,32 +20,36 @@
2020

2121
require 'faraday'
2222
require 'faraday/adapter'
23-
require 'async/http/client'
23+
require 'async/http/internet'
2424

2525
module Async
2626
module HTTP
2727
module Faraday
28+
# Detect whether we can use persistent connections:
29+
PERSISTENT = ::Faraday::Connection.instance_methods.include?(:close)
30+
2831
class Adapter < ::Faraday::Adapter
32+
def initialize(*arguments, **options, &block)
33+
super
34+
35+
@internet = Async::HTTP::Internet.new
36+
end
37+
38+
def close
39+
@internet.close
40+
end
41+
2942
def call(env)
3043
super
3144

32-
client = HTTP::Client.new(*endpoints_for(env).to_a)
45+
response = @internet.call(env[:method], env[:url].to_s, env[:request_headers], env[:body])
3346

34-
response = client.send(env[:method], env[:url].request_uri, env[:request_headers], env[:body] || [])
35-
3647
save_response(env, response.status, response.read, response.headers)
3748

38-
@app.call env
49+
return @app.call(env)
3950
ensure
40-
client.close if client
41-
end
42-
43-
def endpoints_for(env)
44-
return to_enum(:endpoints_for, env) unless block_given?
45-
46-
if url = env[:url]
47-
yield Async::HTTP::Endpoint.new(url)
48-
end
51+
# Don't retain persistent connections unless they will eventually be closed:
52+
@internet.close unless PERSISTENT
4953
end
5054
end
5155
end

spec/async/http/faraday/adapter_spec.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ def get_response(url, path)
5353
end
5454

5555
connection.get(path)
56+
57+
ensure
58+
connection&.close
5659
end
5760

5861
it "client can get resource" do

0 commit comments

Comments
 (0)