diff --git a/lib/s2/connection.rb b/lib/s2/connection.rb index 6640c0f..f9176ad 100644 --- a/lib/s2/connection.rb +++ b/lib/s2/connection.rb @@ -32,7 +32,13 @@ def connect connect_and_run @backoff = INITIAL_BACKOFF rescue StandardError => e - ActiveSupport::Notifications.instrument("connection_errored.session.s2", exception: e) unless @stopping + unless @stopping + ActiveSupport::Notifications.instrument( + "connection_errored.session.s2", + resource_id: @resource_id, + exception: e, + ) + end ensure break if @stopping diff --git a/spec/s2/connection_spec.rb b/spec/s2/connection_spec.rb index 8f8ab80..f16219a 100644 --- a/spec/s2/connection_spec.rb +++ b/spec/s2/connection_spec.rb @@ -101,5 +101,41 @@ expect(connection_attempts.size).to be >= 3 expect(connection_attempts.uniq.size).to eq(1) end + + it "instruments connection_errored with the resource_id and exception" do + ws = FakeWebSocket.new + connection_attempts = 0 + raised = Errno::ECONNREFUSED.new + + allow(Async::WebSocket::Client).to receive(:connect) do |_endpoint, &block| + connection_attempts += 1 + raise raised if connection_attempts < 2 + + block.call(ws) + end + + resource_id = SecureRandom.uuid + events = [] + subscriber = ActiveSupport::Notifications.subscribe("connection_errored.session.s2") do |event| + events << event + end + + connection = described_class.new( + resource_id:, + task: Async::Task.current, + ws_url: "ws://example.com/#{resource_id}", + ) + allow(connection).to receive(:sleep) + + task = Async { connection.connect } + Async::Task.current.sleep 0.1 + connection.disconnect + task.stop + + expect(events).not_to be_empty + expect(events.first.payload).to eq(resource_id:, exception: raised) + ensure + ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber + end end end