Skip to content

Commit

Permalink
Raise the error text of several connection attepts
Browse files Browse the repository at this point in the history
in case of several hosts and async API.

This is what libpq does in sync API as well.
  • Loading branch information
larskanis committed Jan 12, 2025
1 parent 30e1ea0 commit b0b0d9e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
8 changes: 4 additions & 4 deletions lib/pg/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ module Pollable
host_count = conninfo_hash[:host].to_s.count(",") + 1
stop_time = timeo * host_count + Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
connection_attempts = 1
connection_errors = []

poll_status = PG::PGRES_POLLING_WRITING
until poll_status == PG::PGRES_POLLING_OK ||
Expand Down Expand Up @@ -721,12 +721,12 @@ module Pollable
else
connhost = "at \"#{host}\", port #{port}"
end
if connection_attempts < host_count.to_i
connection_attempts += 1
connection_errors << "connection to server #{connhost} failed: timeout expired"
if connection_errors.count < host_count.to_i
new_conninfo_hash = rotate_hosts(conninfo_hash.compact)
send(:reset_start2, self.class.send(:parse_connect_args, new_conninfo_hash))
else
raise PG::ConnectionBad.new("connection to server #{connhost} failed: timeout expired", connection: self)
raise PG::ConnectionBad.new(connection_errors.join("\n"), connection: self)
end
end

Expand Down
10 changes: 5 additions & 5 deletions spec/pg/connection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -369,25 +369,25 @@
end
end

it "times out after connect_timeout seconds" do
it "times out after 2 * connect_timeout seconds on two connections" do
TCPServer.open( 'localhost', 54320 ) do |serv|
start_time = Time.now
expect {
described_class.connect(
host: 'localhost',
host: 'localhost,localhost',
port: 54320,
connect_timeout: 1,
dbname: "test")
}.to raise_error do |error|
expect( error ).to be_an( PG::ConnectionBad )
expect( error.message ).to match( /timeout expired/ )
expect( error.message ).to match( /timeout expired.*timeout expired/m )
if PG.library_version >= 120000
expect( error.message ).to match( /\"localhost\"/ )
expect( error.message ).to match( /\"localhost\".*\"localhost\"/m )
expect( error.message ).to match( /port 54320/ )
end
end

expect( Time.now - start_time ).to be_between(0.9, 10).inclusive
expect( Time.now - start_time ).to be_between(1.9, 10).inclusive
end
end

Expand Down

0 comments on commit b0b0d9e

Please # to comment.