Skip to content

Commit

Permalink
Refactor conditional, add unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
redhotpenguin committed Jul 22, 2019
1 parent 6c54ba7 commit 047f113
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/datadog/statsd.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@ def write(message)
rescue StandardError => boom
# Try once to reconnect if the socket has been closed
retries ||= 1
if retries <= 1 && boom.is_a?(Errno::ENOTCONN) or
retries <= 1 && boom.is_a?(Errno::ECONNREFUSED) or
retries <= 1 && boom.is_a?(IOError) && boom.message =~ /closed stream/i
if retries <= 1 &&
(boom.is_a?(Errno::ENOTCONN) or
boom.is_a?(Errno::ECONNREFUSED) or
boom.is_a?(IOError) && boom.message =~ /closed stream/i)
retries += 1
begin
@socket = connect
Expand Down
31 changes: 31 additions & 0 deletions spec/statsd_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,37 @@ class Datadog::Statsd::SomeClass; end
end
end

describe "handling connection refused" do
before do
@statsd.connection.instance_variable_set(:@logger, Logger.new(@log = StringIO.new))
end

it "tries to reconnect once" do
@statsd.connection.expects(:socket).times(2).returns(socket)
socket.expects(:send).returns("YEP") # 2nd call
socket.expects(:send).raises(Errno::ECONNREFUSED.new("closed stream")) # first call

@statsd.increment('foobar')
end

it "ignores and logs if it fails to reconnect" do
@statsd.connection.expects(:socket).times(2).returns(socket)
socket.expects(:send).raises(RuntimeError) # 2nd call
socket.expects(:send).raises(Errno::ECONNREFUSED.new) # first call

assert_nil @statsd.increment('foobar')
@log.string.must_include 'Statsd: RuntimeError'
end

it "ignores and logs errors while trying to reconnect" do
socket.expects(:send).raises(Errno::ECONNREFUSED.new)
@statsd.connection.expects(:connect).raises(SocketError)

assert_nil @statsd.increment('foobar')
@log.string.must_include 'Statsd: SocketError'
end
end

describe "UDS error handling" do
before do
@statsd = Datadog::Statsd.new('localhost', 1234, {:socket_path => '/tmp/socket'})
Expand Down

0 comments on commit 047f113

Please sign in to comment.