A Serverpod server with documents on disk
A Serverpod backend that holds the documents itself: it stores them, merges every change and authenticates the caller before the socket opens.
A Serverpod server with documents on diskSource ↗
A Serverpod web 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.
- bin/main.dart
- lib/src/host.dart
- Install
import 'dart:async';
import 'dart:io';
import 'package:crdt_socket_sync_serverpod/sync.dart';
import 'package:crdt_socket_sync_serverpod_example/src/host.dart';
import 'package:crdt_socket_sync_serverpod_example/src/server_protocol.dart';
import 'package:serverpod/serverpod.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`.
/// 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.
class ExampleSyncRoute extends CrdtSyncRoute {
ExampleSyncRoute(super.sessionHost);
FutureOr<Result> handleCall(Session session, Request request) {
if (request.url.queryParameters['token'] != exampleToken) {
return Response.unauthorized();
}
return super.handleCall(session, request);
}
}
ServerConfig _serverConfig(int port) {
return ServerConfig(
port: port,
publicScheme: 'http',
publicHost: 'localhost',
publicPort: port,
);
}
/// Serves the host of [example] on `/sync` of the web server at [webPort],
/// and disposes it when the pod shuts down. The API server, at [apiPort], has
/// no endpoints in this example.
///
/// Serverpod handles `SIGINT`/`SIGTERM` itself. Its shutdown tasks run after
/// the web server has stopped, so no new client arrives while the host
/// closes; with a durable registry that is what flushes the writes still
/// waiting.
Future<Serverpod> startServer(
List<String> args,
ExampleHost example, {
int webPort = 8080,
int apiPort = 8081,
}) async {
final pod = Serverpod(
args,
// Local to this example: a real project passes its own generated
// `Protocol()` and `Endpoints()`.
EmptyProtocol(),
NoEndpoints(),
config: ServerpodConfig(
apiServer: _serverConfig(apiPort),
webServer: _serverConfig(webPort),
),
);
pod.webServer.addRoute(ExampleSyncRoute(example.host), '/sync');
pod.experimental.shutdownTasks.addTask('crdt sync host', () async {
await example.dispose();
stdout.writeln('[sync] host disposed');
});
await example.host.start();
await pod.start();
return pod;
}
/// Where the Hive database lives, relative to the working directory.
const _dbPath = 'db';
/// Opens the host and serves it.
Future<void> main(List<String> args) async {
final example = await ExampleHost.open(dbPath: _dbPath);
example.logEvents(stdout.writeln);
final pod = await startServer(args, example);
stdout.writeln(
'sync ws://localhost:${pod.webServer.port}/sync ($exampleDocumentId)',
);
}
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;
/// A [DocumentSessionHost] whose documents live in Hive.
///
/// The host has no socket of its own: the Serverpod route 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. Open one per process and share it with every request: a host
/// per request would give each client its own empty document.
class ExampleHost {
ExampleHost._({
required this._backend,
required PersistentServerRegistry registry,
}) : 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();
}
}
dart pub add crdt_lf_hive crdt_socket_sync crdt_socket_sync_serverpod hive \
serverpod
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.- Authenticate in the route, before the upgrade: a refused caller gets 401 and never reaches the protocol.
- The token travels in the query of the URL:
WebSocketClientsends no headers, and a browser cannot set them on a WebSocket. - A real project passes its own generated
Protocol()andEndpoints()toServerpod. - A browser client served from another origin is refused (403) unless the route accepts it: see
allowAnyOrigin.