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
58 changes: 57 additions & 1 deletion MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@ Across every package:
| ------------------------------------------- | ------------------------------------------- |
| `RealtimeClient.conn` | `RealtimeClient.connection` |
| `RealtimeClient.connState` | `RealtimeClient.connectionState` |
| `RealtimeClient.onConnMessage` | `RealtimeClient.onConnectionMessage` |
| `RealtimeClient.onConnMessage` | removed (internal) |
| `RealtimeClient.params` | `RealtimeClient.parameters` |
| `RealtimeClient.endPoint` | `RealtimeClient.endpoint` |
| `RealtimeClient.endPointURL` | `RealtimeClient.endpointUrl` |
Expand Down Expand Up @@ -1629,6 +1629,62 @@ If you read presence state through `channel.presence`, use `channel.presenceStat
`onPresenceSync`, `onPresenceJoin` and `onPresenceLeave` streams instead. Pass channel configuration
through `RealtimeChannelConfig` when creating the channel.

#### Channel results are typed

`RealtimeChannel.unsubscribe()`, `RealtimeClient.removeChannel()` and
`SupabaseClient.removeChannel()` resolve to a `ChannelResponse` instead of the strings `'ok'`,
`'timed out'` and `'error'`, and `removeAllChannels()` resolves to a `List<ChannelResponse>`.
Comparing the result with a string still compiles but is never true.

```dart skip
// Before
if (await supabase.removeChannel(channel) == 'ok') {}
```

```dart
// After
final channel = supabase.channel('room');
if (await supabase.removeChannel(channel) == ChannelResponse.ok) {}
```

#### `track()` and `untrack()` take a `timeout`

The options map of `track()` and `untrack()` is replaced by a named `timeout`, the only option that
had an effect.

```dart skip
// Before
await channel.track({'online_at': now}, {'timeout': 5000});
```

```dart
// After
final channel = supabase.channel('room').subscribe();
await channel.track(
{'online_at': DateTime.now().toIso8601String()},
timeout: const Duration(seconds: 5),
);
```

#### `RealtimeChannelConfig` presence options are named for presence

| Before | After |
| ----------------------------------- | ------------------------------------------- |
| `RealtimeChannelConfig(key: …)` | `RealtimeChannelConfig(presenceKey: …)` |
| `RealtimeChannelConfig(enabled: …)` | `RealtimeChannelConfig(presenceEnabled: …)` |

#### A channel exposes its topic and state

`RealtimeChannel.topic` and the new `RealtimeChannel.state`, a `ChannelState`, are public, so a
channel can be found in `supabase.channels` and checked without listening to `onStatusChange`:

```dart
final joined = supabase.channels.where(
(channel) =>
channel.topic == 'realtime:room' && channel.state == ChannelState.joined,
);
```

#### Broadcasts no longer fall back to the REST API

`sendBroadcastMessage()` only sends over the WebSocket. Calling it on a channel that was never
Expand Down
4 changes: 2 additions & 2 deletions packages/supabase/lib/src/supabase_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -358,12 +358,12 @@ class SupabaseClient {
/// Unsubscribes and removes Realtime channel from Realtime client.
///
/// [channel] - The Realtime channel to remove.
Future<String> removeChannel(RealtimeChannel channel) {
Future<ChannelResponse> removeChannel(RealtimeChannel channel) {
return realtime.removeChannel(channel);
}

/// Unsubscribes and removes all Realtime channels from Realtime client.
Future<List<String>> removeAllChannels() {
Future<List<ChannelResponse>> removeAllChannels() {
return realtime.removeAllChannels();
}

Expand Down
6 changes: 3 additions & 3 deletions packages/supabase/test/realtime_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ void main() {

final status = await supabase.removeChannel(anotherChannel);

expect(status, 'ok');
expect(status, ChannelResponse.ok);

expect(
supabase.channels,
Expand Down Expand Up @@ -139,11 +139,11 @@ void main() {

expect(
status1,
'ok',
ChannelResponse.ok,
);
expect(
status2,
'ok',
ChannelResponse.ok,
);

expect(
Expand Down
5 changes: 2 additions & 3 deletions packages/supabase_realtime/example/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Future<void> main() async {
parameters: {'apikey': 'SUPABASE_API_KEY'},
);

final channel = socket.channel('realtime:public');
final channel = socket.channel('public');
channel
.onPostgresChanges(
event: PostgresChangeEvent.all,
Expand Down Expand Up @@ -46,8 +46,7 @@ Future<void> main() async {

socket.onMessage.listen((message) => print('MESSAGE $message'));

// on connect and subscribe
await socket.connect();
// subscribing connects the socket
channel.onStatusChange.listen(
(change) => print('STATUS ${change.status.name}'),
);
Expand Down
25 changes: 23 additions & 2 deletions packages/supabase_realtime/lib/src/constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,29 @@ enum SocketState {
disconnected,
}

@internal
enum ChannelState { closed, errored, joined, joining, leaving }
/// The state of a [RealtimeChannel], read through [RealtimeChannel.state].
enum ChannelState {
/// The channel is not joined, either because it was never subscribed or
/// because it left.
closed,

/// The server rejected the join, the join timed out, or the connection
/// dropped.
errored,

/// The server accepted the join.
///
/// For Postgres Changes this does not mean replication is ready. A failure
/// to set it up arrives later as [RealtimeSubscribeStatus.channelError] on
/// [RealtimeChannel.onStatusChange].
joined,

/// A join request is in flight.
joining,

/// A leave request is in flight.
leaving,
}

@internal
enum ChannelEvent {
Expand Down
49 changes: 28 additions & 21 deletions packages/supabase_realtime/lib/src/realtime_channel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ class RealtimeChannel {

/// The full topic this channel subscribes to, for example
/// `realtime:room`.
@internal
final String topic;
final Map<String, dynamic> _parameters;

Expand Down Expand Up @@ -311,6 +310,7 @@ class RealtimeChannel {
),
)
.receive('error', (error) {
_state = ChannelState.errored;
final reply = error as Map<String, dynamic>;
_addStatus(
RealtimeSubscribeStatus.channelError,
Expand Down Expand Up @@ -434,33 +434,34 @@ class RealtimeChannel {

/// Shares [payload] with every other client tracking presence on this
/// channel.
///
/// [timeout] bounds how long to wait for the server to acknowledge it, and
/// defaults to the client's timeout.
Future<ChannelResponse> track(
Map<String, dynamic> payload, [
Map<String, dynamic> options = const {},
]) {
Map<String, dynamic> payload, {
Duration? timeout,
}) {
return send(
type: RealtimeListenType.presence,
payload: {
'event': 'track',
'payload': payload,
},
options: {
'timeout': _timeout,
...options,
},
options: {'timeout': ?timeout},
);
}

/// Stops sharing this client's presence on this channel.
Future<ChannelResponse> untrack([
Map<String, dynamic> options = const {},
]) {
///
/// [timeout] bounds how long to wait for the server to acknowledge it, and
/// defaults to the client's timeout.
Future<ChannelResponse> untrack({Duration? timeout}) {
return send(
type: RealtimeListenType.presence,
payload: {
'event': 'untrack',
},
options: options,
options: {'timeout': ?timeout},
);
}

Expand Down Expand Up @@ -1046,13 +1047,14 @@ class RealtimeChannel {
/// Unsubscribes from server events, and instructs channel to terminate on
/// server. Triggers onClose() hooks.
///
/// Returns a [Future] that resolves to `'ok'`, `'timed out'`, or `'error'`
/// depending on the outcome of the leave request.
/// Resolves once the leave is sent, without waiting for the server to
/// acknowledge it, so the result is normally [ChannelResponse.ok]. The
/// channel is closed and removed from [RealtimeClient.channels] by then.
/// ```dart
/// final status = await channel.unsubscribe();
/// print(status); // 'ok'
/// final response = await channel.unsubscribe();
/// print(response); // ChannelResponse.ok
/// ```
Future<String> unsubscribe([Duration? timeout]) {
Future<ChannelResponse> unsubscribe([Duration? timeout]) {
_state = ChannelState.leaving;
void onClose() {
realtimeLogger.fine('Channel leave: $topic');
Expand All @@ -1062,27 +1064,27 @@ class RealtimeChannel {
// Destroy joinPush to avoid connection timeouts during unsubscription phase
_joinPush.destroy();

final completer = Completer<String>();
final completer = Completer<ChannelResponse>();

final leavePush = Push(this, ChannelEvent.leave, {}, timeout ?? _timeout);

leavePush
.receive('ok', (_) {
onClose();
if (!completer.isCompleted) {
completer.complete('ok');
completer.complete(ChannelResponse.ok);
}
})
.receive('timeout', (_) {
if (!completer.isCompleted) {
onClose();
}
completer.complete('timed out');
completer.complete(ChannelResponse.timedOut);
})
.receive('error', (_) {
onClose();
if (!completer.isCompleted) {
completer.complete('error');
completer.complete(ChannelResponse.error);
}
});

Expand Down Expand Up @@ -1232,6 +1234,11 @@ class RealtimeChannel {
return 'chan_reply_$ref';
}

/// The current state of the channel.
///
/// Listen to [onStatusChange] to be told when the subscription changes.
ChannelState get state => _state;

/// Whether the channel has been closed.
@internal
bool get isClosed => _state == ChannelState.closed;
Expand Down
11 changes: 5 additions & 6 deletions packages/supabase_realtime/lib/src/realtime_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,7 @@ class RealtimeClient {
/// built-in codec.
///
/// [reconnectAfter] The optional function that returns the reconnect
/// interval. Defaults to the stepped backoff of
/// [RetryTimer.createRetryFunction].
/// interval. Defaults to an exponential backoff from 1 to 10 seconds.
///
/// [logLevel] Specifies the log level for the connection on the server.
RealtimeClient(
Expand Down Expand Up @@ -542,13 +541,12 @@ class RealtimeClient {
}

/// Unsubscribes [channel] and removes it from [channels].
Future<String> removeChannel(RealtimeChannel channel) async {
final status = await channel.unsubscribe();
return status;
Future<ChannelResponse> removeChannel(RealtimeChannel channel) {
return channel.unsubscribe();
}

/// Unsubscribes every channel and disconnects the socket.
Future<List<String>> removeAllChannels() async {
Future<List<ChannelResponse>> removeAllChannels() async {
final values = await Future.wait(
_channels.toList().map((channel) => channel.unsubscribe()),
);
Expand Down Expand Up @@ -784,6 +782,7 @@ class RealtimeClient {
/// awaited first, bounded by [timeout] so it cannot stall the chain
/// forever, and its dispatch is chained onto [_pendingDispatch] so that a
/// fast decode never overtakes a slow one that was received before it.
@internal
void onConnectionMessage(Object rawMessage) {
final originConnection = _connection;
final decode = this.decode;
Expand Down
Loading
Loading