Skip to content

Commit

Permalink
io: retry and reconnect on write errors
Browse files Browse the repository at this point in the history
Fixes #66
  • Loading branch information
raggi committed Jan 7, 2021
1 parent b8a7447 commit 6bb1b43
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/statsd.rb
Original file line number Diff line number Diff line change
Expand Up @@ -477,14 +477,14 @@ def send_to_socket(message)
# in an inconsistent state if a partial message is written. If that case
# occurs, the socket is closed down and we retry on a new socket.
message = @protocol == :tcp ? message + "\n" : message
n = socket.write(message)
n = socket.write(message) rescue (err = $!; 0)
if n == message.length
break
end

connect
retries += 1
raise "statsd: Failed to send after #{retries} attempts" if retries >= 5
raise (err || "statsd: Failed to send after #{retries} attempts") if retries >= 5
end
n
rescue => boom
Expand Down
10 changes: 9 additions & 1 deletion spec/statsd_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,8 @@ class Statsd::SomeOtherClass; end
before do
require 'stringio'
Statsd.logger = Logger.new(@log = StringIO.new)
@socket.instance_eval { def write(*) raise SocketError end }
@socket.instance_variable_set(:@err_count, 0)
@socket.instance_eval { def write(*) @err_count+=1; raise SocketError end }
end

it "should ignore socket errors" do
Expand All @@ -352,6 +353,13 @@ class Statsd::SomeOtherClass; end
@statsd.increment('foobar')
_(@log.string).must_match 'Statsd: SocketError'
end

it "should retry and reconnect on socket errors" do
$connect_count = 0
@statsd.increment('foobar')
_(@socket.instance_variable_get(:@err_count)).must_equal 5
_($connect_count).must_equal 5
end
end

describe "batching" do
Expand Down

0 comments on commit 6bb1b43

Please sign in to comment.