Linora

Sync client and protocol (packages/sync-client)

Owner: WP-D, then DC2 (wave 3). ADRs 0019, 0007, 0008, 0006, 0401, 0410, 0103. Contracts: shared/src/session.ts (SyncClient, DocSession, Gesture), messages.ts, codec.ts, presence.ts. Server behaviour it relies on: realtime.md / ADR 0202.

Current

Implemented (wave 1). DOM-free TypeScript for browsers and Node (MCP uses @linorahq/sync-client/connection).

packages/sync-client/src/
  connection.ts   RealtimeConnection: token reuse/refresh, WS lifecycle, hello (+ pipelined subscribes),
                  backoff, close codes, ping/idle, room routing. attach() = raw room for a replica;
                  openRoom() = RoomChannel with ACK promises for peers without a replica (MCP).
  session.ts      ReplicaSession (DocSession): replica, pending ops, per-key shadows, full rebase,
                  ACK settlement, tail matching, reload, gestures, undo/redo, presence.
  pending.ts      pending keys: (node, prop) -> {shadow, shadowSeq, last batch, live}; in-flight edits only
  undo.ts         UndoStack (limit 200) + gesture inverse compaction
  presence.ts     PresenceThrottle (<= 20 Hz, selection only on change) + PeerMap
  client.ts       RemoteSyncClient / createSyncClient: one connection per file, snapshot download, sessions
  local.ts        createLocalSession(doc) (offline, acked at once) + LocalHub (in-process sequencer)
  env.ts          injectable timers / WebSocket / fetch (tests run on a simulated clock)

Connection lifecycle

  1. getRealtimeToken() -> {token, url, expiresAt}; cached and reused across reconnects until 80% of its life; refreshed after a 4001 close or a failed upgrade. A 401/403 from the token call is fatal (unauthorized / forbidden).
  2. WS linora.v1, linora-rt.<token>; hello{protocol, rulesVersion, client, clientGrant?} with the page subscribes pipelined behind it -> welcome{clientId, clientGrant, role}. The grant is kept so reconnects keep the id space (new clientIds are rate limited server-side).
  3. Page open: GET .../snapshot (Content-Encoding gzip, inflated by fetch; X-Linora-Seq) -> docs.decodeSnapshot -> subscribe{pageId, sinceSeq, pendingFromClientSeq?, mode:'live'} -> tail -> synced -> live.
  4. Reconnect: full-jitter backoff 1 s -> 30 s (retryAfterMs honoured). Close codes: 4001 new token, 4003 access revoked (fatal), 4009 version mismatch (fatal, app shows “reload”), 4010 retry after retryAfterMs. PING every 25 s; a socket silent for 60 s is closed and re-opened. role_changed reconnects with a fresh token to pick up the new role.

Sending

Commits apply locally and join an open batch, sealed by a timer at most once per 16 ms (never inside the render loop; Node uses the same timer). Gesture SETs coalesce to the latest value per (node, prop) while unsent; gesture blob props (path points) are sent at most LIVE_BLOB_HZ. Messages are split at op boundaries to respect 4 MiB / 50,000 ops / MAX_BATCH_EXTRAS ids. TRANSFORM / SET_GEOMETRY ops above 262,144 ids (or more than fit a message) are split into id-range chunks at commit; the commit reports one verdict per op it was given. At most 64 batches in flight; further commits accumulate in the open batch until an ACK frees a slot. busy/rate_limited for clientSeq j: pause, resend only j after retryAfterMs (server-driven), and the later batches after j’s ACK (ADR 0410). protocol_error/too_large settle that batch as rejected. A subscribe refused with busy/rate_limited/internal is retried after retryAfterMs. RealtimeConnection.retryNow() skips the backoff (the app calls it on online / tab visible).

Optimistic replica: local = canonical + pending (ADR 0401)

Undo (ADR 0008)

Commits capture inverses (apply(..., {inverse: true})); undo/redo commit the inverse as a new transaction. Only this client’s transactions are on the stacks. A gesture is one entry (inverse compacted to the earliest value per key). Undo of a DELETE commits RESTORE ops (original ids; other clients’ ids are accepted while tombstoned, ADR 0101).

Presence

setPresence merges fields and sends at most once per 50 ms (leading edge, then trailing), selection, tool and follow only when they change (> 1,000 ids become count + bounds). After a reconnect the full state is resent. Interest management (ADR 0203): a peer cursor received outside the local viewport + PRESENCE_VIEW_MARGIN, or left outside by a pan, is stored hidden unless that peer is followed; the server resends it when it enters the view. Incoming PRESENCE_BATCH / peer_joined / peer_left update peers() and otherPeers (“+N”); unknown clients get a placeholder identity until their peer_joined.

How it protects the targets

No per-node memory (pending table = in-flight edits only, a few Maps); one message per frame at most; remote apply is O(changed ops) except the rebase cases above, which are O(pending ops); nothing runs inside the render loop (the engine drains doc changes on its next frame).

Acceptance (WP-D) and status