Skip to content

Commit

Permalink
fix: close sockets on initialize timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
rpeng committed Sep 22, 2023
1 parent 4060ccd commit 6272bdb
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
6 changes: 4 additions & 2 deletions lib/http/connection.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# frozen_string_literal: true

require "forwardable"

require "http/headers"

module HTTP
Expand Down Expand Up @@ -46,6 +45,9 @@ def initialize(req, options)
reset_timer
rescue IOError, SocketError, SystemCallError => e
raise ConnectionError, "failed to connect: #{e}", e.backtrace
rescue TimeoutError
close
raise
end

# @see (HTTP::Response::Parser#status_code)
Expand Down Expand Up @@ -126,7 +128,7 @@ def finish_response
# Close the connection
# @return [void]
def close
@socket.close unless @socket.closed?
@socket.close unless @socket&.closed?

@pending_response = false
@pending_request = false
Expand Down
22 changes: 21 additions & 1 deletion spec/lib/http/connection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,31 @@
:headers => {}
)
end
let(:socket) { double(:connect => nil) }
let(:socket) { double(:connect => nil, :close => nil) }
let(:timeout_class) { double(:new => socket) }
let(:opts) { HTTP::Options.new(:timeout_class => timeout_class) }
let(:connection) { HTTP::Connection.new(req, opts) }

describe "#initialize times out" do
let(:req) do
HTTP::Request.new(
:verb => :get,
:uri => "https://example.com/",
:headers => {}
)
end

before do
expect(socket).to receive(:start_tls).and_raise(HTTP::TimeoutError)
expect(socket).to receive(:closed?) { false }
expect(socket).to receive(:close)
end

it "closes the connection" do
expect { connection }.to raise_error(HTTP::TimeoutError)
end
end

describe "#read_headers!" do
before do
connection.instance_variable_set(:@pending_response, true)
Expand Down

0 comments on commit 6272bdb

Please sign in to comment.