Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ Code that indexes `data` as a list, such as `res.data[0]["id"]`, keeps working a

## Realtime clients connect on the first subscribe

`RealtimeClient` takes the realtime URL and a token callback instead of an open connection. It connects when the first channel subscribes, or when `connect()` is called, and every channel of the client shares that connection. The connection is closed when the last channel is unsubscribed or removed, so a client with no channels holds no connection. `aclose()` closes it too and leaves the channels unsubscribed. Subscribing again opens a new connection, which also replaces a connection that was lost.
`RealtimeClient` takes the realtime URL and a token callback instead of an open connection. It connects when the first channel subscribes, or when `connect()` is called, and every channel of the client shares that connection. The connection is closed when the last channel is unsubscribed or removed, so a client with no channels holds no connection. `aclose()` closes it too and leaves the channels unsubscribed. Subscribing again opens a new connection.

Messages queued on a channel, like the close message of `unsubscribe()`, can still be read from `channel.messages` after the connection is closed. Reading past them raises `NotConnectedError` instead of waiting.

Expand All @@ -285,6 +285,34 @@ Messages queued on a channel, like the close message of `unsubscribe()`, can sti

`unsubscribe()` on a channel that is not joined, for example after `aclose()`, removes the channel without sending a leave message.

## Realtime clients reconnect and join their channels again

`RealtimeClient`, and so `AsyncClient.realtime`, reconnects on its own when its connection drops, until `aclose()` is called or its last channel is removed. Each wait is drawn at random between 0 and a backoff that starts at 1 second and doubles up to 30 seconds. There is no attempt limit. Every channel that was joined is joined again with its options and the current access token, and the presence it tracked with `track()` is tracked again.

`automatically_reconnect`, `exponential_delay` and `MaxRetriesExceeded` are removed. Open the client with `connect_once` or `RealtimeClient` instead.

```python skip
await automatically_reconnect(url, get_token, handler, max_retries=3)
```

```python
from realtime import ChannelStateChange, ChannelStates, RealtimeClient

channel = RealtimeClient(url).channel("room")
await channel.subscribe()
async for message in channel.messages:
if isinstance(message, ChannelStateChange):
print("connection lost" if message.state == ChannelStates.ERRORED else "joined again")
```

`channel.messages` no longer raises the `websockets.ConnectionClosed` or `TimeoutError` that dropped the connection of a joined channel. It yields a `ChannelStateChange` with the state `ERRORED` and that error, then one with the state `JOINED` once the channel is joined again, and keeps yielding the channel's messages. When the server rejects the new join for good, for example with an `AuthorizationError`, the channel is closed and `channel.messages` raises that error. A rejected token is retried once with a fresh one first.

## Realtime pushes time out and channel queues are bounded

`subscribe()`, `unsubscribe()`, `track()`, `untrack()` and an acknowledged `send_broadcast()` raise `RealtimeTimeoutError`, also a built-in `TimeoutError`, when the server does not reply within `timeout` seconds, 10 by default. Before, they waited forever. Pass `timeout` to `connect_once`, `RealtimeClient` or `RealtimeClientOptions` to change it. A join that times out is left, so a late reply does not join the channel.

A channel keeps at most `max_queued_messages` unread messages, 1000 by default. When its queue is full, the oldest message is dropped and a warning is logged. Pass `max_queued_messages` to `connect_once`, `RealtimeClient` or `RealtimeClientOptions` to change it.

## Realtime `close()` is `aclose()`

`RealtimeClient.close()` is renamed to `aclose()`, the name Python uses for an async close, so `contextlib.aclosing(client)` works. `close()` is removed.
Expand Down Expand Up @@ -388,7 +416,7 @@ supabase = create_client(

## One exception hierarchy

Every exception the packages raise themselves inherits from `supabase_utils.errors.SupabaseError`, re-exported as `supabase.SupabaseError`, so `except SupabaseError` catches any failure the SDK reports. The hierarchy is described in the [error handling](src/supabase/README.md#error-handling) section of the README. The realtime connection is the exception: a lost websocket still surfaces as the `websockets.ConnectionClosed` or built-in `TimeoutError` that failed it, as before.
Every exception the packages raise themselves inherits from `supabase_utils.errors.SupabaseError`, re-exported as `supabase.SupabaseError`, so `except SupabaseError` catches any failure the SDK reports. The hierarchy is described in the [error handling](src/supabase/README.md#error-handling) section of the README. The realtime connection is the exception: a lost websocket still surfaces from a send as the `websockets.ConnectionClosed` or built-in `TimeoutError` that failed it, as before. A `subscribe()` it interrupts raises `NotConnectedError`.

Errors a service answered with inherit from `SupabaseAPIError` and expose the HTTP status as `status_code`, with the `response` next to it. The `status` attributes are renamed and the constructors take the status as a keyword argument.

Expand All @@ -406,8 +434,9 @@ Errors a service answered with inherit from `SupabaseAPIError` and expose the HT
| `supabase_functions` | `FunctionsError(message, name, status)`, `.name`, `.status` | `FunctionsError(message)`. Use `type(error).__name__` for the name; the status lives on the response errors |
| `supabase_functions` | `FunctionsHttpError(message, code)`, `.status` | `FunctionsHttpError(message, status_code=..., response=...)`, `.status_code` |
| `supabase_functions` | `FunctionsRelayError(message, code)`, `.status` | `FunctionsRelayError(message, status_code=..., response=...)`, `.status_code` |
| `realtime` | `realtime.client.MaxRetriesExceeded`, an `Exception` | `realtime.MaxRetriesExceeded`, a `RealtimeError` with a `retries` attribute |
| `realtime` | A failed `subscribe()` raised `Exception` | It raises `RealtimeError` |
| `realtime` | `realtime.client.MaxRetriesExceeded`, an `Exception` | Removed. `RealtimeClient` reconnects on its own |
| `realtime` | A failed `subscribe()` raised `Exception` | It raises a `RealtimeError`: `ChannelJoinError`, `AuthorizationError`, `RealtimeTimeoutError` or `NotConnectedError` |
| `realtime` | `AuthorizationError(message)`, never raised | `AuthorizationError(topic, reason)`, a `ChannelJoinError` raised when the server rejects the token or the RLS policies deny the join |

The auth errors are no longer dataclasses. `str(error)` returns the message for every error, as it does for the built-in exceptions, and `==` compares identity.

Expand Down
14 changes: 8 additions & 6 deletions sdk-compliance.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -875,16 +875,15 @@ features:

realtime.client.connect:
status: implemented
note: "RealtimeClient connects when the first channel subscribes, or when connect() is called, and reuses that connection for every channel until the last channel is removed. AsyncClient.realtime is one RealtimeClient per supabase client, closed when the supabase client exits. connect_once(url, ...) is awaitable and an async context manager that connects a RealtimeClient and closes it on exit; automatically_reconnect wraps it with reconnection."
note: "RealtimeClient connects when the first channel subscribes, or when connect() is called, and reuses that connection for every channel until the last channel is removed. AsyncClient.realtime is one RealtimeClient per supabase client, closed when the supabase client exits. connect_once(url, ...) is awaitable and an async context manager that connects a RealtimeClient and closes it on exit. A dropped connection is reopened with full-jitter backoff until aclose(), and every joined channel is joined again with its options, the current token and its tracked presence; RealtimeChannel.messages yields a ChannelStateChange when the connection drops and when the channel is joined again."
symbols:
- RealtimeClient.connect
- connect_once
- automatically_reconnect
supporting_symbols:
- RealtimeClient
- RealtimeClient.endpoint_url
- normalize_url
- MaxRetriesExceeded
- ChannelStateChange
realtime.client.disconnect:
status: implemented
symbols:
Expand Down Expand Up @@ -922,6 +921,7 @@ features:

realtime.channel.subscribe:
status: implemented
note: "subscribe() waits for the join reply at most the client's timeout (10 seconds by default), then raises RealtimeTimeoutError and leaves the join. A rejected join raises ChannelJoinError with the server's reason and code, or AuthorizationError for a rejected token or an RLS denial; a dropped connection raises NotConnectedError."
symbols:
- RealtimeChannel.subscribe
supporting_symbols:
Expand Down Expand Up @@ -1041,9 +1041,9 @@ features:
realtime.configuration.custom_websocket_transport: not_implemented
realtime.configuration.reconnect_backoff:
status: partially_implemented
note: "automatically_reconnect() retries failed and dropped connections with exponential backoff capped at 60 seconds, up to max_retries attempts in a row; the count resets once a connection has stayed up for 60 seconds. supabase-js accepts a custom reconnect function mapping attempt count to delay; Python only supports the fixed strategy."
note: "RealtimeClient reconnects a dropped connection with full jitter: each wait is random between 0 and a backoff that starts at 1 second and doubles up to 30 seconds, with no attempt limit. The attempt count resets once a connection has stayed up for 30 seconds. supabase-js accepts a custom reconnect function mapping attempt count to delay; Python only supports the fixed strategy."
supporting_symbols:
- exponential_delay
- reconnect_delay
realtime.configuration.heartbeat_interval:
status: implemented
note: "heartbeat_interval and heartbeat_timeout parameters (float seconds) on connect_once, and RealtimeClientOptions on the supabase client. Values must be positive."
Expand All @@ -1052,6 +1052,7 @@ features:
supporting_symbols:
- RealtimeClientOptions
- validate_heartbeat
- validate_push_options
realtime.configuration.access_token_callback:
status: implemented
note: "token_callback parameter on connect_once and RealtimeClient, awaited on connect, on every channel join and on each heartbeat. Every join carries the token, and a token that changes while a join is pending is sent once the join completes. AsyncClient.realtime passes a callback that reads the session through auth.get_session(), so an expiring session is refreshed first, and returns its access token, or the Authorization token of the client, the project key by default, when there is none (see cross_client_token_sync)."
Expand Down Expand Up @@ -1619,8 +1620,9 @@ supporting_symbols:
- FunctionsHttpError
- FunctionsRelayError
- AuthorizationError
- ChannelJoinError
- NotConnectedError
- MaxRetriesExceeded
- RealtimeTimeoutError
- RealtimeError
- SupabaseError
- SupabaseAPIError
Expand Down
25 changes: 23 additions & 2 deletions src/realtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,31 @@ asyncio.run(main())

- `REALTIME_URL` is `http://localhost:54321/realtime/v1` when developing locally with the Supabase CLI and `https://<project_ref>.supabase.co/realtime/v1` when connecting to your Supabase project. The client switches to `ws`/`wss` and appends `/websocket` itself.
- The token callback is awaited when connecting, on every channel join and on every heartbeat, so it can return a refreshed user access token. `client.set_auth()` awaits it right away and sends a new token to the joined channels. A token passed as `client.set_auth(token)` is used instead of the callback until `client.set_auth()` is called without one. It must return a JWT whose claims contain `exp` and `role` (an existing database role), or the publishable key. An error it raises fails `subscribe()`. After a heartbeat the error is logged instead and the channels keep their token.
- `async with client.channel(...)` subscribes on entry and unsubscribes on exit. `subscribe()` raises if the server rejects the join.
- `async with client.channel(...)` subscribes on entry and unsubscribes on exit. `subscribe()` raises `ChannelJoinError` with the server's `reason` if the server rejects the join, `AuthorizationError` (a `ChannelJoinError`) if it rejects the token or the RLS policies deny a private channel, `RealtimeTimeoutError` if it does not reply within `timeout` seconds and `NotConnectedError` if the connection drops first.
- `RealtimeClient(url, get_token)` creates a client without connecting. It connects when the first channel subscribes, shares that connection with every channel, and closes it when the last channel is unsubscribed or `aclose()` is called.
- Channel name can be any `string`.
- Use `realtime.client.automatically_reconnect(url, get_token, handler)` instead of `connect_once` to reconnect with exponential backoff when the connection drops.
- `subscribe()`, `unsubscribe()`, `track()`, `untrack()` and an acknowledged `send_broadcast()` wait `timeout` seconds for the server's reply, 10 by default, then raise `RealtimeTimeoutError`. Pass `timeout` to `connect_once` or `RealtimeClient` to change it.
- A channel keeps at most `max_queued_messages` unread messages, 1000 by default. When its queue is full, the oldest message is dropped and a warning is logged.

## Reconnecting

When the connection drops, the client reconnects on its own until `aclose()` is called. Each wait is drawn at random between 0 and a backoff that starts at 1 second and doubles up to 30 seconds. Every joined channel is joined again with its options and the current access token, and the presence it tracked is tracked again.

`channel.messages` yields a `ChannelStateChange` when the connection of the channel drops, with the state `ERRORED` and the error, and when the channel is joined again, with the state `JOINED`. Messages sent while the connection was down are lost. If the server rejects the new join for good, for example with an `AuthorizationError`, the channel is closed and `channel.messages` raises that error.

```python
from realtime import ChannelStateChange, ChannelStates

async with client.channel("room") as channel:
async for message in channel.messages:
if isinstance(message, ChannelStateChange):
if message.state == ChannelStates.ERRORED:
print("Connection lost:", message.error)
else:
print("Joined again")
else:
print(message)
```

## Broadcast

Expand Down
9 changes: 6 additions & 3 deletions src/realtime/src/realtime/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@

from realtime.version import __version__

from .channel import RealtimeChannel, RealtimeChannelOptions
from .channel import ChannelStateChange, RealtimeChannel, RealtimeChannelOptions
from .client import RealtimeClient, connect_once
from .exceptions import (
AuthorizationError,
MaxRetriesExceeded,
ChannelJoinError,
NotConnectedError,
RealtimeError,
RealtimeTimeoutError,
)
from .message import (
AccessTokenMessage,
Expand Down Expand Up @@ -92,15 +93,16 @@
"ChannelCloseMessage",
"ChannelErrorMessage",
"ChannelEvents",
"ChannelJoinError",
"ChannelLeaveMessage",
"ChannelStateChange",
"ChannelStates",
"ClientMessage",
"ErrorReplyMessage",
"ErrorSystemPayload",
"HeartbeatMessage",
"HeartbeatPayload",
"JoinMessage",
"MaxRetriesExceeded",
"Message",
"NotConnectedError",
"Payload",
Expand Down Expand Up @@ -136,6 +138,7 @@
"RealtimePresenceListenEvents",
"RealtimePresenceState",
"RealtimeSubscribeStates",
"RealtimeTimeoutError",
"ReplayOption",
"ReplyMessage",
"ReplyPostgresChanges",
Expand Down
Loading
Loading