Skip to main content

Server frameworks

The sync protocol runs inside the backend you already have. An adapter gives your framework a ready-made endpoint for each mode; the framework keeps routing, authentication and deployment. Clients connect with the plain WebSocketClient / WebSocketRelayClient of crdt_socket_sync.

Dart FrogServerpod
Packagecrdt_socket_sync_dart_frogcrdt_socket_sync_serverpod
Server–client endpointcrdtSyncWebSocketHandler (+ crdtSyncHostProvider)CrdtSyncRoute
Relay endpointcrdtRelayWebSocketHandler (+ crdtRelayHostProvider)CrdtRelayRoute
Framework docsdart-frog.devdocs.serverpod.dev

Each endpoint serves a session host: RelaySessionHost for the relay, DocumentSessionHost for the server–client mode. The host keeps the rooms, the sessions and the broadcasting; the endpoint only hands it the sockets (see Custom transport).

Install​

dart pub add crdt_socket_sync crdt_socket_sync_dart_frog
// Server–client mode: crdtSyncWebSocketHandler, crdtSyncHostProvider,
// DocumentSessionHost
import 'package:crdt_socket_sync_dart_frog/sync.dart';

// Relay mode: crdtRelayWebSocketHandler, crdtRelayHostProvider,
// RelaySessionHost
import 'package:crdt_socket_sync_dart_frog/relay.dart';

Relay mode​

The host, built once and shared by every request:

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());

The middleware puts it in the request context, and the route hands it the socket:

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);
}

Clients connect with WebSocketRelayClient, pointed at ws://localhost:8080/relay. The complete backends are the recipes Dart Frog: relay and Serverpod: relay.

Server–client mode​

The server serves only the documents its registry holds, so the host creates them before a client asks. For anything that must survive a restart, use a PersistentServerRegistry on one of the storage adapters, as below with Hive: see Server registry.

import 'package:crdt_lf_hive/crdt_lf_hive.dart';
import 'package:crdt_socket_sync/server.dart';
import 'package:hive/hive.dart';

/// The document the route serves.
///
/// In this mode the server holds the documents, so it has to be told which
/// ones exist before a client may handshake against one. A real backend would
/// create them from whatever owns that decision.
const exampleDocumentId = 'example-document';

/// Snapshot a document once its log passes this many changes.
const _compactAfter = 20;

/// The host for this process.
///
/// Set by `init()` in `main.dart`, which Dart Frog awaits before it builds the
/// handler tree — so `_middleware.dart` finds it ready. One instance per
/// process, shared by every request: a host per request would give each
/// client its own empty document.
late final ExampleHost example;

/// A [DocumentSessionHost] whose documents live in Hive.
///
/// The host has no socket of its own — Dart Frog upgrades the requests and
/// hands them over. [PersistentServerRegistry] does the storing; this class
/// only says where (a Hive database in a directory) and owns the lifecycle.
class ExampleHost {
ExampleHost._({
required CRDTHiveBackend backend,
required PersistentServerRegistry registry,
}) : _backend = backend,
host = DocumentSessionHost(serverRegistry: registry);

/// Opens the Hive database in [dbPath] and makes sure [exampleDocumentId]
/// exists. The host is left for the caller to start, so it can subscribe to
/// [DocumentSessionHost.serverEvents] first.
///
/// A second call with the same [dbPath] finds the document and its history
/// again: that is the persistence.
static Future<ExampleHost> open({required String dbPath}) async {
Hive.init(dbPath);
_registerAdapters();

final backend = await CRDTHive.open();
final registry = PersistentServerRegistry(
backend: backend,
compactAfter: _compactAfter,
);
if (!await registry.hasDocument(exampleDocumentId)) {
await registry.addDocument(exampleDocumentId);
}

return ExampleHost._(backend: backend, registry: registry);
}

static bool _adaptersRegistered = false;

// Hive throws on a type id registered twice, and `open` runs more than once
// in the tests.
static void _registerAdapters() {
if (_adaptersRegistered) {
return;
}
CRDTHive.initialize();
_adaptersRegistered = true;
}

final CRDTHiveBackend _backend;

/// The CRDT-aware host behind `/sync`.
final DocumentSessionHost host;

/// Sends every server event to [log], so the console shows what the
/// protocol is doing. A real backend would use its logger.
void logEvents(void Function(String line) log) {
host.serverEvents.listen((e) => log('[sync] ${e.type.name}: ${e.message}'));
}

/// Closes the open sessions, then the registry and the database under it.
///
/// The registry is closed by [DocumentSessionHost.dispose]: that is where
/// the writes still waiting are flushed, so a backend that skips this loses
/// data on shutdown. Every Hive box is closed after it — the backend closes
/// only its own, and the box the identities share stays open otherwise.
Future<void> dispose() async {
await host.dispose();
await _backend.close();
await CRDTHive.closeAllBoxes();
}
}
import 'dart:io';

import 'package:crdt_socket_sync_dart_frog/sync.dart';
import 'package:crdt_socket_sync_dart_frog_example/src/host.dart';
import 'package:dart_frog/dart_frog.dart';

/// The token a client sends. Replace it with a real check.
const exampleToken = 'example-token';

/// Server–client mode: the server holds the document, validates the changes
/// and takes aligned snapshots.
///
/// Connect with `WebSocketClient` at
/// `ws://localhost:8080/sync?token=example-token`, using [exampleDocumentId]:
/// the handshake is refused for a document the registry does not have.
///
/// The token travels in the query: `WebSocketClient` sends no headers, and a
/// browser cannot set them on a WebSocket. A caller without the token gets an
/// ordinary 401 and never reaches the protocol.
Future<Response> onRequest(RequestContext context) async {
final token = context.request.uri.queryParameters['token'];
if (token != exampleToken) {
return Response(statusCode: HttpStatus.unauthorized);
}

return crdtSyncWebSocketHandler(context.read<DocumentSessionHost>())(context);
}

A durable registry is opened asynchronously, so open it in Dart Frog's init() (see Lifecycle) and keep it in a top-level late final.

The complete backends are the recipes Dart Frog: server and Serverpod: server.

Authenticating before the upgrade​

Check the request first, and upgrade only when the check passes. A rejected client gets a plain 401 and never reaches the protocol.

The handler is a value, so call it only after the check:

Future<Response> onRequest(RequestContext context) async {
final token = context.request.headers['authorization'];
if (!await isAuthorized(token)) {
return Response(statusCode: HttpStatus.unauthorized);
}
return crdtSyncWebSocketHandler(context.read<DocumentSessionHost>())(context);
}
Clients send no headers

WebSocketClient sends no headers, and browsers cannot set them on a WebSocket. Send the key in a query parameter or a cookie, and check it yourself before the upgrade: the server recipes read a token query parameter.

Lifecycle​

Build the host once, outside the request. A host per request would give every client its own empty room.

start() is optional: a host with no transport of its own starts on its first connection. dispose() closes the open sessions and, in server–client mode, the registry under them. For a durable registry that is where pending writes are flushed, so skipping it loses data. A RelayStore has no close: a durable one is yours to close after dispose().

Dart Frog has no shutdown hook, so signals are the place for it. Start the host from a custom init method: init() runs once, before the handler tree is built. The custom entrypoint run() is called again on every hot reload, so a listener registered there would pile up.

// main.dart
import 'dart:io';

import 'package:dart_frog/dart_frog.dart';

Future<void> init(InternetAddress ip, int port) async {
await relayHost.start();

for (final signal in [ProcessSignal.sigint, ProcessSignal.sigterm]) {
signal.watch().listen((_) async {
await relayHost.dispose();
exit(0);
});
}
}

Gotchas​

  • Handler is ambiguous. crdt_lf exports a CRDT Handler and dart_frog exports a request Handler. In a file that needs both, hide one: import 'package:crdt_lf/crdt_lf.dart' hide Handler;.

For both frameworks:

  • One plugin instance per host. A ServerSyncPlugin binds to the host it is given to, once. Handing the same instance to a second host throws a LateInitializationError far from the line that caused it.
  • A refused connection is closed, not rejected. Once the response is a 101, there is no status code left to send. A host that is stopped or disposed closes the socket instead, and the client sees its stream end.

Examples​

Two runnable servers per framework, one per mode:

Server–client (/sync, Hive, a token check)Relay (/relay, rooms in memory)Run
Dart Frogexample/relay_example/dart_frog dev
Serverpodexample/relay_example/dart run bin/main.dart

The Serverpod examples build the pod without a database and without generated code, to stay small: a real project passes its generated Protocol() and Endpoints().

Greyhound Markdown also runs locally against a Dart Frog or a Serverpod relay server.

Your framework is not here? Open an issue, or put the host on it yourself: see Custom transport.