A relay in a Serverpod backend
Add a relay to a Serverpod backend you already have: one route on its web server.
A relay in a Serverpod backendSource ↗
A Serverpod web route that serves a relay: any document id is a room, with no setup. The rooms live in memory.
- bin/main.dart
- lib/src/host.dart
- Install
import 'dart:io';
import 'package:crdt_socket_sync_serverpod/relay.dart';
import 'package:crdt_socket_sync_serverpod_relay_example/src/host.dart';
import 'package:crdt_socket_sync_serverpod_relay_example/src/server_protocol.dart';
import 'package:serverpod/serverpod.dart';
ServerConfig _serverConfig(int port) {
return ServerConfig(
port: port,
publicScheme: 'http',
publicHost: 'localhost',
publicPort: port,
);
}
/// Starts the relay host, serves it on `/relay` 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.
///
/// Relay mode: the server rebroadcasts opaque CRDT blobs to the other clients
/// of a room and persists them, without ever reading them. The room is the
/// document id inside the hello frame, not part of the path.
///
/// Serverpod handles `SIGINT`/`SIGTERM` itself. Its shutdown tasks run after
/// the web server has stopped, so no new client arrives while the host closes.
/// To authenticate, subclass [CrdtRelayRoute] the way `../example` does.
Future<Serverpod> startServer(
List<String> args, {
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(CrdtRelayRoute(relayHost), '/relay');
pod.experimental.shutdownTasks.addTask('crdt relay host', () async {
await relayHost.dispose();
stdout.writeln('[relay] host disposed');
});
await relayHost.start();
await pod.start();
return pod;
}
Future<void> main(List<String> args) async {
logRelayEvents(stdout.writeln);
final pod = await startServer(args);
stdout.writeln('relay ws://localhost:${pod.webServer.port}/relay');
}
import 'package:crdt_socket_sync/relay_server.dart';
/// The relay host for this process.
///
/// 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: the Serverpod route 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}'),
);
}
dart pub add crdt_socket_sync crdt_socket_sync_serverpod serverpod
Key points
- The route lives on the web server of Serverpod, not on its API server: clients connect to the web server's port.
- A real project passes its own generated
Protocol()andEndpoints()toServerpod. - Dispose the host in a shutdown task, so the pod closes the sessions on its way down.
- Clients connect with
WebSocketRelayClientto the route's URL. - A browser client served from another origin is refused (403) unless the route accepts it: see
allowAnyOrigin.