Phoenix Channels client

Phoenix Channels is the realtime protocol of Phoenix (Elixir) servers, and of services built on it, such as Supabase Realtime. It puts many topics on one WebSocket connection: a client joins a topic (room:42), receives the events the server sends on it, and pushes its own events, each answered by a reply. The starter speaks it as a client: a @PhoenixChannel interface is declared like a @WebSocketClient.

Why

On top of a WebSocket, the protocol needs an envelope around every message, replies matched to pushes by a reference, a heartbeat, and after every reconnection a new join of every topic. Written by hand, that is a state machine per topic. The starter keeps it: listening to a stream joins the topic, and the application sees streams and futures.

Example

@PhoenixChannel('chat', topic: 'room:{id}', url: r'${chat.url}')
abstract interface class Room {
  @OnEvent('new_msg')
  Stream<ChatMessage> messages(String id);

  @Push('new_msg')
  Future<Ack> send(String id, ChatMessage message);

  @Push('typing', reply: false)
  Future<void> typing(String id);

  Future<void> leave(String id);
}

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

  final Room room;

  // Listening joins room:42; it stays joined while someone listens.
  void open() => room.messages('42').listen(show);

  Future<Ack> say(String text) =>
      room.send('42', ChatMessage(from: 'me', text: text));
}
# lib/resources/application.properties: the socket's WebSocket endpoint, "/websocket" included.
chat.url=wss://chat.neon.books/socket/websocket

The methods

@PhoenixChannel(name, topic:, url:, vsn:): name is the client's name, for its settings (spring.websocket.client.config.<name>.*); url is the address of the socket's WebSocket endpoint, /websocket included; when given it wins over the configured url, and without both the start fails.

Method What it does
@OnEvent('name') Stream<T> name(...) The events of that name on the topic. A payload that already is a T (a String, a Map<String, Object?>) is given as it is, any other type is read as JSON. A payload that cannot be read arrives as an error event (MessageConversionException), and the stream goes on. Listening joins the topic.
@Push('name') Future<T> name(..., payload) Pushes the event, joining the topic first when needed, and completes with the response of the server's reply read as T. Future<void> waits for the reply and ignores its response. At most one parameter besides the topic's: the payload, written as JSON ({} without one).
@Push('name', reply: false) Future<void> name(...) The same for an event the server does not answer: completes once it is sent.
Future<void> leave(...) Optional. Leaves the topic now; its streams are done.

A push fails with a PhoenixPushException for an error reply (its reply.response says why), with a TimeoutException without a reply within phoenix.push-timeout, and with a PhoenixJoinException when the topic cannot be joined.

Any other method stops the application at startup, with every problem of the interface in one message. So does a missing or wrong URL, an unknown vsn, or a method without a parameter the topic names.

Topics and the connection

The join payload

What a join sends comes from two places. A parameter marked @JoinPayload(), on any method, is used when that call joins the topic; a call on a topic that is joined already ignores it. And every PhoenixJoinInterceptor bean may change the payload of every join, the ones after a reconnection included, which is how a token is added:

@OnEvent('new_msg')
Stream<ChatMessage> messagesSince(String id, @JoinPayload() RoomJoin join);

// The rooms want the user's current token when joined.
@Component()
class RoomAuth implements PhoenixJoinInterceptor {
  RoomAuth(this.tokens);

  final TokenStore tokens;

  @override
  Future<void> apply(PhoenixJoin join) async {
    if (join.topic.startsWith('room:')) {      // join.clientName: 'chat'
      join.payload['token'] = await tokens.current();
    }
  }
}

A token the server wants in the socket's URL instead is added by a handshake interceptor, as for any client.

In code: PhoenixSocket

The interfaces sit on a layer a library can use directly. The PhoenixSocketFactory bean gives the socket of a client name (one per name and address, closed when the application stops); a socket gives a channel per topic:

@Service()
class Presence {
  Presence(PhoenixSocketFactory sockets, this.tokens)
    : _socket = sockets.socket(
        'chat',                                 // ...config.chat.url
        parameters: () async => {'token': await tokens.current()},
      );

  final TokenStore tokens;
  final PhoenixSocket _socket;

  Future<void> watch() async {
    final lobby = _socket.channel(
      'lobby',
      payload: () => {'user': 'ann'},           // asked at every join
    );
    lobby.on('presence_diff').listen(update);   // or lobby.messages
    lobby.states.listen(show);                  // joining, joined, errored...
    await lobby.join();                         // the reply's response
    final reply = await lobby.push('status', {'text': 'here'});
    await lobby.send('typing');                 // no reply awaited
    await lobby.leave();
  }
}
PhoenixChannelSession Meaning
join() Joins and completes with the response of the join's reply; a PhoenixJoinException for a refusal or a timeout.
push(event, [payload]) Pushes and completes with the PhoenixReply.
send(event, [payload]) Sends without waiting for a reply.
messages, on(event) Every PhoenixMessage of the topic; the payloads of one event.
state, states PhoenixChannelState: closed, joining, joined, errored, leaving.
leave() Leaves the topic.

parameters are the extra query parameters of the handshake, asked at every connection. A channel joins again by itself after a reconnection and after a phx_error, and goes on trying after a failed join, until leave(). Pushes made while it is joining are sent once it joined. Replies are matched by their ref, and a message of an earlier join of the topic (another join_ref) is dropped.

WebSocketConnectionManager.connectionChanges (each change of isConnected) and reconnect([reason]) are what the socket is built on, for another protocol kept on top of a connection.

Wire formats

The wire format is a PhoenixSerializer, chosen by vsn:

vsn Class A message on the wire
2.0.0 (default) PhoenixSerializerV2 a JSON array: [join_ref, ref, topic, event, payload]
1.0.0 PhoenixSerializerV1 a JSON object: {topic, event, payload, ref, join_ref}

A bean implementing PhoenixSerializer adds another vsn. Only text frames are read; Phoenix's binary payloads are not supported. Long polling is not supported.

Testing

A @PhoenixChannel is tested like any client, with MockWebSocketTransport playing the server. The frames are those of the protocol:

room.messages('42').listen(messages.add);            // joins room:42
final server = await sockets.nextConnection;
await pumpEventQueue();
final join = server.sentJson.single! as List;        // ["1","1","room:42","phx_join",{}]
server.pushJson([join[0], join[1], join[2], 'phx_reply',
    {'status': 'ok', 'response': {}}]);              // the join is accepted
server.pushJson([null, null, 'room:42', 'new_msg',
    {'from': 'ann', 'text': 'hi'}]);                 // an event

The properties

Beside the keys every client has (Client configuration), under spring.websocket.client.config.<name>.:

Key Type Default Meaning
phoenix.heartbeat-interval Duration 30s The time between two heartbeats; 0 sends none.
phoenix.push-timeout Duration 10s The longest a join, a push or a leave waits for its reply.
phoenix.vsn String 2.0.0 The version of the wire format, sent as the vsn query parameter: 2.0.0 or 1.0.0. @PhoenixChannel(vsn:) wins.
spring.websocket.client.config.chat.phoenix.heartbeat-interval=15s
spring.websocket.client.config.chat.phoenix.push-timeout=5s

A Phoenix client takes the message size limits of its name too.

Compared with phoenix.js

phoenix.js Here
new Socket(endPoint, {params, heartbeatIntervalMs, timeout, vsn}) PhoenixSocketFactory.socket(name, parameters: ...) with phoenix.* properties; the URL is the full WebSocket address (.../websocket)
socket.connect() / disconnect() not needed: the connection follows the channels
socket.channel(topic, params) socket.channel(topic, payload: ...), or a @PhoenixChannel interface
channel.join().receive("ok" / "error" / "timeout", ...) await channel.join(), a PhoenixJoinException
channel.on(event, callback) channel.on(event) (a Stream), @OnEvent
channel.push(event, payload).receive(...) await channel.push(event, payload), @Push
the reconnect and rejoin timers reconnect.* of the client, for both
long polling not supported

In Spring (Java)

No counterpart: Spring has no Phoenix client. The declared interface follows this starter's @WebSocketClient.

See also