Skip to content

keep the websocket close code and reason on WebSocket - #47

Merged
bentsku merged 1 commit into
mainfrom
websocket-close-code-reason-attributes
Sep 30, 2026
Merged

bentsku merged 1 commit into
mainfrom
websocket-close-code-reason-attributes

Conversation

@bentsku

@bentsku bentsku commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator

Motivation

Follow-up to #46. WebSocket.__iter__ ends silently when the client disconnects, which is the intended behavior for for msg in ws loops, but it swallows the WebSocketDisconnectedError along with the close code and reason. Consumers that need them (e.g. LocalStack's API Gateway $disconnect route, which reports disconnectStatusCode / disconnectReason) have to drop the iterator and handle receive() + the exception manually.

Changes

  • WebSocket gets close_code and close_reason attributes (similar to the websockets library), None until a disconnect is seen.
  • WebSocket.receive records the code and reason of the first WebSocketDisconnectedError before re-raising it. Later calls only see the server's internal close event (code 1005, no reason), so they don't overwrite it.
  • The iterator behavior is unchanged, so this is backwards compatible:
    for msg in ws:
        handle(msg)
    ws.close_code, ws.close_reason  # e.g. 4001, "test reason"
  • Removes test_twisted_gateway_import_and_wsproto_dependency (added in Add missing wsproto dependency and twisted extra #44): every twisted test already imports rolo.serving.twisted, which imports wsproto, so it didn't check anything extra.

Testing

  • New test_close_code_and_reason_after_iter: the client sends a message and closes with 4001 / "test reason". After the server-side for loop ends, ws.close_code / ws.close_reason must hold them. It fails without the change. Like the test from surface the client's websocket close code and reason #46, it runs against twisted only, because hypercorn doesn't forward the client's close code or reason.
  • Full test suite passes (179 passed), lint clean.

🤖 Generated with Claude Code

WebSocket.receive now records the code and reason of the first disconnect
in close_code / close_reason, so they are still available after the
iterator ended silently on disconnect. Also removes the redundant
twisted/wsproto import test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@bentsku
bentsku marked this pull request as ready for review September 30, 2026 14:31
@bentsku
bentsku merged commit e5964a1 into main Sep 30, 2026
5 checks passed
@bentsku
bentsku deleted the websocket-close-code-reason-attributes branch September 30, 2026 14:32
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