Skip to main content

Rooms on demand with a relay

A relay never reads the documents: it stores and forwards their changes. So any document id is a room, with nothing to register. This is how Greyhound Markdown shares its rooms.

Rooms on demand with a relaySource ↗

A relay server that hosts any number of rooms, with no setup, and a client that joins a room by its document id. The relay stores and rebroadcasts the changes; the clients merge them.

Dart VMFlutter native✓ tested in CI
import 'dart:io';

import 'package:crdt_socket_sync/web_socket_relay_server.dart';

/// Starts a relay server on [port]. Rooms are created on demand.
Future<WebSocketRelayServer> startRelay({int port = 8080}) async {
// No registration: a client can join any room id.
final server = WebSocketRelayServer(
serverFactory: () => HttpServer.bind(InternetAddress.anyIPv4, port),
// The default store keeps the rooms in memory: a restart loses them.
store: InMemoryRelayStore(),
);
await server.start();
return server;
}

Future<void> main() async {
final server = await startRelay();
stdout.writeln('Relay on ws://localhost:${server.port}');

await ProcessSignal.sigint.watch().first;
await server.dispose();
}

Key points

  • The document id is the room: there is nothing to register, and the store keeps a room from its first change.
  • A client that joins late gets the room's text in the welcome.
  • InMemoryRelayStore loses every room on restart. A durable RelayStore must keep, per room, the log with its seq numbers and the latest snapshot.
  • The relay never reads CRDT data. It asks one client for a snapshot (compact: true) when the log grows, and the client does it on its own.