Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(sync): route document sync through the connection gateway

Wolf Mermelstein9fa8b0d2ca78
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index d300553216..28d244fccb 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -4273,12 +4273,14 @@
"crates/connection_gateway_models",
"crates/cowlike",
"crates/macro_tower_layers",
+ "crates/macro_user_id",
"crates/model-entity",
"crates/workspace-hack"
],
"connection_gateway_models": [
"crates/connection_gateway_models",
"crates/cowlike",
+ "crates/macro_user_id",
"crates/model-entity",
"crates/workspace-hack"
],
@@ -13282,6 +13284,18 @@
"crates/stream",
"crates/workspace-hack"
],
+ "sync_router": [
+ "crates/connection_gateway_models",
+ "crates/cowlike",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_user_id",
+ "crates/model-entity",
+ "crates/workspace-hack",
+ "services/sync-router",
+ "services/sync-service/bebop-schema"
+ ],
"sync_service": [
"crates/macro_sync_service_jwt",
"crates/worker-rs-otel",
diff --git a/Cargo.lock b/Cargo.lock
index 83bc1691a2..f43243fe63 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4897,6 +4897,7 @@ dependencies = [
"model-entity",
"models_bulk_upload",
"opentelemetry",
+ "postcard",
"redis",
"secretsmanager_client",
"serde",
@@ -4937,7 +4938,9 @@ dependencies = [
name = "connection_gateway_models"
version = "0.1.0"
dependencies = [
+ "macro_user_id",
"model-entity",
+ "postcard",
"serde",
"serde_json",
"utoipa",
@@ -19449,6 +19452,29 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "sync_router"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bebop",
+ "connection_gateway_models",
+ "futures",
+ "macro_entrypoint",
+ "macro_env_var",
+ "mockall",
+ "opentelemetry",
+ "postcard",
+ "redis",
+ "sync_service_bebop_schema",
+ "thiserror 2.0.18",
+ "tokio",
+ "tokio-tungstenite 0.28.0",
+ "tracing",
+ "tracing-opentelemetry",
+ "workspace-hack",
+]
+
[[package]]
name = "sync_service"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index f8879db36f..f58b267c89 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -174,6 +174,7 @@ members = [
"services/sha_cleanup_worker",
"services/slack_import_worker",
"services/static_file_service",
+ "services/sync-router",
"services/sync-service",
"services/sync-service/bebop-schema",
"services/unfurl_service",
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 3e46c235e0..c4e2b63384 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -206,6 +206,12 @@ export const ENABLE_SCRIPTING = defineFlag({
default: false,
}).enabled;
+// Multiplex document sync over the connection gateway.
+export const SYNC_VIA_GATEWAY = defineFlag({
+ env: 'SYNC_VIA_GATEWAY',
+ default: true,
+}).enabled;
+
export const ENABLE_PDF_MULTISPLIT = defineFlag({
env: 'ENABLE_PDF_MULTISPLIT',
default: true,
diff --git a/apps/web/src/lib/service-clients/service-connection/websocket-url.ts b/apps/web/src/lib/service-clients/service-connection/websocket-url.ts
new file mode 100644
index 0000000000..6c12247938
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-connection/websocket-url.ts
@@ -0,0 +1,17 @@
+import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';
+import { SERVER_HOSTS } from '@core/constant/servers';
+import { fetchToken } from '@core/util/fetchWithToken';
+import { getMacroApiToken } from '@service-auth/fetch';
+
+/** Resolve gateway credentials without initializing a connection. */
+export async function resolveWsUrl() {
+ const wsHost = SERVER_HOSTS['connection-gateway'];
+ if (ENABLE_BEARER_TOKEN_AUTH) {
+ const apiToken = await getMacroApiToken();
+ if (!apiToken) throw new Error('No Macro API token');
+
+ return `${wsHost}?macro-api-token=${apiToken}`;
+ }
+ await fetchToken();
+ return wsHost;
+}
diff --git a/apps/web/src/lib/service-clients/service-connection/websocket.ts b/apps/web/src/lib/service-clients/service-connection/websocket.ts
index cea45c78bb..1e01b9576f 100644
--- a/apps/web/src/lib/service-clients/service-connection/websocket.ts
+++ b/apps/web/src/lib/service-clients/service-connection/websocket.ts
@@ -1,7 +1,4 @@
import { createBlockEffect, inBlock } from '@core/block';
-import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';
-import { SERVER_HOSTS } from '@core/constant/servers';
-import { fetchToken } from '@core/util/fetchWithToken';
import {
ArrayQueue,
createSocketEffect,
@@ -11,16 +8,14 @@ import {
WebsocketBuilder,
} from '@macro-inc/collaboration/websocket';
import { createWebsocketStateSignal } from '@macro-inc/collaboration/websocket/solid/state-signal';
-import { getMacroApiToken } from '@service-auth/fetch';
import { createCallback } from '@solid-primitives/rootless';
import { createSessionWebsocketTelemetry } from '../session-websocket-telemetry';
import type { ToWebsocketMessage } from './generated/schemas/toWebsocketMessage';
import { instrumentGatewaySocket } from './presence-telemetry';
+import { resolveWsUrl } from './websocket-url';
export { parseWebsocketPayload } from './websocket-payload';
-const wsHost: string = SERVER_HOSTS['connection-gateway'];
-
export type ConnectionGatewayWebsocket = Websocket<
ToWebsocketMessage,
FromWebsocketMessage
@@ -31,17 +26,6 @@ export type FromWebsocketMessage = {
data: any;
};
-async function resolveWsUrl() {
- if (ENABLE_BEARER_TOKEN_AUTH) {
- const apiToken = await getMacroApiToken();
- if (!apiToken) throw new Error('No Macro API token');
-
- return `${wsHost}?macro-api-token=${apiToken}`;
- }
- await fetchToken();
- return wsHost;
-}
-
export const connectionGatewaySessionTelemetry =
createSessionWebsocketTelemetry('connection-gateway', resolveWsUrl);
diff --git a/apps/web/src/lib/service-clients/service-sync/source/helpers.test.ts b/apps/web/src/lib/service-clients/service-sync/source/helpers.test.ts
index 5f2ee41b5f..31fef56618 100644
--- a/apps/web/src/lib/service-clients/service-sync/source/helpers.test.ts
+++ b/apps/web/src/lib/service-clients/service-sync/source/helpers.test.ts
@@ -19,6 +19,10 @@ vi.mock('@block-md/observability', () => ({
vi.mock('@core/constant/servers', () => ({
SYNC_SERVICE_HOSTS: { ws: 'wss://sync.test' },
}));
+vi.mock('@core/constant/featureFlags', () => ({ SYNC_VIA_GATEWAY: false }));
+vi.mock('@service-connection/websocket-url', () => ({
+ resolveWsUrl: () => 'ws://gateway.test',
+}));
vi.mock('@service-storage/client', () => ({ storageServiceClient: {} }));
import {
diff --git a/apps/web/src/lib/service-clients/service-sync/source/helpers.ts b/apps/web/src/lib/service-clients/service-sync/source/helpers.ts
index 4e671cc8df..52deb84635 100644
--- a/apps/web/src/lib/service-clients/service-sync/source/helpers.ts
+++ b/apps/web/src/lib/service-clients/service-sync/source/helpers.ts
@@ -1,4 +1,5 @@
import { resumeDocumentSpan } from '@block-md/observability';
+import { SYNC_VIA_GATEWAY } from '@core/constant/featureFlags';
import { SYNC_SERVICE_HOSTS } from '@core/constant/servers';
import type {
InitialSync,
@@ -6,8 +7,10 @@ import type {
SyncError,
TimeoutError,
} from '@macro-inc/collaboration/collab/source';
+import { GatewaySyncTransport } from '@macro-inc/collaboration/sync-service/gateway';
import {
createSyncSocket,
+ type SyncSocket,
type SyncWebsocket,
} from '@macro-inc/collaboration/sync-service/socket';
import {
@@ -16,6 +19,7 @@ import {
} from '@macro-inc/collaboration/sync-service/source';
import type { UrlResolver } from '@macro-inc/collaboration/websocket';
import { createWebsocketStateSignal } from '@macro-inc/collaboration/websocket/solid/state-signal';
+import { resolveWsUrl as resolveGatewayWsUrl } from '@service-connection/websocket-url';
import { storageServiceClient } from '@service-storage/client';
import type { ResultAsync } from 'neverthrow';
import type { DocumentSyncAuthorization } from './authorization';
@@ -103,6 +107,21 @@ export function createSyncServiceSocket(
);
}
+let gatewayTransport: GatewaySyncTransport | undefined;
+function syncGatewayTransport(): GatewaySyncTransport {
+ gatewayTransport ??= new GatewaySyncTransport(resolveGatewayWsUrl);
+ return gatewayTransport;
+}
+
+async function refreshPermissionToken(documentId: string): Promise<string> {
+ const response =
+ await storageServiceClient.permissionsTokens.createPermissionToken({
+ document_id: documentId,
+ });
+ if (response.isErr()) throw new Error('Unable to authorize sync connection');
+ return response.value.token;
+}
+
export const createSyncServiceSource = (
documentId: string,
token: string | undefined,
@@ -111,7 +130,13 @@ export const createSyncServiceSource = (
source: LiveSyncSource;
doInitialSync: () => ResultAsync<InitialSync, SyncError>;
} => {
- const ws = createSyncServiceSocket(documentId, token, authorization);
+ const ws: SyncSocket = SYNC_VIA_GATEWAY
+ ? syncGatewayTransport().attach(
+ documentId,
+ authorization ? undefined : token,
+ authorization?.getToken ?? (() => refreshPermissionToken(documentId))
+ )
+ : createSyncServiceSocket(documentId, token, authorization);
const state = createWebsocketStateSignal(ws);
const source = new SyncServiceSource(ws, documentId, {
status: () => mapToSyncStatus(state()),
diff --git a/crates/connection_gateway_models/Cargo.toml b/crates/connection_gateway_models/Cargo.toml
index da13111e3c..3ca6ada5df 100644
--- a/crates/connection_gateway_models/Cargo.toml
+++ b/crates/connection_gateway_models/Cargo.toml
@@ -5,8 +5,12 @@ publish = false
version = "0.1.0"
[dependencies]
+macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
serde = { workspace = true }
serde_json = { workspace = true }
utoipa = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+postcard = { workspace = true }
diff --git a/crates/connection_gateway_models/src/fanout.rs b/crates/connection_gateway_models/src/fanout.rs
new file mode 100644
index 0000000000..bbe18b8075
--- /dev/null
+++ b/crates/connection_gateway_models/src/fanout.rs
@@ -0,0 +1,134 @@
+//! Wire types for the gateway's inbound fan-out.
+//!
+//! Every gateway instance republishes its entire client websocket traffic —
+//! connection lifecycle and every frame, text or binary, unparsed — to Redis
+//! on [`INBOUND_CHANNEL`]. Consumer services subscribe and pick out what they
+//! care about (the sync tier consumes binary frames; others may follow). A
+//! consumer replies to a specific connection on that gateway instance's
+//! [`outbound_channel`].
+//!
+//! Encoding on both channels is `postcard`; Redis pub/sub is binary-safe.
+//!
+//! Delivery is fire-and-forget. Consumers detect a dead gateway instance by
+//! its [`FromGateway::Heartbeat`] going quiet, not by any delivery guarantee.
+//! In particular, a crashed gateway never publishes its connections'
+//! [`FromGateway::Disconnected`] — consumers must treat heartbeat silence as
+//! the disconnect of everything that instance held, and must tolerate
+//! duplicate or missing lifecycle messages generally.
+
+#[cfg(test)]
+mod test;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use std::fmt;
+
+/// Boot-unique id of a gateway instance. Minted fresh at gateway startup, so
+/// a restarted instance is a new id and the old one simply goes quiet.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct GatewayId(pub String);
+
+impl fmt::Display for GatewayId {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+// For string literals in tests and constructors at the wire boundary.
+impl From<&str> for GatewayId {
+ fn from(id: &str) -> Self {
+ Self(id.to_string())
+ }
+}
+
+/// Gateway-local id of one websocket connection. Only meaningful together
+/// with the [`GatewayId`] that minted it.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct ConnId(pub String);
+
+impl fmt::Display for ConnId {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+// For string literals in tests and constructors at the wire boundary.
+impl From<&str> for ConnId {
+ fn from(id: &str) -> Self {
+ Self(id.to_string())
+ }
+}
+
+/// Channel every gateway instance publishes its inbound traffic to.
+pub const INBOUND_CHANNEL: &str = "connection_gateway.fanout.inbound";
+
+/// Interval between [`FromGateway::Heartbeat`] messages.
+pub const HEARTBEAT_INTERVAL_SECS: u64 = 5;
+
+/// The per-instance channel consumers reply on. `gateway` is minted fresh at
+/// gateway boot, so a restarted instance is a new peer and the old id simply
+/// goes quiet.
+pub fn outbound_channel(gateway: &GatewayId) -> String {
+ format!("connection_gateway.fanout.outbound.{gateway}")
+}
+
+/// Everything a gateway instance publishes on [`INBOUND_CHANNEL`].
+#[derive(Debug, Serialize, Deserialize)]
+pub enum FromGateway {
+ /// A websocket connection was accepted and its user authenticated.
+ Connected {
+ /// Boot-unique id of the publishing gateway instance.
+ gateway: GatewayId,
+ /// Gateway-local id of the websocket connection.
+ conn: ConnId,
+ /// User the gateway authenticated at the socket edge.
+ user_id: MacroUserIdStr<'static>,
+ },
+ /// One client frame, in per-connection order, unparsed.
+ Frame {
+ /// Boot-unique id of the publishing gateway instance.
+ gateway: GatewayId,
+ /// Gateway-local id of the websocket connection.
+ conn: ConnId,
+ /// Whether the frame was a text websocket message (else binary).
+ text: bool,
+ /// The client's bytes, unparsed.
+ payload: Vec<u8>,
+ },
+ /// The websocket connection closed.
+ Disconnected {
+ /// Boot-unique id of the publishing gateway instance.
+ gateway: GatewayId,
+ /// Gateway-local id of the websocket connection.
+ conn: ConnId,
+ },
+ /// Liveness beacon, published every [`HEARTBEAT_INTERVAL_SECS`].
+ /// Consumers should drop all state for a gateway id that goes quiet.
+ Heartbeat {
+ /// Boot-unique id of the publishing gateway instance.
+ gateway: GatewayId,
+ },
+}
+
+/// Messages a consumer publishes on a gateway's [`outbound_channel`].
+#[derive(Debug, Serialize, Deserialize)]
+pub enum ToGateway {
+ /// Deliver a frame to a connection's websocket.
+ Frame {
+ /// Gateway-local id of the target websocket connection.
+ conn: ConnId,
+ /// Whether to send as a text websocket message (else binary).
+ text: bool,
+ /// The bytes to send, unparsed.
+ payload: Vec<u8>,
+ },
+ /// Close a connection's websocket.
+ Close {
+ /// Gateway-local id of the target websocket connection.
+ conn: ConnId,
+ /// Websocket close code to send.
+ code: u16,
+ },
+}
diff --git a/crates/connection_gateway_models/src/fanout/test.rs b/crates/connection_gateway_models/src/fanout/test.rs
new file mode 100644
index 0000000000..664d46c75b
--- /dev/null
+++ b/crates/connection_gateway_models/src/fanout/test.rs
@@ -0,0 +1,46 @@
+use super::*;
+
+/// The gateway encodes and the sync tier decodes (and vice versa); this pins
+/// the postcard round trip both directions.
+#[test]
+fn from_gateway_round_trips() {
+ let message = FromGateway::Frame {
+ gateway: GatewayId("g-1".into()),
+ conn: ConnId("c-1".into()),
+ text: false,
+ payload: vec![0xff, 0x00, 0x7f],
+ };
+ let bytes = postcard::to_stdvec(&message).unwrap();
+ let decoded: FromGateway = postcard::from_bytes(&bytes).unwrap();
+ match decoded {
+ FromGateway::Frame {
+ gateway,
+ conn,
+ text,
+ payload,
+ } => {
+ assert_eq!(gateway, GatewayId("g-1".into()));
+ assert_eq!(conn, ConnId("c-1".into()));
+ assert!(!text);
+ assert_eq!(payload, vec![0xff, 0x00, 0x7f]);
+ }
+ other => panic!("wrong variant: {other:?}"),
+ }
+}
+
+#[test]
+fn to_gateway_round_trips() {
+ let message = ToGateway::Close {
+ conn: ConnId("c-9".into()),
+ code: 4000,
+ };
+ let bytes = postcard::to_stdvec(&message).unwrap();
+ let decoded: ToGateway = postcard::from_bytes(&bytes).unwrap();
+ match decoded {
+ ToGateway::Close { conn, code } => {
+ assert_eq!(conn, ConnId("c-9".into()));
+ assert_eq!(code, 4000);
+ }
+ other => panic!("wrong variant: {other:?}"),
+ }
+}
diff --git a/crates/connection_gateway_models/src/lib.rs b/crates/connection_gateway_models/src/lib.rs
index 13b39e8898..49d907ae0d 100644
--- a/crates/connection_gateway_models/src/lib.rs
+++ b/crates/connection_gateway_models/src/lib.rs
@@ -1,6 +1,8 @@
#![deny(missing_docs)]
//! Shared types for the connection gateway service and client.
+pub mod fanout;
+
use model_entity::Entity;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml
index 29c1774ff8..8c9e6580c7 100644
--- a/docker/docker-compose.yml
+++ b/docker/docker-compose.yml
@@ -67,6 +67,18 @@ services:
# connection_gateway (Port 8082)
# WebSocket gateway - Redis only
# ============================================================================
+ sync_router:
+ <<: [*common-env, *rust-services-image]
+ command: ["/app/out/sync_router"]
+ environment:
+ - SYNC_SERVICE_URL=http://sync-service:8787
+ depends_on:
+ - redis
+ - sync_service
+ networks:
+ databases:
+ services:
+
connection_gateway:
<<: [*common-env, *rust-services-image]
command: ["/app/out/connection_gateway_service"]
diff --git a/docs/development/running-locally.md b/docs/development/running-locally.md
index 52420053c8..5f0f60a480 100644
--- a/docs/development/running-locally.md
+++ b/docs/development/running-locally.md
@@ -121,7 +121,7 @@ Local authentication includes a working signing key pair for Macro API tokens,
which settings actions such as enabling CRM require. New teams start with CRM
disabled; enable it in Settings > CRM before creating pipelines.
-The stack boots with stubbed values for every config the services require, including the third-party integrations (Google, GitHub, Stripe, CloudFront). Those flows do not work against real services with the stubs. The rest of the stack is fully functional: auth, documents, email, and search.
+The stack supplies stubbed values for required configuration, including third-party integrations (Google, GitHub, Stripe, CloudFront). Those flows do not work against real services with the stubs. Local auth, documents, and search work independently. The agent harness currently also requires a configured Google Gmail identity provider for its public MCP routes; without real Google OAuth configuration, it exits during startup.
To use a real integration locally, supply its keys via `--env-file` — see [Integration Secrets](#integration-secrets) below.
@@ -222,11 +222,12 @@ persona accounts it created. It is safe to run against a stack that you tested i
## Integration Secrets
-A `--no-doppler` stack boots with deterministic stubs for every value the services' config loaders require. The stubs are enough to start the services. The third-party integrations they back do not work until you supply real values:
+A `--no-doppler` stack supplies deterministic stubs for required configuration. External integrations still need real values, and the agent harness additionally needs the Google Gmail identity provider created from real Google OAuth configuration:
| Integration | Keys | Stub behavior |
| --- | --- | --- |
-| Google login / Gmail | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET_KEY` | Google SSO and Gmail inbox linking are unavailable. Local signup still works. The email service reports no Gmail grant and skips inbox syncing. |
+| Google login / Gmail | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET_KEY` | Google SSO and Gmail inbox linking are unavailable. Local signup still works. The email service skips inbox syncing without a Gmail grant. The agent harness cannot start its public MCP routes without the Google Gmail identity provider. |
+| Pipedream | `PIPEDREAM_CLIENT_ID`, `PIPEDREAM_CLIENT_SECRET`, `PIPEDREAM_PROJECT_ID` | Placeholders satisfy the harness configuration loader; Pipedream integrations require real credentials. |
| GitHub login | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_IDP_ID` | Login with GitHub is unavailable |
| Stripe billing | `STRIPE_SECRET_KEY`, `STRIPE_PRICE_ID` | Checkout and subscription endpoints fail. Signup skips Stripe and leaves profile billing unset, so free-team creation works. Only the required legacy account field stores a local placeholder. |
| CloudFront signed URLs | `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`, `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`, `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY` | Document download URLs are unsigned (fine against local S3) |
@@ -447,6 +448,11 @@ If you started without the flag and suspect a stale image, press `q`. Then start
`just stack` runs the same stack without an attached terminal. There is no hotkey loop and no dev server. The frontend is built once and served statically by the proxy. The whole product lives behind one origin. A finished `up` leaves only Docker containers running.
+Both headless and attached startup prepare the browser WebAssembly packages
+through `bun run dev:prepare`. A fresh worktree builds them before serving the app;
+later starts reuse the generated packages when they are current. See
+[Integration Secrets](#integration-secrets) for credential-free startup limitations.
+
```bash
just stack up # bring everything up, print URLs, return
just stack status --json # machine-readable state (containers, health, URLs)
diff --git a/packages/collaboration/src/sync-service/gateway.test.ts b/packages/collaboration/src/sync-service/gateway.test.ts
new file mode 100644
index 0000000000..e06e566649
--- /dev/null
+++ b/packages/collaboration/src/sync-service/gateway.test.ts
@@ -0,0 +1,154 @@
+import { once } from 'node:events';
+import type { AddressInfo } from 'node:net';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { type WebSocket, WebSocketServer } from 'ws';
+import { WebsocketEvent } from '../websocket';
+import { intoFrames, Reassembler } from '../websocket/platform/framing';
+import { GatewaySyncTransport } from './gateway';
+import { FromPeer, FromRemote, FromRouter, ToRouter } from './generated/schema';
+import type { SyncSocket } from './socket';
+
+describe('gateway document transport', () => {
+ let server: WebSocketServer;
+ let transport: GatewaySyncTransport;
+ let peer: WebSocket;
+ let received: ToRouter[];
+ let sockets: SyncSocket[];
+
+ beforeEach(async () => {
+ received = [];
+ sockets = [];
+ server = new WebSocketServer({ port: 0 });
+ await once(server, 'listening');
+ server.on('connection', (socket) => {
+ peer = socket;
+ socket.on('message', (bytes) => {
+ received.push(ToRouter.decode(new Uint8Array(bytes as Buffer)));
+ });
+ });
+ const port = (server.address() as AddressInfo).port;
+ transport = new GatewaySyncTransport(`ws://127.0.0.1:${port}`);
+ });
+
+ afterEach(async () => {
+ for (const socket of sockets) socket.close();
+ transport.socket().close();
+ for (const client of server.clients) client.terminate();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ function attach(
+ id: string,
+ token: string | undefined,
+ refresh = async () => 'fresh'
+ ) {
+ const socket = transport.attach(id, token, refresh);
+ sockets.push(socket);
+ return socket;
+ }
+
+ async function subscribed(id: string) {
+ await vi.waitFor(() =>
+ expect(
+ received.some(
+ (message) => message.isRouterSubscribe() && message.value.docId === id
+ )
+ ).toBe(true)
+ );
+ peer.send(
+ FromRouter.encode(FromRouter.fromRouterSubscribed({ docId: id }))
+ );
+ }
+
+ test('multiplexes documents and reassembles their interleaved downstream chunks', async () => {
+ const a = attach('a', 'token');
+ const b = attach('b', 'token');
+ const seenA: FromRemote[] = [];
+ const seenB: FromRemote[] = [];
+ a.addEventListener(WebsocketEvent.Message, (_, event) =>
+ seenA.push(event.data)
+ );
+ b.addEventListener(WebsocketEvent.Message, (_, event) =>
+ seenB.push(event.data)
+ );
+ await subscribed('a');
+ await subscribed('b');
+ const message = FromRemote.fromRemoteSnapshot({
+ snapshot: new Uint8Array([4, 5, 6]),
+ });
+ for (const payload of intoFrames(FromRemote.encode(message), 3)) {
+ for (const docId of ['a', 'b']) {
+ peer.send(
+ FromRouter.encode(FromRouter.fromRouterDocFrame({ docId, payload }))
+ );
+ }
+ }
+ await vi.waitFor(() => {
+ expect(seenA).toHaveLength(1);
+ expect(seenB).toHaveLength(1);
+ });
+ expect(seenA[0]).toEqual(message);
+ expect(seenB[0]).toEqual(message);
+ expect(server.clients.size).toBe(1);
+ });
+
+ test('waits for fresh authorization and subscription before sending framed edits', async () => {
+ const grant = Promise.withResolvers<string>();
+ const socket = attach('doc', undefined, () => grant.promise);
+ const update = FromPeer.fromPeerUpdate({
+ id: 'edit',
+ updates: [new Uint8Array(900_010)],
+ });
+ socket.send(update);
+ expect(received).toEqual([]);
+ grant.resolve('fresh-grant');
+ await vi.waitFor(() => expect(received).toHaveLength(1));
+ expect(received[0]).toEqual(
+ ToRouter.fromRouterSubscribe({ docId: 'doc', token: 'fresh-grant' })
+ );
+ await subscribed('doc');
+ await vi.waitFor(() => expect(received).toHaveLength(3));
+ const reassembler = new Reassembler();
+ let complete: Uint8Array | null = null;
+ for (const message of received.slice(1)) {
+ expect(message.isRouterFrame()).toBe(true);
+ if (message.isRouterFrame())
+ complete = reassembler.push(message.value.payload);
+ }
+ expect(complete).not.toBeNull();
+ const decoded = FromPeer.decode(complete!);
+ expect(decoded.isPeerUpdate()).toBe(true);
+ if (decoded.isPeerUpdate()) {
+ expect(decoded.value.id).toBe('edit');
+ expect(decoded.value.updates).toHaveLength(1);
+ expect(
+ Buffer.from(decoded.value.updates[0]).equals(Buffer.alloc(900_010))
+ ).toBe(true);
+ }
+ });
+
+ test('retries a failed initial token refresh', async () => {
+ const refresh = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValue('fresh');
+ attach('doc', undefined, refresh);
+ await vi.waitFor(() => expect(received).toHaveLength(1), {
+ timeout: 2_000,
+ });
+ expect(refresh).toHaveBeenCalledTimes(2);
+ expect(received[0]).toEqual(
+ ToRouter.fromRouterSubscribe({ docId: 'doc', token: 'fresh' })
+ );
+ });
+
+ test('does not subscribe after the document is disposed during authorization', async () => {
+ const grant = Promise.withResolvers<string>();
+ const socket = attach('doc', undefined, () => grant.promise);
+ socket.close();
+ grant.resolve('stale');
+ await grant.promise;
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(received).toEqual([]);
+ });
+});
diff --git a/packages/collaboration/src/sync-service/gateway.ts b/packages/collaboration/src/sync-service/gateway.ts
new file mode 100644
index 0000000000..b19965d3f4
--- /dev/null
+++ b/packages/collaboration/src/sync-service/gateway.ts
@@ -0,0 +1,403 @@
+import { match } from 'ts-pattern';
+import {
+ ArrayQueue,
+ BebopSerializer,
+ ExponentialBackoff,
+ type UrlResolver,
+ type Websocket,
+ WebsocketBuilder,
+ WebsocketConnectionState,
+ WebsocketEvent,
+ type WebsocketEventListener,
+} from '../websocket';
+import { intoFrames, Reassembler } from '../websocket/platform/framing';
+import {
+ FromPeer,
+ FromRemote,
+ FromRouter,
+ type IFromPeer,
+ type IToRouter,
+ ToRouter,
+} from './generated/schema';
+import type { SyncSocket } from './socket';
+
+/**
+ * Multiplexes many documents' sync traffic over ONE websocket to the
+ * connection gateway, instead of one direct sync-service socket per document.
+ *
+ * Wire shape: every frame is a Bebop `ToRouter`/`FromRouter` envelope naming
+ * the document; the inner payloads are the same `FromPeer`/`FromRemote`
+ * messages the direct socket speaks, unchanged. Server side, the
+ * connection-gateway fans inbound frames out to the sync-router, which holds
+ * one upstream connection per (socket, document).
+ *
+ * Each document gets a {@link SyncSocket}-compatible virtual socket, so
+ * `SyncServiceSource` works unmodified on top of this transport.
+ */
+export class GatewaySyncTransport {
+ private readonly getUrl: UrlResolver;
+ private ws: Websocket<IToRouter, FromRouter> | undefined;
+ private readonly docs = new Map<string, VirtualSyncSocket>();
+ private heartbeatStarted = false;
+
+ public constructor(getUrl: UrlResolver) {
+ this.getUrl = getUrl;
+ }
+
+ /**
+ * Attach a document to the shared socket: subscribes immediately and
+ * returns the virtual socket for it. `refreshToken` is consulted on every
+ * re-subscribe (upstream drop, gateway reconnect), mirroring how the direct
+ * socket refetches a permission token per reconnect.
+ */
+ public attach(
+ documentId: string,
+ initialToken: string | undefined,
+ refreshToken: () => Promise<string>
+ ): SyncSocket {
+ const existing = this.docs.get(documentId);
+ if (existing) return existing;
+
+ const virtual = new VirtualSyncSocket(
+ this,
+ documentId,
+ initialToken,
+ refreshToken
+ );
+ this.docs.set(documentId, virtual);
+ virtual.subscribe();
+ return virtual;
+ }
+
+ /** Called by a virtual socket when it is closed for good. */
+ public detach(documentId: string): void {
+ this.docs.delete(documentId);
+ }
+
+ /** The shared gateway websocket, built lazily on first use. */
+ public socket(): Websocket<IToRouter, FromRouter> {
+ if (this.ws) return this.ws;
+ const ws = new WebsocketBuilder<IToRouter, FromRouter>(this.getUrl)
+ .withSerializer(new BebopSerializer(ToRouter, FromRouter))
+ .withBackoff(new ExponentialBackoff(250, 5))
+ .withMaxRetries(20)
+ // Document frames are held by each virtual socket until the router
+ // acknowledges its fresh subscription.
+ .withBuffer(new ArrayQueue())
+ .withHeartbeat({
+ interval: 10_000,
+ timeout: 5_000,
+ pingMessage: 'ping',
+ pongMessage: 'pong',
+ maxMissedHeartbeats: 2,
+ autoStart: false,
+ })
+ .build();
+
+ ws.addEventListener(WebsocketEvent.Message, (_ws, event) => {
+ this.route(event.data);
+ });
+ ws.addEventListener(WebsocketEvent.Reconnect, () => {
+ // A new gateway socket is a new fanout connection server-side: every
+ // route was torn down, so every document must re-subscribe.
+ for (const virtual of this.docs.values()) virtual.resubscribe();
+ });
+ ws.addEventListener(WebsocketEvent.Close, (_ws, event) => {
+ for (const virtual of this.docs.values()) virtual.onGatewayClose(event);
+ });
+ ws.addEventListener(WebsocketEvent.HeartbeatMissed, (_ws, event) => {
+ for (const virtual of this.docs.values()) {
+ virtual.onGatewayHeartbeatMissed(event);
+ }
+ });
+
+ this.ws = ws;
+ return ws;
+ }
+
+ /** Start the shared heartbeat once any document finishes its initial sync. */
+ public startHeartbeat(): void {
+ if (this.heartbeatStarted) return;
+ this.heartbeatStarted = true;
+ this.socket().startHeartbeat();
+ }
+
+ private route(message: FromRouter): void {
+ const documentId = message.value.docId;
+ const virtual = this.docs.get(documentId);
+ if (!virtual) return;
+ if (message.isRouterSubscribed()) {
+ virtual.onSubscribed();
+ } else if (message.isRouterDocFrame()) {
+ virtual.onDocFrame(message.value.payload);
+ } else if (message.isRouterSubscribeFailed()) {
+ virtual.onDocClosed(4401, message.value.reason);
+ } else if (message.isRouterDocClosed()) {
+ virtual.onDocClosed(4000, message.value.reason);
+ }
+ }
+}
+
+type ListenerSets = {
+ [K in WebsocketEvent]?: Set<WebsocketEventListener<K, IFromPeer, FromRemote>>;
+};
+
+/** Backoff for per-document re-subscribes after an upstream drop. */
+const RESUBSCRIBE_BASE_MS = 500;
+const RESUBSCRIBE_MAX_MS = 8_000;
+
+/**
+ * A {@link SyncSocket} for one document, riding the shared gateway socket.
+ *
+ * Lifecycle mapping (virtual event ← gateway/envelope cause):
+ * - Open ← first `RouterSubscribed`
+ * - Message ← `RouterDocFrame` (decoded to `FromRemote`)
+ * - Close ← `RouterSubscribeFailed` / `RouterDocClosed` / gateway close
+ * - Reconnect ← any later `RouterSubscribed` (upstream or gateway recovery)
+ */
+class VirtualSyncSocket implements SyncSocket {
+ private readonly transport: GatewaySyncTransport;
+ private readonly documentId: string;
+ private readonly refreshToken: () => Promise<string>;
+ private initialToken: string | undefined;
+ private reassembler = new Reassembler();
+ private subscriptionAttempt = 0;
+
+ private readonly listeners: ListenerSets = {};
+ private state: 'subscribing' | 'open' | 'dropped' | 'closed' = 'subscribing';
+ private wasEverOpen = false;
+ private resubscribeTimer: ReturnType<typeof setTimeout> | undefined;
+ private resubscribeDelay = RESUBSCRIBE_BASE_MS;
+ /** Frames sent while dropped, flushed after the next Subscribe. */
+ private pending: IFromPeer[] = [];
+
+ public constructor(
+ transport: GatewaySyncTransport,
+ documentId: string,
+ initialToken: string | undefined,
+ refreshToken: () => Promise<string>
+ ) {
+ this.transport = transport;
+ this.documentId = documentId;
+ this.initialToken = initialToken;
+ this.refreshToken = refreshToken;
+ }
+
+ public get connectionState(): WebsocketConnectionState {
+ const gateway = this.transport.socket().connectionState;
+ if (gateway !== WebsocketConnectionState.Open) return gateway;
+ return match(this.state)
+ .with('open', () => WebsocketConnectionState.Open)
+ .with('subscribing', () => WebsocketConnectionState.Connecting)
+ .with('dropped', () => WebsocketConnectionState.Reconnecting)
+ .with('closed', () => WebsocketConnectionState.Closed)
+ .exhaustive();
+ }
+
+ public send(message: IFromPeer): boolean {
+ if (this.state === 'closed') return false;
+ if (this.state !== 'open') {
+ // Hold edits until fresh authorization and the downstream handshake
+ // complete. This also prevents stale frames overtaking a resubscribe.
+ this.pending.push(message);
+ return true;
+ }
+ return this.sendFrame(message);
+ }
+
+ public startHeartbeat(): void {
+ this.transport.startHeartbeat();
+ }
+
+ public reconnectIfDisconnected(): void {
+ this.transport.socket().reconnectIfDisconnected();
+ if (this.state === 'dropped') this.resubscribe();
+ }
+
+ public close(): void {
+ if (this.state === 'closed') return;
+ this.clearResubscribeTimer();
+ if (
+ this.state !== 'dropped' &&
+ this.transport.socket().connectionState === WebsocketConnectionState.Open
+ ) {
+ this.transport
+ .socket()
+ .send(ToRouter.fromRouterUnsubscribe({ docId: this.documentId }));
+ }
+ this.state = 'closed';
+ this.subscriptionAttempt++;
+ this.pending = [];
+ this.transport.detach(this.documentId);
+ }
+
+ public addEventListener<K extends WebsocketEvent>(
+ type: K,
+ listener: WebsocketEventListener<K, IFromPeer, FromRemote>
+ ): void {
+ // The per-key generic can't be proven against the mapped type; the
+ // add/dispatch pair keeps K consistent.
+ let listeners = this.listeners[type] as unknown as
+ | Set<WebsocketEventListener<K, IFromPeer, FromRemote>>
+ | undefined;
+ if (!listeners) {
+ listeners = new Set();
+ (this.listeners as Record<K, unknown>)[type] = listeners;
+ }
+ listeners.add(listener);
+ }
+
+ public removeEventListener<K extends WebsocketEvent>(
+ type: K,
+ listener: WebsocketEventListener<K, IFromPeer, FromRemote>
+ ): void {
+ (
+ this.listeners[type] as unknown as
+ | Set<WebsocketEventListener<K, IFromPeer, FromRemote>>
+ | undefined
+ )?.delete(listener);
+ }
+
+ /** Send `RouterSubscribe`, minting a fresh token when the initial is spent. */
+ public subscribe(): void {
+ if (this.state === 'closed') return;
+ const attempt = ++this.subscriptionAttempt;
+ this.state = 'subscribing';
+ void this.authorizeSubscription(attempt);
+ }
+
+ private async authorizeSubscription(attempt: number): Promise<void> {
+ const initial = this.initialToken;
+ this.initialToken = undefined;
+ try {
+ const token = initial ?? (await this.refreshToken());
+ if (this.state === 'closed' || attempt !== this.subscriptionAttempt)
+ return;
+ this.transport
+ .socket()
+ .send(ToRouter.fromRouterSubscribe({ docId: this.documentId, token }));
+ } catch {
+ if (this.state === 'closed' || attempt !== this.subscriptionAttempt)
+ return;
+ this.state = 'dropped';
+ this.scheduleResubscribe();
+ }
+ }
+
+ public resubscribe(): void {
+ this.clearResubscribeTimer();
+ this.subscribe();
+ }
+
+ public onSubscribed(): void {
+ const reconnected = this.wasEverOpen;
+ this.state = 'open';
+ this.reassembler = new Reassembler();
+ const pending = this.pending.splice(0);
+ for (const message of pending) this.sendFrame(message);
+ this.wasEverOpen = true;
+ this.resubscribeDelay = RESUBSCRIBE_BASE_MS;
+ // Mirror the concrete Websocket's ordering: Reconnect (when applicable)
+ // and then Open, so state signals settle on Open.
+ if (reconnected) {
+ this.dispatch(
+ WebsocketEvent.Reconnect,
+ new CustomEvent(WebsocketEvent.Reconnect, {
+ detail: { retries: 0, lastConnection: undefined, url: 'gateway' },
+ })
+ );
+ }
+ this.dispatch(WebsocketEvent.Open, new Event(WebsocketEvent.Open));
+ }
+
+ public onDocFrame(payload: Uint8Array): void {
+ const complete = this.reassembler.push(payload);
+ if (!complete) return;
+ const message = FromRemote.decode(complete);
+ this.dispatch(
+ WebsocketEvent.Message,
+ new MessageEvent(WebsocketEvent.Message, { data: message })
+ );
+ }
+
+ public onDocClosed(code: number, reason: string): void {
+ if (this.state === 'closed') return;
+ this.state = 'dropped';
+ this.subscriptionAttempt++;
+ this.reassembler = new Reassembler();
+ this.dispatch(
+ WebsocketEvent.Close,
+ new CloseEvent(WebsocketEvent.Close, { code, reason, wasClean: false })
+ );
+ this.scheduleResubscribe();
+ }
+
+ public onGatewayClose(event: CloseEvent): void {
+ if (this.state === 'closed') return;
+ // The gateway socket owns reconnection; we just report the drop and wait
+ // for the transport's Reconnect handler to re-subscribe us.
+ this.clearResubscribeTimer();
+ this.state = 'dropped';
+ this.subscriptionAttempt++;
+ this.reassembler = new Reassembler();
+ this.dispatch(WebsocketEvent.Close, event);
+ }
+
+ public onGatewayHeartbeatMissed(
+ event: CustomEvent<{ missedHeartbeats: number; willReconnect: boolean }>
+ ): void {
+ this.dispatch(
+ WebsocketEvent.HeartbeatMissed,
+ event as Parameters<
+ WebsocketEventListener<
+ WebsocketEvent.HeartbeatMissed,
+ IFromPeer,
+ FromRemote
+ >
+ >[1]
+ );
+ }
+
+ private sendFrame(message: IFromPeer): boolean {
+ for (const payload of intoFrames(FromPeer.encode(message))) {
+ if (
+ !this.transport
+ .socket()
+ .send(ToRouter.fromRouterFrame({ docId: this.documentId, payload }))
+ )
+ return false;
+ }
+ return true;
+ }
+
+ private scheduleResubscribe(): void {
+ if (this.state === 'closed' || this.resubscribeTimer) return;
+ const delay = this.resubscribeDelay;
+ this.resubscribeDelay = Math.min(delay * 2, RESUBSCRIBE_MAX_MS);
+ this.resubscribeTimer = setTimeout(() => {
+ this.resubscribeTimer = undefined;
+ if (this.state === 'dropped') this.subscribe();
+ }, delay);
+ }
+
+ private clearResubscribeTimer(): void {
+ if (this.resubscribeTimer) {
+ clearTimeout(this.resubscribeTimer);
+ this.resubscribeTimer = undefined;
+ }
+ }
+
+ private dispatch<K extends WebsocketEvent>(
+ type: K,
+ event: Parameters<WebsocketEventListener<K, IFromPeer, FromRemote>>[1]
+ ): void {
+ const listeners = this.listeners[type] as unknown as
+ | Set<WebsocketEventListener<K, IFromPeer, FromRemote>>
+ | undefined;
+ if (!listeners) return;
+ // The listener signature carries the concrete Websocket for convenience;
+ // sources only use the event, so the virtual socket passes itself.
+ const instance = this as unknown as Websocket<IFromPeer, FromRemote>;
+ for (const listener of [...listeners]) listener(instance, event);
+ }
+}
diff --git a/packages/collaboration/src/sync-service/generated/schema.bop b/packages/collaboration/src/sync-service/generated/schema.bop
index 2b2bf47a00..2cc08b4b06 100644
--- a/packages/collaboration/src/sync-service/generated/schema.bop
+++ b/packages/collaboration/src/sync-service/generated/schema.bop
@@ -7,11 +7,10 @@ union FromPeer {
byte[] awareness;
}
3 -> struct PeerRequestSince {
- // We send a version vector instead of frontiers because the client may
- // have local ops the server hasn't received yet (offline edits or
- // unflushed WAL on reconnect). Frontiers would reference those ops
- // directly and `frontiersToVV` would panic on the server. A VV is just
- // per-peer counters — unknown peers are harmless.
+ // We send a version vector instead of a frontier from the client to
+ // request updates. This is because I could make updates while offline,
+ // and then when I request updates I want to request updates up to a
+ // point that doesn't exist on the server.
byte[] vv;
}
4 -> struct PeerRequestSnapshot {}
@@ -56,3 +55,45 @@ struct InitializeFromSnapshotRequest {
byte[] snapshot;
}
+
+/*
+ * Multiplex envelope between the browser and the sync-router (rides the
+ * connection-gateway socket as binary frames). Inner payloads are the
+ * existing FromPeer/FromRemote unions, already bebop-encoded — the router
+ * forwards them without parsing.
+ */
+union ToRouter {
+ 1 -> struct RouterSubscribe {
+ string docId;
+ // DocumentPermissionToken; passed through to the downstream unverified
+ // (the downstream authenticates, exactly as with a direct connection).
+ string token;
+ }
+ 2 -> struct RouterUnsubscribe {
+ string docId;
+ }
+ 3 -> struct RouterFrame {
+ string docId;
+ // A serialized FromPeer, untouched.
+ byte[] payload;
+ }
+}
+
+union FromRouter {
+ 1 -> struct RouterSubscribed {
+ string docId;
+ }
+ 2 -> struct RouterSubscribeFailed {
+ string docId;
+ string reason;
+ }
+ 3 -> struct RouterDocFrame {
+ string docId;
+ // A serialized FromRemote, untouched.
+ byte[] payload;
+ }
+ 4 -> struct RouterDocClosed {
+ string docId;
+ string reason;
+ }
+}
diff --git a/packages/collaboration/src/sync-service/generated/schema.ts b/packages/collaboration/src/sync-service/generated/schema.ts
index 632b3deea0..eb33150f9e 100644
--- a/packages/collaboration/src/sync-service/generated/schema.ts
+++ b/packages/collaboration/src/sync-service/generated/schema.ts
@@ -14,60 +14,95 @@
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
-import {
- BebopJson,
- BebopRecord,
- BebopRuntimeError,
- BebopTypeGuard,
- BebopView,
- Guid,
- GuidMap,
-} from 'bebop';
-
-export const BEBOP_SCHEMA = new Uint8Array([
- 3, 16, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116, 101, 0, 1, 0, 0, 8,
- 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 115, 0, 242, 255, 255, 255, 1,
- 254, 255, 255, 255, 0, 105, 100, 0, 245, 255, 255, 255, 0, 80, 101, 101, 114,
- 65, 119, 97, 114, 101, 110, 101, 115, 115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97,
- 119, 97, 114, 101, 110, 101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255,
- 255, 255, 0, 80, 101, 101, 114, 82, 101, 113, 117, 101, 115, 116, 83, 105,
- 110, 99, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 118, 118, 0, 242, 255, 255, 255,
- 0, 254, 255, 255, 255, 0, 80, 101, 101, 114, 82, 101, 113, 117, 101, 115, 116,
- 83, 110, 97, 112, 115, 104, 111, 116, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 80, 101,
- 101, 114, 82, 101, 103, 105, 115, 116, 101, 114, 73, 100, 0, 1, 0, 0, 8, 0, 0,
- 0, 1, 1, 112, 101, 101, 114, 105, 100, 0, 249, 255, 255, 255, 0, 70, 114, 111,
- 109, 80, 101, 101, 114, 0, 3, 0, 5, 0, 0, 0, 5, 1, 0, 0, 0, 0, 2, 1, 0, 0, 0,
- 3, 2, 0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 82, 101, 109, 111, 116, 101, 73,
- 110, 105, 116, 105, 97, 108, 83, 121, 110, 99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2,
- 115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255, 255, 0, 254, 255,
- 255, 255, 0, 97, 119, 97, 114, 101, 110, 101, 115, 115, 0, 242, 255, 255, 255,
- 0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116,
- 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97, 116, 101, 0, 242, 255,
- 255, 255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116, 101, 65, 119, 97,
- 114, 101, 110, 101, 115, 115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97, 114,
- 101, 110, 101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 82,
- 101, 109, 111, 116, 101, 83, 110, 97, 112, 115, 104, 111, 116, 0, 1, 0, 0, 4,
- 0, 0, 0, 0, 1, 115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255, 255,
- 0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116,
- 101, 65, 99, 107, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 105, 100, 0, 245, 255, 255,
- 255, 0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101, 83, 105, 110,
- 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242,
- 255, 255, 255, 0, 254, 255, 255, 255, 0, 118, 118, 0, 242, 255, 255, 255, 0,
- 254, 255, 255, 255, 0, 70, 114, 111, 109, 82, 101, 109, 111, 116, 101, 0, 3,
- 0, 9, 0, 0, 0, 6, 1, 6, 0, 0, 0, 2, 7, 0, 0, 0, 3, 8, 0, 0, 0, 4, 9, 0, 0, 0,
- 5, 10, 0, 0, 0, 6, 11, 0, 0, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 0,
- 1, 0, 0, 12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242, 255, 255,
- 255, 0, 254, 255, 255, 255, 0, 116, 105, 109, 101, 115, 116, 97, 109, 112, 0,
- 243, 255, 255, 255, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 76, 111,
- 103, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101, 114, 97, 116, 105, 111, 110,
- 115, 0, 242, 255, 255, 255, 0, 13, 0, 0, 0, 0, 73, 110, 105, 116, 105, 97,
- 108, 105, 122, 101, 70, 114, 111, 109, 83, 110, 97, 112, 115, 104, 111, 116,
- 82, 101, 113, 117, 101, 115, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 115, 110, 97,
- 112, 115, 104, 111, 116, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 0,
- 0, 0, 0,
+import { BebopView, BebopRuntimeError, BebopRecord, BebopJson, BebopTypeGuard, Guid, GuidMap } from "bebop";
+
+export const BEBOP_SCHEMA = new Uint8Array ([
+3, 25, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116,
+101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116,
+101, 115, 0, 242, 255, 255, 255, 1, 254, 255, 255, 255, 0,
+105, 100, 0, 245, 255, 255, 255, 0, 80, 101, 101, 114, 65,
+119, 97, 114, 101, 110, 101, 115, 115, 0, 1, 0, 0, 4, 0,
+0, 0, 0, 1, 97, 119, 97, 114, 101, 110, 101, 115, 115, 0,
+242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 80, 101,
+101, 114, 82, 101, 113, 117, 101, 115, 116, 83, 105, 110,
+99, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 118, 118, 0, 242,
+255, 255, 255, 0, 254, 255, 255, 255, 0, 80, 101, 101,
+114, 82, 101, 113, 117, 101, 115, 116, 83, 110, 97, 112,
+115, 104, 111, 116, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 80, 101,
+101, 114, 82, 101, 103, 105, 115, 116, 101, 114, 73, 100,
+0, 1, 0, 0, 8, 0, 0, 0, 1, 1, 112, 101, 101, 114, 105,
+100, 0, 249, 255, 255, 255, 0, 70, 114, 111, 109, 80, 101,
+101, 114, 0, 3, 0, 5, 0, 0, 0, 5, 1, 0, 0, 0, 0, 2, 1, 0,
+0, 0, 3, 2, 0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 82,
+101, 109, 111, 116, 101, 73, 110, 105, 116, 105, 97, 108,
+83, 121, 110, 99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 115, 110,
+97, 112, 115, 104, 111, 116, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 97, 119, 97, 114, 101, 110, 101,
+115, 115, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
+82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101,
+0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97, 116, 101,
+0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 82, 101,
+109, 111, 116, 101, 65, 119, 97, 114, 101, 110, 101, 115,
+115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97, 114, 101,
+110, 101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255,
+255, 255, 0, 82, 101, 109, 111, 116, 101, 83, 110, 97,
+112, 115, 104, 111, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
+115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
+255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116,
+101, 85, 112, 100, 97, 116, 101, 65, 99, 107, 0, 1, 0, 0,
+4, 0, 0, 0, 0, 1, 105, 100, 0, 245, 255, 255, 255, 0, 82,
+101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101, 83,
+105, 110, 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112,
+100, 97, 116, 101, 0, 242, 255, 255, 255, 0, 254, 255,
+255, 255, 0, 118, 118, 0, 242, 255, 255, 255, 0, 254, 255,
+255, 255, 0, 70, 114, 111, 109, 82, 101, 109, 111, 116,
+101, 0, 3, 0, 9, 0, 0, 0, 6, 1, 6, 0, 0, 0, 2, 7, 0, 0, 0,
+3, 8, 0, 0, 0, 4, 9, 0, 0, 0, 5, 10, 0, 0, 0, 6, 11, 0, 0,
+0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 0, 1, 0, 0,
+12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242,
+255, 255, 255, 0, 254, 255, 255, 255, 0, 116, 105, 109,
+101, 115, 116, 97, 109, 112, 0, 243, 255, 255, 255, 0, 79,
+112, 101, 114, 97, 116, 105, 111, 110, 76, 111, 103, 0, 1,
+0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101, 114, 97, 116, 105,
+111, 110, 115, 0, 242, 255, 255, 255, 0, 13, 0, 0, 0, 0,
+73, 110, 105, 116, 105, 97, 108, 105, 122, 101, 70, 114,
+111, 109, 83, 110, 97, 112, 115, 104, 111, 116, 82, 101,
+113, 117, 101, 115, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
+115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
+255, 0, 254, 255, 255, 255, 0, 82, 111, 117, 116, 101,
+114, 83, 117, 98, 115, 99, 114, 105, 98, 101, 0, 1, 0, 0,
+8, 0, 0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255,
+255, 0, 116, 111, 107, 101, 110, 0, 245, 255, 255, 255, 0,
+82, 111, 117, 116, 101, 114, 85, 110, 115, 117, 98, 115,
+99, 114, 105, 98, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 100,
+111, 99, 73, 100, 0, 245, 255, 255, 255, 0, 82, 111, 117,
+116, 101, 114, 70, 114, 97, 109, 101, 0, 1, 0, 0, 8, 0, 0,
+0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255, 0,
+112, 97, 121, 108, 111, 97, 100, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 84, 111, 82, 111, 117, 116, 101,
+114, 0, 3, 0, 9, 0, 0, 0, 3, 1, 16, 0, 0, 0, 2, 17, 0, 0,
+0, 3, 18, 0, 0, 0, 82, 111, 117, 116, 101, 114, 83, 117,
+98, 115, 99, 114, 105, 98, 101, 100, 0, 1, 0, 0, 4, 0, 0,
+0, 0, 1, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255, 0,
+82, 111, 117, 116, 101, 114, 83, 117, 98, 115, 99, 114,
+105, 98, 101, 70, 97, 105, 108, 101, 100, 0, 1, 0, 0, 8,
+0, 0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255,
+255, 0, 114, 101, 97, 115, 111, 110, 0, 245, 255, 255,
+255, 0, 82, 111, 117, 116, 101, 114, 68, 111, 99, 70, 114,
+97, 109, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99,
+73, 100, 0, 245, 255, 255, 255, 0, 112, 97, 121, 108, 111,
+97, 100, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
+82, 111, 117, 116, 101, 114, 68, 111, 99, 67, 108, 111,
+115, 101, 100, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99,
+73, 100, 0, 245, 255, 255, 255, 0, 114, 101, 97, 115, 111,
+110, 0, 245, 255, 255, 255, 0, 70, 114, 111, 109, 82, 111,
+117, 116, 101, 114, 0, 3, 0, 9, 0, 0, 0, 4, 1, 20, 0, 0,
+0, 2, 21, 0, 0, 0, 3, 22, 0, 0, 0, 4, 23, 0, 0, 0, 0, 0,
+0, 0
]);
export interface IPeerUpdate extends BebopRecord {
+
readonly updates: Array<Uint8Array>;
readonly id: string;
@@ -109,17 +144,15 @@ export class PeerUpdate implements IPeerUpdate {
* Validates that the specified dynamic object can become an instance of {@link PeerUpdate}.
*/
public static validateCompatibility(record: IPeerUpdate): void {
- BebopTypeGuard.ensureArray(record.updates, (element) =>
- BebopTypeGuard.ensureArray(element, BebopTypeGuard.ensureUint8)
- );
- BebopTypeGuard.ensureString(record.id);
+ BebopTypeGuard.ensureArray(record.updates, (element) => BebopTypeGuard.ensureArray(element, BebopTypeGuard.ensureUint8));
+ BebopTypeGuard.ensureString(record.id)
}
/**
* Unsafely creates an instance of {@link PeerUpdate} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IPeerUpdate {
- return new PeerUpdate(record);
+ return new PeerUpdate(record);
}
/**
@@ -185,7 +218,9 @@ export class PeerUpdate implements IPeerUpdate {
}
}
+
export interface IPeerAwareness extends BebopRecord {
+
readonly awareness: Uint8Array;
}
@@ -230,7 +265,7 @@ export class PeerAwareness implements IPeerAwareness {
* Unsafely creates an instance of {@link PeerAwareness} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IPeerAwareness {
- return new PeerAwareness(record);
+ return new PeerAwareness(record);
}
/**
@@ -278,7 +313,9 @@ export class PeerAwareness implements IPeerAwareness {
}
}
+
export interface IPeerRequestSince extends BebopRecord {
+
readonly vv: Uint8Array;
}
@@ -323,7 +360,7 @@ export class PeerRequestSince implements IPeerRequestSince {
* Unsafely creates an instance of {@link PeerRequestSince} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IPeerRequestSince {
- return new PeerRequestSince(record);
+ return new PeerRequestSince(record);
}
/**
@@ -371,13 +408,16 @@ export class PeerRequestSince implements IPeerRequestSince {
}
}
-export interface IPeerRequestSnapshot extends BebopRecord {}
+
+export interface IPeerRequestSnapshot extends BebopRecord {
+}
export class PeerRequestSnapshot implements IPeerRequestSnapshot {
public readonly discriminator: number = 4 as 4;
public static readonly discriminator: number = 4 as 4;
- constructor(record: IPeerRequestSnapshot) {}
+ constructor(record: IPeerRequestSnapshot) {
+ }
/**
* Serializes the current instance into a JSON-Over-Bebop string
@@ -403,13 +443,15 @@ export class PeerRequestSnapshot implements IPeerRequestSnapshot {
/**
* Validates that the specified dynamic object can become an instance of {@link PeerRequestSnapshot}.
*/
- public static validateCompatibility(record: IPeerRequestSnapshot): void {}
+ public static validateCompatibility(record: IPeerRequestSnapshot): void {
+
+ }
/**
* Unsafely creates an instance of {@link PeerRequestSnapshot} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IPeerRequestSnapshot {
- return new PeerRequestSnapshot(record);
+ return new PeerRequestSnapshot(record);
}
/**
@@ -417,9 +459,7 @@ export class PeerRequestSnapshot implements IPeerRequestSnapshot {
*/
public static fromJSON(json: string): IPeerRequestSnapshot {
if (typeof json !== 'string' || json.trim().length === 0) {
- throw new BebopRuntimeError(
- `PeerRequestSnapshot.fromJSON: expected string`
- );
+ throw new BebopRuntimeError(`PeerRequestSnapshot.fromJSON: expected string`);
}
const parsed = JSON.parse(json, BebopJson.reviver);
PeerRequestSnapshot.validateCompatibility(parsed);
@@ -436,10 +476,7 @@ export class PeerRequestSnapshot implements IPeerRequestSnapshot {
return view.toArray();
}
- public static encodeInto(
- record: IPeerRequestSnapshot,
- view: BebopView
- ): number {
+ public static encodeInto(record: IPeerRequestSnapshot, view: BebopView): number {
const before = view.length;
const after = view.length;
@@ -453,12 +490,15 @@ export class PeerRequestSnapshot implements IPeerRequestSnapshot {
}
public static readFrom(view: BebopView): IPeerRequestSnapshot {
- let message: IPeerRequestSnapshot = {};
+ let message: IPeerRequestSnapshot = {
+ };
return new PeerRequestSnapshot(message);
}
}
+
export interface IPeerRegisterId extends BebopRecord {
+
readonly peerid: bigint;
}
@@ -496,14 +536,14 @@ export class PeerRegisterId implements IPeerRegisterId {
* Validates that the specified dynamic object can become an instance of {@link PeerRegisterId}.
*/
public static validateCompatibility(record: IPeerRegisterId): void {
- BebopTypeGuard.ensureUint64(record.peerid);
+ BebopTypeGuard.ensureUint64(record.peerid)
}
/**
* Unsafely creates an instance of {@link PeerRegisterId} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IPeerRegisterId {
- return new PeerRegisterId(record);
+ return new PeerRegisterId(record);
}
/**
@@ -551,17 +591,19 @@ export class PeerRegisterId implements IPeerRegisterId {
}
}
-export type IFromPeerType =
- | { discriminator: 1; value: IPeerUpdate }
- | { discriminator: 2; value: IPeerAwareness }
- | { discriminator: 3; value: IPeerRequestSince }
- | { discriminator: 4; value: IPeerRequestSnapshot }
- | { discriminator: 5; value: IPeerRegisterId };
+
+export type IFromPeerType
+ = { discriminator: 1, value: IPeerUpdate }
+ | { discriminator: 2, value: IPeerAwareness }
+ | { discriminator: 3, value: IPeerRequestSince }
+ | { discriminator: 4, value: IPeerRequestSnapshot }
+ | { discriminator: 5, value: IPeerRegisterId };
export interface IFromPeer extends BebopRecord {
readonly data: IFromPeerType;
}
export class FromPeer implements IFromPeer {
+
public readonly data: IFromPeerType;
private constructor(data: IFromPeerType) {
@@ -577,61 +619,46 @@ export class FromPeer implements IFromPeer {
}
public static fromPeerUpdate(value: IPeerUpdate) {
- return new FromPeer({ discriminator: 1, value: new PeerUpdate(value) });
+ return new FromPeer({ discriminator: 1, value: new PeerUpdate(value)});
}
- public isPeerUpdate(): this is { value: PeerUpdate } & {
- data: Extract<IFromPeerType, { discriminator: 1 }>;
- } {
+ public isPeerUpdate(): this is { value: PeerUpdate } & { data: Extract<IFromPeerType, { discriminator: 1 }> } {
return this.data.value instanceof PeerUpdate;
}
public static fromPeerAwareness(value: IPeerAwareness) {
- return new FromPeer({ discriminator: 2, value: new PeerAwareness(value) });
+ return new FromPeer({ discriminator: 2, value: new PeerAwareness(value)});
}
- public isPeerAwareness(): this is { value: PeerAwareness } & {
- data: Extract<IFromPeerType, { discriminator: 2 }>;
- } {
+ public isPeerAwareness(): this is { value: PeerAwareness } & { data: Extract<IFromPeerType, { discriminator: 2 }> } {
return this.data.value instanceof PeerAwareness;
}
public static fromPeerRequestSince(value: IPeerRequestSince) {
- return new FromPeer({
- discriminator: 3,
- value: new PeerRequestSince(value),
- });
+ return new FromPeer({ discriminator: 3, value: new PeerRequestSince(value)});
}
- public isPeerRequestSince(): this is { value: PeerRequestSince } & {
- data: Extract<IFromPeerType, { discriminator: 3 }>;
- } {
+ public isPeerRequestSince(): this is { value: PeerRequestSince } & { data: Extract<IFromPeerType, { discriminator: 3 }> } {
return this.data.value instanceof PeerRequestSince;
}
public static fromPeerRequestSnapshot(value: IPeerRequestSnapshot) {
- return new FromPeer({
- discriminator: 4,
- value: new PeerRequestSnapshot(value),
- });
+ return new FromPeer({ discriminator: 4, value: new PeerRequestSnapshot(value)});
}
- public isPeerRequestSnapshot(): this is { value: PeerRequestSnapshot } & {
- data: Extract<IFromPeerType, { discriminator: 4 }>;
- } {
+ public isPeerRequestSnapshot(): this is { value: PeerRequestSnapshot } & { data: Extract<IFromPeerType, { discriminator: 4 }> } {
return this.data.value instanceof PeerRequestSnapshot;
}
public static fromPeerRegisterId(value: IPeerRegisterId) {
- return new FromPeer({ discriminator: 5, value: new PeerRegisterId(value) });
+ return new FromPeer({ discriminator: 5, value: new PeerRegisterId(value)});
}
- public isPeerRegisterId(): this is { value: PeerRegisterId } & {
- data: Extract<IFromPeerType, { discriminator: 5 }>;
- } {
+ public isPeerRegisterId(): this is { value: PeerRegisterId } & { data: Extract<IFromPeerType, { discriminator: 5 }> } {
return this.data.value instanceof PeerRegisterId;
}
+
/**
* Serializes the current instance into a JSON-Over-Bebop string
*/
@@ -691,42 +718,25 @@ export class FromPeer implements IFromPeer {
* Unsafely creates an instance of {@link FromPeer} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): FromPeer {
- const discriminator = record.data.discriminator;
- switch (discriminator) {
- case 1: {
- return new FromPeer({
- discriminator: 1,
- value: PeerUpdate.unsafeCast(record.value),
- });
- }
- case 2: {
- return new FromPeer({
- discriminator: 2,
- value: PeerAwareness.unsafeCast(record.value),
- });
- }
- case 3: {
- return new FromPeer({
- discriminator: 3,
- value: PeerRequestSince.unsafeCast(record.value),
- });
- }
- case 4: {
- return new FromPeer({
- discriminator: 4,
- value: PeerRequestSnapshot.unsafeCast(record.value),
- });
- }
- case 5: {
- return new FromPeer({
- discriminator: 5,
- value: PeerRegisterId.unsafeCast(record.value),
- });
+ const discriminator = record.data.discriminator;
+ switch (discriminator) {
+ case 1: {
+ return new FromPeer({ discriminator: 1, value: PeerUpdate.unsafeCast(record.value) });
+ }
+ case 2: {
+ return new FromPeer({ discriminator: 2, value: PeerAwareness.unsafeCast(record.value) });
+ }
+ case 3: {
+ return new FromPeer({ discriminator: 3, value: PeerRequestSince.unsafeCast(record.value) });
+ }
+ case 4: {
+ return new FromPeer({ discriminator: 4, value: PeerRequestSnapshot.unsafeCast(record.value) });
+ }
+ case 5: {
+ return new FromPeer({ discriminator: 5, value: PeerRegisterId.unsafeCast(record.value) });
+ }
}
- }
- throw new BebopRuntimeError(
- `Failed to unsafely cast union from discriminator: ${discriminator}`
- );
+ throw new BebopRuntimeError(`Failed to unsafely cast union from discriminator: ${discriminator}`);
}
/**
@@ -801,14 +811,14 @@ export class FromPeer implements IFromPeer {
return this.fromPeerRegisterId(PeerRegisterId.readFrom(view));
default:
view.index = end;
- throw new BebopRuntimeError(
- 'Unrecognized discriminator while decoding FromPeer'
- );
+ throw new BebopRuntimeError("Unrecognized discriminator while decoding FromPeer");
}
}
}
+
export interface IRemoteInitialSync extends BebopRecord {
+
readonly snapshot: Uint8Array;
readonly awareness: Uint8Array;
@@ -858,7 +868,7 @@ export class RemoteInitialSync implements IRemoteInitialSync {
* Unsafely creates an instance of {@link RemoteInitialSync} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IRemoteInitialSync {
- return new RemoteInitialSync(record);
+ return new RemoteInitialSync(record);
}
/**
@@ -866,9 +876,7 @@ export class RemoteInitialSync implements IRemoteInitialSync {
*/
public static fromJSON(json: string): IRemoteInitialSync {
if (typeof json !== 'string' || json.trim().length === 0) {
- throw new BebopRuntimeError(
- `RemoteInitialSync.fromJSON: expected string`
- );
+ throw new BebopRuntimeError(`RemoteInitialSync.fromJSON: expected string`);
}
const parsed = JSON.parse(json, BebopJson.reviver);
RemoteInitialSync.validateCompatibility(parsed);
@@ -885,10 +893,7 @@ export class RemoteInitialSync implements IRemoteInitialSync {
return view.toArray();
}
- public static encodeInto(
- record: IRemoteInitialSync,
- view: BebopView
- ): number {
+ public static encodeInto(record: IRemoteInitialSync, view: BebopView): number {
const before = view.length;
view.writeBytes(record.snapshot);
view.writeBytes(record.awareness);
@@ -915,7 +920,9 @@ export class RemoteInitialSync implements IRemoteInitialSync {
}
}
+
export interface IRemoteUpdate extends BebopRecord {
+
readonly update: Uint8Array;
}
@@ -960,7 +967,7 @@ export class RemoteUpdate implements IRemoteUpdate {
* Unsafely creates an instance of {@link RemoteUpdate} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IRemoteUpdate {
- return new RemoteUpdate(record);
+ return new RemoteUpdate(record);
}
/**
@@ -1008,7 +1015,9 @@ export class RemoteUpdate implements IRemoteUpdate {
}
}
+
export interface IRemoteAwareness extends BebopRecord {
+
readonly awareness: Uint8Array;
}
@@ -1053,7 +1062,7 @@ export class RemoteAwareness implements IRemoteAwareness {
* Unsafely creates an instance of {@link RemoteAwareness} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IRemoteAwareness {
- return new RemoteAwareness(record);
+ return new RemoteAwareness(record);
}
/**
@@ -1101,7 +1110,9 @@ export class RemoteAwareness implements IRemoteAwareness {
}
}
+
export interface IRemoteSnapshot extends BebopRecord {
+
readonly snapshot: Uint8Array;
}
@@ -1146,7 +1157,7 @@ export class RemoteSnapshot implements IRemoteSnapshot {
* Unsafely creates an instance of {@link RemoteSnapshot} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IRemoteSnapshot {
- return new RemoteSnapshot(record);
+ return new RemoteSnapshot(record);
}
/**
@@ -1194,7 +1205,9 @@ export class RemoteSnapshot implements IRemoteSnapshot {
}
}
+
export interface IRemoteUpdateAck extends BebopRecord {
+
readonly id: string;
}
@@ -1232,14 +1245,14 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
* Validates that the specified dynamic object can become an instance of {@link RemoteUpdateAck}.
*/
public static validateCompatibility(record: IRemoteUpdateAck): void {
- BebopTypeGuard.ensureString(record.id);
+ BebopTypeGuard.ensureString(record.id)
}
/**
* Unsafely creates an instance of {@link RemoteUpdateAck} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IRemoteUpdateAck {
- return new RemoteUpdateAck(record);
+ return new RemoteUpdateAck(record);
}
/**
@@ -1287,7 +1300,9 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
}
}
+
export interface IRemoteUpdateSince extends BebopRecord {
+
readonly update: Uint8Array;
readonly vv: Uint8Array;
@@ -1337,7 +1352,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
* Unsafely creates an instance of {@link RemoteUpdateSince} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IRemoteUpdateSince {
- return new RemoteUpdateSince(record);
+ return new RemoteUpdateSince(record);
}
/**
@@ -1345,9 +1360,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
*/
public static fromJSON(json: string): IRemoteUpdateSince {
if (typeof json !== 'string' || json.trim().length === 0) {
- throw new BebopRuntimeError(
- `RemoteUpdateSince.fromJSON: expected string`
- );
+ throw new BebopRuntimeError(`RemoteUpdateSince.fromJSON: expected string`);
}
const parsed = JSON.parse(json, BebopJson.reviver);
RemoteUpdateSince.validateCompatibility(parsed);
@@ -1364,10 +1377,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
return view.toArray();
}
- public static encodeInto(
- record: IRemoteUpdateSince,
- view: BebopView
- ): number {
+ public static encodeInto(record: IRemoteUpdateSince, view: BebopView): number {
const before = view.length;
view.writeBytes(record.update);
view.writeBytes(record.vv);
@@ -1394,18 +1404,20 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
}
}
-export type IFromRemoteType =
- | { discriminator: 1; value: IRemoteInitialSync }
- | { discriminator: 2; value: IRemoteUpdate }
- | { discriminator: 3; value: IRemoteAwareness }
- | { discriminator: 4; value: IRemoteSnapshot }
- | { discriminator: 5; value: IRemoteUpdateAck }
- | { discriminator: 6; value: IRemoteUpdateSince };
+
+export type IFromRemoteType
+ = { discriminator: 1, value: IRemoteInitialSync }
+ | { discriminator: 2, value: IRemoteUpdate }
+ | { discriminator: 3, value: IRemoteAwareness }
+ | { discriminator: 4, value: IRemoteSnapshot }
+ | { discriminator: 5, value: IRemoteUpdateAck }
+ | { discriminator: 6, value: IRemoteUpdateSince };
export interface IFromRemote extends BebopRecord {
readonly data: IFromRemoteType;
}
export class FromRemote implements IFromRemote {
+
public readonly data: IFromRemoteType;
private constructor(data: IFromRemoteType) {
@@ -1421,80 +1433,54 @@ export class FromRemote implements IFromRemote {
}
public static fromRemoteInitialSync(value: IRemoteInitialSync) {
- return new FromRemote({
- discriminator: 1,
- value: new RemoteInitialSync(value),
- });
+ return new FromRemote({ discriminator: 1, value: new RemoteInitialSync(value)});
}
- public isRemoteInitialSync(): this is { value: RemoteInitialSync } & {
- data: Extract<IFromRemoteType, { discriminator: 1 }>;
- } {
+ public isRemoteInitialSync(): this is { value: RemoteInitialSync } & { data: Extract<IFromRemoteType, { discriminator: 1 }> } {
return this.data.value instanceof RemoteInitialSync;
}
public static fromRemoteUpdate(value: IRemoteUpdate) {
- return new FromRemote({ discriminator: 2, value: new RemoteUpdate(value) });
+ return new FromRemote({ discriminator: 2, value: new RemoteUpdate(value)});
}
- public isRemoteUpdate(): this is { value: RemoteUpdate } & {
- data: Extract<IFromRemoteType, { discriminator: 2 }>;
- } {
+ public isRemoteUpdate(): this is { value: RemoteUpdate } & { data: Extract<IFromRemoteType, { discriminator: 2 }> } {
return this.data.value instanceof RemoteUpdate;
}
public static fromRemoteAwareness(value: IRemoteAwareness) {
- return new FromRemote({
- discriminator: 3,
- value: new RemoteAwareness(value),
- });
+ return new FromRemote({ discriminator: 3, value: new RemoteAwareness(value)});
}
- public isRemoteAwareness(): this is { value: RemoteAwareness } & {
- data: Extract<IFromRemoteType, { discriminator: 3 }>;
- } {
+ public isRemoteAwareness(): this is { value: RemoteAwareness } & { data: Extract<IFromRemoteType, { discriminator: 3 }> } {
return this.data.value instanceof RemoteAwareness;
}
public static fromRemoteSnapshot(value: IRemoteSnapshot) {
- return new FromRemote({
- discriminator: 4,
- value: new RemoteSnapshot(value),
- });
+ return new FromRemote({ discriminator: 4, value: new RemoteSnapshot(value)});
}
- public isRemoteSnapshot(): this is { value: RemoteSnapshot } & {
- data: Extract<IFromRemoteType, { discriminator: 4 }>;
- } {
+ public isRemoteSnapshot(): this is { value: RemoteSnapshot } & { data: Extract<IFromRemoteType, { discriminator: 4 }> } {
return this.data.value instanceof RemoteSnapshot;
}
public static fromRemoteUpdateAck(value: IRemoteUpdateAck) {
- return new FromRemote({
- discriminator: 5,
- value: new RemoteUpdateAck(value),
- });
+ return new FromRemote({ discriminator: 5, value: new RemoteUpdateAck(value)});
}
- public isRemoteUpdateAck(): this is { value: RemoteUpdateAck } & {
- data: Extract<IFromRemoteType, { discriminator: 5 }>;
- } {
+ public isRemoteUpdateAck(): this is { value: RemoteUpdateAck } & { data: Extract<IFromRemoteType, { discriminator: 5 }> } {
return this.data.value instanceof RemoteUpdateAck;
}
public static fromRemoteUpdateSince(value: IRemoteUpdateSince) {
- return new FromRemote({
- discriminator: 6,
- value: new RemoteUpdateSince(value),
- });
+ return new FromRemote({ discriminator: 6, value: new RemoteUpdateSince(value)});
}
- public isRemoteUpdateSince(): this is { value: RemoteUpdateSince } & {
- data: Extract<IFromRemoteType, { discriminator: 6 }>;
- } {
+ public isRemoteUpdateSince(): this is { value: RemoteUpdateSince } & { data: Extract<IFromRemoteType, { discriminator: 6 }> } {
return this.data.value instanceof RemoteUpdateSince;
}
+
/**
* Serializes the current instance into a JSON-Over-Bebop string
*/
@@ -1549,9 +1535,7 @@ export class FromRemote implements IFromRemote {
break;
}
default: {
- throw new Error(
- `Unknown discriminator for FromRemote: ${discriminator}`
- );
+ throw new Error(`Unknown discriminator for FromRemote: ${discriminator}`);
}
}
}
@@ -1560,48 +1544,28 @@ export class FromRemote implements IFromRemote {
* Unsafely creates an instance of {@link FromRemote} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): FromRemote {
- const discriminator = record.data.discriminator;
- switch (discriminator) {
- case 1: {
- return new FromRemote({
- discriminator: 1,
- value: RemoteInitialSync.unsafeCast(record.value),
- });
- }
- case 2: {
- return new FromRemote({
- discriminator: 2,
- value: RemoteUpdate.unsafeCast(record.value),
- });
+ const discriminator = record.data.discriminator;
+ switch (discriminator) {
+ case 1: {
+ return new FromRemote({ discriminator: 1, value: RemoteInitialSync.unsafeCast(record.value) });
+ }
+ case 2: {
+ return new FromRemote({ discriminator: 2, value: RemoteUpdate.unsafeCast(record.value) });
+ }
+ case 3: {
+ return new FromRemote({ discriminator: 3, value: RemoteAwareness.unsafeCast(record.value) });
+ }
+ case 4: {
+ return new FromRemote({ discriminator: 4, value: RemoteSnapshot.unsafeCast(record.value) });
+ }
+ case 5: {
+ return new FromRemote({ discriminator: 5, value: RemoteUpdateAck.unsafeCast(record.value) });
+ }
+ case 6: {
+ return new FromRemote({ discriminator: 6, value: RemoteUpdateSince.unsafeCast(record.value) });
+ }
}
- case 3: {
- return new FromRemote({
- discriminator: 3,
- value: RemoteAwareness.unsafeCast(record.value),
- });
- }
- case 4: {
- return new FromRemote({
- discriminator: 4,
- value: RemoteSnapshot.unsafeCast(record.value),
- });
- }
- case 5: {
- return new FromRemote({
- discriminator: 5,
- value: RemoteUpdateAck.unsafeCast(record.value),
- });
- }
- case 6: {
- return new FromRemote({
- discriminator: 6,
- value: RemoteUpdateSince.unsafeCast(record.value),
- });
- }
- }
- throw new BebopRuntimeError(
- `Failed to unsafely cast union from discriminator: ${discriminator}`
- );
+ throw new BebopRuntimeError(`Failed to unsafely cast union from discriminator: ${discriminator}`);
}
/**
@@ -1681,14 +1645,14 @@ export class FromRemote implements IFromRemote {
return this.fromRemoteUpdateSince(RemoteUpdateSince.readFrom(view));
default:
view.index = end;
- throw new BebopRuntimeError(
- 'Unrecognized discriminator while decoding FromRemote'
- );
+ throw new BebopRuntimeError("Unrecognized discriminator while decoding FromRemote");
}
}
}
+
export interface IOperation extends BebopRecord {
+
readonly update: Uint8Array;
readonly timestamp: Date;
@@ -1729,14 +1693,14 @@ export class Operation implements IOperation {
*/
public static validateCompatibility(record: IOperation): void {
BebopTypeGuard.ensureArray(record.update, BebopTypeGuard.ensureUint8);
- BebopTypeGuard.ensureDate(record.timestamp);
+ BebopTypeGuard.ensureDate(record.timestamp)
}
/**
* Unsafely creates an instance of {@link Operation} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IOperation {
- return new Operation(record);
+ return new Operation(record);
}
/**
@@ -1788,7 +1752,9 @@ export class Operation implements IOperation {
}
}
+
export interface IOperationLog extends BebopRecord {
+
readonly operations: Array<IOperation>;
}
@@ -1824,17 +1790,14 @@ export class OperationLog implements IOperationLog {
* Validates that the specified dynamic object can become an instance of {@link OperationLog}.
*/
public static validateCompatibility(record: IOperationLog): void {
- BebopTypeGuard.ensureArray(
- record.operations,
- Operation.validateCompatibility
- );
+ BebopTypeGuard.ensureArray(record.operations, Operation.validateCompatibility);
}
/**
* Unsafely creates an instance of {@link OperationLog} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IOperationLog {
- return new OperationLog(record);
+ return new OperationLog(record);
}
/**
@@ -1865,7 +1828,7 @@ export class OperationLog implements IOperationLog {
const length0 = record.operations.length;
view.writeUint32(length0);
for (let i0 = 0; i0 < length0; i0++) {
- Operation.encodeInto(record.operations[i0], view);
+ Operation.encodeInto(record.operations[i0], view)
}
}
const after = view.length;
@@ -1896,13 +1859,13 @@ export class OperationLog implements IOperationLog {
}
}
+
export interface IInitializeFromSnapshotRequest extends BebopRecord {
+
readonly snapshot: Uint8Array;
}
-export class InitializeFromSnapshotRequest
- implements IInitializeFromSnapshotRequest
-{
+export class InitializeFromSnapshotRequest implements IInitializeFromSnapshotRequest {
public readonly snapshot: Uint8Array;
constructor(record: IInitializeFromSnapshotRequest) {
@@ -1933,9 +1896,7 @@ export class InitializeFromSnapshotRequest
/**
* Validates that the specified dynamic object can become an instance of {@link InitializeFromSnapshotRequest}.
*/
- public static validateCompatibility(
- record: IInitializeFromSnapshotRequest
- ): void {
+ public static validateCompatibility(record: IInitializeFromSnapshotRequest): void {
BebopTypeGuard.ensureArray(record.snapshot, BebopTypeGuard.ensureUint8);
}
@@ -1943,7 +1904,7 @@ export class InitializeFromSnapshotRequest
* Unsafely creates an instance of {@link InitializeFromSnapshotRequest} from the specified dynamic object. No type checking is performed.
*/
public static unsafeCast(record: any): IInitializeFromSnapshotRequest {
- return new InitializeFromSnapshotRequest(record);
+ return new InitializeFromSnapshotRequest(record);
}
/**
@@ -1951,9 +1912,7 @@ export class InitializeFromSnapshotRequest
*/
public static fromJSON(json: string): IInitializeFromSnapshotRequest {
if (typeof json !== 'string' || json.trim().length === 0) {
- throw new BebopRuntimeError(
- `InitializeFromSnapshotRequest.fromJSON: expected string`
- );
+ throw new BebopRuntimeError(`InitializeFromSnapshotRequest.fromJSON: expected string`);
}
const parsed = JSON.parse(json, BebopJson.reviver);
InitializeFromSnapshotRequest.validateCompatibility(parsed);
@@ -1970,10 +1929,7 @@ export class InitializeFromSnapshotRequest
return view.toArray();
}
- public static encodeInto(
- record: IInitializeFromSnapshotRequest,
- view: BebopView
- ): number {
+ public static encodeInto(record: IInitializeFromSnapshotRequest, view: BebopView): number {
const before = view.length;
view.writeBytes(record.snapshot);
const after = view.length;
@@ -1995,3 +1951,1105 @@ export class InitializeFromSnapshotRequest
return new InitializeFromSnapshotRequest(message);
}
}
+
+
+export interface IRouterSubscribe extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly token: string;
+}
+
+export class RouterSubscribe implements IRouterSubscribe {
+ public readonly discriminator: number = 1 as 1;
+ public static readonly discriminator: number = 1 as 1;
+ public readonly docId: string;
+ public readonly token: string;
+
+ constructor(record: IRouterSubscribe) {
+ this.docId = record.docId;
+ this.token = record.token;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterSubscribe.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterSubscribe): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterSubscribe.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterSubscribe}.
+ */
+ public static validateCompatibility(record: IRouterSubscribe): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureString(record.token)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterSubscribe} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterSubscribe {
+ return new RouterSubscribe(record);
+ }
+
+ /**
+ * Creates a new {@link RouterSubscribe} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterSubscribe {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterSubscribe.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterSubscribe.validateCompatibility(parsed);
+ return RouterSubscribe.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterSubscribe.encode(this);
+ }
+
+ public static encode(record: IRouterSubscribe): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterSubscribe.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterSubscribe, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeString(record.token);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterSubscribe {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterSubscribe.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterSubscribe {
+ let field0: string;
+ field0 = view.readString();
+ let field1: string;
+ field1 = view.readString();
+ let message: IRouterSubscribe = {
+ docId: field0,
+ token: field1,
+ };
+ return new RouterSubscribe(message);
+ }
+}
+
+
+export interface IRouterUnsubscribe extends BebopRecord {
+
+ readonly docId: string;
+}
+
+export class RouterUnsubscribe implements IRouterUnsubscribe {
+ public readonly discriminator: number = 2 as 2;
+ public static readonly discriminator: number = 2 as 2;
+ public readonly docId: string;
+
+ constructor(record: IRouterUnsubscribe) {
+ this.docId = record.docId;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterUnsubscribe.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterUnsubscribe): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterUnsubscribe.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterUnsubscribe}.
+ */
+ public static validateCompatibility(record: IRouterUnsubscribe): void {
+ BebopTypeGuard.ensureString(record.docId)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterUnsubscribe} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterUnsubscribe {
+ return new RouterUnsubscribe(record);
+ }
+
+ /**
+ * Creates a new {@link RouterUnsubscribe} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterUnsubscribe {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterUnsubscribe.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterUnsubscribe.validateCompatibility(parsed);
+ return RouterUnsubscribe.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterUnsubscribe.encode(this);
+ }
+
+ public static encode(record: IRouterUnsubscribe): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterUnsubscribe.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterUnsubscribe, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterUnsubscribe {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterUnsubscribe.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterUnsubscribe {
+ let field0: string;
+ field0 = view.readString();
+ let message: IRouterUnsubscribe = {
+ docId: field0,
+ };
+ return new RouterUnsubscribe(message);
+ }
+}
+
+
+export interface IRouterFrame extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly payload: Uint8Array;
+}
+
+export class RouterFrame implements IRouterFrame {
+ public readonly discriminator: number = 3 as 3;
+ public static readonly discriminator: number = 3 as 3;
+ public readonly docId: string;
+ public readonly payload: Uint8Array;
+
+ constructor(record: IRouterFrame) {
+ this.docId = record.docId;
+ this.payload = record.payload;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterFrame.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterFrame): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterFrame.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterFrame}.
+ */
+ public static validateCompatibility(record: IRouterFrame): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureArray(record.payload, BebopTypeGuard.ensureUint8);
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterFrame} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterFrame {
+ return new RouterFrame(record);
+ }
+
+ /**
+ * Creates a new {@link RouterFrame} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterFrame {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterFrame.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterFrame.validateCompatibility(parsed);
+ return RouterFrame.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterFrame.encode(this);
+ }
+
+ public static encode(record: IRouterFrame): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterFrame.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterFrame, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeBytes(record.payload);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterFrame {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterFrame.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterFrame {
+ let field0: string;
+ field0 = view.readString();
+ let field1: Uint8Array;
+ field1 = view.readBytes();
+ let message: IRouterFrame = {
+ docId: field0,
+ payload: field1,
+ };
+ return new RouterFrame(message);
+ }
+}
+
+/**
+ * Multiplex envelope between the browser and the sync-router (rides the
+ * connection-gateway socket as binary frames). Inner payloads are the
+ * existing FromPeer/FromRemote unions, already bebop-encoded — the router
+ * forwards them without parsing.
+ */
+export type IToRouterType
+ = { discriminator: 1, value: IRouterSubscribe }
+ | { discriminator: 2, value: IRouterUnsubscribe }
+ | { discriminator: 3, value: IRouterFrame };
+
+export interface IToRouter extends BebopRecord {
+ readonly data: IToRouterType;
+}
+export class ToRouter implements IToRouter {
+
+ public readonly data: IToRouterType;
+
+ private constructor(data: IToRouterType) {
+ this.data = data;
+ }
+
+ public get discriminator() {
+ return this.data.discriminator;
+ }
+
+ public get value() {
+ return this.data.value;
+ }
+
+ public static fromRouterSubscribe(value: IRouterSubscribe) {
+ return new ToRouter({ discriminator: 1, value: new RouterSubscribe(value)});
+ }
+
+ public isRouterSubscribe(): this is { value: RouterSubscribe } & { data: Extract<IToRouterType, { discriminator: 1 }> } {
+ return this.data.value instanceof RouterSubscribe;
+ }
+
+ public static fromRouterUnsubscribe(value: IRouterUnsubscribe) {
+ return new ToRouter({ discriminator: 2, value: new RouterUnsubscribe(value)});
+ }
+
+ public isRouterUnsubscribe(): this is { value: RouterUnsubscribe } & { data: Extract<IToRouterType, { discriminator: 2 }> } {
+ return this.data.value instanceof RouterUnsubscribe;
+ }
+
+ public static fromRouterFrame(value: IRouterFrame) {
+ return new ToRouter({ discriminator: 3, value: new RouterFrame(value)});
+ }
+
+ public isRouterFrame(): this is { value: RouterFrame } & { data: Extract<IToRouterType, { discriminator: 3 }> } {
+ return this.data.value instanceof RouterFrame;
+ }
+
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return ToRouter.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IToRouter): string {
+ delete (record.data.value as any).discriminator;
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ ToRouter.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link ToRouter}.
+ */
+ public static validateCompatibility(record: IToRouter): void {
+ const discriminator = record.data.discriminator;
+ BebopTypeGuard.ensureUint8(discriminator);
+ switch (discriminator) {
+ case 1: {
+ RouterSubscribe.validateCompatibility(record.data.value);
+ break;
+ }
+ case 2: {
+ RouterUnsubscribe.validateCompatibility(record.data.value);
+ break;
+ }
+ case 3: {
+ RouterFrame.validateCompatibility(record.data.value);
+ break;
+ }
+ default: {
+ throw new Error(`Unknown discriminator for ToRouter: ${discriminator}`);
+ }
+ }
+ }
+
+ /**
+ * Unsafely creates an instance of {@link ToRouter} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): ToRouter {
+ const discriminator = record.data.discriminator;
+ switch (discriminator) {
+ case 1: {
+ return new ToRouter({ discriminator: 1, value: RouterSubscribe.unsafeCast(record.value) });
+ }
+ case 2: {
+ return new ToRouter({ discriminator: 2, value: RouterUnsubscribe.unsafeCast(record.value) });
+ }
+ case 3: {
+ return new ToRouter({ discriminator: 3, value: RouterFrame.unsafeCast(record.value) });
+ }
+ }
+ throw new BebopRuntimeError(`Failed to unsafely cast union from discriminator: ${discriminator}`);
+ }
+
+ /**
+ * Creates a new {@link ToRouter} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): ToRouter {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`ToRouter.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ ToRouter.validateCompatibility(parsed);
+ return ToRouter.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return ToRouter.encode(this);
+ }
+
+ public static encode(record: IToRouter): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ ToRouter.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IToRouter, view: BebopView): number {
+ const before = view.length;
+ const pos = view.reserveMessageLength();
+ const start = view.length + 1;
+ view.writeByte(record.data.discriminator);
+ switch (record.data.discriminator) {
+ case 1:
+ RouterSubscribe.encodeInto(record.data.value, view);
+ break;
+ case 2:
+ RouterUnsubscribe.encodeInto(record.data.value, view);
+ break;
+ case 3:
+ RouterFrame.encodeInto(record.data.value, view);
+ break;
+ }
+ const end = view.length;
+ view.fillMessageLength(pos, end - start);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): ToRouter {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return ToRouter.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): ToRouter {
+ const length = view.readMessageLength();
+ const end = view.index + 1 + length;
+ switch (view.readByte()) {
+ case 1:
+ return this.fromRouterSubscribe(RouterSubscribe.readFrom(view));
+ case 2:
+ return this.fromRouterUnsubscribe(RouterUnsubscribe.readFrom(view));
+ case 3:
+ return this.fromRouterFrame(RouterFrame.readFrom(view));
+ default:
+ view.index = end;
+ throw new BebopRuntimeError("Unrecognized discriminator while decoding ToRouter");
+ }
+ }
+}
+
+
+export interface IRouterSubscribed extends BebopRecord {
+
+ readonly docId: string;
+}
+
+export class RouterSubscribed implements IRouterSubscribed {
+ public readonly discriminator: number = 1 as 1;
+ public static readonly discriminator: number = 1 as 1;
+ public readonly docId: string;
+
+ constructor(record: IRouterSubscribed) {
+ this.docId = record.docId;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterSubscribed.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterSubscribed): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterSubscribed.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterSubscribed}.
+ */
+ public static validateCompatibility(record: IRouterSubscribed): void {
+ BebopTypeGuard.ensureString(record.docId)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterSubscribed} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterSubscribed {
+ return new RouterSubscribed(record);
+ }
+
+ /**
+ * Creates a new {@link RouterSubscribed} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterSubscribed {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterSubscribed.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterSubscribed.validateCompatibility(parsed);
+ return RouterSubscribed.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterSubscribed.encode(this);
+ }
+
+ public static encode(record: IRouterSubscribed): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterSubscribed.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterSubscribed, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterSubscribed {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterSubscribed.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterSubscribed {
+ let field0: string;
+ field0 = view.readString();
+ let message: IRouterSubscribed = {
+ docId: field0,
+ };
+ return new RouterSubscribed(message);
+ }
+}
+
+
+export interface IRouterSubscribeFailed extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly reason: string;
+}
+
+export class RouterSubscribeFailed implements IRouterSubscribeFailed {
+ public readonly discriminator: number = 2 as 2;
+ public static readonly discriminator: number = 2 as 2;
+ public readonly docId: string;
+ public readonly reason: string;
+
+ constructor(record: IRouterSubscribeFailed) {
+ this.docId = record.docId;
+ this.reason = record.reason;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterSubscribeFailed.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterSubscribeFailed): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterSubscribeFailed.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterSubscribeFailed}.
+ */
+ public static validateCompatibility(record: IRouterSubscribeFailed): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureString(record.reason)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterSubscribeFailed} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterSubscribeFailed {
+ return new RouterSubscribeFailed(record);
+ }
+
+ /**
+ * Creates a new {@link RouterSubscribeFailed} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterSubscribeFailed {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterSubscribeFailed.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterSubscribeFailed.validateCompatibility(parsed);
+ return RouterSubscribeFailed.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterSubscribeFailed.encode(this);
+ }
+
+ public static encode(record: IRouterSubscribeFailed): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterSubscribeFailed.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterSubscribeFailed, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeString(record.reason);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterSubscribeFailed {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterSubscribeFailed.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterSubscribeFailed {
+ let field0: string;
+ field0 = view.readString();
+ let field1: string;
+ field1 = view.readString();
+ let message: IRouterSubscribeFailed = {
+ docId: field0,
+ reason: field1,
+ };
+ return new RouterSubscribeFailed(message);
+ }
+}
+
+
+export interface IRouterDocFrame extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly payload: Uint8Array;
+}
+
+export class RouterDocFrame implements IRouterDocFrame {
+ public readonly discriminator: number = 3 as 3;
+ public static readonly discriminator: number = 3 as 3;
+ public readonly docId: string;
+ public readonly payload: Uint8Array;
+
+ constructor(record: IRouterDocFrame) {
+ this.docId = record.docId;
+ this.payload = record.payload;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterDocFrame.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterDocFrame): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterDocFrame.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterDocFrame}.
+ */
+ public static validateCompatibility(record: IRouterDocFrame): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureArray(record.payload, BebopTypeGuard.ensureUint8);
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterDocFrame} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterDocFrame {
+ return new RouterDocFrame(record);
+ }
+
+ /**
+ * Creates a new {@link RouterDocFrame} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterDocFrame {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterDocFrame.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterDocFrame.validateCompatibility(parsed);
+ return RouterDocFrame.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterDocFrame.encode(this);
+ }
+
+ public static encode(record: IRouterDocFrame): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterDocFrame.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterDocFrame, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeBytes(record.payload);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterDocFrame {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterDocFrame.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterDocFrame {
+ let field0: string;
+ field0 = view.readString();
+ let field1: Uint8Array;
+ field1 = view.readBytes();
+ let message: IRouterDocFrame = {
+ docId: field0,
+ payload: field1,
+ };
+ return new RouterDocFrame(message);
+ }
+}
+
+
+export interface IRouterDocClosed extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly reason: string;
+}
+
+export class RouterDocClosed implements IRouterDocClosed {
+ public readonly discriminator: number = 4 as 4;
+ public static readonly discriminator: number = 4 as 4;
+ public readonly docId: string;
+ public readonly reason: string;
+
+ constructor(record: IRouterDocClosed) {
+ this.docId = record.docId;
+ this.reason = record.reason;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterDocClosed.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterDocClosed): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterDocClosed.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterDocClosed}.
+ */
+ public static validateCompatibility(record: IRouterDocClosed): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureString(record.reason)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterDocClosed} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterDocClosed {
+ return new RouterDocClosed(record);
+ }
+
+ /**
+ * Creates a new {@link RouterDocClosed} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterDocClosed {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterDocClosed.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterDocClosed.validateCompatibility(parsed);
+ return RouterDocClosed.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterDocClosed.encode(this);
+ }
+
+ public static encode(record: IRouterDocClosed): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterDocClosed.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterDocClosed, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeString(record.reason);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterDocClosed {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterDocClosed.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterDocClosed {
+ let field0: string;
+ field0 = view.readString();
+ let field1: string;
+ field1 = view.readString();
+ let message: IRouterDocClosed = {
+ docId: field0,
+ reason: field1,
+ };
+ return new RouterDocClosed(message);
+ }
+}
+
+
+export type IFromRouterType
+ = { discriminator: 1, value: IRouterSubscribed }
+ | { discriminator: 2, value: IRouterSubscribeFailed }
+ | { discriminator: 3, value: IRouterDocFrame }
+ | { discriminator: 4, value: IRouterDocClosed };
+
+export interface IFromRouter extends BebopRecord {
+ readonly data: IFromRouterType;
+}
+export class FromRouter implements IFromRouter {
+
+ public readonly data: IFromRouterType;
+
+ private constructor(data: IFromRouterType) {
+ this.data = data;
+ }
+
+ public get discriminator() {
+ return this.data.discriminator;
+ }
+
+ public get value() {
+ return this.data.value;
+ }
+
+ public static fromRouterSubscribed(value: IRouterSubscribed) {
+ return new FromRouter({ discriminator: 1, value: new RouterSubscribed(value)});
+ }
+
+ public isRouterSubscribed(): this is { value: RouterSubscribed } & { data: Extract<IFromRouterType, { discriminator: 1 }> } {
+ return this.data.value instanceof RouterSubscribed;
+ }
+
+ public static fromRouterSubscribeFailed(value: IRouterSubscribeFailed) {
+ return new FromRouter({ discriminator: 2, value: new RouterSubscribeFailed(value)});
+ }
+
+ public isRouterSubscribeFailed(): this is { value: RouterSubscribeFailed } & { data: Extract<IFromRouterType, { discriminator: 2 }> } {
+ return this.data.value instanceof RouterSubscribeFailed;
+ }
+
+ public static fromRouterDocFrame(value: IRouterDocFrame) {
+ return new FromRouter({ discriminator: 3, value: new RouterDocFrame(value)});
+ }
+
+ public isRouterDocFrame(): this is { value: RouterDocFrame } & { data: Extract<IFromRouterType, { discriminator: 3 }> } {
+ return this.data.value instanceof RouterDocFrame;
+ }
+
+ public static fromRouterDocClosed(value: IRouterDocClosed) {
+ return new FromRouter({ discriminator: 4, value: new RouterDocClosed(value)});
+ }
+
+ public isRouterDocClosed(): this is { value: RouterDocClosed } & { data: Extract<IFromRouterType, { discriminator: 4 }> } {
+ return this.data.value instanceof RouterDocClosed;
+ }
+
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return FromRouter.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IFromRouter): string {
+ delete (record.data.value as any).discriminator;
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ FromRouter.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link FromRouter}.
+ */
+ public static validateCompatibility(record: IFromRouter): void {
+ const discriminator = record.data.discriminator;
+ BebopTypeGuard.ensureUint8(discriminator);
+ switch (discriminator) {
+ case 1: {
+ RouterSubscribed.validateCompatibility(record.data.value);
+ break;
+ }
+ case 2: {
+ RouterSubscribeFailed.validateCompatibility(record.data.value);
+ break;
+ }
+ case 3: {
+ RouterDocFrame.validateCompatibility(record.data.value);
+ break;
+ }
+ case 4: {
+ RouterDocClosed.validateCompatibility(record.data.value);
+ break;
+ }
+ default: {
+ throw new Error(`Unknown discriminator for FromRouter: ${discriminator}`);
+ }
+ }
+ }
+
+ /**
+ * Unsafely creates an instance of {@link FromRouter} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): FromRouter {
+ const discriminator = record.data.discriminator;
+ switch (discriminator) {
+ case 1: {
+ return new FromRouter({ discriminator: 1, value: RouterSubscribed.unsafeCast(record.value) });
+ }
+ case 2: {
+ return new FromRouter({ discriminator: 2, value: RouterSubscribeFailed.unsafeCast(record.value) });
+ }
+ case 3: {
+ return new FromRouter({ discriminator: 3, value: RouterDocFrame.unsafeCast(record.value) });
+ }
+ case 4: {
+ return new FromRouter({ discriminator: 4, value: RouterDocClosed.unsafeCast(record.value) });
+ }
+ }
+ throw new BebopRuntimeError(`Failed to unsafely cast union from discriminator: ${discriminator}`);
+ }
+
+ /**
+ * Creates a new {@link FromRouter} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): FromRouter {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`FromRouter.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ FromRouter.validateCompatibility(parsed);
+ return FromRouter.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return FromRouter.encode(this);
+ }
+
+ public static encode(record: IFromRouter): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ FromRouter.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IFromRouter, view: BebopView): number {
+ const before = view.length;
+ const pos = view.reserveMessageLength();
+ const start = view.length + 1;
+ view.writeByte(record.data.discriminator);
+ switch (record.data.discriminator) {
+ case 1:
+ RouterSubscribed.encodeInto(record.data.value, view);
+ break;
+ case 2:
+ RouterSubscribeFailed.encodeInto(record.data.value, view);
+ break;
+ case 3:
+ RouterDocFrame.encodeInto(record.data.value, view);
+ break;
+ case 4:
+ RouterDocClosed.encodeInto(record.data.value, view);
+ break;
+ }
+ const end = view.length;
+ view.fillMessageLength(pos, end - start);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): FromRouter {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return FromRouter.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): FromRouter {
+ const length = view.readMessageLength();
+ const end = view.index + 1 + length;
+ switch (view.readByte()) {
+ case 1:
+ return this.fromRouterSubscribed(RouterSubscribed.readFrom(view));
+ case 2:
+ return this.fromRouterSubscribeFailed(RouterSubscribeFailed.readFrom(view));
+ case 3:
+ return this.fromRouterDocFrame(RouterDocFrame.readFrom(view));
+ case 4:
+ return this.fromRouterDocClosed(RouterDocClosed.readFrom(view));
+ default:
+ view.index = end;
+ throw new BebopRuntimeError("Unrecognized discriminator while decoding FromRouter");
+ }
+ }
+}
diff --git a/packages/collaboration/src/websocket/solid/state-signal.ts b/packages/collaboration/src/websocket/solid/state-signal.ts
index 5e3f6ab916..a95d3a6ed7 100644
--- a/packages/collaboration/src/websocket/solid/state-signal.ts
+++ b/packages/collaboration/src/websocket/solid/state-signal.ts
@@ -3,14 +3,22 @@ import type { Websocket } from '../core/websocket';
import { WebsocketConnectionState } from '../core/websocket-connection-state';
import { WebsocketEvent } from '../core/websocket-event';
+/** The slice of {@link Websocket} the signal needs — satisfied by the
+ * concrete websocket and by virtual sockets (e.g. the gateway sync
+ * transport's per-document sockets). */
+export type StateSignalSocket<Send, Receive> = Pick<
+ Websocket<Send, Receive>,
+ 'connectionState' | 'addEventListener' | 'removeEventListener'
+>;
+
/**
* Creates a reactive signal that tracks the connection state of a websocket.
*
* @param ws The websocket to track the connection state of.
* @returns A reactive signal that tracks the connection state of the websocket.
*/
-export function createWebsocketStateSignal(
- ws: Websocket<any, any>
+export function createWebsocketStateSignal<Send, Receive>(
+ ws: StateSignalSocket<Send, Receive>
): Accessor<WebsocketConnectionState> {
const [state, setState] = createSignal(ws.connectionState);
diff --git a/services/connection_gateway/Cargo.toml b/services/connection_gateway/Cargo.toml
index 7bfa664736..f4e6d6486e 100644
--- a/services/connection_gateway/Cargo.toml
+++ b/services/connection_gateway/Cargo.toml
@@ -61,6 +61,7 @@ macro_env = { path = "../../crates/macro_env" }
macro_env_var = { path = "../../crates/macro_env_var" }
macro_tower_layers = { path = "../../crates/macro_tower_layers" }
mockall.workspace = true
+postcard = { workspace = true }
model = { path = "../../crates/model" }
model-entity = { path = "../../crates/model-entity" }
models_bulk_upload = { path = "../../crates/models_bulk_upload" }
diff --git a/services/connection_gateway/src/api/connection.rs b/services/connection_gateway/src/api/connection.rs
index d113de0dc4..8b180879a4 100644
--- a/services/connection_gateway/src/api/connection.rs
+++ b/services/connection_gateway/src/api/connection.rs
@@ -103,6 +103,8 @@ async fn handle_websocket_connection(
connection_id: &connection_id,
};
+ crate::service::fanout::connected(&connection_context, &macro_user_id).await;
+
let receiver_task = handle_websocket_stream(connection_context, stream, sender.clone()).fuse();
tokio::select! {
@@ -133,6 +135,10 @@ async fn handle_websocket_connection(
);
})
.ok();
+
+ // After remove_connection, so consumers never see "gone" while the
+ // gateway can still route to the socket.
+ crate::service::fanout::disconnected(&connection_context).await;
drop(last_online_guard);
}
@@ -164,7 +170,7 @@ async fn forwarder(
}
span
}
- OutgoingMessage::Pong => tracing::Span::none(),
+ OutgoingMessage::Pong | OutgoingMessage::Binary(_) => tracing::Span::none(),
};
if let OutgoingMessage::Message(message) = &mut message {
message.trace.clear();
diff --git a/services/connection_gateway/src/api/connection/messages.rs b/services/connection_gateway/src/api/connection/messages.rs
index 2de7340358..506ab63d0e 100644
--- a/services/connection_gateway/src/api/connection/messages.rs
+++ b/services/connection_gateway/src/api/connection/messages.rs
@@ -5,7 +5,7 @@ use crate::{
tracking::{EntityConnectionExt, TrackingData},
websocket::ToWebsocketMessage,
},
- service::{stream_event::handle_stream_events, tracker},
+ service::{fanout, stream_event::handle_stream_events, tracker},
};
use anyhow::{Context, Result};
use axum::extract::ws::{Message, WebSocket};
@@ -50,6 +50,25 @@ pub async fn handle_message(
message: Message,
sender: &Sender<OutgoingMessage>,
) -> Result<()> {
+ // Every client frame is republished to the fanout channel, unparsed,
+ // before any in-gateway handling. Backend services consume what they care
+ // about (the sync tier reads binary frames); the gateway stays a dumb tap.
+ //
+ // TODO: the in-gateway handling below (entity tracking / frecency,
+ // stream-event subscriptions) should probably migrate to services
+ // consuming this same fanout, keeping the gateway a pure edge.
+ match &message {
+ Message::Text(text) => {
+ fanout::frame(&connection_context, true, text.as_bytes().to_vec()).await;
+ }
+ Message::Binary(payload) => {
+ fanout::frame(&connection_context, false, payload.to_vec()).await;
+ // Binary frames have no in-gateway handling; fanout is it.
+ return Ok(());
+ }
+ _ => {}
+ }
+
let text_message = match message {
Message::Text(text) => Some(text),
Message::Ping(_) | Message::Pong(_) => return Ok(()),
diff --git a/services/connection_gateway/src/context.rs b/services/connection_gateway/src/context.rs
index 936dd7dcc6..2b48abdd89 100644
--- a/services/connection_gateway/src/context.rs
+++ b/services/connection_gateway/src/context.rs
@@ -18,6 +18,9 @@ pub type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValida
#[derive(Clone, FromRef)]
pub struct ApiContext {
pub connection_manager: crate::service::connection::ConnectionManager,
+ /// Boot-unique id of this gateway instance, used to tag fanout
+ /// messages and name this instance's outbound fanout channel.
+ pub fanout_gateway_id: Arc<str>,
pub frecency_ingestor_service: EventIngestorImpl<FrecencyPgStorage>,
pub redis_client: Arc<redis::Client>,
pub redis_connection: MultiplexedConnection,
diff --git a/services/connection_gateway/src/main.rs b/services/connection_gateway/src/main.rs
index 550ead31bc..2ef4f22f89 100644
--- a/services/connection_gateway/src/main.rs
+++ b/services/connection_gateway/src/main.rs
@@ -114,8 +114,10 @@ async fn main() -> Result<()> {
let stream_service = RedisPostgresStreamRepo::new((*redis_client).clone(), pgpool.clone());
let stream_manager = RedisPostgresStreamManager::new(stream_service.obj());
+ let fanout_gateway_id: Arc<str> = Arc::from(uuid::Uuid::new_v4().to_string());
let context = context::ApiContext {
connection_manager,
+ fanout_gateway_id: Arc::clone(&fanout_gateway_id),
redis_client: Arc::clone(&redis_client),
redis_connection,
frecency_ingestor_service: EventIngestorImpl::new(FrecencyPgStorage::new(pgpool.clone())),
@@ -124,6 +126,11 @@ async fn main() -> Result<()> {
};
tokio::spawn(poll_messages(context.clone()));
+ tokio::spawn(service::fanout::poll_outbound(context.clone()));
+ tokio::spawn(service::fanout::heartbeat_loop(
+ context.redis_connection.clone(),
+ fanout_gateway_id,
+ ));
let config = Arc::new(config);
let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(
diff --git a/services/connection_gateway/src/model/message.rs b/services/connection_gateway/src/model/message.rs
index 382152e5f7..e326743056 100644
--- a/services/connection_gateway/src/model/message.rs
+++ b/services/connection_gateway/src/model/message.rs
@@ -60,6 +60,9 @@ impl TryFrom<StreamEvent> for Message {
pub enum OutgoingMessage {
Pong,
Message(Message),
+ /// A raw binary frame (sync-protocol traffic from the fanout's consumers),
+ /// sent to the client as a binary websocket message, unparsed.
+ Binary(Vec<u8>),
}
impl TryFrom<Message> for axum::extract::ws::Message {
@@ -78,6 +81,7 @@ impl TryFrom<OutgoingMessage> for axum::extract::ws::Message {
match msg {
OutgoingMessage::Pong => Ok(axum::extract::ws::Message::Text("pong".into())),
OutgoingMessage::Message(message) => message.try_into(),
+ OutgoingMessage::Binary(bytes) => Ok(axum::extract::ws::Message::Binary(bytes.into())),
}
}
}
diff --git a/services/connection_gateway/src/service/connection.rs b/services/connection_gateway/src/service/connection.rs
index 904c34775b..6fbc8f1401 100644
--- a/services/connection_gateway/src/service/connection.rs
+++ b/services/connection_gateway/src/service/connection.rs
@@ -254,6 +254,21 @@ impl ConnectionManager {
Ok(())
}
+ /// Send a raw binary frame to a connection held by this instance.
+ pub async fn send_binary(&self, id: &str, bytes: Vec<u8>) -> Result<()> {
+ let sender = match self.connections.get(id) {
+ Some(connection) => connection.sender.clone(),
+ None => anyhow::bail!("connection not found"),
+ };
+
+ if let Err(err) = sender.try_send(OutgoingMessage::Binary(bytes)) {
+ self.remove_connection(id).await?;
+ anyhow::bail!("failed to send binary message: {}", err);
+ }
+
+ Ok(())
+ }
+
pub fn get_entries_by_entity<'a>(
&'a self,
entity: &'a Entity<'a>,
diff --git a/services/connection_gateway/src/service/connection/test.rs b/services/connection_gateway/src/service/connection/test.rs
index 66878e6b51..f368a50eb0 100644
--- a/services/connection_gateway/src/service/connection/test.rs
+++ b/services/connection_gateway/src/service/connection/test.rs
@@ -170,3 +170,28 @@ async fn removing_a_connection_twice_does_not_wrap_the_count() {
"only the removal that took the entry may decrement the count"
);
}
+
+#[tokio::test(start_paused = true)]
+async fn binary_delivery_drops_a_full_connection_without_blocking_the_relay() {
+ let manager = ConnectionManager::new(UnusedRepo);
+ let (sender, _receiver) = tokio::sync::mpsc::channel(1);
+ sender.try_send(OutgoingMessage::Binary(vec![1])).unwrap();
+ let forwarder = tokio::spawn(std::future::pending::<()>());
+ manager.connections.insert(
+ "connection".to_owned(),
+ Connection {
+ sender,
+ abort_handle: forwarder.abort_handle(),
+ },
+ );
+
+ let result = tokio::time::timeout(
+ std::time::Duration::from_millis(100),
+ manager.send_binary("connection", vec![2]),
+ )
+ .await
+ .expect("a stalled client must not block other clients' sync replies");
+ assert!(result.is_err());
+ assert!(!manager.has_connection("connection"));
+ assert!(forwarder.await.unwrap_err().is_cancelled());
+}
diff --git a/services/connection_gateway/src/service/fanout.rs b/services/connection_gateway/src/service/fanout.rs
new file mode 100644
index 0000000000..51a0f385b5
--- /dev/null
+++ b/services/connection_gateway/src/service/fanout.rs
@@ -0,0 +1,166 @@
+//! Republish this instance's entire inbound websocket traffic to Redis.
+//!
+//! Every accepted connection, every client frame (text or binary, unparsed),
+//! and every disconnect is published on
+//! [`connection_gateway_models::fanout::INBOUND_CHANNEL`], so backend services
+//! can consume client traffic without the gateway knowing they exist. The
+//! sync tier is the first consumer.
+//!
+//! Publishing is fire-and-forget by design: a publish failure is logged and
+//! never fails the connection's own message handling.
+
+use crate::context::ApiContext;
+use crate::model::connection::ConnectionContext;
+use anyhow::{Context, Result};
+use connection_gateway_models::fanout::{
+ ConnId, FromGateway, GatewayId, HEARTBEAT_INTERVAL_SECS, INBOUND_CHANNEL, ToGateway,
+ outbound_channel,
+};
+use futures::StreamExt;
+use macro_user_id::user_id::MacroUserIdStr;
+use redis::AsyncCommands;
+
+async fn publish(ctx: &ConnectionContext<'_>, message: &FromGateway) -> Result<()> {
+ let payload = postcard::to_stdvec(message).context("failed to encode fanout message")?;
+ let mut connection = ctx.api_context.get_multiplexed_async_connection()?;
+ connection
+ .publish::<&str, &[u8], ()>(INBOUND_CHANNEL, &payload)
+ .await
+ .context("failed to publish fanout message")?;
+ Ok(())
+}
+
+/// Log-and-continue wrapper: fanout must never break connection handling.
+async fn publish_best_effort(ctx: &ConnectionContext<'_>, message: &FromGateway) {
+ publish(ctx, message)
+ .await
+ .inspect_err(|error| tracing::warn!(error=?error, "failed to publish fanout message"))
+ .ok();
+}
+
+/// Announce an accepted, authenticated connection.
+pub async fn connected(ctx: &ConnectionContext<'_>, user_id: &MacroUserIdStr<'static>) {
+ publish_best_effort(
+ ctx,
+ &FromGateway::Connected {
+ gateway: GatewayId(ctx.api_context.fanout_gateway_id.to_string()),
+ conn: ConnId(ctx.connection_id.to_string()),
+ user_id: user_id.clone(),
+ },
+ )
+ .await;
+}
+
+/// Forward one client frame, unparsed.
+pub async fn frame(ctx: &ConnectionContext<'_>, text: bool, payload: Vec<u8>) {
+ publish_best_effort(
+ ctx,
+ &FromGateway::Frame {
+ gateway: GatewayId(ctx.api_context.fanout_gateway_id.to_string()),
+ conn: ConnId(ctx.connection_id.to_string()),
+ text,
+ payload,
+ },
+ )
+ .await;
+}
+
+/// Announce a closed connection.
+pub async fn disconnected(ctx: &ConnectionContext<'_>) {
+ publish_best_effort(
+ ctx,
+ &FromGateway::Disconnected {
+ gateway: GatewayId(ctx.api_context.fanout_gateway_id.to_string()),
+ conn: ConnId(ctx.connection_id.to_string()),
+ },
+ )
+ .await;
+}
+
+/// Liveness beacon so consumers can drop state for dead gateway instances.
+/// Spawned once at boot.
+pub async fn heartbeat_loop(
+ redis_connection: redis::aio::MultiplexedConnection,
+ gateway_id: std::sync::Arc<str>,
+) {
+ let mut tick = tokio::time::interval(std::time::Duration::from_secs(HEARTBEAT_INTERVAL_SECS));
+ loop {
+ tick.tick().await;
+ let message = FromGateway::Heartbeat {
+ gateway: GatewayId(gateway_id.to_string()),
+ };
+ let Ok(payload) = postcard::to_stdvec(&message) else {
+ continue;
+ };
+ let mut connection = redis_connection.clone();
+ connection
+ .publish::<&str, &[u8], ()>(INBOUND_CHANNEL, &payload)
+ .await
+ .inspect_err(|error| tracing::warn!(error=?error, "failed to publish fanout heartbeat"))
+ .ok();
+ }
+}
+
+/// Consume this instance's outbound fanout channel: frames published by
+/// backend consumers (the sync tier) addressed to connections whose sockets
+/// this instance holds. Mirrors [`crate::service::redis::poll_messages`].
+pub async fn poll_outbound(ctx: ApiContext) -> Result<()> {
+ let gateway_id = GatewayId(ctx.fanout_gateway_id.to_string());
+ let channel = outbound_channel(&gateway_id);
+
+ let (mut sink, mut stream) = ctx.redis_client.get_async_pubsub().await?.split();
+ sink.subscribe(&channel)
+ .await
+ .context("failed to subscribe to fanout outbound channel")?;
+ tracing::debug!(channel, "subscribed to fanout outbound channel");
+
+ while let Some(message) = stream.next().await {
+ let payload: Vec<u8> = match message.get_payload() {
+ Ok(payload) => payload,
+ Err(error) => {
+ tracing::warn!(error = ?error, "unreadable outbound fanout payload; skipping");
+ continue;
+ }
+ };
+ match postcard::from_bytes::<ToGateway>(&payload) {
+ Ok(ToGateway::Frame {
+ conn,
+ text: false,
+ payload,
+ }) => {
+ ctx.connection_manager
+ .send_binary(&conn.0, payload)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(error = ?error, conn = %conn, "failed to deliver outbound frame");
+ })
+ .ok();
+ }
+ Ok(ToGateway::Frame {
+ conn, text: true, ..
+ }) => {
+ // No consumer sends text frames yet; refuse rather than guess
+ // at framing for the existing JSON protocol.
+ tracing::warn!(conn = %conn, "text outbound frames are not supported; dropping");
+ }
+ Ok(ToGateway::Close { conn, code }) => {
+ // TODO: plumb a real close (with code) through the connection
+ // manager; for now drop the connection, which closes the socket.
+ tracing::debug!(conn = %conn, code, "closing connection at consumer request");
+ ctx.connection_manager
+ .remove_connection(&conn.0)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(error = ?error, conn = %conn, "failed to close connection");
+ })
+ .ok();
+ }
+ Err(error) => {
+ tracing::warn!(error = ?error, "undecodable outbound fanout message; skipping");
+ }
+ }
+ }
+
+ tracing::warn!("fanout outbound poller exited");
+ Ok(())
+}
diff --git a/services/connection_gateway/src/service/mod.rs b/services/connection_gateway/src/service/mod.rs
index 4724ee0abb..02eb553f0c 100644
--- a/services/connection_gateway/src/service/mod.rs
+++ b/services/connection_gateway/src/service/mod.rs
@@ -1,5 +1,6 @@
pub mod connection;
pub mod dynamodb;
+pub mod fanout;
pub mod redis;
pub mod sender;
pub mod stream_event;
diff --git a/services/sync-router/AGENTS.md b/services/sync-router/AGENTS.md
new file mode 100644
index 0000000000..03d6bb2ce8
--- /dev/null
+++ b/services/sync-router/AGENTS.md
@@ -0,0 +1,44 @@
+# sync_router
+
+## What it is
+
+Routes document collaboration from the connection gateway's Redis fanout to
+Cloudflare Durable Object sync sockets. It owns routing, not document state.
+
+## Start here
+
+- `src/main.rs`: Redis and downstream adapter wiring, subscriber restart loop.
+- `src/domain/router.rs`: one owner for routes keyed by gateway, connection,
+ and document; route epochs protect replacements from stale close events.
+- `src/inbound/redis_edge.rs`: binary-frame filtering and gateway liveness.
+- `src/outbound/do_downstream.rs`: downstream dialing, buffering, and replies.
+
+## Scope
+
+- Owns subscription routing and teardown when clients or gateways disappear.
+- Document authorization and state belong to `services/sync-service`; forward
+ the scoped token to that service rather than interpreting it here.
+- Redis wire types belong to `crates/connection_gateway_models`; browser
+ envelopes are generated from `services/sync-service/bebop/schema.bop`.
+
+## Checks
+
+- `cargo test -p sync_router` (domain and adapter tests need no live services).
+- `cargo fmt --all -- --check` and `just clippy`.
+- After changing dependencies, `cargo x deps --check`.
+
+## Gotchas
+
+- `REDIS_HOST` and `SYNC_SERVICE_URL` are required at startup.
+- Document payloads retain the sync protocol's chunk framing. The router does
+ not decode or reassemble CRDT updates.
+- Redis pub/sub is best effort. Do not assume replay or durable delivery.
+- Every router subscribes to the same inbound channel; multiple instances do
+ not partition work. Add ownership coordination before horizontal scaling.
+- Local Docker and service inventory wiring are not a hosted deployment.
+ Provision the router before enabling `VITE_SYNC_VIA_GATEWAY` for clients.
+
+## Related
+
+- Architecture: `../../.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md`
+- Rules: `../../.agents/rules/observability.md`
diff --git a/services/sync-router/CLAUDE.md b/services/sync-router/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/sync-router/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/sync-router/Cargo.toml b/services/sync-router/Cargo.toml
new file mode 100644
index 0000000000..84ed82c195
--- /dev/null
+++ b/services/sync-router/Cargo.toml
@@ -0,0 +1,26 @@
+[package]
+edition = "2024"
+name = "sync_router"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+anyhow = { workspace = true }
+bebop = { workspace = true }
+connection_gateway_models = { path = "../../crates/connection_gateway_models" }
+futures = { workspace = true }
+macro_entrypoint = { path = "../../crates/macro_entrypoint" }
+macro_env_var = { path = "../../crates/macro_env_var" }
+opentelemetry = { workspace = true }
+postcard = { workspace = true }
+redis = { workspace = true, features = ["aio", "tokio-comp", "tokio-rustls-comp"] }
+sync_service_bebop_schema = { path = "../sync-service/bebop-schema", features = ["bebop-owned-all"] }
+thiserror = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "sync", "time"] }
+tokio-tungstenite = { workspace = true }
+tracing = { workspace = true }
+tracing-opentelemetry = { workspace = true }
+workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }
+
+[dev-dependencies]
+mockall = { workspace = true }
diff --git a/services/sync-router/src/domain/envelope.rs b/services/sync-router/src/domain/envelope.rs
new file mode 100644
index 0000000000..989a2802a8
--- /dev/null
+++ b/services/sync-router/src/domain/envelope.rs
@@ -0,0 +1,74 @@
+//! Encode/decode helpers for the multiplex envelope.
+//!
+//! The wire types are the bebop `ToRouter` / `FromRouter` unions from the
+//! sync-service schema. Decoding returns the generated *owned* variant
+//! (`owned::ToRouter`) so the rest of the router never touches wire
+//! lifetimes; encoding uses the borrowed variants for zero-copy serialize.
+
+#[cfg(test)]
+mod test;
+
+use bebop::{Record, SliceWrapper, SubRecord};
+use sync_service_bebop_schema::{FromRouter, owned};
+
+/// A decoded client envelope: the generated owned `ToRouter`, with the
+/// `Unknown` discriminator already rejected.
+pub type ClientEnvelope = owned::ToRouter;
+
+/// Errors from decoding a client envelope.
+#[derive(Debug, thiserror::Error)]
+pub enum EnvelopeError {
+ /// The bytes were not a valid `ToRouter` frame.
+ #[error("failed to decode ToRouter envelope: {0}")]
+ Decode(String),
+ /// The frame used a discriminator this build doesn't know.
+ #[error("unknown ToRouter variant")]
+ Unknown,
+}
+
+/// Decode a client's binary frame.
+pub fn decode_client(bytes: &[u8]) -> Result<ClientEnvelope, EnvelopeError> {
+ let envelope = owned::ToRouter::deserialize(bytes)
+ .map_err(|error| EnvelopeError::Decode(error.to_string()))?;
+ if matches!(envelope, owned::ToRouter::Unknown) {
+ return Err(EnvelopeError::Unknown);
+ }
+ Ok(envelope)
+}
+
+fn encode(frame: &FromRouter<'_>) -> Vec<u8> {
+ let mut buffer = Vec::with_capacity(frame.serialized_size());
+ frame
+ .serialize(&mut buffer)
+ .expect("serializing FromRouter into a Vec cannot fail");
+ buffer
+}
+
+/// The subscription is live (the downstream accepted the connection).
+pub fn subscribed(doc: &str) -> Vec<u8> {
+ encode(&FromRouter::RouterSubscribed { doc_id: doc })
+}
+
+/// The subscription was rejected or the dial failed.
+pub fn subscribe_failed(doc: &str, reason: &str) -> Vec<u8> {
+ encode(&FromRouter::RouterSubscribeFailed {
+ doc_id: doc,
+ reason,
+ })
+}
+
+/// One inner sync frame (a serialized `FromRemote`) from the downstream.
+pub fn doc_frame(doc: &str, payload: &[u8]) -> Vec<u8> {
+ encode(&FromRouter::RouterDocFrame {
+ doc_id: doc,
+ payload: SliceWrapper::Raw(payload),
+ })
+}
+
+/// The downstream connection closed; the client should re-subscribe.
+pub fn doc_closed(doc: &str, reason: &str) -> Vec<u8> {
+ encode(&FromRouter::RouterDocClosed {
+ doc_id: doc,
+ reason,
+ })
+}
diff --git a/services/sync-router/src/domain/envelope/test.rs b/services/sync-router/src/domain/envelope/test.rs
new file mode 100644
index 0000000000..78f5a2dfb2
--- /dev/null
+++ b/services/sync-router/src/domain/envelope/test.rs
@@ -0,0 +1,65 @@
+use super::*;
+use sync_service_bebop_schema::ToRouter;
+
+#[test]
+fn subscribe_round_trips() {
+ let mut buffer = Vec::new();
+ ToRouter::RouterSubscribe {
+ doc_id: "doc-1",
+ token: "tok",
+ }
+ .serialize(&mut buffer)
+ .unwrap();
+ assert_eq!(
+ decode_client(&buffer).unwrap(),
+ ClientEnvelope::RouterSubscribe {
+ doc_id: "doc-1".into(),
+ token: "tok".into()
+ },
+ );
+}
+
+#[test]
+fn frame_round_trips() {
+ let mut buffer = Vec::new();
+ ToRouter::RouterFrame {
+ doc_id: "doc-2",
+ payload: SliceWrapper::Raw(&[1, 2, 3]),
+ }
+ .serialize(&mut buffer)
+ .unwrap();
+ assert_eq!(
+ decode_client(&buffer).unwrap(),
+ ClientEnvelope::RouterFrame {
+ doc_id: "doc-2".into(),
+ payload: vec![1, 2, 3]
+ },
+ );
+}
+
+#[test]
+fn unknown_discriminator_is_the_unknown_error() {
+ // bebop union wire shape: u32 LE body length, then discriminator, then body.
+ let bytes = [1u8, 0, 0, 0, 99];
+ assert!(matches!(decode_client(&bytes), Err(EnvelopeError::Unknown)));
+}
+
+#[test]
+fn garbage_is_a_decode_error() {
+ assert!(matches!(
+ decode_client(&[0xde, 0xad]),
+ Err(EnvelopeError::Decode(_))
+ ));
+}
+
+#[test]
+fn server_frames_decode_as_from_router() {
+ let bytes = doc_frame("doc-3", &[9, 9]);
+ match FromRouter::deserialize(&bytes).unwrap() {
+ FromRouter::RouterDocFrame { doc_id, payload } => {
+ assert_eq!(doc_id, "doc-3");
+ assert_eq!(payload.to_vec(), vec![9, 9]);
+ }
+ other => panic!("wrong variant: {other:?}"),
+ }
+}
diff --git a/services/sync-router/src/domain/mod.rs b/services/sync-router/src/domain/mod.rs
new file mode 100644
index 0000000000..34e81c9b7d
--- /dev/null
+++ b/services/sync-router/src/domain/mod.rs
@@ -0,0 +1,6 @@
+//! Core routing logic: models, ports, the envelope codec, and the router loop.
+
+pub mod envelope;
+pub mod models;
+pub mod ports;
+pub mod router;
diff --git a/services/sync-router/src/domain/models.rs b/services/sync-router/src/domain/models.rs
new file mode 100644
index 0000000000..698af897ff
--- /dev/null
+++ b/services/sync-router/src/domain/models.rs
@@ -0,0 +1,67 @@
+//! Core types shared across the router.
+
+pub use connection_gateway_models::fanout::{ConnId, GatewayId};
+
+/// A client connection, globally identified by the gateway instance that owns
+/// its socket plus that gateway's local connection id.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct ConnectionId {
+ /// Boot-unique id of the gateway instance holding the socket.
+ pub gateway: GatewayId,
+ /// Gateway-local websocket connection id.
+ pub conn: ConnId,
+}
+
+/// A document id, as it appears in envelope frames and downstream URLs.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct DocId(pub String);
+
+impl DocId {
+ /// Borrow the raw id.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+/// Events from the gateway edge, already filtered to what the router handles
+/// (text frames never reach it).
+#[derive(Debug)]
+pub enum EdgeEvent {
+ /// A client sent a binary frame: a serialized `ToRouter` envelope.
+ Frame {
+ /// The sending connection.
+ conn: ConnectionId,
+ /// The raw envelope bytes.
+ payload: Vec<u8>,
+ },
+ /// A client connection closed.
+ Disconnected {
+ /// The closed connection.
+ conn: ConnectionId,
+ },
+ /// A gateway instance stopped heartbeating: every connection it held is gone.
+ GatewayLost {
+ /// The dead gateway instance's boot-unique id.
+ gateway: GatewayId,
+ },
+}
+
+/// Everything the router loop reacts to.
+#[derive(Debug)]
+pub enum Event {
+ /// An event from the gateway edge.
+ Edge(EdgeEvent),
+ /// A downstream connection died (upstream close or dial failure). The
+ /// client was already sent `RouterDocClosed` / `RouterSubscribeFailed` by
+ /// the downstream pump; this only cleans up the route.
+ DownstreamClosed {
+ /// The connection whose downstream died.
+ conn: ConnectionId,
+ /// The document it was for.
+ doc: DocId,
+ /// Which incarnation of the route died. A stale close (e.g. a slow
+ /// dial failing after the client already re-subscribed) must not tear
+ /// down the replacement route.
+ epoch: u64,
+ },
+}
diff --git a/services/sync-router/src/domain/ports.rs b/services/sync-router/src/domain/ports.rs
new file mode 100644
index 0000000000..0a77bb7ec0
--- /dev/null
+++ b/services/sync-router/src/domain/ports.rs
@@ -0,0 +1,45 @@
+//! Ports the router core depends on.
+
+use crate::domain::models::{ConnectionId, DocId};
+use std::fmt::Debug;
+use tokio::sync::mpsc;
+
+/// Delivers an already-serialized `FromRouter` envelope to a client
+/// connection. Implemented over the gateway's Redis outbound channel.
+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
+pub trait EdgeSink: Send + Sync + 'static {
+ /// The error type returned by delivery.
+ type Err: Into<anyhow::Error> + Send + Debug;
+
+ /// Deliver `frame` to `conn`'s websocket, best effort.
+ fn deliver(
+ &self,
+ conn: &ConnectionId,
+ frame: Vec<u8>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Opens the downstream for one `(connection, document)` subscription.
+///
+/// Returns a sender immediately; dialing happens in a background task, so
+/// frames sent before the dial completes buffer in the channel. The
+/// implementation delivers `RouterSubscribed` / `RouterSubscribeFailed` /
+/// `RouterDocFrame` / `RouterDocClosed` to the client itself and reports
+/// route teardown via [`crate::domain::models::Event::DownstreamClosed`].
+///
+/// Chapter 1 dials the Cloudflare Durable Object; chapter 2 consistent-hashes
+/// `doc` across native sync services.
+#[cfg_attr(test, mockall::automock)]
+pub trait DownstreamFactory: Send + Sync + 'static {
+ /// Open the downstream, returning where to send the client's inner
+ /// (already-serialized `FromPeer`) frames. `epoch` identifies this route
+ /// incarnation and must be echoed in the resulting
+ /// [`crate::domain::models::Event::DownstreamClosed`].
+ fn open(
+ &self,
+ conn: ConnectionId,
+ doc: DocId,
+ token: String,
+ epoch: u64,
+ ) -> mpsc::Sender<Vec<u8>>;
+}
diff --git a/services/sync-router/src/domain/router.rs b/services/sync-router/src/domain/router.rs
new file mode 100644
index 0000000000..cc44f65ba1
--- /dev/null
+++ b/services/sync-router/src/domain/router.rs
@@ -0,0 +1,196 @@
+//! The router core: one task owns this, so per-connection ordering is
+//! enforced by construction and no state needs locks.
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::{
+ envelope::{self, ClientEnvelope},
+ models::{ConnectionId, DocId, EdgeEvent, Event},
+ ports::{DownstreamFactory, EdgeSink},
+};
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
+use tokio::sync::mpsc;
+use tracing::{debug, warn};
+
+/// Routes envelope frames between gateway connections and per-document
+/// downstreams. Owned and driven by a single task; see [`Router::handle`].
+pub struct Router<Sink: EdgeSink, Downstreams: DownstreamFactory> {
+ sink: Arc<Sink>,
+ downstreams: Downstreams,
+ routes: HashMap<(ConnectionId, DocId), Route>,
+ /// Which documents each connection has open, for disconnect teardown.
+ by_conn: HashMap<ConnectionId, HashSet<DocId>>,
+ /// Monotonic route-incarnation counter; see [`Event::DownstreamClosed`].
+ next_epoch: u64,
+}
+
+/// One live (or dialing) downstream route.
+struct Route {
+ epoch: u64,
+ sender: mpsc::Sender<Vec<u8>>,
+}
+
+/// Documents one connection may hold open at once. The downstream token is
+/// only validated after the dial, so this bounds how much outbound work an
+/// authenticated-but-unauthorized client can trigger.
+const MAX_DOCS_PER_CONN: usize = 64;
+
+impl<Sink: EdgeSink, Downstreams: DownstreamFactory> Router<Sink, Downstreams> {
+ /// Create a router over the given sink and downstream factory.
+ pub fn new(sink: Arc<Sink>, downstreams: Downstreams) -> Self {
+ Self {
+ sink,
+ downstreams,
+ routes: HashMap::new(),
+ by_conn: HashMap::new(),
+ next_epoch: 0,
+ }
+ }
+
+ /// Drive the router from an event stream until it closes.
+ pub async fn run(mut self, mut events: mpsc::Receiver<Event>) {
+ while let Some(event) = events.recv().await {
+ self.handle(event).await;
+ }
+ }
+
+ /// Process one event.
+ #[tracing::instrument(skip_all)]
+ pub async fn handle(&mut self, event: Event) {
+ match event {
+ Event::Edge(EdgeEvent::Frame { conn, payload }) => {
+ match envelope::decode_client(&payload) {
+ Ok(frame) => self.handle_client(conn, frame).await,
+ Err(error) => {
+ warn!(error = ?error, conn = ?conn, "dropping undecodable client frame");
+ }
+ }
+ }
+ Event::Edge(EdgeEvent::Disconnected { conn }) => self.drop_conn(&conn),
+ Event::Edge(EdgeEvent::GatewayLost { gateway }) => {
+ let conns: Vec<ConnectionId> = self
+ .by_conn
+ .keys()
+ .filter(|conn| conn.gateway == gateway)
+ .cloned()
+ .collect();
+ debug!(
+ gateway = %gateway,
+ count = conns.len(),
+ "gateway lost; dropping its connections"
+ );
+ for conn in conns {
+ self.drop_conn(&conn);
+ }
+ }
+ Event::DownstreamClosed { conn, doc, epoch } => {
+ // The pump already told the client; forget the route — but
+ // only if it is still the incarnation that died. A stale
+ // close must not tear down a replacement route.
+ let is_current = self
+ .routes
+ .get(&(conn.clone(), doc.clone()))
+ .is_some_and(|route| route.epoch == epoch);
+ if is_current {
+ self.forget(&conn, &doc);
+ }
+ }
+ }
+ }
+
+ #[tracing::instrument(skip_all, fields(conn = %conn.conn, gateway = %conn.gateway))]
+ async fn handle_client(&mut self, conn: ConnectionId, frame: ClientEnvelope) {
+ match frame {
+ ClientEnvelope::RouterSubscribe { doc_id, token } => {
+ let doc = DocId(doc_id);
+ let key = (conn.clone(), doc.clone());
+ if self.routes.contains_key(&key) {
+ // Idempotent: the downstream is already up (or dialing).
+ // Re-ack so a retrying client settles.
+ self.deliver(&conn, envelope::subscribed(doc.as_str()))
+ .await;
+ return;
+ }
+ if self
+ .by_conn
+ .get(&conn)
+ .is_some_and(|docs| docs.len() >= MAX_DOCS_PER_CONN)
+ {
+ warn!(doc = doc.as_str(), "per-connection document cap reached");
+ self.deliver(
+ &conn,
+ envelope::subscribe_failed(doc.as_str(), "too many open documents"),
+ )
+ .await;
+ return;
+ }
+ debug!(doc = doc.as_str(), "opening downstream");
+ self.next_epoch += 1;
+ let epoch = self.next_epoch;
+ let sender = self
+ .downstreams
+ .open(conn.clone(), doc.clone(), token, epoch);
+ self.routes.insert(key, Route { epoch, sender });
+ self.by_conn.entry(conn).or_default().insert(doc);
+ }
+ ClientEnvelope::RouterUnsubscribe { doc_id } => {
+ // Dropping the sender closes the downstream quietly (the pump
+ // distinguishes our hangup from an upstream death).
+ self.forget(&conn, &DocId(doc_id));
+ }
+ // decode_client rejects Unknown before we get here.
+ ClientEnvelope::Unknown => {}
+ ClientEnvelope::RouterFrame { doc_id, payload } => {
+ let doc = DocId(doc_id);
+ let Some(sender) = self.routes.get(&(conn.clone(), doc.clone())) else {
+ warn!(
+ doc = doc.as_str(),
+ "frame for unsubscribed document; dropping"
+ );
+ return;
+ };
+ // try_send: a full buffer means a downstream that can't keep
+ // up; drop the frame — the sync protocol self-heals via
+ // catch-up requests. A closed channel means the downstream
+ // died; DownstreamClosed will clean the route up.
+ if let Err(error) = sender.sender.try_send(payload) {
+ warn!(doc = doc.as_str(), error = %error, "dropping frame for downstream");
+ }
+ }
+ }
+ }
+
+ fn drop_conn(&mut self, conn: &ConnectionId) {
+ let Some(docs) = self.by_conn.remove(conn) else {
+ return;
+ };
+ debug!(conn = %conn.conn, count = docs.len(), "dropping connection's downstreams");
+ for doc in docs {
+ self.routes.remove(&(conn.clone(), doc));
+ }
+ }
+
+ /// Remove one route and its `by_conn` entry (and the set itself once empty).
+ fn forget(&mut self, conn: &ConnectionId, doc: &DocId) {
+ self.routes.remove(&(conn.clone(), doc.clone()));
+ if let Some(docs) = self.by_conn.get_mut(conn) {
+ docs.remove(doc);
+ if docs.is_empty() {
+ self.by_conn.remove(conn);
+ }
+ }
+ }
+
+ async fn deliver(&self, conn: &ConnectionId, frame: Vec<u8>) {
+ self.sink
+ .deliver(conn, frame)
+ .await
+ .map_err(Into::into)
+ .inspect_err(|error: &anyhow::Error| {
+ warn!(error = ?error, conn = %conn.conn, "failed to deliver frame to client");
+ })
+ .ok();
+ }
+}
diff --git a/services/sync-router/src/domain/router/test.rs b/services/sync-router/src/domain/router/test.rs
new file mode 100644
index 0000000000..903ed89c2e
--- /dev/null
+++ b/services/sync-router/src/domain/router/test.rs
@@ -0,0 +1,183 @@
+use super::*;
+use crate::domain::ports::{MockDownstreamFactory, MockEdgeSink};
+use bebop::{Record, SliceWrapper};
+use sync_service_bebop_schema::ToRouter;
+
+fn conn(gateway: &str, id: &str) -> ConnectionId {
+ ConnectionId {
+ gateway: gateway.into(),
+ conn: id.into(),
+ }
+}
+
+fn frame_event(c: &ConnectionId, inner: ToRouter<'_>) -> Event {
+ let mut payload = Vec::new();
+ inner.serialize(&mut payload).unwrap();
+ Event::Edge(EdgeEvent::Frame {
+ conn: c.clone(),
+ payload,
+ })
+}
+
+fn subscribe(c: &ConnectionId, doc: &str) -> Event {
+ frame_event(
+ c,
+ ToRouter::RouterSubscribe {
+ doc_id: doc,
+ token: "tok",
+ },
+ )
+}
+
+fn doc_frame(c: &ConnectionId, doc: &str, bytes: &[u8]) -> Event {
+ frame_event(
+ c,
+ ToRouter::RouterFrame {
+ doc_id: doc,
+ payload: SliceWrapper::Raw(bytes),
+ },
+ )
+}
+
+/// A factory that hands out channels and records what it opened.
+fn recording_factory(
+ capacity: usize,
+) -> (
+ MockDownstreamFactory,
+ std::sync::Arc<std::sync::Mutex<Vec<(DocId, mpsc::Receiver<Vec<u8>>)>>>,
+) {
+ let opened = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let record = std::sync::Arc::clone(&opened);
+ let mut factory = MockDownstreamFactory::new();
+ factory
+ .expect_open()
+ .returning(move |_conn, doc, _token, _epoch| {
+ let (tx, rx) = mpsc::channel(capacity);
+ record.lock().unwrap().push((doc, rx));
+ tx
+ });
+ (factory, opened)
+}
+
+#[tokio::test]
+async fn frames_buffer_into_the_downstream_channel_before_dial_completes() {
+ let (factory, opened) = recording_factory(8);
+ let mut router = Router::new(std::sync::Arc::new(MockEdgeSink::new()), factory);
+
+ let c = conn("g1", "c1");
+ router.handle(subscribe(&c, "doc-a")).await;
+ router.handle(doc_frame(&c, "doc-a", b"first")).await;
+ router.handle(doc_frame(&c, "doc-a", b"second")).await;
+
+ let mut opened = opened.lock().unwrap();
+ let (doc, rx) = &mut opened[0];
+ assert_eq!(doc.as_str(), "doc-a");
+ assert_eq!(rx.try_recv().unwrap(), b"first");
+ assert_eq!(rx.try_recv().unwrap(), b"second");
+}
+
+#[tokio::test]
+async fn resubscribe_is_idempotent_and_reacks() {
+ let (factory, opened) = recording_factory(8);
+ let mut sink = MockEdgeSink::new();
+ // Exactly one re-ack for the duplicate subscribe.
+ sink.expect_deliver()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ let mut router = Router::new(std::sync::Arc::new(sink), factory);
+
+ let c = conn("g1", "c1");
+ router.handle(subscribe(&c, "doc-a")).await;
+ router.handle(subscribe(&c, "doc-a")).await;
+
+ assert_eq!(opened.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn disconnect_tears_down_every_route_for_the_connection() {
+ let (factory, opened) = recording_factory(8);
+ let mut router = Router::new(std::sync::Arc::new(MockEdgeSink::new()), factory);
+
+ let c = conn("g1", "c1");
+ router.handle(subscribe(&c, "doc-a")).await;
+ router.handle(subscribe(&c, "doc-b")).await;
+ router
+ .handle(Event::Edge(EdgeEvent::Disconnected { conn: c.clone() }))
+ .await;
+
+ // Dropped senders close the channels — the downstream pumps see hangup.
+ let mut opened = opened.lock().unwrap();
+ for (_, rx) in opened.iter_mut() {
+ assert!(matches!(
+ rx.try_recv(),
+ Err(mpsc::error::TryRecvError::Disconnected)
+ ));
+ }
+ // And frames after disconnect are dropped, not routed.
+ router.handle(doc_frame(&c, "doc-a", b"late")).await;
+}
+
+#[tokio::test]
+async fn gateway_lost_drops_only_that_gateways_connections() {
+ let (factory, opened) = recording_factory(8);
+ let mut router = Router::new(std::sync::Arc::new(MockEdgeSink::new()), factory);
+
+ let dead = conn("g1", "c1");
+ let alive = conn("g2", "c2");
+ router.handle(subscribe(&dead, "doc-a")).await;
+ router.handle(subscribe(&alive, "doc-b")).await;
+ router
+ .handle(Event::Edge(EdgeEvent::GatewayLost {
+ gateway: "g1".into(),
+ }))
+ .await;
+
+ let mut opened = opened.lock().unwrap();
+ let (_, dead_rx) = &mut opened[0];
+ assert!(matches!(
+ dead_rx.try_recv(),
+ Err(mpsc::error::TryRecvError::Disconnected)
+ ));
+ let (_, alive_rx) = &mut opened[1];
+ assert!(matches!(
+ alive_rx.try_recv(),
+ Err(mpsc::error::TryRecvError::Empty)
+ ));
+}
+
+#[tokio::test]
+async fn unknown_doc_frames_and_garbage_are_dropped_without_panic() {
+ let (factory, _opened) = recording_factory(8);
+ let mut router = Router::new(std::sync::Arc::new(MockEdgeSink::new()), factory);
+
+ let c = conn("g1", "c1");
+ router.handle(doc_frame(&c, "never-subscribed", b"x")).await;
+ router
+ .handle(Event::Edge(EdgeEvent::Frame {
+ conn: c,
+ payload: vec![0xde, 0xad],
+ }))
+ .await;
+}
+
+#[tokio::test]
+async fn downstream_closed_forgets_the_route_so_resubscribe_reopens() {
+ let (factory, opened) = recording_factory(8);
+ let mut sink = MockEdgeSink::new();
+ sink.expect_deliver()
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ let mut router = Router::new(std::sync::Arc::new(sink), factory);
+
+ let c = conn("g1", "c1");
+ router.handle(subscribe(&c, "doc-a")).await;
+ router
+ .handle(Event::DownstreamClosed {
+ conn: c.clone(),
+ doc: DocId("doc-a".into()),
+ epoch: 1,
+ })
+ .await;
+ router.handle(subscribe(&c, "doc-a")).await;
+
+ assert_eq!(opened.lock().unwrap().len(), 2);
+}
diff --git a/services/sync-router/src/inbound/mod.rs b/services/sync-router/src/inbound/mod.rs
new file mode 100644
index 0000000000..247ae8a686
--- /dev/null
+++ b/services/sync-router/src/inbound/mod.rs
@@ -0,0 +1,3 @@
+//! Driving adapters: sources of [`crate::domain::models::Event`].
+
+pub mod redis_edge;
diff --git a/services/sync-router/src/inbound/redis_edge.rs b/services/sync-router/src/inbound/redis_edge.rs
new file mode 100644
index 0000000000..8bcd089664
--- /dev/null
+++ b/services/sync-router/src/inbound/redis_edge.rs
@@ -0,0 +1,129 @@
+//! Consume the connection gateway's Redis fanout and translate it into
+//! [`EdgeEvent`]s. All Redis-isms (heartbeats, gateway liveness, text-frame
+//! filtering) are absorbed here; the router core never sees them.
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::models::{ConnectionId, EdgeEvent, Event};
+use anyhow::{Context, Result};
+use connection_gateway_models::fanout::{
+ FromGateway, GatewayId, HEARTBEAT_INTERVAL_SECS, INBOUND_CHANNEL,
+};
+use futures::StreamExt;
+use std::collections::HashMap;
+use std::time::Duration;
+use tokio::sync::mpsc;
+use tokio::time::Instant;
+use tracing::{debug, warn};
+
+/// A gateway instance is declared dead after this long without a heartbeat
+/// (or any other message from it).
+const GATEWAY_STALE_AFTER: Duration = Duration::from_secs(HEARTBEAT_INTERVAL_SECS * 3);
+
+/// Subscribe to the fanout channel and pump events until Redis drops us.
+/// The caller is expected to reconnect-and-rerun on exit.
+pub async fn run(redis_client: &redis::Client, events: mpsc::Sender<Event>) -> Result<()> {
+ let mut pubsub = redis_client
+ .get_async_pubsub()
+ .await
+ .context("failed to open redis pubsub connection")?;
+ pubsub
+ .subscribe(INBOUND_CHANNEL)
+ .await
+ .context("failed to subscribe to fanout channel")?;
+ debug!(channel = INBOUND_CHANNEL, "subscribed to gateway fanout");
+
+ let mut liveness: HashMap<GatewayId, Instant> = HashMap::new();
+ let mut sweep = tokio::time::interval(Duration::from_secs(HEARTBEAT_INTERVAL_SECS));
+ let mut stream = pubsub.on_message();
+
+ loop {
+ tokio::select! {
+ message = stream.next() => {
+ let Some(message) = message else {
+ // Redis connection died; surface it so main reconnects.
+ anyhow::bail!("fanout pubsub stream ended");
+ };
+ let payload: Vec<u8> = match message.get_payload() {
+ Ok(payload) => payload,
+ Err(error) => {
+ warn!(error = ?error, "unreadable fanout payload; skipping");
+ continue;
+ }
+ };
+ let decoded: FromGateway = match postcard::from_bytes(&payload) {
+ Ok(decoded) => decoded,
+ Err(error) => {
+ warn!(error = ?error, "undecodable fanout message; skipping");
+ continue;
+ }
+ };
+ if let Some(event) = translate(decoded, &mut liveness)
+ && events.send(event).await.is_err()
+ {
+ return Ok(()); // router shut down
+ }
+ }
+ _ = sweep.tick() => {
+ let now = Instant::now();
+ let stale: Vec<GatewayId> = liveness
+ .iter()
+ .filter(|(_, seen)| now.duration_since(**seen) > GATEWAY_STALE_AFTER)
+ .map(|(gateway, _)| gateway.clone())
+ .collect();
+ for gateway in stale {
+ warn!(gateway = %gateway, "gateway heartbeat went quiet; dropping its connections");
+ liveness.remove(&gateway);
+ if events
+ .send(Event::Edge(EdgeEvent::GatewayLost { gateway }))
+ .await
+ .is_err()
+ {
+ return Ok(());
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Turn one fanout message into an edge event, updating gateway liveness.
+/// Returns `None` for messages the router doesn't act on (text frames,
+/// heartbeats, `Connected` — the router keys everything off `Subscribe`).
+fn translate(message: FromGateway, liveness: &mut HashMap<GatewayId, Instant>) -> Option<Event> {
+ let mark = |liveness: &mut HashMap<GatewayId, Instant>, gateway: &GatewayId| {
+ liveness.insert(gateway.clone(), Instant::now());
+ };
+ match message {
+ FromGateway::Heartbeat { gateway } => {
+ mark(liveness, &gateway);
+ None
+ }
+ FromGateway::Connected { gateway, .. } => {
+ mark(liveness, &gateway);
+ None
+ }
+ FromGateway::Frame {
+ gateway,
+ conn,
+ text,
+ payload,
+ } => {
+ mark(liveness, &gateway);
+ if text {
+ return None; // existing gateway JSON traffic, not ours
+ }
+ Some(Event::Edge(EdgeEvent::Frame {
+ conn: ConnectionId { gateway, conn },
+ payload,
+ }))
+ }
+ FromGateway::Disconnected { gateway, conn } => {
+ mark(liveness, &gateway);
+ Some(Event::Edge(EdgeEvent::Disconnected {
+ conn: ConnectionId { gateway, conn },
+ }))
+ }
+ }
+}
diff --git a/services/sync-router/src/inbound/redis_edge/test.rs b/services/sync-router/src/inbound/redis_edge/test.rs
new file mode 100644
index 0000000000..6b581657e8
--- /dev/null
+++ b/services/sync-router/src/inbound/redis_edge/test.rs
@@ -0,0 +1,75 @@
+use super::*;
+use connection_gateway_models::fanout::ConnId;
+
+fn gateway(id: &str) -> GatewayId {
+ GatewayId(id.into())
+}
+
+#[test]
+fn text_frames_are_filtered_but_still_mark_liveness() {
+ let mut liveness = HashMap::new();
+ let event = translate(
+ FromGateway::Frame {
+ gateway: gateway("g1"),
+ conn: ConnId("c1".into()),
+ text: true,
+ payload: b"{}".to_vec(),
+ },
+ &mut liveness,
+ );
+ assert!(event.is_none());
+ assert!(liveness.contains_key(&gateway("g1")));
+}
+
+#[test]
+fn binary_frames_become_edge_frames() {
+ let mut liveness = HashMap::new();
+ let event = translate(
+ FromGateway::Frame {
+ gateway: gateway("g1"),
+ conn: ConnId("c1".into()),
+ text: false,
+ payload: vec![1, 2],
+ },
+ &mut liveness,
+ );
+ match event {
+ Some(Event::Edge(EdgeEvent::Frame { conn, payload })) => {
+ assert_eq!(conn.gateway, gateway("g1"));
+ assert_eq!(conn.conn, ConnId("c1".into()));
+ assert_eq!(payload, vec![1, 2]);
+ }
+ other => panic!("wrong event: {other:?}"),
+ }
+}
+
+#[test]
+fn heartbeats_and_connected_mark_liveness_without_events() {
+ let mut liveness = HashMap::new();
+ assert!(
+ translate(
+ FromGateway::Heartbeat {
+ gateway: gateway("g1")
+ },
+ &mut liveness
+ )
+ .is_none()
+ );
+ assert!(liveness.contains_key(&gateway("g1")));
+}
+
+#[test]
+fn disconnected_becomes_an_edge_event() {
+ let mut liveness = HashMap::new();
+ let event = translate(
+ FromGateway::Disconnected {
+ gateway: gateway("g1"),
+ conn: ConnId("c1".into()),
+ },
+ &mut liveness,
+ );
+ assert!(matches!(
+ event,
+ Some(Event::Edge(EdgeEvent::Disconnected { .. }))
+ ));
+}
diff --git a/services/sync-router/src/lib.rs b/services/sync-router/src/lib.rs
new file mode 100644
index 0000000000..3007b904e3
--- /dev/null
+++ b/services/sync-router/src/lib.rs
@@ -0,0 +1,17 @@
+#![deny(missing_docs)]
+//! The sync-router: forwards sync-protocol frames between the connection
+//! gateway's Redis fanout and a per-document downstream.
+//!
+//! Chapter 1: the downstream is the existing Cloudflare Durable Object
+//! sync-service, dialed per `(connection, document)` so the DO sees each user
+//! as an ordinary peer. The router parses only the multiplex envelope
+//! ([`sync_service_bebop_schema`]'s `ToRouter`/`FromRouter`); inner sync
+//! payloads pass through untouched.
+//!
+//! Chapter 2 swaps the [`domain::ports::DownstreamFactory`] implementation for
+//! one that consistent-hashes document ids across native sync services. The
+//! router core does not change.
+
+pub mod domain;
+pub mod inbound;
+pub mod outbound;
diff --git a/services/sync-router/src/main.rs b/services/sync-router/src/main.rs
new file mode 100644
index 0000000000..4ec89b66e2
--- /dev/null
+++ b/services/sync-router/src/main.rs
@@ -0,0 +1,57 @@
+//! sync-router: forwards sync frames between the connection gateway's Redis
+//! fanout and per-document downstreams (Durable Objects, chapter 1).
+
+use anyhow::{Context, Result};
+use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
+use std::sync::Arc;
+use sync_router::domain::router::Router;
+use sync_router::inbound::redis_edge;
+use sync_router::outbound::{do_downstream::DoDownstreamFactory, redis_sink::RedisSink};
+use tokio::sync::mpsc;
+
+env_vars! {
+ pub struct RedisHost;
+ pub struct SyncServiceUrl;
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ MacroEntrypoint::default().init();
+
+ let redis_host = RedisHost::new().context("REDIS_HOST must be provided")?;
+ let sync_service_url = SyncServiceUrl::new().context("SYNC_SERVICE_URL must be provided")?;
+
+ let redis_client =
+ redis::Client::open(redis_host.to_string()).context("failed to create redis client")?;
+ let redis_connection = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .context("failed to connect to redis")?;
+
+ let (events_tx, events_rx) = mpsc::channel(4096);
+ let sink = Arc::new(RedisSink::new(redis_connection));
+ let downstreams = DoDownstreamFactory::new(
+ sync_service_url.to_string(),
+ Arc::clone(&sink),
+ events_tx.clone(),
+ );
+
+ let router = Router::new(sink, downstreams);
+ tokio::spawn(router.run(events_rx));
+
+ tracing::info!("sync-router started");
+
+ // The subscriber is the process's spine: resubscribe forever on Redis
+ // failure. An Ok return means the router task itself is gone, which is
+ // unrecoverable — exit non-zero and let the supervisor restart us.
+ loop {
+ match redis_edge::run(&redis_client, events_tx.clone()).await {
+ Ok(()) => anyhow::bail!("router task shut down"),
+ Err(error) => {
+ tracing::error!(error = ?error, "fanout subscriber failed; reconnecting");
+ }
+ }
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+ }
+}
diff --git a/services/sync-router/src/outbound/do_downstream.rs b/services/sync-router/src/outbound/do_downstream.rs
new file mode 100644
index 0000000000..3dae0ce951
--- /dev/null
+++ b/services/sync-router/src/outbound/do_downstream.rs
@@ -0,0 +1,194 @@
+//! [`DownstreamFactory`] that dials the Cloudflare Durable Object
+//! sync-service, one websocket per `(connection, document)` — the DO sees
+//! each client as an ordinary peer, so nothing changes on the Cloudflare side.
+//!
+//! Chapter 2 replaces this with a factory that consistent-hashes the document
+//! id across native sync services; the router core is unaware.
+
+use crate::domain::envelope;
+use crate::domain::models::{ConnectionId, DocId, Event};
+use crate::domain::ports::{DownstreamFactory, EdgeSink};
+use futures::{SinkExt, StreamExt};
+use opentelemetry::trace::TraceContextExt;
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::sync::mpsc;
+use tokio_tungstenite::connect_async;
+use tokio_tungstenite::tungstenite::Message;
+use tracing::{debug, warn};
+use tracing_opentelemetry::OpenTelemetrySpanExt;
+
+/// How many client frames may buffer while the dial is in flight (or the
+/// upstream is slow). Overflow drops frames; the sync protocol self-heals.
+const DOWNSTREAM_BUFFER: usize = 256;
+
+/// Keep the upstream (and its Durable Object) alive, mirroring the ping the
+/// browser used to send on its direct per-document socket.
+const UPSTREAM_PING_INTERVAL: Duration = Duration::from_secs(30);
+
+/// Dials `{base_url}/document/{doc}/connect?token=…&traceparent=…`.
+pub struct DoDownstreamFactory<Sink: EdgeSink> {
+ base_url: String,
+ sink: Arc<Sink>,
+ events: mpsc::Sender<Event>,
+}
+
+impl<Sink: EdgeSink> DoDownstreamFactory<Sink> {
+ /// `base_url` is the sync-service origin, e.g. `http://localhost:8787`.
+ pub fn new(base_url: String, sink: Arc<Sink>, events: mpsc::Sender<Event>) -> Self {
+ Self {
+ base_url,
+ sink,
+ events,
+ }
+ }
+}
+
+impl<Sink: EdgeSink> DownstreamFactory for DoDownstreamFactory<Sink> {
+ #[tracing::instrument(skip(self, token), fields(document.id = doc.as_str()))]
+ fn open(
+ &self,
+ conn: ConnectionId,
+ doc: DocId,
+ token: String,
+ epoch: u64,
+ ) -> mpsc::Sender<Vec<u8>> {
+ let (sender, receiver) = mpsc::channel(DOWNSTREAM_BUFFER);
+
+ let ws_base = self
+ .base_url
+ .replacen("http://", "ws://", 1)
+ .replacen("https://", "wss://", 1);
+ let mut url = format!("{ws_base}/document/{}/connect?token={token}", doc.as_str());
+ // The DO reads `traceparent` from the query string (browser websocket
+ // upgrades can't carry headers, so the DO accepts it there; we use the
+ // same mechanism).
+ if let Some(traceparent) = current_traceparent() {
+ url.push_str(&format!("&traceparent={traceparent}"));
+ }
+
+ tokio::spawn(pump(
+ url,
+ conn,
+ doc,
+ epoch,
+ receiver,
+ Arc::clone(&self.sink),
+ self.events.clone(),
+ ));
+ sender
+ }
+}
+
+/// The whole life of one downstream connection: dial, then pump frames both
+/// ways until either side hangs up.
+#[tracing::instrument(skip_all, fields(document.id = doc.as_str(), conn = %conn.conn))]
+async fn pump<Sink: EdgeSink>(
+ url: String,
+ conn: ConnectionId,
+ doc: DocId,
+ epoch: u64,
+ mut from_client: mpsc::Receiver<Vec<u8>>,
+ sink: Arc<Sink>,
+ events: mpsc::Sender<Event>,
+) {
+ let deliver = |frame: Vec<u8>| {
+ let sink = Arc::clone(&sink);
+ let conn = conn.clone();
+ async move {
+ sink.deliver(&conn, frame)
+ .await
+ .map_err(Into::into)
+ .inspect_err(|error: &anyhow::Error| {
+ warn!(error = ?error, "failed to deliver to client");
+ })
+ .ok();
+ }
+ };
+
+ let upstream = match connect_async(&url).await {
+ Ok((upstream, _response)) => upstream,
+ Err(error) => {
+ warn!(error = ?error, "downstream dial failed");
+ deliver(envelope::subscribe_failed(doc.as_str(), "dial failed")).await;
+ events
+ .send(Event::DownstreamClosed { conn, doc, epoch })
+ .await
+ .ok();
+ return;
+ }
+ };
+ debug!("downstream connected");
+ deliver(envelope::subscribed(doc.as_str())).await;
+
+ let (mut write, mut read) = upstream.split();
+ let mut ping = tokio::time::interval(UPSTREAM_PING_INTERVAL);
+ ping.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+
+ // `None` = the router dropped our sender (unsubscribe / client
+ // disconnect): close quietly. `Some(reason)` = the upstream went away:
+ // tell the client (a coarse reason only — raw errors can leak internals)
+ // so it can re-subscribe.
+ let closed_reason: Option<&str> = loop {
+ tokio::select! {
+ frame = from_client.recv() => match frame {
+ Some(bytes) => {
+ if let Err(error) = write.send(Message::Binary(bytes.into())).await {
+ warn!(error = ?error, "upstream write failed");
+ break Some("upstream write failed");
+ }
+ }
+ None => break None,
+ },
+ incoming = read.next() => match incoming {
+ Some(Ok(Message::Binary(bytes))) => {
+ deliver(envelope::doc_frame(doc.as_str(), &bytes)).await;
+ }
+ // The DO's "pong" heartbeat replies (and any other text).
+ Some(Ok(Message::Text(_))) => {}
+ Some(Ok(Message::Close(_))) | None => break Some("upstream closed"),
+ Some(Ok(_)) => {}
+ Some(Err(error)) => {
+ warn!(error = ?error, "upstream read failed");
+ break Some("upstream error");
+ }
+ },
+ _ = ping.tick() => {
+ if let Err(error) = write.send(Message::Text("ping".into())).await {
+ warn!(error = ?error, "upstream ping failed");
+ break Some("upstream ping failed");
+ }
+ }
+ }
+ };
+
+ match closed_reason {
+ Some(reason) => {
+ debug!(reason, "downstream closed");
+ deliver(envelope::doc_closed(doc.as_str(), reason)).await;
+ events
+ .send(Event::DownstreamClosed { conn, doc, epoch })
+ .await
+ .ok();
+ }
+ None => {
+ debug!("router hung up; closing downstream");
+ write.send(Message::Close(None)).await.ok();
+ }
+ }
+}
+
+/// The current span's context as a W3C traceparent, if a trace is recording.
+fn current_traceparent() -> Option<String> {
+ let context = tracing::Span::current().context();
+ let span = context.span();
+ let span_context = span.span_context();
+ span_context.is_valid().then(|| {
+ format!(
+ "00-{}-{}-{:02x}",
+ span_context.trace_id(),
+ span_context.span_id(),
+ span_context.trace_flags().to_u8(),
+ )
+ })
+}
diff --git a/services/sync-router/src/outbound/mod.rs b/services/sync-router/src/outbound/mod.rs
new file mode 100644
index 0000000000..f64e965481
--- /dev/null
+++ b/services/sync-router/src/outbound/mod.rs
@@ -0,0 +1,4 @@
+//! Driven adapters: implementations of the domain ports.
+
+pub mod do_downstream;
+pub mod redis_sink;
diff --git a/services/sync-router/src/outbound/redis_sink.rs b/services/sync-router/src/outbound/redis_sink.rs
new file mode 100644
index 0000000000..07066c7509
--- /dev/null
+++ b/services/sync-router/src/outbound/redis_sink.rs
@@ -0,0 +1,39 @@
+//! [`EdgeSink`] over the gateway's per-instance Redis outbound channel.
+
+use crate::domain::models::ConnectionId;
+use crate::domain::ports::EdgeSink;
+use anyhow::Context;
+use connection_gateway_models::fanout::{ToGateway, outbound_channel};
+use redis::AsyncCommands;
+
+/// Publishes `FromRouter` envelope bytes to the gateway instance that holds
+/// the target connection's socket.
+pub struct RedisSink {
+ connection: redis::aio::MultiplexedConnection,
+}
+
+impl RedisSink {
+ /// Wrap an established Redis connection.
+ pub fn new(connection: redis::aio::MultiplexedConnection) -> Self {
+ Self { connection }
+ }
+}
+
+impl EdgeSink for RedisSink {
+ type Err = anyhow::Error;
+
+ async fn deliver(&self, conn: &ConnectionId, frame: Vec<u8>) -> Result<(), Self::Err> {
+ let message = ToGateway::Frame {
+ conn: conn.conn.clone(),
+ text: false,
+ payload: frame,
+ };
+ let payload = postcard::to_stdvec(&message).context("failed to encode ToGateway frame")?;
+ let mut connection = self.connection.clone();
+ connection
+ .publish::<String, &[u8], ()>(outbound_channel(&conn.gateway), &payload)
+ .await
+ .context("failed to publish frame to gateway outbound channel")?;
+ Ok(())
+ }
+}
diff --git a/services/sync-service/bebop-schema/src/generated.rs b/services/sync-service/bebop-schema/src/generated.rs
index 9f0e62fafa..9c8f984588 100644
--- a/services/sync-service/bebop-schema/src/generated.rs
+++ b/services/sync-service/bebop-schema/src/generated.rs
@@ -544,6 +544,334 @@ impl<'raw> ::bebop::SubRecord<'raw> for InitializeFromSnapshotRequest<'raw> {
impl<'raw> ::bebop::Record<'raw> for InitializeFromSnapshotRequest<'raw> {}
+/// Multiplex envelope between the browser and the sync-router (rides the
+/// connection-gateway socket as binary frames). Inner payloads are the
+/// existing FromPeer/FromRemote unions, already bebop-encoded — the router
+/// forwards them without parsing.
+#[derive(Clone, Debug, PartialEq)]
+pub enum ToRouter<'raw> {
+ /// An unknown type which is likely defined in a newer version of the schema.
+ Unknown,
+
+ /// Discriminator 1
+ RouterSubscribe {
+ doc_id: &'raw str,
+ token: &'raw str,
+ },
+
+ /// Discriminator 2
+ RouterUnsubscribe {
+ doc_id: &'raw str,
+ },
+
+ /// Discriminator 3
+ RouterFrame {
+ doc_id: &'raw str,
+ payload: ::bebop::SliceWrapper<'raw, u8>,
+ },
+}
+
+impl<'raw> ::bebop::SubRecord<'raw> for ToRouter<'raw> {
+ const MIN_SERIALIZED_SIZE: usize = ::bebop::LEN_SIZE + 1;
+
+ fn serialized_size(&self) -> usize {
+ ::bebop::LEN_SIZE + 1 +
+ match self {
+ ToRouter::Unknown => {
+ 0
+ }
+ Self::RouterSubscribe {
+ doc_id: ref _doc_id,
+ token: ref _token,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _token.serialized_size()
+ }
+ Self::RouterUnsubscribe {
+ doc_id: ref _doc_id,
+ }
+ => {
+ _doc_id.serialized_size()
+ }
+ Self::RouterFrame {
+ doc_id: ref _doc_id,
+ payload: ref _payload,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _payload.serialized_size()
+ }
+ }
+ }
+
+ ::bebop::define_serialize_chained!(Self => |zelf, dest| {
+ let size = zelf.serialized_size();
+ ::bebop::write_len(dest, size - ::bebop::LEN_SIZE - 1)?;
+ match zelf {
+ Self::Unknown => {
+ return Err(::bebop::SerializeError::CannotSerializeUnknownUnion);
+ }
+ Self::RouterSubscribe {
+ doc_id: ref _doc_id,
+ token: ref _token,
+ }
+ => {
+ 1u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _token._serialize_chained(dest)?;
+ }
+ Self::RouterUnsubscribe {
+ doc_id: ref _doc_id,
+ }
+ => {
+ 2u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ }
+ Self::RouterFrame {
+ doc_id: ref _doc_id,
+ payload: ref _payload,
+ }
+ => {
+ 3u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _payload._serialize_chained(dest)?;
+ }
+ }
+ Ok(size)
+ });
+
+ fn _deserialize_chained(raw: &'raw [u8]) -> ::bebop::DeResult<(usize, Self)> {
+ let len = ::bebop::read_len(raw)? + ::bebop::LEN_SIZE + 1;
+ let mut i = ::bebop::LEN_SIZE + 1;
+ let de = match raw[::bebop::LEN_SIZE] {
+ 1 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ ToRouter::RouterSubscribe {
+ doc_id: v0,
+ token: v1,
+ }
+ }
+ 2 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ ToRouter::RouterUnsubscribe {
+ doc_id: v0,
+ }
+ }
+ 3 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ ToRouter::RouterFrame {
+ doc_id: v0,
+ payload: v1,
+ }
+ }
+ _ => {
+ i = len;
+ ToRouter::Unknown
+ }
+ };
+ if !cfg!(feature = "unchecked") && i != len {
+ debug_assert!(i > len);
+ Err(::bebop::DeserializeError::CorruptFrame)
+ }
+ else {
+ Ok((i, de))
+ }
+ }
+
+}
+
+impl<'raw> ::bebop::Record<'raw> for ToRouter<'raw> {}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum FromRouter<'raw> {
+ /// An unknown type which is likely defined in a newer version of the schema.
+ Unknown,
+
+ /// Discriminator 1
+ RouterSubscribed {
+ doc_id: &'raw str,
+ },
+
+ /// Discriminator 2
+ RouterSubscribeFailed {
+ doc_id: &'raw str,
+ reason: &'raw str,
+ },
+
+ /// Discriminator 3
+ RouterDocFrame {
+ doc_id: &'raw str,
+ payload: ::bebop::SliceWrapper<'raw, u8>,
+ },
+
+ /// Discriminator 4
+ RouterDocClosed {
+ doc_id: &'raw str,
+ reason: &'raw str,
+ },
+}
+
+impl<'raw> ::bebop::SubRecord<'raw> for FromRouter<'raw> {
+ const MIN_SERIALIZED_SIZE: usize = ::bebop::LEN_SIZE + 1;
+
+ fn serialized_size(&self) -> usize {
+ ::bebop::LEN_SIZE + 1 +
+ match self {
+ FromRouter::Unknown => {
+ 0
+ }
+ Self::RouterSubscribed {
+ doc_id: ref _doc_id,
+ }
+ => {
+ _doc_id.serialized_size()
+ }
+ Self::RouterSubscribeFailed {
+ doc_id: ref _doc_id,
+ reason: ref _reason,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _reason.serialized_size()
+ }
+ Self::RouterDocFrame {
+ doc_id: ref _doc_id,
+ payload: ref _payload,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _payload.serialized_size()
+ }
+ Self::RouterDocClosed {
+ doc_id: ref _doc_id,
+ reason: ref _reason,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _reason.serialized_size()
+ }
+ }
+ }
+
+ ::bebop::define_serialize_chained!(Self => |zelf, dest| {
+ let size = zelf.serialized_size();
+ ::bebop::write_len(dest, size - ::bebop::LEN_SIZE - 1)?;
+ match zelf {
+ Self::Unknown => {
+ return Err(::bebop::SerializeError::CannotSerializeUnknownUnion);
+ }
+ Self::RouterSubscribed {
+ doc_id: ref _doc_id,
+ }
+ => {
+ 1u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ }
+ Self::RouterSubscribeFailed {
+ doc_id: ref _doc_id,
+ reason: ref _reason,
+ }
+ => {
+ 2u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _reason._serialize_chained(dest)?;
+ }
+ Self::RouterDocFrame {
+ doc_id: ref _doc_id,
+ payload: ref _payload,
+ }
+ => {
+ 3u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _payload._serialize_chained(dest)?;
+ }
+ Self::RouterDocClosed {
+ doc_id: ref _doc_id,
+ reason: ref _reason,
+ }
+ => {
+ 4u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _reason._serialize_chained(dest)?;
+ }
+ }
+ Ok(size)
+ });
+
+ fn _deserialize_chained(raw: &'raw [u8]) -> ::bebop::DeResult<(usize, Self)> {
+ let len = ::bebop::read_len(raw)? + ::bebop::LEN_SIZE + 1;
+ let mut i = ::bebop::LEN_SIZE + 1;
+ let de = match raw[::bebop::LEN_SIZE] {
+ 1 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromRouter::RouterSubscribed {
+ doc_id: v0,
+ }
+ }
+ 2 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromRouter::RouterSubscribeFailed {
+ doc_id: v0,
+ reason: v1,
+ }
+ }
+ 3 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromRouter::RouterDocFrame {
+ doc_id: v0,
+ payload: v1,
+ }
+ }
+ 4 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromRouter::RouterDocClosed {
+ doc_id: v0,
+ reason: v1,
+ }
+ }
+ _ => {
+ i = len;
+ FromRouter::Unknown
+ }
+ };
+ if !cfg!(feature = "unchecked") && i != len {
+ debug_assert!(i > len);
+ Err(::bebop::DeserializeError::CorruptFrame)
+ }
+ else {
+ Ok((i, de))
+ }
+ }
+
+}
+
+impl<'raw> ::bebop::Record<'raw> for FromRouter<'raw> {}
+
#[cfg(feature = "bebop-owned-all")]
pub mod owned {
#![allow(warnings)]
@@ -1211,4 +1539,414 @@ pub mod owned {
}
}
- impl<'raw> ::bebop::Record<'raw> for InitializeFromSnapshotRequest {}}
+ impl<'raw> ::bebop::Record<'raw> for InitializeFromSnapshotRequest {}
+
+ #[derive(Clone, Debug, PartialEq)]
+ pub enum ToRouter {
+ /// An unknown type which is likely defined in a newer version of the schema.
+ Unknown,
+
+ /// Discriminator 1
+ RouterSubscribe {
+ doc_id: String,
+ token: String,
+ },
+
+ /// Discriminator 2
+ RouterUnsubscribe {
+ doc_id: String,
+ },
+
+ /// Discriminator 3
+ RouterFrame {
+ doc_id: String,
+ payload: ::std::vec::Vec<u8>,
+ },
+ }
+
+ impl<'raw> ::core::convert::From<super::ToRouter<'raw>> for ToRouter {
+ fn from(value: super::ToRouter) -> Self {
+ match value {
+ super::ToRouter::Unknown => {
+ Self::Unknown
+ }
+ super::ToRouter::RouterSubscribe {
+ doc_id: _doc_id,
+ token: _token,
+ }
+ => {
+ Self::RouterSubscribe {
+ doc_id: _doc_id.into(),
+ token: _token.into(),
+ }
+ }
+ super::ToRouter::RouterUnsubscribe {
+ doc_id: _doc_id,
+ }
+ => {
+ Self::RouterUnsubscribe {
+ doc_id: _doc_id.into(),
+ }
+ }
+ super::ToRouter::RouterFrame {
+ doc_id: _doc_id,
+ payload: _payload,
+ }
+ => {
+ Self::RouterFrame {
+ doc_id: _doc_id.into(),
+ payload: _payload.iter().map(|value| value).collect(),
+ }
+ }
+ }
+ }
+
+ }
+ impl<'raw> ::bebop::SubRecord<'raw> for ToRouter {
+ const MIN_SERIALIZED_SIZE: usize = ::bebop::LEN_SIZE + 1;
+
+ fn serialized_size(&self) -> usize {
+ ::bebop::LEN_SIZE + 1 +
+ match self {
+ ToRouter::Unknown => {
+ 0
+ }
+ Self::RouterSubscribe {
+ doc_id: ref _doc_id,
+ token: ref _token,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _token.serialized_size()
+ }
+ Self::RouterUnsubscribe {
+ doc_id: ref _doc_id,
+ }
+ => {
+ _doc_id.serialized_size()
+ }
+ Self::RouterFrame {
+ doc_id: ref _doc_id,
+ payload: ref _payload,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _payload.serialized_size()
+ }
+ }
+ }
+
+ ::bebop::define_serialize_chained!(Self => |zelf, dest| {
+ let size = zelf.serialized_size();
+ ::bebop::write_len(dest, size - ::bebop::LEN_SIZE - 1)?;
+ match zelf {
+ Self::Unknown => {
+ return Err(::bebop::SerializeError::CannotSerializeUnknownUnion);
+ }
+ Self::RouterSubscribe {
+ doc_id: ref _doc_id,
+ token: ref _token,
+ }
+ => {
+ 1u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _token._serialize_chained(dest)?;
+ }
+ Self::RouterUnsubscribe {
+ doc_id: ref _doc_id,
+ }
+ => {
+ 2u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ }
+ Self::RouterFrame {
+ doc_id: ref _doc_id,
+ payload: ref _payload,
+ }
+ => {
+ 3u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _payload._serialize_chained(dest)?;
+ }
+ }
+ Ok(size)
+ });
+
+ fn _deserialize_chained(raw: &'raw [u8]) -> ::bebop::DeResult<(usize, Self)> {
+ let len = ::bebop::read_len(raw)? + ::bebop::LEN_SIZE + 1;
+ let mut i = ::bebop::LEN_SIZE + 1;
+ let de = match raw[::bebop::LEN_SIZE] {
+ 1 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ ToRouter::RouterSubscribe {
+ doc_id: v0,
+ token: v1,
+ }
+ }
+ 2 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ ToRouter::RouterUnsubscribe {
+ doc_id: v0,
+ }
+ }
+ 3 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ ToRouter::RouterFrame {
+ doc_id: v0,
+ payload: v1,
+ }
+ }
+ _ => {
+ i = len;
+ ToRouter::Unknown
+ }
+ };
+ if !cfg!(feature = "unchecked") && i != len {
+ debug_assert!(i > len);
+ Err(::bebop::DeserializeError::CorruptFrame)
+ }
+ else {
+ Ok((i, de))
+ }
+ }
+
+ }
+
+ impl<'raw> ::bebop::Record<'raw> for ToRouter {}
+
+ #[derive(Clone, Debug, PartialEq)]
+ pub enum FromRouter {
+ /// An unknown type which is likely defined in a newer version of the schema.
+ Unknown,
+
+ /// Discriminator 1
+ RouterSubscribed {
+ doc_id: String,
+ },
+
+ /// Discriminator 2
+ RouterSubscribeFailed {
+ doc_id: String,
+ reason: String,
+ },
+
+ /// Discriminator 3
+ RouterDocFrame {
+ doc_id: String,
+ payload: ::std::vec::Vec<u8>,
+ },
+
+ /// Discriminator 4
+ RouterDocClosed {
+ doc_id: String,
+ reason: String,
+ },
+ }
+
+ impl<'raw> ::core::convert::From<super::FromRouter<'raw>> for FromRouter {
+ fn from(value: super::FromRouter) -> Self {
+ match value {
+ super::FromRouter::Unknown => {
+ Self::Unknown
+ }
+ super::FromRouter::RouterSubscribed {
+ doc_id: _doc_id,
+ }
+ => {
+ Self::RouterSubscribed {
+ doc_id: _doc_id.into(),
+ }
+ }
+ super::FromRouter::RouterSubscribeFailed {
+ doc_id: _doc_id,
+ reason: _reason,
+ }
+ => {
+ Self::RouterSubscribeFailed {
+ doc_id: _doc_id.into(),
+ reason: _reason.into(),
+ }
+ }
+ super::FromRouter::RouterDocFrame {
+ doc_id: _doc_id,
+ payload: _payload,
+ }
+ => {
+ Self::RouterDocFrame {
+ doc_id: _doc_id.into(),
+ payload: _payload.iter().map(|value| value).collect(),
+ }
+ }
+ super::FromRouter::RouterDocClosed {
+ doc_id: _doc_id,
+ reason: _reason,
+ }
+ => {
+ Self::RouterDocClosed {
+ doc_id: _doc_id.into(),
+ reason: _reason.into(),
+ }
+ }
+ }
+ }
+
+ }
+ impl<'raw> ::bebop::SubRecord<'raw> for FromRouter {
+ const MIN_SERIALIZED_SIZE: usize = ::bebop::LEN_SIZE + 1;
+
+ fn serialized_size(&self) -> usize {
+ ::bebop::LEN_SIZE + 1 +
+ match self {
+ FromRouter::Unknown => {
+ 0
+ }
+ Self::RouterSubscribed {
+ doc_id: ref _doc_id,
+ }
+ => {
+ _doc_id.serialized_size()
+ }
+ Self::RouterSubscribeFailed {
+ doc_id: ref _doc_id,
+ reason: ref _reason,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _reason.serialized_size()
+ }
+ Self::RouterDocFrame {
+ doc_id: ref _doc_id,
+ payload: ref _payload,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _payload.serialized_size()
+ }
+ Self::RouterDocClosed {
+ doc_id: ref _doc_id,
+ reason: ref _reason,
+ }
+ => {
+ _doc_id.serialized_size() +
+ _reason.serialized_size()
+ }
+ }
+ }
+
+ ::bebop::define_serialize_chained!(Self => |zelf, dest| {
+ let size = zelf.serialized_size();
+ ::bebop::write_len(dest, size - ::bebop::LEN_SIZE - 1)?;
+ match zelf {
+ Self::Unknown => {
+ return Err(::bebop::SerializeError::CannotSerializeUnknownUnion);
+ }
+ Self::RouterSubscribed {
+ doc_id: ref _doc_id,
+ }
+ => {
+ 1u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ }
+ Self::RouterSubscribeFailed {
+ doc_id: ref _doc_id,
+ reason: ref _reason,
+ }
+ => {
+ 2u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _reason._serialize_chained(dest)?;
+ }
+ Self::RouterDocFrame {
+ doc_id: ref _doc_id,
+ payload: ref _payload,
+ }
+ => {
+ 3u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _payload._serialize_chained(dest)?;
+ }
+ Self::RouterDocClosed {
+ doc_id: ref _doc_id,
+ reason: ref _reason,
+ }
+ => {
+ 4u8._serialize_chained(dest)?;
+ _doc_id._serialize_chained(dest)?;
+ _reason._serialize_chained(dest)?;
+ }
+ }
+ Ok(size)
+ });
+
+ fn _deserialize_chained(raw: &'raw [u8]) -> ::bebop::DeResult<(usize, Self)> {
+ let len = ::bebop::read_len(raw)? + ::bebop::LEN_SIZE + 1;
+ let mut i = ::bebop::LEN_SIZE + 1;
+ let de = match raw[::bebop::LEN_SIZE] {
+ 1 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromRouter::RouterSubscribed {
+ doc_id: v0,
+ }
+ }
+ 2 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromRouter::RouterSubscribeFailed {
+ doc_id: v0,
+ reason: v1,
+ }
+ }
+ 3 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromRouter::RouterDocFrame {
+ doc_id: v0,
+ payload: v1,
+ }
+ }
+ 4 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromRouter::RouterDocClosed {
+ doc_id: v0,
+ reason: v1,
+ }
+ }
+ _ => {
+ i = len;
+ FromRouter::Unknown
+ }
+ };
+ if !cfg!(feature = "unchecked") && i != len {
+ debug_assert!(i > len);
+ Err(::bebop::DeserializeError::CorruptFrame)
+ }
+ else {
+ Ok((i, de))
+ }
+ }
+
+ }
+
+ impl<'raw> ::bebop::Record<'raw> for FromRouter {}}
diff --git a/services/sync-service/bebop/generated/schema.ts b/services/sync-service/bebop/generated/schema.ts
index 2456f76f70..18ffe7ff9d 100644
--- a/services/sync-service/bebop/generated/schema.ts
+++ b/services/sync-service/bebop/generated/schema.ts
@@ -17,7 +17,7 @@
import { BebopView, BebopRuntimeError, BebopRecord, BebopJson, BebopTypeGuard, Guid, GuidMap } from "bebop";
export const BEBOP_SCHEMA = new Uint8Array ([
-3, 16, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116,
+3, 25, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116,
101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116,
101, 115, 0, 242, 255, 255, 255, 1, 254, 255, 255, 255, 0,
105, 100, 0, 245, 255, 255, 255, 0, 80, 101, 101, 114, 65,
@@ -69,7 +69,36 @@ export const BEBOP_SCHEMA = new Uint8Array ([
111, 109, 83, 110, 97, 112, 115, 104, 111, 116, 82, 101,
113, 117, 101, 115, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
-255, 0, 254, 255, 255, 255, 0, 0, 0, 0, 0
+255, 0, 254, 255, 255, 255, 0, 82, 111, 117, 116, 101,
+114, 83, 117, 98, 115, 99, 114, 105, 98, 101, 0, 1, 0, 0,
+8, 0, 0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255,
+255, 0, 116, 111, 107, 101, 110, 0, 245, 255, 255, 255, 0,
+82, 111, 117, 116, 101, 114, 85, 110, 115, 117, 98, 115,
+99, 114, 105, 98, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 100,
+111, 99, 73, 100, 0, 245, 255, 255, 255, 0, 82, 111, 117,
+116, 101, 114, 70, 114, 97, 109, 101, 0, 1, 0, 0, 8, 0, 0,
+0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255, 0,
+112, 97, 121, 108, 111, 97, 100, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 84, 111, 82, 111, 117, 116, 101,
+114, 0, 3, 0, 9, 0, 0, 0, 3, 1, 16, 0, 0, 0, 2, 17, 0, 0,
+0, 3, 18, 0, 0, 0, 82, 111, 117, 116, 101, 114, 83, 117,
+98, 115, 99, 114, 105, 98, 101, 100, 0, 1, 0, 0, 4, 0, 0,
+0, 0, 1, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255, 0,
+82, 111, 117, 116, 101, 114, 83, 117, 98, 115, 99, 114,
+105, 98, 101, 70, 97, 105, 108, 101, 100, 0, 1, 0, 0, 8,
+0, 0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255,
+255, 0, 114, 101, 97, 115, 111, 110, 0, 245, 255, 255,
+255, 0, 82, 111, 117, 116, 101, 114, 68, 111, 99, 70, 114,
+97, 109, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99,
+73, 100, 0, 245, 255, 255, 255, 0, 112, 97, 121, 108, 111,
+97, 100, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
+82, 111, 117, 116, 101, 114, 68, 111, 99, 67, 108, 111,
+115, 101, 100, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99,
+73, 100, 0, 245, 255, 255, 255, 0, 114, 101, 97, 115, 111,
+110, 0, 245, 255, 255, 255, 0, 70, 114, 111, 109, 82, 111,
+117, 116, 101, 114, 0, 3, 0, 9, 0, 0, 0, 4, 1, 20, 0, 0,
+0, 2, 21, 0, 0, 0, 3, 22, 0, 0, 0, 4, 23, 0, 0, 0, 0, 0,
+0, 0
]);
export interface IPeerUpdate extends BebopRecord {
@@ -1923,3 +1952,1105 @@ export class InitializeFromSnapshotRequest implements IInitializeFromSnapshotReq
}
}
+
+export interface IRouterSubscribe extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly token: string;
+}
+
+export class RouterSubscribe implements IRouterSubscribe {
+ public readonly discriminator: number = 1 as 1;
+ public static readonly discriminator: number = 1 as 1;
+ public readonly docId: string;
+ public readonly token: string;
+
+ constructor(record: IRouterSubscribe) {
+ this.docId = record.docId;
+ this.token = record.token;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterSubscribe.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterSubscribe): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterSubscribe.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterSubscribe}.
+ */
+ public static validateCompatibility(record: IRouterSubscribe): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureString(record.token)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterSubscribe} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterSubscribe {
+ return new RouterSubscribe(record);
+ }
+
+ /**
+ * Creates a new {@link RouterSubscribe} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterSubscribe {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterSubscribe.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterSubscribe.validateCompatibility(parsed);
+ return RouterSubscribe.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterSubscribe.encode(this);
+ }
+
+ public static encode(record: IRouterSubscribe): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterSubscribe.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterSubscribe, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeString(record.token);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterSubscribe {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterSubscribe.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterSubscribe {
+ let field0: string;
+ field0 = view.readString();
+ let field1: string;
+ field1 = view.readString();
+ let message: IRouterSubscribe = {
+ docId: field0,
+ token: field1,
+ };
+ return new RouterSubscribe(message);
+ }
+}
+
+
+export interface IRouterUnsubscribe extends BebopRecord {
+
+ readonly docId: string;
+}
+
+export class RouterUnsubscribe implements IRouterUnsubscribe {
+ public readonly discriminator: number = 2 as 2;
+ public static readonly discriminator: number = 2 as 2;
+ public readonly docId: string;
+
+ constructor(record: IRouterUnsubscribe) {
+ this.docId = record.docId;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterUnsubscribe.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterUnsubscribe): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterUnsubscribe.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterUnsubscribe}.
+ */
+ public static validateCompatibility(record: IRouterUnsubscribe): void {
+ BebopTypeGuard.ensureString(record.docId)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterUnsubscribe} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterUnsubscribe {
+ return new RouterUnsubscribe(record);
+ }
+
+ /**
+ * Creates a new {@link RouterUnsubscribe} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterUnsubscribe {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterUnsubscribe.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterUnsubscribe.validateCompatibility(parsed);
+ return RouterUnsubscribe.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterUnsubscribe.encode(this);
+ }
+
+ public static encode(record: IRouterUnsubscribe): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterUnsubscribe.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterUnsubscribe, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterUnsubscribe {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterUnsubscribe.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterUnsubscribe {
+ let field0: string;
+ field0 = view.readString();
+ let message: IRouterUnsubscribe = {
+ docId: field0,
+ };
+ return new RouterUnsubscribe(message);
+ }
+}
+
+
+export interface IRouterFrame extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly payload: Uint8Array;
+}
+
+export class RouterFrame implements IRouterFrame {
+ public readonly discriminator: number = 3 as 3;
+ public static readonly discriminator: number = 3 as 3;
+ public readonly docId: string;
+ public readonly payload: Uint8Array;
+
+ constructor(record: IRouterFrame) {
+ this.docId = record.docId;
+ this.payload = record.payload;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterFrame.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterFrame): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterFrame.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterFrame}.
+ */
+ public static validateCompatibility(record: IRouterFrame): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureArray(record.payload, BebopTypeGuard.ensureUint8);
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterFrame} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterFrame {
+ return new RouterFrame(record);
+ }
+
+ /**
+ * Creates a new {@link RouterFrame} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterFrame {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterFrame.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterFrame.validateCompatibility(parsed);
+ return RouterFrame.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterFrame.encode(this);
+ }
+
+ public static encode(record: IRouterFrame): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterFrame.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterFrame, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeBytes(record.payload);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterFrame {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterFrame.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterFrame {
+ let field0: string;
+ field0 = view.readString();
+ let field1: Uint8Array;
+ field1 = view.readBytes();
+ let message: IRouterFrame = {
+ docId: field0,
+ payload: field1,
+ };
+ return new RouterFrame(message);
+ }
+}
+
+/**
+ * Multiplex envelope between the browser and the sync-router (rides the
+ * connection-gateway socket as binary frames). Inner payloads are the
+ * existing FromPeer/FromRemote unions, already bebop-encoded — the router
+ * forwards them without parsing.
+ */
+export type IToRouterType
+ = { discriminator: 1, value: IRouterSubscribe }
+ | { discriminator: 2, value: IRouterUnsubscribe }
+ | { discriminator: 3, value: IRouterFrame };
+
+export interface IToRouter extends BebopRecord {
+ readonly data: IToRouterType;
+}
+export class ToRouter implements IToRouter {
+
+ public readonly data: IToRouterType;
+
+ private constructor(data: IToRouterType) {
+ this.data = data;
+ }
+
+ public get discriminator() {
+ return this.data.discriminator;
+ }
+
+ public get value() {
+ return this.data.value;
+ }
+
+ public static fromRouterSubscribe(value: IRouterSubscribe) {
+ return new ToRouter({ discriminator: 1, value: new RouterSubscribe(value)});
+ }
+
+ public isRouterSubscribe(): this is { value: RouterSubscribe } & { data: Extract<IToRouterType, { discriminator: 1 }> } {
+ return this.data.value instanceof RouterSubscribe;
+ }
+
+ public static fromRouterUnsubscribe(value: IRouterUnsubscribe) {
+ return new ToRouter({ discriminator: 2, value: new RouterUnsubscribe(value)});
+ }
+
+ public isRouterUnsubscribe(): this is { value: RouterUnsubscribe } & { data: Extract<IToRouterType, { discriminator: 2 }> } {
+ return this.data.value instanceof RouterUnsubscribe;
+ }
+
+ public static fromRouterFrame(value: IRouterFrame) {
+ return new ToRouter({ discriminator: 3, value: new RouterFrame(value)});
+ }
+
+ public isRouterFrame(): this is { value: RouterFrame } & { data: Extract<IToRouterType, { discriminator: 3 }> } {
+ return this.data.value instanceof RouterFrame;
+ }
+
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return ToRouter.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IToRouter): string {
+ delete (record.data.value as any).discriminator;
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ ToRouter.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link ToRouter}.
+ */
+ public static validateCompatibility(record: IToRouter): void {
+ const discriminator = record.data.discriminator;
+ BebopTypeGuard.ensureUint8(discriminator);
+ switch (discriminator) {
+ case 1: {
+ RouterSubscribe.validateCompatibility(record.data.value);
+ break;
+ }
+ case 2: {
+ RouterUnsubscribe.validateCompatibility(record.data.value);
+ break;
+ }
+ case 3: {
+ RouterFrame.validateCompatibility(record.data.value);
+ break;
+ }
+ default: {
+ throw new Error(`Unknown discriminator for ToRouter: ${discriminator}`);
+ }
+ }
+ }
+
+ /**
+ * Unsafely creates an instance of {@link ToRouter} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): ToRouter {
+ const discriminator = record.data.discriminator;
+ switch (discriminator) {
+ case 1: {
+ return new ToRouter({ discriminator: 1, value: RouterSubscribe.unsafeCast(record.value) });
+ }
+ case 2: {
+ return new ToRouter({ discriminator: 2, value: RouterUnsubscribe.unsafeCast(record.value) });
+ }
+ case 3: {
+ return new ToRouter({ discriminator: 3, value: RouterFrame.unsafeCast(record.value) });
+ }
+ }
+ throw new BebopRuntimeError(`Failed to unsafely cast union from discriminator: ${discriminator}`);
+ }
+
+ /**
+ * Creates a new {@link ToRouter} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): ToRouter {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`ToRouter.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ ToRouter.validateCompatibility(parsed);
+ return ToRouter.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return ToRouter.encode(this);
+ }
+
+ public static encode(record: IToRouter): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ ToRouter.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IToRouter, view: BebopView): number {
+ const before = view.length;
+ const pos = view.reserveMessageLength();
+ const start = view.length + 1;
+ view.writeByte(record.data.discriminator);
+ switch (record.data.discriminator) {
+ case 1:
+ RouterSubscribe.encodeInto(record.data.value, view);
+ break;
+ case 2:
+ RouterUnsubscribe.encodeInto(record.data.value, view);
+ break;
+ case 3:
+ RouterFrame.encodeInto(record.data.value, view);
+ break;
+ }
+ const end = view.length;
+ view.fillMessageLength(pos, end - start);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): ToRouter {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return ToRouter.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): ToRouter {
+ const length = view.readMessageLength();
+ const end = view.index + 1 + length;
+ switch (view.readByte()) {
+ case 1:
+ return this.fromRouterSubscribe(RouterSubscribe.readFrom(view));
+ case 2:
+ return this.fromRouterUnsubscribe(RouterUnsubscribe.readFrom(view));
+ case 3:
+ return this.fromRouterFrame(RouterFrame.readFrom(view));
+ default:
+ view.index = end;
+ throw new BebopRuntimeError("Unrecognized discriminator while decoding ToRouter");
+ }
+ }
+}
+
+
+export interface IRouterSubscribed extends BebopRecord {
+
+ readonly docId: string;
+}
+
+export class RouterSubscribed implements IRouterSubscribed {
+ public readonly discriminator: number = 1 as 1;
+ public static readonly discriminator: number = 1 as 1;
+ public readonly docId: string;
+
+ constructor(record: IRouterSubscribed) {
+ this.docId = record.docId;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterSubscribed.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterSubscribed): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterSubscribed.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterSubscribed}.
+ */
+ public static validateCompatibility(record: IRouterSubscribed): void {
+ BebopTypeGuard.ensureString(record.docId)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterSubscribed} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterSubscribed {
+ return new RouterSubscribed(record);
+ }
+
+ /**
+ * Creates a new {@link RouterSubscribed} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterSubscribed {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterSubscribed.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterSubscribed.validateCompatibility(parsed);
+ return RouterSubscribed.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterSubscribed.encode(this);
+ }
+
+ public static encode(record: IRouterSubscribed): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterSubscribed.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterSubscribed, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterSubscribed {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterSubscribed.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterSubscribed {
+ let field0: string;
+ field0 = view.readString();
+ let message: IRouterSubscribed = {
+ docId: field0,
+ };
+ return new RouterSubscribed(message);
+ }
+}
+
+
+export interface IRouterSubscribeFailed extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly reason: string;
+}
+
+export class RouterSubscribeFailed implements IRouterSubscribeFailed {
+ public readonly discriminator: number = 2 as 2;
+ public static readonly discriminator: number = 2 as 2;
+ public readonly docId: string;
+ public readonly reason: string;
+
+ constructor(record: IRouterSubscribeFailed) {
+ this.docId = record.docId;
+ this.reason = record.reason;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterSubscribeFailed.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterSubscribeFailed): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterSubscribeFailed.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterSubscribeFailed}.
+ */
+ public static validateCompatibility(record: IRouterSubscribeFailed): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureString(record.reason)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterSubscribeFailed} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterSubscribeFailed {
+ return new RouterSubscribeFailed(record);
+ }
+
+ /**
+ * Creates a new {@link RouterSubscribeFailed} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterSubscribeFailed {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterSubscribeFailed.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterSubscribeFailed.validateCompatibility(parsed);
+ return RouterSubscribeFailed.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterSubscribeFailed.encode(this);
+ }
+
+ public static encode(record: IRouterSubscribeFailed): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterSubscribeFailed.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterSubscribeFailed, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeString(record.reason);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterSubscribeFailed {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterSubscribeFailed.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterSubscribeFailed {
+ let field0: string;
+ field0 = view.readString();
+ let field1: string;
+ field1 = view.readString();
+ let message: IRouterSubscribeFailed = {
+ docId: field0,
+ reason: field1,
+ };
+ return new RouterSubscribeFailed(message);
+ }
+}
+
+
+export interface IRouterDocFrame extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly payload: Uint8Array;
+}
+
+export class RouterDocFrame implements IRouterDocFrame {
+ public readonly discriminator: number = 3 as 3;
+ public static readonly discriminator: number = 3 as 3;
+ public readonly docId: string;
+ public readonly payload: Uint8Array;
+
+ constructor(record: IRouterDocFrame) {
+ this.docId = record.docId;
+ this.payload = record.payload;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterDocFrame.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterDocFrame): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterDocFrame.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterDocFrame}.
+ */
+ public static validateCompatibility(record: IRouterDocFrame): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureArray(record.payload, BebopTypeGuard.ensureUint8);
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterDocFrame} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterDocFrame {
+ return new RouterDocFrame(record);
+ }
+
+ /**
+ * Creates a new {@link RouterDocFrame} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterDocFrame {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterDocFrame.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterDocFrame.validateCompatibility(parsed);
+ return RouterDocFrame.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterDocFrame.encode(this);
+ }
+
+ public static encode(record: IRouterDocFrame): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterDocFrame.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterDocFrame, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeBytes(record.payload);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterDocFrame {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterDocFrame.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterDocFrame {
+ let field0: string;
+ field0 = view.readString();
+ let field1: Uint8Array;
+ field1 = view.readBytes();
+ let message: IRouterDocFrame = {
+ docId: field0,
+ payload: field1,
+ };
+ return new RouterDocFrame(message);
+ }
+}
+
+
+export interface IRouterDocClosed extends BebopRecord {
+
+ readonly docId: string;
+
+ readonly reason: string;
+}
+
+export class RouterDocClosed implements IRouterDocClosed {
+ public readonly discriminator: number = 4 as 4;
+ public static readonly discriminator: number = 4 as 4;
+ public readonly docId: string;
+ public readonly reason: string;
+
+ constructor(record: IRouterDocClosed) {
+ this.docId = record.docId;
+ this.reason = record.reason;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return RouterDocClosed.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IRouterDocClosed): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ RouterDocClosed.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link RouterDocClosed}.
+ */
+ public static validateCompatibility(record: IRouterDocClosed): void {
+ BebopTypeGuard.ensureString(record.docId)
+ BebopTypeGuard.ensureString(record.reason)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link RouterDocClosed} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IRouterDocClosed {
+ return new RouterDocClosed(record);
+ }
+
+ /**
+ * Creates a new {@link RouterDocClosed} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IRouterDocClosed {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`RouterDocClosed.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ RouterDocClosed.validateCompatibility(parsed);
+ return RouterDocClosed.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return RouterDocClosed.encode(this);
+ }
+
+ public static encode(record: IRouterDocClosed): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ RouterDocClosed.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IRouterDocClosed, view: BebopView): number {
+ const before = view.length;
+ view.writeString(record.docId);
+ view.writeString(record.reason);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IRouterDocClosed {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return RouterDocClosed.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IRouterDocClosed {
+ let field0: string;
+ field0 = view.readString();
+ let field1: string;
+ field1 = view.readString();
+ let message: IRouterDocClosed = {
+ docId: field0,
+ reason: field1,
+ };
+ return new RouterDocClosed(message);
+ }
+}
+
+
+export type IFromRouterType
+ = { discriminator: 1, value: IRouterSubscribed }
+ | { discriminator: 2, value: IRouterSubscribeFailed }
+ | { discriminator: 3, value: IRouterDocFrame }
+ | { discriminator: 4, value: IRouterDocClosed };
+
+export interface IFromRouter extends BebopRecord {
+ readonly data: IFromRouterType;
+}
+export class FromRouter implements IFromRouter {
+
+ public readonly data: IFromRouterType;
+
+ private constructor(data: IFromRouterType) {
+ this.data = data;
+ }
+
+ public get discriminator() {
+ return this.data.discriminator;
+ }
+
+ public get value() {
+ return this.data.value;
+ }
+
+ public static fromRouterSubscribed(value: IRouterSubscribed) {
+ return new FromRouter({ discriminator: 1, value: new RouterSubscribed(value)});
+ }
+
+ public isRouterSubscribed(): this is { value: RouterSubscribed } & { data: Extract<IFromRouterType, { discriminator: 1 }> } {
+ return this.data.value instanceof RouterSubscribed;
+ }
+
+ public static fromRouterSubscribeFailed(value: IRouterSubscribeFailed) {
+ return new FromRouter({ discriminator: 2, value: new RouterSubscribeFailed(value)});
+ }
+
+ public isRouterSubscribeFailed(): this is { value: RouterSubscribeFailed } & { data: Extract<IFromRouterType, { discriminator: 2 }> } {
+ return this.data.value instanceof RouterSubscribeFailed;
+ }
+
+ public static fromRouterDocFrame(value: IRouterDocFrame) {
+ return new FromRouter({ discriminator: 3, value: new RouterDocFrame(value)});
+ }
+
+ public isRouterDocFrame(): this is { value: RouterDocFrame } & { data: Extract<IFromRouterType, { discriminator: 3 }> } {
+ return this.data.value instanceof RouterDocFrame;
+ }
+
+ public static fromRouterDocClosed(value: IRouterDocClosed) {
+ return new FromRouter({ discriminator: 4, value: new RouterDocClosed(value)});
+ }
+
+ public isRouterDocClosed(): this is { value: RouterDocClosed } & { data: Extract<IFromRouterType, { discriminator: 4 }> } {
+ return this.data.value instanceof RouterDocClosed;
+ }
+
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return FromRouter.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IFromRouter): string {
+ delete (record.data.value as any).discriminator;
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ FromRouter.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link FromRouter}.
+ */
+ public static validateCompatibility(record: IFromRouter): void {
+ const discriminator = record.data.discriminator;
+ BebopTypeGuard.ensureUint8(discriminator);
+ switch (discriminator) {
+ case 1: {
+ RouterSubscribed.validateCompatibility(record.data.value);
+ break;
+ }
+ case 2: {
+ RouterSubscribeFailed.validateCompatibility(record.data.value);
+ break;
+ }
+ case 3: {
+ RouterDocFrame.validateCompatibility(record.data.value);
+ break;
+ }
+ case 4: {
+ RouterDocClosed.validateCompatibility(record.data.value);
+ break;
+ }
+ default: {
+ throw new Error(`Unknown discriminator for FromRouter: ${discriminator}`);
+ }
+ }
+ }
+
+ /**
+ * Unsafely creates an instance of {@link FromRouter} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): FromRouter {
+ const discriminator = record.data.discriminator;
+ switch (discriminator) {
+ case 1: {
+ return new FromRouter({ discriminator: 1, value: RouterSubscribed.unsafeCast(record.value) });
+ }
+ case 2: {
+ return new FromRouter({ discriminator: 2, value: RouterSubscribeFailed.unsafeCast(record.value) });
+ }
+ case 3: {
+ return new FromRouter({ discriminator: 3, value: RouterDocFrame.unsafeCast(record.value) });
+ }
+ case 4: {
+ return new FromRouter({ discriminator: 4, value: RouterDocClosed.unsafeCast(record.value) });
+ }
+ }
+ throw new BebopRuntimeError(`Failed to unsafely cast union from discriminator: ${discriminator}`);
+ }
+
+ /**
+ * Creates a new {@link FromRouter} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): FromRouter {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`FromRouter.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ FromRouter.validateCompatibility(parsed);
+ return FromRouter.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return FromRouter.encode(this);
+ }
+
+ public static encode(record: IFromRouter): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ FromRouter.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IFromRouter, view: BebopView): number {
+ const before = view.length;
+ const pos = view.reserveMessageLength();
+ const start = view.length + 1;
+ view.writeByte(record.data.discriminator);
+ switch (record.data.discriminator) {
+ case 1:
+ RouterSubscribed.encodeInto(record.data.value, view);
+ break;
+ case 2:
+ RouterSubscribeFailed.encodeInto(record.data.value, view);
+ break;
+ case 3:
+ RouterDocFrame.encodeInto(record.data.value, view);
+ break;
+ case 4:
+ RouterDocClosed.encodeInto(record.data.value, view);
+ break;
+ }
+ const end = view.length;
+ view.fillMessageLength(pos, end - start);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): FromRouter {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return FromRouter.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): FromRouter {
+ const length = view.readMessageLength();
+ const end = view.index + 1 + length;
+ switch (view.readByte()) {
+ case 1:
+ return this.fromRouterSubscribed(RouterSubscribed.readFrom(view));
+ case 2:
+ return this.fromRouterSubscribeFailed(RouterSubscribeFailed.readFrom(view));
+ case 3:
+ return this.fromRouterDocFrame(RouterDocFrame.readFrom(view));
+ case 4:
+ return this.fromRouterDocClosed(RouterDocClosed.readFrom(view));
+ default:
+ view.index = end;
+ throw new BebopRuntimeError("Unrecognized discriminator while decoding FromRouter");
+ }
+ }
+}
+
diff --git a/services/sync-service/bebop/schema.bop b/services/sync-service/bebop/schema.bop
index df66c49d91..2cc08b4b06 100644
--- a/services/sync-service/bebop/schema.bop
+++ b/services/sync-service/bebop/schema.bop
@@ -55,3 +55,45 @@ struct InitializeFromSnapshotRequest {
byte[] snapshot;
}
+
+/*
+ * Multiplex envelope between the browser and the sync-router (rides the
+ * connection-gateway socket as binary frames). Inner payloads are the
+ * existing FromPeer/FromRemote unions, already bebop-encoded — the router
+ * forwards them without parsing.
+ */
+union ToRouter {
+ 1 -> struct RouterSubscribe {
+ string docId;
+ // DocumentPermissionToken; passed through to the downstream unverified
+ // (the downstream authenticates, exactly as with a direct connection).
+ string token;
+ }
+ 2 -> struct RouterUnsubscribe {
+ string docId;
+ }
+ 3 -> struct RouterFrame {
+ string docId;
+ // A serialized FromPeer, untouched.
+ byte[] payload;
+ }
+}
+
+union FromRouter {
+ 1 -> struct RouterSubscribed {
+ string docId;
+ }
+ 2 -> struct RouterSubscribeFailed {
+ string docId;
+ string reason;
+ }
+ 3 -> struct RouterDocFrame {
+ string docId;
+ // A serialized FromRemote, untouched.
+ byte[] payload;
+ }
+ 4 -> struct RouterDocClosed {
+ string docId;
+ string reason;
+ }
+}
diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend.rs b/tooling/xtask/crates/xtask_local/src/local/frontend.rs
index 7bc657edf3..90d5940202 100644
--- a/tooling/xtask/crates/xtask_local/src/local/frontend.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/frontend.rs
@@ -18,6 +18,12 @@ fn app_dir() -> std::path::PathBuf {
repo_root().join("apps/web")
}
+fn prepare_dependencies(stage: &Stage) -> Result<()> {
+ let mut prepare = Command::new("bun");
+ prepare.current_dir(app_dir()).args(["run", "dev:prepare"]);
+ stage.run("Preparing frontend dependencies", &mut prepare)
+}
+
/// Host-facing frontend URL.
pub fn url(instance: &Instance) -> String {
format!("http://localhost:{}/app", instance.port(Port::Frontend))
@@ -64,6 +70,7 @@ pub fn static_dir(instance: &Instance) -> std::path::PathBuf {
/// paths such as passwordless auto-login (`just run_local` uses `vite serve`,
/// where DEV is already true). Headless `stack up` sets the same origin env.
pub fn build_static(stage: &Stage, instance: &Instance, mode: Mode) -> Result<()> {
+ prepare_dependencies(stage)?;
let dist = {
let mut cmd = Command::new("bun");
cmd.current_dir(app_dir())
@@ -331,12 +338,7 @@ pub fn start(
previous run. Free it (`lsof -ti tcp:{port} | xargs kill`) and retry."
);
}
- let mut prepare = Command::new("bash");
- prepare.current_dir(app_dir()).args([
- "-lc",
- "just ensure-cache-wasm && just ensure-agent-fold-wasm",
- ]);
- stage.run("Preparing frontend dependencies", &mut prepare)?;
+ prepare_dependencies(stage)?;
// Vite's node-http-proxy WebSocket upgrades hang under Bun (including
// 1.3.13). Use Node for the dev server, while keeping Bun for dependencies
diff --git a/tooling/xtask/crates/xtask_local/src/local/inventory.rs b/tooling/xtask/crates/xtask_local/src/local/inventory.rs
index 28ab6ca0bc..3fd60c7a4d 100644
--- a/tooling/xtask/crates/xtask_local/src/local/inventory.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/inventory.rs
@@ -116,6 +116,17 @@ pub const RUST_SERVICES: &[RustService] = &[
// (`no_rate_limit`, `return_passwordless_code`) is additive.
no_default_features: false,
},
+ RustService {
+ compose_name: "sync_router",
+ cargo_bin: "sync_router",
+ package: "sync_router",
+ host_port: None,
+ path_prefix: None,
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
RustService {
compose_name: "connection_gateway",
cargo_bin: "connection_gateway_service",
diff --git a/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs b/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs
index e37d56208c..9fc98cc52f 100644
--- a/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs
@@ -3,8 +3,9 @@ use super::*;
#[test]
fn local_binaries_are_unique_and_complete() {
let bins = local_binaries();
- assert_eq!(bins.len(), 16, "{bins:?}");
+ assert_eq!(bins.len(), 17, "{bins:?}");
assert!(bins.contains(&"whatsapp_session_service"));
+ assert!(bins.contains(&"sync_router"));
assert!(bins.contains(&"pubsub_workers"));
assert!(bins.contains(&"seed_cli"));
assert!(bins.contains(&"document_upload_finalizer_local_worker"));
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
index 28db2d5c34..9ce0731acb 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
@@ -712,8 +712,17 @@ impl BootStubEnv {
"MACRO_DB_URL".into(),
"postgres://user:password@postgres:5432/macrodb".into(),
);
- // search_processing_service; the local cluster has the security plugin
- // disabled so these are accepted but ignored (same as opensearch.rs).
+ // The harness requires Pipedream credentials even when integrations
+ // are unused. Real credentials can override these boot placeholders.
+ env.insert(
+ "PIPEDREAM_CLIENT_ID".into(),
+ "local-pipedream-client".into(),
+ );
+ env.insert(
+ "PIPEDREAM_CLIENT_SECRET".into(),
+ "local-pipedream-secret".into(),
+ );
+ env.insert("PIPEDREAM_PROJECT_ID".into(), "proj_local".into());
// the harness cognition module mounts the Pipedream webhook when both
// values are set. Nothing local can receive Pipedream's callbacks, so
// these only need to be well-formed: the URI must carry the same
@@ -723,6 +732,8 @@ impl BootStubEnv {
"http://localhost:8080/pipedream/mcp/webhook?secret=local".into(),
);
env.insert("PIPEDREAM_WEBHOOK_SECRET".into(), "local".into());
+ // search_processing_service; the local cluster has the security plugin
+ // disabled so these are accepted but ignored (same as opensearch.rs).
env.insert("OPENSEARCH_USERNAME".into(), "macrouser".into());
env.insert("OPENSEARCH_PASSWORD".into(), "local".into());
// Local document URLs use the instance endpoint supplied by InfraEnv;
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
index 75326796ce..e15e293781 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
@@ -104,6 +104,9 @@ fn emits_required_keys() {
"REDIS_HOST",
"MACRO_DB_URL",
"INTERNAL_API_KEY",
+ "PIPEDREAM_CLIENT_ID",
+ "PIPEDREAM_CLIENT_SECRET",
+ "PIPEDREAM_PROJECT_ID",
"AUTHENTICATION_SERVICE_SECRET_KEY",
"OPENSEARCH_USERNAME",
"OPENSEARCH_PASSWORD",