Skip to content

Commit 22a623b

Browse files
committed
Fix subtractive timeout and add specs.
1 parent 2c15a4f commit 22a623b

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

lib/rabbitmq/client/connection.rb

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,15 +103,19 @@ def login!
103103
@server_properties = FFI::Table.new(FFI.amqp_get_server_properties(@ptr)).to_h
104104
end
105105

106+
# Calculate the amount of the timeout remaining from the given start time
107+
def remaining_timeout(timeout=0, start=Time.now)
108+
return nil unless timeout
109+
timeout = timeout - (Time.now - start)
110+
timeout < 0 ? 0 : timeout
111+
end
112+
106113
# Block until there is readable data on the internal ruby socket,
107114
# returning true if there is readable data, or false if time expired.
108115
def select(timeout=0, start=Time.now)
109-
if timeout
110-
timeout = timeout - (start-Time.now)
111-
timeout = 0 if timeout < 0
112-
end
113-
114-
IO.select([@ruby_socket], [], [], timeout) ? true : false
116+
IO.select([@ruby_socket], [], [],
117+
remaining_timeout(timeout, start)
118+
) ? true : false
115119
end
116120

117121
# Return the next available frame, or nil if time expired.

spec/client/connection_spec.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,22 @@
7979
subject.options[:ssl] .should eq false
8080
end
8181

82+
describe "remaining_timeout" do
83+
it "returns nil when given a timeout of nil" do
84+
subject.remaining_timeout(nil).should eq nil
85+
end
86+
87+
it "returns 0 when time has already run out" do
88+
time_now = Time.now
89+
subject.remaining_timeout(0, time_now) .should eq 0
90+
subject.remaining_timeout(5.0, time_now - 5) .should eq 0
91+
subject.remaining_timeout(5.0, time_now - 10) .should eq 0
92+
subject.remaining_timeout(5.0, time_now - 100).should eq 0
93+
end
94+
95+
it "returns the remaining time when there is time remaining" do
96+
subject.remaining_timeout(10.0, Time.now-5).should be_within(1.0).of(5.0)
97+
end
98+
end
99+
82100
end

0 commit comments

Comments
 (0)