A relay in a Dart Frog backend
Add a relay to a Dart Frog backend you already have: a host, a middleware and one route.
A relay in a Dart Frog backendSource ↗
A Dart Frog route that serves a relay: any document id is a room, with no setup. The rooms live in memory.
- lib/src/host.dart
- routes/_middleware.dart
- routes/relay.dart
- main.dart
- Install
import 'package:crdt_socket_sync/relay_server.dart';
/// The relay host for this process.
///
/// Constructed at the top level, so `_middleware.dart` finds it when Dart Frog
/// builds the handler tree; started by `init()` in `main.dart`. One instance
/// per process, shared by every request: a host per request would give each
/// client its own empty room.
///
/// The host has no socket of its own — Dart Frog upgrades the requests and
/// hands them over. The store is in-memory, so a restart loses every room;
/// there is no durable `RelayStore` in this repository yet, so a real backend
/// implements one over its database and closes it after `dispose()`.
final relayHost = RelaySessionHost(store: InMemoryRelayStore());
/// Sends every server event to [log], so the console shows what the protocol
/// is doing. A real backend would use its logger.
void logRelayEvents(void Function(String line) log) {
relayHost.serverEvents.listen(
(e) => log('[relay] ${e.type.name}: ${e.message}'),
);
}
import 'package:crdt_socket_sync_dart_frog/relay.dart';
import 'package:crdt_socket_sync_dart_frog_relay_example/src/host.dart';
import 'package:dart_frog/dart_frog.dart';
/// Puts the host in the context, under the type `context.read` matches on.
///
/// The host is built once, at the top level of `host.dart`; this only hands
/// the same instance to every request.
Handler middleware(Handler handler) {
return handler.use(crdtRelayHostProvider(relayHost));
}
import 'package:crdt_socket_sync_dart_frog/relay.dart';
import 'package:dart_frog/dart_frog.dart';
/// Relay mode: the server rebroadcasts opaque CRDT blobs to the other clients
/// of a room and persists them, without ever reading them.
///
/// Connect with `WebSocketRelayClient` at `ws://localhost:8080/relay`. The
/// room is the document id inside the hello frame, not part of this path.
Future<Response> onRequest(RequestContext context) async {
return crdtRelayWebSocketHandler(context.read<RelaySessionHost>())(context);
}
import 'dart:io';
import 'package:crdt_socket_sync_dart_frog_relay_example/src/host.dart';
import 'package:dart_frog/dart_frog.dart';
/// Custom init: runs once, before Dart Frog builds the handler tree.
///
/// Starts the host and disposes it on `SIGINT`/`SIGTERM`. Dart Frog has no
/// shutdown hook, so the signals are where an orderly teardown goes.
///
/// Not in [run]: `dart_frog dev` calls [run] again on every hot reload, so a
/// listener registered there piles up one copy per reload.
Future<void> init(InternetAddress ip, int port) async {
logRelayEvents(stdout.writeln);
await relayHost.start();
for (final signal in [ProcessSignal.sigint, ProcessSignal.sigterm]) {
signal.watch().listen((_) async {
await relayHost.dispose();
exit(0);
});
}
}
/// Custom entrypoint: serves the handler Dart Frog built.
///
/// The host is already up by now — see [init].
Future<HttpServer> run(Handler handler, InternetAddress ip, int port) {
stdout.writeln('relay ws://${ip.address}:$port/relay');
return serve(handler, ip, port);
}
dart pub add crdt_socket_sync crdt_socket_sync_dart_frog dart_frog
Key points
- Build the host once, outside the routes, and share it with every request: a host per request gives each client an empty room.
- The middleware puts the host in the request context; the route upgrades the request and hands it to the host.
- Start the host before serving, and dispose it on shutdown.
- Clients connect with
WebSocketRelayClientto the route's URL.