Skip to content

feat(realtime): surface upgrade rejection details as RealtimeConnectException - #1626

Closed
spydon wants to merge 3 commits into
mainfrom
feat/realtime-surface-upgrade-error
Closed

spydon wants to merge 3 commits into
mainfrom
feat/realtime-surface-upgrade-error

Conversation

@spydon

@spydon spydon commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When the Realtime server rejects the WebSocket upgrade, for example on a missing or invalid apikey, the client previously surfaced only a bare status code buried in a WebSocketChannelException:

WebSocketChannelException: WebSocketException: Connection to '...' was not upgraded to websocket, HTTP status code: 401

The server returns a helpful body, but the WebSocket handshake discards it (only the status is visible on native, nothing at all on web). This PR recovers that information and surfaces it as a new RealtimeConnectException on both native and web:

type: RealtimeConnectException
statusCode: 401
errorCode: UNAUTHORIZED_INVALID_API_KEY
message: Invalid API key
hint: Double check your Supabase `anon` or `service_role` API key.

What changed

  • RealtimeClient: when WebSocketChannel.ready fails, a new _fetchConnectionError helper re-requests the same endpoint over HTTP to recover the server's error response, then surfaces it through the existing onError and subscribe error paths.
  • New public RealtimeConnectException (statusCode, message, hint, errorCode), exported from the package barrel.
  • New integration test test/invalid_apikey_test.dart asserting an invalid apikey yields a RealtimeConnectException.

How it works

On a failed upgrade, _fetchConnectionError issues a plain GET to the same endpoint (scheme mapped ws/wss to http/https, with the apikey already present in the query). A non-2xx response is parsed into RealtimeConnectException(statusCode, message, hint, errorCode), reading message/hint from a JSON body and the code from the sb-error-code header. On a 2xx response or an unreachable server it falls back to the original error. The request reuses the injected httpClient when provided, otherwise a short-lived client with a 5 second timeout.

The standard WebSocket transport is left untouched, so this works identically on native and web with no new dependency and no reimplementation of the WebSocket handshake.

Testing

  • New test/invalid_apikey_test.dart (integration): an invalid apikey yields a RealtimeConnectException with a 401 or 403 status.
  • Full existing realtime_integration_test.dart suite passes for both protocol versions (subscribe, broadcast, presence, postgres changes, heartbeats), plus socket_test, mock_test, and websocket_io_test.
  • Verified end to end against a hosted project: message, hint, and sb-error-code are surfaced as shown above.

Commit history

The first commit implements a native-only alternative that reads the body during a manual HttpClient handshake. The second commit reverts it in favor of the cross-platform follow-up fetch, which is the net content of this PR. The first commit is kept only so the two approaches can be compared, and can be squashed away on merge.

Open items

  • Compliance symbols: RealtimeConnectException is a new public symbol; the sdk-compliance.yaml check needs a canonical capability ID from supabase/sdk to register it against.
  • Confirm the one extra request on connection failure is acceptable, since it also fires during reconnect backoff.

The native transport connected through IOWebSocketChannel.connect, which
uses WebSocket.connect and discards the HTTP response when the upgrade is
rejected with a non-101 status. That hid the server's error body, so an
invalid apikey surfaced only as "HTTP status code: 401/403".

Drive the upgrade with HttpClient instead: on a successful 101 the socket
is detached and wrapped in an IOWebSocketChannel exactly as before, and on
a rejected upgrade the response body and sb-error-code header are parsed
into a new RealtimeConnectException (statusCode, message, hint, errorCode)
in the same request, without a follow-up round trip.

The browser WebSocket API exposes neither the status nor the body of a
failed upgrade, so the web transport is unchanged and RealtimeConnectException
is native-only.
@github-actions github-actions Bot added the realtime This issue or pull request is related to realtime label Jul 21, 2026
@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b61f2566-ddb4-4330-907c-adefe34e06ea

📥 Commits

Reviewing files that changed from the base of the PR and between 0931f0a and 744f673.

📒 Files selected for processing (5)
  • packages/realtime_client/lib/realtime_client.dart
  • packages/realtime_client/lib/src/realtime_client.dart
  • packages/realtime_client/lib/src/websocket/realtime_connect_exception.dart
  • packages/realtime_client/test/invalid_apikey_test.dart
  • sdk-compliance.yaml

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added RealtimeConnectException for clearer WebSocket connection failure details.
    • Connection errors now include available status codes, messages, hints, and error codes.
    • Made the new exception available through the public client API.
  • Bug Fixes

    • Improved handling of rejected connections, including invalid API keys, with more actionable error information.
  • Tests

    • Added coverage confirming invalid API keys produce the new exception type.

Walkthrough

The realtime client now exposes RealtimeConnectException publicly. Failed WebSocket upgrades trigger an HTTP follow-up request to retrieve the server’s status, message, hint, and error code, with fallback to the original error when enrichment fails. An integration test covers invalid API keys, and SDK compliance metadata includes the new exception symbols.

Sequence Diagram(s)

sequenceDiagram
  participant RealtimeClient
  participant WebSocketEndpoint
  participant HTTPEndpoint
  RealtimeClient->>WebSocketEndpoint: Attempt WebSocket connection
  WebSocketEndpoint-->>RealtimeClient: Return upgrade failure
  RealtimeClient->>HTTPEndpoint: Fetch mapped HTTP error response
  HTTPEndpoint-->>RealtimeClient: Return status and error details
  RealtimeClient-->>RealtimeClient: Emit RealtimeConnectException
Loading

Possibly related PRs

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Checkov (3.3.8)
sdk-compliance.yaml

Traceback (most recent call last):
File "/usr/local/bin/checkov", line 2, in
from checkov.main import Checkov
ModuleNotFoundError: No module named 'checkov'


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…l handshake

Replace the native-only manual handshake with a cross-platform approach:
keep the standard WebSocket transport untouched, and when the upgrade is
rejected, re-request the same endpoint over HTTP to recover the server's
error body. The WebSocket API discards the handshake response (status only
on native, nothing on web), but a plain follow-up GET returns the same
response, so the message, hint and sb-error-code are surfaced as a
RealtimeConnectException on both native and web.

Reverts the manual HttpClient handshake and the crypto dependency added in
the previous commit.
@spydon spydon changed the title feat(realtime): surface WebSocket upgrade rejection details on native feat(realtime): surface WebSocket upgrade rejection details Jul 21, 2026
@spydon spydon changed the title feat(realtime): surface WebSocket upgrade rejection details feat(realtime): surface upgrade rejection details as RealtimeConnectException Jul 21, 2026
…ymbols

Add a const constructor to satisfy the prefer-declaring-const-constructor
DCM rule, and register RealtimeConnectException and its members in
sdk-compliance.yaml under realtime.client.connect so the capability matrix
symbol check passes.
@spydon
spydon marked this pull request as ready for review July 21, 2026 11:28
@spydon
spydon requested a review from a team as a code owner July 21, 2026 11:28
spydon added a commit that referenced this pull request Jul 22, 2026
## What

Adds a repo-level `.coderabbit.yaml` that disables CodeRabbit's failing
commit status:

```yaml
reviews:
  commit_status: true
  fail_commit_status: false
```

## Why

Open PRs are currently showing a red `CodeRabbit` check with the reason
**"Review rate limited"** (e.g. #1630, #1629, #1627), even though
nothing is actually wrong with the change. A completed review shows
`pass` (e.g. #1626).

- `commit_status: true` keeps the useful passing check for completed
reviews.
- `fail_commit_status: false` stops CodeRabbit from setting a `failure`
status when it can't review (which is what the rate-limit case
triggers).

Committing the config overrides CodeRabbit's cloud/org defaults.

## Note

If a rate-limited PR still goes red after this lands, the rate-limit
failure path ignores this flag and the only remaining lever is
`commit_status: false` (disables the check entirely, losing the green
pass too).
@Vinzent03
Vinzent03 self-requested a review July 22, 2026 14:05
@Vinzent03

Vinzent03 commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

In its current implementation it retries for every kind of exception, but I think we should make this retry more specific. The example in your issue description is a WebSocketChannelException, which exposes an inner exception, which in your example is a WebSocketException. So I think we should check whether these conditions are the case.
As a counterexample when I have no internet connection I get this error:

WebSocketChannelException: SocketException: Failed host lookup: 'xxxx.supabase.co' (OS error: No address associated with hostname, errno = 7)
So the inner one is a SocketException.
And retrying the endpoint with http only would only delay the error reporting not produce any new insights.

This would also be a breaking change as the previous exception is no longer thrown. So I would check whether we can extend the WebSocketException to be compatible with existing exception checks.

@spydon

spydon commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

In its current implementation it retries for every kind of exception, but I think we should make this retry more specific. The example in your issue description is a WebSocketChannelException, which exposes an inner exception, which in your example is a WebSocketException. So I think we should check whether these conditions are the case. As a counterexample when I have no internet connection I get this error:

WebSocketChannelException: SocketException: Failed host lookup: 'xxxx.supabase.co' (OS error: No address associated with hostname, errno = 7) So the inner one is a SocketException. And retrying the endpoint with http only would only delay the error reporting not produce any new insights.

This would also be a breaking change as the previous exception is no longer thrown. So I would check whether we can extend the WebSocketException to be compatible with existing exception checks.

Hmm, after further research I think we should just close this one, the native users will already be able to get the status code and that ought to be enough for them to figure out what is wrong. Users on web don't get any information, even if we keep the GET, and there is nothing we can do about that due to the underlying that the browser's WebSocket API deliberately hides it.

We should really fix a list of exceptions we shouldn't retry though, but that's a separate issue.

@spydon spydon closed this Jul 23, 2026
Vinzent03 pushed a commit that referenced this pull request Jul 28, 2026
## What

Adds a repo-level `.coderabbit.yaml` that disables CodeRabbit's failing
commit status:

```yaml
reviews:
  commit_status: true
  fail_commit_status: false
```

## Why

Open PRs are currently showing a red `CodeRabbit` check with the reason
**"Review rate limited"** (e.g. #1630, #1629, #1627), even though
nothing is actually wrong with the change. A completed review shows
`pass` (e.g. #1626).

- `commit_status: true` keeps the useful passing check for completed
reviews.
- `fail_commit_status: false` stops CodeRabbit from setting a `failure`
status when it can't review (which is what the rate-limit case
triggers).

Committing the config overrides CodeRabbit's cloud/org defaults.

## Note

If a rate-limited PR still goes red after this lands, the rate-limit
failure path ignores this flag and the only remaining lever is
`commit_status: false` (disables the check entirely, losing the green
pass too).
@spydon
spydon deleted the feat/realtime-surface-upgrade-error branch October 29, 2026 13:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

realtime This issue or pull request is related to realtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants