Skip to content

feat(realtime): add support for protocol format 2.0.0 - #1397

Merged
spydon merged 16 commits into
mainfrom
lukasklingsbo/sdk-583-realtime-protocol-200
Jun 12, 2026
Merged

spydon merged 16 commits into
mainfrom
lukasklingsbo/sdk-583-realtime-protocol-200

Conversation

@spydon

@spydon spydon commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds Realtime protocol 2.0.0 support to the Dart/Flutter SDK and makes the protocol version selectable.

Closes SDK-583.

Protocol 2.0.0 changes the WebSocket frame format:

  • Text frames use the positional JSON array [join_ref, ref, topic, event, payload] instead of the 1.0.0 object layout, reducing JSON work on the backend (lower latency).
  • Binary frames allow raw binary payloads for broadcast user events.

Changes

Serializer (serializer.dart, new)

  • Text encode/decode as the positional array [join_ref, ref, topic, event, payload].
  • Binary encode for broadcast pushes (userBroadcastPush, kind 3).
  • Binary decode for incoming broadcasts (userBroadcast, kind 4).
  • JSON/binary encoding flag and allowedMetadataKeys.
  • decode validates the text frame shape and throws a clear FormatException on malformed input; onConnMessage logs and drops such frames instead of crashing the connection.

Selectable protocol version

  • New RealtimeProtocolVersion enum (v1 → 1.0.0, v2 → 2.0.0); each carries the vsn value sent as the connection parameter.
  • RealtimeClient takes a version parameter, defaulting to v2. v2 uses the serializer; v1 uses the legacy object-shaped JSON frames.

Codec override

  • Optional encode / decode constructor arguments (and the RealtimeEncode / RealtimeDecode typedefs) let consumers swap in a custom serializer; they default to the codec for the selected version.
  • Return-based signatures: RealtimeEncode = Object Function(Map<String, dynamic>), RealtimeDecode = Map<String, dynamic> Function(Object) (synchronous — async/isolate codec is a follow-up, see below).

Binary broadcasts

Incoming binary broadcast frames are decoded into the same map shape as JSON broadcasts. To send binary, provide a Uint8List (or any TypedData) under the payload key:

```dart
channel.sendBroadcastMessage(event: 'file', payload: {'payload': myUint8List});
```

Binary frames are delivered as Uint8List on every platform; the web transport sets binaryType to arraybuffer explicitly.

Misc

  • Expanded a few abbreviated identifiers (obj/msg/res) in touched code.

Breaking changes

  • Default Realtime protocol is now 2.0.0 (pass version: RealtimeProtocolVersion.v1 to keep the old behavior).
  • RealtimeEncode / RealtimeDecode changed from callback-based to return-based signatures.

Related

Tests

  • realtime_client: 121 passing (new serializer_test.dart, endpointURL v1, legacy encode, legacy decode + dispatch, custom-encode override, malformed-frame, binary-broadcast receive).
  • supabase: 83 passing.
  • supabase_flutter/test/lifecycle_test.dart: analyze clean.

@github-actions github-actions Bot added the realtime This issue or pull request is related to realtime label Jun 12, 2026
spydon added 13 commits June 12, 2026 14:08
Implements Realtime protocol 2.0.0 for the Dart/Flutter SDK (SDK-583).

- Add a `Serializer` ported from the supabase-js reference that encodes
  text frames as the positional JSON array `[join_ref, ref, topic, event,
  payload]` and handles binary frames (`userBroadcastPush` kind 3 encode,
  `userBroadcast` kind 4 decode) with the JSON/binary encoding flag and
  `allowedMetadataKeys`.
- Default the connection to `vsn=2.0.0` and wire the serializer as the
  default encode/decode.
- Decode incoming binary broadcast frames and send broadcasts whose payload
  is a `Uint8List`/`TypedData` as binary frames.
- Loosen `RealtimeEncode`/`RealtimeDecode` to carry `String` or bytes and
  let the connection listener accept binary frames.
- Rename the `conn` family to avoid abbreviations: `conn` -> `connection`,
  `connState` -> `connectionStatus`, `onConnMessage` -> `onConnectionMessage`,
  `_onConn*` -> `_onConnection*`.
- Update realtime frame mocks/tests to the 2.0.0 array format and add
  `serializer_test.dart`.

BREAKING CHANGE: the default Realtime protocol is now 2.0.0, and the
`RealtimeClient.conn`/`connState` fields are renamed to
`connection`/`connectionStatus`.
…allback

The callback form was a port artifact from the realtime-js/Phoenix
serializer. Both encode and decode are synchronous here, so return the
result directly: RealtimeEncode is now Object Function(Map<String,
dynamic>) and RealtimeDecode is Map<String, dynamic> Function(Object).
Remove the custom encode/decode constructor hook and the RealtimeEncode/
RealtimeDecode typedefs. With the protocol pinned to 2.0.0, a custom codec
that does not emit valid frames would only break the connection, and the
hook was unused. The client now holds a private Serializer directly.

BREAKING CHANGE: the RealtimeClient encode/decode constructor parameters,
the encode/decode fields, and the RealtimeEncode/RealtimeDecode typedefs
are removed.
Add a RealtimeProtocolVersion enum (v1/v2) and a version constructor
parameter on RealtimeClient, defaulting to v2. v1 uses the legacy
object-shaped JSON frames; v2 uses the serializer. The enum carries the
wire vsn string sent as the connection parameter.

Also drop the porting references from the doc comments.
Re-add optional encode/decode constructor arguments (and the
RealtimeEncode/RealtimeDecode typedefs). They default to the codec
selected by version, so consumers can swap in a faster serializer.
- decode() validates the 2.0.0 text frame shape and throws a clear
  FormatException instead of an obscure cast error
- onConnectionMessage drops malformed frames instead of crashing the
  connection, and guards the status log against non-map payloads
- set the web binaryType explicitly to arraybuffer/list
- document the ASCII assumption for binary frame string fields
…et constant

Avoid copying frame slices during binary decode, name the userBroadcast
header offset, and add an end-to-end test for dispatching a received
binary broadcast to onBroadcast.
Write the header directly into the final frame buffer instead of
allocating a separate header and copying it, removing one allocation and
one copy per binary broadcast push.
Make encode/decode plain final fields resolved in the initializer list
instead of late, using a shared static serializer and static legacy
codec helpers. Removes the late modifier and a per-client serializer
allocation.
@spydon
spydon force-pushed the lukasklingsbo/sdk-583-realtime-protocol-200 branch from 512d1ce to 06f375d Compare June 12, 2026 12:10
spydon added 2 commits June 12, 2026 14:20
Rename obj -> source in the serializer, msg -> message in the logger
and log(), and res -> response in the channel HTTP helpers.
The mock_test suites now exercise v2; add a v1 decode + dispatch test so
the legacy object-frame path keeps coverage alongside the existing v1
endpointURL and encode tests.
@spydon
spydon marked this pull request as ready for review June 12, 2026 12:47
@spydon
spydon requested a review from a team as a code owner June 12, 2026 12:47
Keep the original conn/connState fields, the onConnMessage method, and the
_onConn* handlers in this PR so it carries only the protocol 2.0.0 feature
and RealtimeProtocolVersion. The breaking renames move to a follow-up PR
targeting v3.
@spydon
spydon merged commit c04d5d1 into main Jun 12, 2026
21 checks passed
@spydon
spydon deleted the lukasklingsbo/sdk-583-realtime-protocol-200 branch June 12, 2026 15:13
spydon added a commit that referenced this pull request Aug 6, 2026
)

## What

Cleans up the connection-related naming on `RealtimeClient`. Split out
of #1397 so that PR could carry only the protocol 2.0.0 feature without
breaking changes.

### Spell out the `conn` abbreviation

| Before | After |
| --- | --- |
| `RealtimeClient.conn` | `connection` |
| `RealtimeClient.connState` | `connectionState` (see below) |
| `RealtimeClient.onConnMessage` | `onConnectionMessage` |

Private and local: `_onConnOpen` / `_onConnClose` / `_onConnError`
became `_onConnectionOpen` / `_onConnectionClose` /
`_onConnectionError`, and the `localConn` local in `connect()` became
`localConnection`.

Also the shortenings the rename itself did not reach: the heartbeat
timeout log message now reads "Attempting to re-establish connection", a
`channel_test` description that said "via ws conn", and `chanParams` on
the test stub's `channel` override (renamed to `config`, matching the
`RealtimeClient.channel` signature it overrides).

### Collapse the two socket-state accessors

Spelling out `connState` left it one word away from the existing `String
get connectionState`, and both carried the same information. The
stringly typed getter is gone and the typed field takes the name:

```dart
// before
SocketStates? connState;
String get connectionState => switch (connState) { ... };

// after
SocketState? connectionState;
```

For the string form use `connectionState?.name`; for the common case
`isConnected` is unchanged.

### Singularize the enum

`SocketStates` is now `SocketState`, matching Dart convention and the
large majority of the 51 enums in the repository.

Consumers updated: `supabase_flutter` (`supabase.dart`,
`lifecycle_test.dart`).

## Breaking changes

- `RealtimeClient.conn` → `connection`
- `RealtimeClient.onConnMessage` → `onConnectionMessage`
- `RealtimeClient.connState` → `connectionState`
- `RealtimeClient.connectionState` changes type from `String` to
`SocketState?`. This one is a silent change for anyone reading it as a
string, so it is worth calling out in the release notes.
- `SocketStates` → `SocketState`

Renames and one removal. No behaviour change.

## Capability matrix

`RealtimeClient.connection`, `RealtimeClient.onConnectionMessage`, and
`SocketState` are registered in `sdk-compliance.yaml`.
`RealtimeClient.connectionState` keeps its name and its existing entry.

## Notes

- Rebased onto `main` now that #1397 has merged.
- The description previously said this would be retargeted to `v3`
(tracked in #1278). It still targets `main`; happy to flip the base if
that is still the plan.
- The remaining plural enums are tracked in #1652. Only `PostgresTypes`
among them is actually exported, so three of the four can land before
v3; left out here to keep this PR scoped.

## Tests

`realtime_client` 203 passing, `supabase` 135 passing,
`supabase_flutter` 63 passing. `dart analyze` and `dart format` clean.
The capability matrix symbol and schema checks were run locally against
`main` and pass.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Breaking Changes**
- Renamed realtime connection APIs for clearer terminology, including
`SocketState`, `connection`, `connectionState`, and
`onConnectionMessage`.
  - Removed the previous string-based connection-state getter.
- Connection status is now represented directly through typed socket
states.

- **Bug Fixes**
- Disconnecting now reliably cancels pending reconnect attempts and
clears the active connection.

- **Documentation**
- Updated SDK capability information to reflect the renamed realtime
APIs.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
spydon added a commit that referenced this pull request Aug 21, 2026
Closes #1401

## What

The realtime codec overrides (`RealtimeEncode` / `RealtimeDecode`, added
in #1397) were synchronous and worked on raw `Map<String, dynamic>`s, so
`jsonEncode`/`jsonDecode` of every message ran on the main isolate. A
large payload blocks the event loop, and a background-isolate codec
could not be plugged in at all.

Both typedefs now work on a `RealtimeMessage` and return a `Future`:

| Before | After |
| --- | --- |
| `Object Function(Map<String, dynamic>)` | `Future<Object>
Function(RealtimeMessage)` |
| `Map<String, dynamic> Function(Object)` | `Future<RealtimeMessage>
Function(Object)` |

```dart
final isolate = YAJsonIsolate();

await Supabase.initialize(
  url: url,
  anonKey: anonKey,
  realtimeClientOptions: RealtimeClientOptions(
    encode: (message) => isolate.encode(message.toJson()),
    decode: (frame) async =>
        RealtimeMessage.fromJson(await isolate.decode(frame as String)),
  ),
);
```

`RealtimeClientOptions` carries the two callbacks through
`SupabaseClient` and `Supabase.initialize`, so a `supabase_flutter` user
never has to construct a `RealtimeClient` by hand.

## `RealtimeMessage`

A new exported class carrying `joinRef`, `ref`, `topic`, `event` and
`payload`, with `toJson([version])` and `RealtimeMessage.fromJson(json,
[version])` converting to and from the shape each protocol version puts
on the wire (positional array for `2.0.0`, object for `1.0.0`, both
defaulting to `2.0.0`). A codec only has to turn that shape into bytes
and back rather than hand-building the positional array.

It replaces the internal `Message` class. An `@internal`
`RealtimeMessage.outgoing` builds one from a `ChannelEvent` and replaces
`Binding`s in the payload with their serializable shape, which matters
more now: a `Binding` holds a callback and could never be sent to an
isolate.

## Ordering

Introducing awaits into the message pipeline is the risky part, so both
directions are chained:

- Encoding starts as soon as a message is pushed, but the write to the
sink is chained onto the previous pending write, so frames reach the
socket in push order even when a later encode finishes first.
- Incoming frames chain the same way, so messages are dispatched to the
channels in receive order.
- The chain future never completes with an error, so a failed encode or
decode drops only its own message instead of stalling the ones behind
it.

## Fast path

`encode` and `decode` are `null` unless one is passed, and the built-in
codec is used while they are. That codec is synchronous, so a client
that does not override it writes and dispatches without a microtask hop,
and no `FutureOr` is needed anywhere.

## Tests

- `async_codec_test.dart`: completion-order scrambling in both
directions, an immediate codec queued behind a slow one, failure
isolation, buffered flush ordering, and the no-hop fast path for the
built-in codec.
- `realtime_message_test.dart`: event naming, binding stripping, and
`toJson`/`fromJson` round trips per protocol version.
- An integration test runs a real `Isolate.run` codec against the local
Realtime server, delaying each broadcast in reverse order so the encodes
and decodes complete backwards. It fails without the chaining and passes
with it.
- `serializer_test.dart`, `socket_test.dart` and `heartbeat_test.dart`
ported to the new types.

- `client_test.dart` covers the `RealtimeClientOptions` passthrough
reaching the realtime client, and the default staying `null`.

`sdk-compliance.yaml` registers the new `RealtimeMessage` and
`RealtimeClientOptions` symbols; the symbol and drift checks pass
locally.

## Performance

The message class costs nothing to introduce. Benchmarked against the
old map-based path (best of 7 rounds per variant), a `RealtimeMessage`
replaces a `LinkedHashMap` allocation in each direction and turns hash
lookups plus `as` casts in the dispatch into field reads:

| payload | encode | decode |
| --- | --- | --- |
| 118 B broadcast | -17% (1.06 → 0.87 µs) | -32% (0.59 → 0.40 µs) |
| 1.1 KB row | -10% (3.82 → 3.45 µs) | -10% (2.15 → 1.94 µs) |
| 1 MB blob | -0.5% (603 → 600 µs) | -0.1% (569 → 568 µs) |

AOT numbers track the same way. The 1 MB case is flat because
`jsonEncode`/`jsonDecode` is essentially all of it, which is the case
the async codec exists to move off the event loop.

### Isolate codecs, end to end

Benchmarked through a real `RealtimeClient` with a stub WebSocket
transport, one broadcast message per event-loop turn (like frames
arriving from a socket), comparing the built-in synchronous codec
against a per-message `Isolate.run` codec and a persistent-isolate codec
(`YAJsonIsolate`, the shape the docs recommend). *Max stall* is the
longest main-isolate event-loop blockage observed by a 1 ms heartbeat
timer, *total stall* the sum of all blockages above 2 ms; stalls below
~1 ms read as 0. Apple M5, Dart 3.13.0 JIT. The benchmark script is
deliberately not part of the PR.

**Encode**

| codec | payload | messages | wall | per message | max stall | total
stall |
| --- | --- | --- | --- | --- | --- | --- |
| built-in sync | 1 KB | 1000 | 9.1 ms | 0.0 ms | 1.0 ms | 0 ms |
| `Isolate.run` | 1 KB | 1000 | 45.3 ms | 0.0 ms | 0.8 ms | 0 ms |
| `YAJsonIsolate` | 1 KB | 1000 | 13.1 ms | 0.0 ms | 1.0 ms | 1.0 ms |
| built-in sync | 64 KB | 300 | 83.0 ms | 0.3 ms | 0.4 ms | 0 ms |
| `Isolate.run` | 64 KB | 300 | 30.0 ms | 0.1 ms | 0.7 ms | 0 ms |
| `YAJsonIsolate` | 64 KB | 300 | 102.1 ms | 0.3 ms | 3.0 ms | 8.0 ms |
| built-in sync | 1 MB | 30 | 138.1 ms | 4.6 ms | 5.7 ms | 108.1 ms |
| `Isolate.run` | 1 MB | 30 | 69.3 ms | 2.3 ms | 7.7 ms | 36.4 ms |
| `YAJsonIsolate` | 1 MB | 30 | 146.0 ms | 4.9 ms | 5.3 ms | 22.8 ms |

**Decode**

| codec | payload | messages | wall | per message | max stall | total
stall |
| --- | --- | --- | --- | --- | --- | --- |
| built-in sync | 1 KB | 1000 | 10.8 ms | 0.0 ms | 0.7 ms | 0 ms |
| `Isolate.run` | 1 KB | 1000 | 34.8 ms | 0.0 ms | 0.8 ms | 0 ms |
| `YAJsonIsolate` | 1 KB | 1000 | 9.1 ms | 0.0 ms | 0.9 ms | 0 ms |
| built-in sync | 64 KB | 300 | 54.4 ms | 0.2 ms | 0.9 ms | 0 ms |
| `Isolate.run` | 64 KB | 300 | 94.8 ms | 0.3 ms | 56.6 ms | 83.9 ms |
| `YAJsonIsolate` | 64 KB | 300 | 117.0 ms | 0.4 ms | 5.6 ms | 29.4 ms |
| built-in sync | 1 MB | 30 | 85.6 ms | 2.9 ms | 3.3 ms | 55.6 ms |
| `Isolate.run` | 1 MB | 30 | 114.7 ms | 3.8 ms | 32.6 ms | 84.4 ms |
| `YAJsonIsolate` | 1 MB | 30 | 182.0 ms | 6.1 ms | 7.3 ms | 51.5 ms |

What the numbers say:

- **Small payloads confirm the fast-path design.** At 1 KB the built-in
synchronous codec is the fastest option in both directions and never
blocks measurably; an isolate hop is pure overhead there. This is why
`encode`/`decode` default to `null` and the built-in codec stays
synchronous.
- **Encoding large payloads is where the isolate pays off.** At 1 MB the
synchronous codec blocks the main isolate ~4.6 ms per message, 108 ms in
total over 30 messages. The persistent-isolate codec cuts total blocking
to 22.8 ms (~5x) at the same throughput. The remaining ~5 ms max stall
is the copy of the payload map into the isolate, which is inherent to
isolate message passing, not to this API.
- **Decoding plain JSON on an isolate is roughly a wash on this
machine.** Copying the decoded 1 MB map back across the isolate boundary
costs about as much as decoding it in place, so total stall barely moves
(55.6 → 51.5 ms). The API still enables the cases where the isolate
clearly wins: slower devices, binary payloads (`Uint8List` transfers
cheaply), and codecs that do real work such as decompression or
decryption.
- **A persistent isolate is the right shape; `Isolate.run` per message
is not.** Per-message spawning shows large, erratic stalls (up to ~57 ms
at 64 KB) from spawn and copy churn, and its numbers vary noticeably
between runs.
- Wall time for the isolate encoders can beat the synchronous codec (30
ms vs 83 ms at 64 KB) because encodes run concurrently while the
pending-write chain keeps frames in push order; every run delivered all
frames in order.

## Breaking

Documented in `MIGRATION.md`.



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Added the public `RealtimeMessage` model for typed WebSocket messages.
- Added protocol-aware JSON conversion for Realtime protocol versions 1
and 2.
  - Added optional asynchronous custom encoding and decoding callbacks.
  - Exposed codec configuration through client initialization options.

- **Improvements**
  - Preserved message order during asynchronous processing.
  - Added timeout handling for codec operations.
- Improved resilience when individual codec or message operations fail.

- **Documentation**
- Added migration guidance for updated codec APIs and typed message
handling.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

2 participants