
# Realtime

`SupabaseRealtime` (the bean `supabaseRealtime`) gives the three things Supabase Realtime sends, as streams: the changes of rows of the database (Postgres Changes), messages between clients (Broadcast) and who is online (Presence). Usually an application declares a `@RealtimeChannel` interface and the generator writes the bean.

## Why

Realtime speaks the Phoenix Channels protocol over one WebSocket: topics to join, replies to match, a heartbeat, a rejoin after every reconnection, and the user's token to send again when it changes. On top, the configuration of a channel is taken at its join only. The starter does all of it: a channel is joined while something listens to it, and the application only sees streams and futures.

## Example

```dart
@Introspected()
class Cursor {
  Cursor({required this.x, required this.y});

  final int x;
  final int y;
}

@Introspected()
class Member {
  Member({required this.name, this.typing = false});

  final String name;
  final bool typing;
}

@RealtimeChannel('room:{id}', presenceKey: '#{authentication.name}')
abstract interface class Room {
  @Broadcast('cursor')
  Stream<Cursor> cursors(String id);

  @Broadcast('cursor')
  Future<void> moveCursor(String id, Cursor cursor);

  @Presence()
  Stream<List<Member>> members(String id);

  @Presence()
  Future<void> join(String id, Member me);

  @PostgresChanges(table: 'messages', filter: 'room_id=eq.{id}')
  Stream<RealtimeRowChange> messages(String id);
}

@Service()
class Board {
  Board(this.room);              // the generated bean

  final Room room;

  void open(String id) {
    room.cursors(id).listen(drawCursor);     // listening joins room:<id>
    room.members(id).listen(showMembers);
    room.join(id, Member(name: 'Ann'));
  }
}
```

## The declared channel

`@RealtimeChannel(name, private:, self:, ack:, presenceKey:)` marks the interface of the channel `name` (the topic `realtime:<name>`).

| Option | Meaning |
|---|---|
| `private` | A channel whose members are authorized by the policies of row-level security on `realtime.messages`. |
| `self` | This client receives its own broadcasts too. |
| `ack` | A `@Broadcast` method that sends waits until the server took the message. |
| `presenceKey` | The key this client is present under. `#{authentication.name}` makes the devices of one user one member. Without it the server makes one up per connection. |

| Method | What it does |
|---|---|
| `@Broadcast('event') Stream<T> name(...)` | The broadcasts of the other clients, each payload read as `T` with the `ObjectMapper` (a `Map<String, Object?>` as it is). A payload that cannot be read is an error event (`MessageConversionException`), and the stream goes on. |
| `@Broadcast('event') Future<void> name(..., payload)` | Sends one. The payload is the parameter the channel's name does not use (or the one marked `@RequestBody()`), written as JSON; without one, `{}` is sent. |
| `@Presence() Stream<List<T>> name(...)` | Everyone present, now and after each change; what each tracked is read as `T` (`RealtimePresence` gives the key and the reference too). |
| `@Presence() Future<void> name(..., state)` | Makes this client present with the state, written as a JSON object. |
| `@Presence() Future<void> name(...)` | Without a state parameter: ends this client's presence. |
| `@PostgresChanges(table:, schema:, filter:, kind:) Stream<RealtimeRowChange> name(...)` | The changes of the rows of a table. |

- **Names.** The channel's name, the `presenceKey` and a filter take `${property}` from the configuration, `{name}` from the method's parameter of that name, and SpEL in `#{...}` (the parameters as `#name`, `authentication` and `principal` as in `@PreAuthorize`, beans as `@name`). So one interface serves every room.
- **One name, one channel.** Each name that comes out is one channel: joined when one of its methods is first used, left when its last stream is cancelled and nothing is tracked.
- **Checked at startup.** A method declared wrongly stops the start, and the message names every problem of the interface.
- **AOP.** The bean takes AOP like any other (`@PreAuthorize`).
- **A kind of method of your own** is a bean that implements `RealtimeChannelOperation`; it is asked before the starter's own.

## Changes of rows

```dart
realtime
    .postgresChanges(table: 'todos', filter: 'list_id=eq.7')
    .listen((change) {
      if (change.kind == RealtimeChangeKind.delete) {
        remove(change.oldRecord['id']);
      } else {
        put(change.record);
      }
    });
```

A `RealtimeRowChange` is one change, sent after it is committed:

| Member | Meaning |
|---|---|
| `kind` | `RealtimeChangeKind.insert`, `update` or `delete`. |
| `schema`, `table` | Where. |
| `record` | The row after the change, column names to JSON values; empty for a delete. |
| `oldRecord` | The row before an update or a delete: only the primary key, unless the table has `replica identity full`; empty for an insert. |
| `commitTime` | When the change was committed, when the server said. |
| `columns` | The PostgreSQL types of the columns, by name. |
| `errors` | What the server could not do for this change, such as `Error 413: Payload Too Large`. |

- The table must be in the publication `supabase_realtime`.
- The user must be allowed to read the rows: row-level security applies, and what the user may not read is left out.
- `filter` narrows the rows on the server: `column=operator.value` with `eq`, `neq`, `lt`, `lte`, `gt`, `gte` or `in` (`id=in.(1,2,3)`). `kind` gives only inserts, updates or deletes.
- In a declared filter, what a parameter or an expression gives is one value, never a part of the filter: a value with a `,`, `(`, `)`, `"` or `\` is put in double quotes, and a list gives its values separated by commas, for `in.({ids})`.
- A subscription the server cannot make (a wrong filter, a table that is not published) is an error event, a `RealtimeException`; the stream stays open.

The rows are JSON, not entities. For entities, declare `watch…By` (`Stream<List<T>>`, the rows kept up to date) and `changes…By` (`Stream<RowChange<T>>`) methods on a repository: the [REST data store](data.md) reports the changes of its rows from here. A condition Realtime can filter (one condition with `eq`, `neq`, `lt`, `lte`, `gt` or `gte`) is filtered on the server, and anything else on this side:

```dart
@UseStore('supabase')
abstract interface class Todos implements ListCrudRepository<Todo, int> {
  Stream<List<Todo>> watchByListId(String listId);

  Stream<RowChange<Todo>> changesByListId(String listId);
}
// changesByListId('l1') joins with {event: *, schema: public, table: todos, filter: list_id=eq.l1}
```

`watch…By` runs its query when listened to and again after every change, and `changes…By` gives each insert, update and delete as a `RowChange` (`previous` only with `replica identity full`). See [Data](data.md) and [Changes of rows](../spring-boot-starter-data/changes.md).

## Broadcast and presence in code

For a channel whose name or use is not known when the application is built, ask `SupabaseRealtime`:

```dart
final room = realtime.channel('room:42', presenceKey: userId);
room.broadcast('cursor').listen(moveCursor);
room.presence().listen(showMembers);
await room.track({'name': 'Ann'});
await room.send('cursor', {'x': 3, 'y': 4});
```

`realtime.channel(name, private:, self:, ack:, presenceKey:)` gives a `RealtimeChannelSession`. Every call with the same name gives the same channel; the options must be the same while it is used, or its use fails with a `StateError`.

| Member | What it does |
|---|---|
| `broadcast(event)` | The payloads of the broadcasts named `event`, as JSON objects; one that is not an object is an error event. |
| `events(event)` | The same, whatever their JSON (an object, a list, a text). |
| `send(event, [payload])` | Broadcasts, joining the channel first when needed. With `ack` it waits for the server and fails with a `PhoenixPushException` when the server refuses it. |
| `presence()` | Who is present: the list now, then again after every change. |
| `track(state)`, `untrack()` | Makes this client present with a state (tracking again replaces it); ends its presence. |
| `postgresChanges(table:, schema:, filter:, kind:)` | The changes of rows on this channel. |
| `leave()` | Leaves the channel now: its streams are done. Using it again joins it again. |

A `RealtimePresence` has the `key` the client joined with, the server's `ref` of this one presence, and the `state` it tracked. The same key may be present several times: a user on two devices.

The server takes the configuration of a channel at its join only. So when a stream of database changes is added or cancelled, or presence is first used, while the channel is joined, it is joined again: the other streams go on, but a broadcast sent in that moment is missed. Listen to what a channel needs at once, or give database changes a channel of their own; `realtime.postgresChanges` does.

## The connection

- **One connection** for every channel. It opens with the first channel that is used and closes with the last one that is left, and when the application stops.
- **Reconnection.** After a lost connection every channel is joined again by itself, with a fresh access token; what was tracked is tracked again, and the streams go on. A join the server refuses is an error event (a `PhoenixJoinException`) and is tried again.
- **When the server ends a channel** (a limit that was passed, a token it refused), its streams get a `RealtimeException` and are done.
- The connection is the WebSocket client `supabase-realtime`, a [Phoenix socket](../spring-boot-starter-websocket/phoenix.md) of the WebSocket starter. `spring.websocket.client.config.supabase-realtime.*` tunes it (`reconnect.*`, `connect-timeout`, `max-text-message-size`, `phoenix.*`); its `url` is not read.

## Tokens

- Every channel is joined with the access token of [`SupabaseCredentials`](credentials.md), asked again at each join.
- When the application has a `LoginSession` (a signed-in user), each change of the login sends the new token to the joined channels, without joining again: the anon key after a logout.
- A token that was refreshed is sent at the next heartbeat. `realtime.refreshAuth()` sends the current token now.
- **A channel acts as the application itself:** its login, or the anon key. It outlives a server's request, so it never takes the token of the request it was asked in.
- A channel asked inside `asServiceRole` is joined as the service role, whenever it is used.

## Not supported

- The wire format `2.0.0`, in which Realtime sends broadcasts as binary frames. The connection uses `1.0.0`, where every message is JSON text.
- A REST fallback for a broadcast: `send` joins the channel.
- `connect()`, `subscribe()` and `removeChannel()`: a channel is joined while it is used.

## The properties

| Key | Type | Default | Meaning |
|---|---|---|---|
| `spring.supabase.realtime.heartbeat-interval` | `Duration` | `25s` | How often the connection says it is alive. `spring.websocket.client.config.supabase-realtime.phoenix.heartbeat-interval` wins. |
| `spring.supabase.realtime.timeout` | `Duration` | `10s` | How long a join or a message waits for its answer. `…supabase-realtime.phoenix.push-timeout` wins. |
| `spring.supabase.realtime.max-message-size` | `DataSize` | `4MB` | The largest message read; a larger one closes the connection. `…supabase-realtime.max-text-message-size` wins. |
| `spring.supabase.connect-timeout` | `Duration` | `10s` | How long the connection may take to open. `…supabase-realtime.connect-timeout` (or `default`'s) wins. |

## In Supabase (JavaScript)

| `realtime-js` | Here |
|---|---|
| `supabase.channel(name, {config})` | `realtime.channel(name, …)`, or a `@RealtimeChannel` interface |
| `channel.on('postgres_changes', {event, schema, table, filter}, fn)` | `postgresChanges(table:, schema:, filter:, kind:)`, `@PostgresChanges` |
| `channel.on('broadcast', {event}, fn)`, `channel.send({type: 'broadcast', event, payload})` | `broadcast(event)`, `send(event, payload)`, `@Broadcast` |
| `channel.on('presence', {event: 'sync'}, fn)`, `channel.track(state)`, `channel.untrack()` | `presence()`, `track(state)`, `untrack()`, `@Presence` |
| `channel.subscribe()` | not needed |
| `supabase.removeChannel(channel)` | `leave()` |
| `realtime.setAuth()` | `refreshAuth()`, called by itself |

## See also

- [The Phoenix Channels client](../spring-boot-starter-websocket/phoenix.md)
- [Changes of rows in the data starter](../spring-boot-starter-data/changes.md)
- [Who a call is made as](credentials.md)
- [Data](data.md)
