Skip to content

Ensure connection is closed when raw SSE stream raises#248

Open
jsxs0 wants to merge 1 commit intorage-rb:mainfrom
jsxs0:fix-raw-stream-connection-leak
Open

Ensure connection is closed when raw SSE stream raises#248
jsxs0 wants to merge 1 commit intorage-rb:mainfrom
jsxs0:fix-raw-stream-connection-leak

Conversation

@jsxs0
Copy link
Contributor

@jsxs0 jsxs0 commented Mar 26, 2026

Summary

Add an ensure block to SSE::Application#start_raw_stream so the Iodine connection is always closed if the user's Proc raises an exception without calling close.

Problem

start_formatted_stream (Enumerator path) has ensure connection.close — the connection always cleans up, even on exception. start_raw_stream (Proc path) does not — if the Proc raises before calling connection.close, the connection leaks until Iodine's socket timeout.

# Has ensure — connection always closed
def start_formatted_stream(connection)
  @stream.each { |event| ... }
ensure
  connection.close
end

# Missing ensure — connection leaks on exception
def start_raw_stream(connection)
  @stream.call(Rage::SSE::ConnectionProxy.new(connection))
end

Fix

def start_raw_stream(connection)
  @stream.call(Rage::SSE::ConnectionProxy.new(connection))
ensure
  connection.close if connection.open?
end

The connection.open? guard avoids double-closing when the Proc already called close.

Test plan

  • Added spec/sse/application_spec.rb with 3 test cases:
    • Proc raises → connection closed
    • Proc closes normally → no double-close
    • Proc forgets to close → connection still closed
  • bundle exec rspec spec/sse/ — 47 examples, 0 failures

Add an `ensure` block to `start_raw_stream` so the connection is
always closed if the user's Proc raises an exception without
calling `close`. This matches the cleanup behavior already present
in `start_formatted_stream`, which has `ensure connection.close`.

Without this fix, a Proc that raises before closing leaves the
Iodine connection open until socket timeout.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant