A Dart Frog server with documents on disk
A Dart Frog backend that holds the documents itself: it stores them, merges every change and checks the caller before the socket opens.
A Dart Frog server with documents on diskSource ↗
A Dart Frog route in server–client mode: the server holds the documents, stores them with Hive, and refuses a caller without the token before the WebSocket opens.
- lib/src/host.dart
- routes/_middleware.dart
- routes/sync.dart
- main.dart
- Install
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 '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';
/// Puts the host in the context, under the type `context.read` matches on.
///
/// The host is opened once by `init()` in `main.dart`; this only hands the
/// same instance to every request.
Handler middleware(Handler handler) {
return handler.use(crdtSyncHostProvider(example.host));
}
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);
}
import 'dart:io';
import 'package:crdt_socket_sync_dart_frog_example/src/host.dart';
import 'package:dart_frog/dart_frog.dart';
/// Where the Hive database lives, relative to the project directory
/// `dart_frog dev` runs in.
const _dbPath = 'db';
/// Custom init: runs once, before Dart Frog builds the handler tree.
///
/// Opens the database, starts the host and disposes it on `SIGINT`/`SIGTERM`.
/// Dart Frog has no shutdown hook, so the signals are where an orderly
/// teardown goes; with a durable registry that is what flushes the writes
/// still waiting.
///
/// 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 {
example = await ExampleHost.open(dbPath: _dbPath);
example.logEvents(stdout.writeln);
await example.host.start();
for (final signal in [ProcessSignal.sigint, ProcessSignal.sigterm]) {
signal.watch().listen((_) async {
await example.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('sync ws://${ip.address}:$port/sync ($exampleDocumentId)');
return serve(handler, ip, port);
}
dart pub add crdt_lf_hive crdt_socket_sync crdt_socket_sync_dart_frog \
dart_frog hive
Key points
- The server serves only the documents its registry holds: create them before a client asks.
PersistentServerRegistrykeeps the documents on disk, and compacts them on a threshold.- A route sees the request before the socket opens: check the caller there, and answer 401 before the upgrade.
- The token travels in the query of the URL:
WebSocketClientsends no headers, and a browser cannot set them on a WebSocket. - Dispose the host on shutdown: that is where the writes still waiting are flushed.