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.
- server.dart
- client.dart
- Install
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();
}
import 'dart:io';
import 'package:crdt_lf/crdt_lf.dart';
import 'package:crdt_socket_sync/web_socket_relay_client.dart';
/// Opens the text of [room] and joins it on the relay at [url].
Future<({WebSocketRelayClient client, CRDTFugueTextHandler text})> joinRoom(
String url,
String room,
) async {
// The document id is the room: the same id on two clients, the same room.
final document = CRDTDocument(documentId: room, peerId: PeerId.generate());
final text = CRDTFugueTextHandler(document, 'body');
final client = WebSocketRelayClient(
url: url,
document: document,
author: document.peerId,
);
// The welcome brings what the room already holds, merged into the document.
await client.connect();
return (client: client, text: text);
}
Future<void> main(List<String> args) async {
final room = args.isEmpty ? 'lobby' : args.first;
final (:client, :text) = await joinRoom('ws://localhost:8080', room);
client.document.updates.listen((_) => stdout.writeln(text.value));
text.insert(text.value.runes.length, 'Hello from ${client.author}\n');
await ProcessSignal.sigint.watch().first;
await client.disconnect();
client.dispose();
client.document.dispose();
}
dart pub add crdt_lf crdt_socket_sync
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.
InMemoryRelayStoreloses every room on restart. A durableRelayStoremust 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.