// One WS connection, deliberately lean: ~8 fields, two small sets and one token bucket. // // Bun's WS profile is what makes a million sockets affordable, and this object must not spend it. // The token bucket is the frame budget: five numbers, and the only thing standing between one // authenticated socket and this node's whole subscribe path. // Budget is ~1KB of JS heap per connection on top of Bun's own per-socket cost — anything richer // (row caches, per-socket buffers) belongs in the transport or the change buffer, never here. // `sync` is stateless: nothing on this object survives a restart, and nothing needs to. import { type Actor, type Clock, finiteOption, logger, recordConnection, systemClock, uuidV7, } from '@ultimat3/core'; import { channelFramesDropped, GapRepairs } from './channel-gaps'; import type { Audience } from './channel-tenant'; import type { ChannelRecordsFrame } from './channel-wire'; import { CLOSE } from './close-codes'; import { DropWindow } from './socket-drops'; import { DEFAULT_IDLE_TIMEOUT_MS } from './socket-idle'; import { encode, type Frame } from './sync-protocol'; import { AcceptBudget } from './thundering-herd'; /** Defined in `close-codes.ts`, below both halves; re-exported for the node-side files. */ export { CLOSE } from './close-codes'; /** * The slice of Bun's `ServerWebSocket` this package uses. Structural, so tests need no server. * * `subscribe`/`unsubscribe` are Bun's native pub/sub and this package does NOT use them: nothing * here publishes to a native topic, and nothing will — a native publish cannot be refused per * socket, cannot report the frame it dropped and cannot mark a subscriber desynced, which is * exactly what `SocketRegistry.deliver` and `SyncSocket.send` exist to do. They are still declared * because `WsLike` is the slice of Bun's own object, and an app already implements it; deleting * them is a separate, breaking edit to every implementer. */ export interface WsLike { send(data: string): number; close(code?: number, reason?: string): void; subscribe(topic: string): void; unsubscribe(topic: string): void; getBufferedAmount(): number; } export interface SyncSocketOptions { readonly ws: WsLike; /** * Build id the *client* reported on the dial (`?build=`), or this node's own when it sent none; * `sawHello` overwrites it with what the `hello` frame says. Version skew is a first-class * connection state. */ readonly clientBuildId: string; readonly serverBuildId: string; readonly actor?: Actor | null; /** * The caller's address, resolved ONCE at the upgrade (`UpgradeDeps.clientAddressOf`) — the * only subject an anonymous reader has. `null` when the host cannot say. */ readonly clientAddress?: string | null; readonly id?: string; readonly clock?: Clock; /** Frames are dropped rather than queued past this. See `desynced`. */ readonly maxBufferedBytes?: number; readonly maxDroppedFrames?: number; /** Sustained inbound frames this socket may have routed per second. See `frameBudget`. */ readonly maxFramesPerSecond?: number; /** Burst allowance, so a client subscribing its whole cap at connect is never refused. */ readonly frameBurst?: number; } import { DEFAULT_FRAME_BURST, DEFAULT_MAX_BUFFERED_BYTES, DEFAULT_MAX_FRAMES_PER_SECOND, } from './socket-defaults'; export function actorIdOf(actor: Actor | null): string | null { return actor === null ? null : actor.id; } /** * MEASURED, both directions: with `maxBufferedBytes: NaN`, `getBufferedAmount() > NaN` is false and * `send()` answered TRUE with 10 MB already buffered — backpressure never trips, the caller is told * the frame left, and the drop reaches neither `channel_frames_dropped_total` nor the desync mark; * with `idleTimeoutMs: NaN`, `idleFor(now) > NaN` is false and a socket idle for 10,000,000 ms is * not in `idle()`, so a wedged client holds its grant, its subscriptions and its topic membership * forever. `@ultimat3/core`'s `finiteOption` is the one refusal; `bun run finite-bounds` is the ratchet over it. */ export class SyncSocket { readonly id: string; readonly serverBuildId: string; readonly openedAt: number; /** Channel topics (tier 1). Live-query subscriptions are keyed separately, by sid. */ readonly topics = new Set(); /** sid -> qid for live queries (tier 2/3) on this connection. */ readonly queries = new Map(); /** * Subscriptions whose patch stream was interrupted by backpressure. Dropping a patch is safe * *only* because the cursor makes a re-snapshot cheap; the drop is recorded here so the next * flush re-snapshots instead of silently diverging. */ readonly desynced = new Set(); /** * Channel topics whose `records` stream this socket lost a frame of, with the epoch it was lost * in. The channel twin of `desynced`: written on a drop, read on the next delivery or drain, which * sends `replay-gap` and clears it. Bounded by `topics`, so it adds nothing a socket did not hold. */ readonly gaps = new Map(); /** * Inbound frames this socket may still have routed. The accept budget spends one token per * UPGRADE, so nothing bounded what happened after: one authenticated socket reached a DB read, * a shared-store presence write and a fleet-wide publish once per frame, unbounded and * unawaited. Same token bucket, one per socket — the mechanism already existed, one rung down. */ readonly frameBudget: AcceptBudget; actor: Actor | null; readonly clientAddress: string | null; /** * MONOTONIC milliseconds, not an instant — the idle sweep measures a duration, and a duration * read off the wall clock is decided by whatever NTP last wrote. A step forward evicts sockets * that are talking; a step backward makes `idleFor` negative and spares sockets that are dead. * Named for the units so nobody hands it to `new Date()`; `openedAt` is the wall-clock one. */ lastSeenMonotonicMs: number; droppedFrames = 0; sentFrames = 0; readonly #ws: WsLike; readonly #clock: Clock; readonly #maxBufferedBytes: number; readonly #maxDroppedFrames: number; #clientBuildId: string; #closed = false; readonly #drops: DropWindow; constructor(options: SyncSocketOptions) { this.#ws = options.ws; this.#clock = options.clock ?? systemClock; this.id = options.id ?? uuidV7(); this.#clientBuildId = options.clientBuildId; this.serverBuildId = options.serverBuildId; this.actor = options.actor ?? null; this.clientAddress = options.clientAddress ?? null; this.#maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES; finiteOption('SyncSocket', 'maxBufferedBytes', this.#maxBufferedBytes); this.#maxDroppedFrames = options.maxDroppedFrames ?? 32; finiteOption('SyncSocket', 'maxDroppedFrames', this.#maxDroppedFrames); this.#drops = new DropWindow(this.#maxDroppedFrames); this.frameBudget = new AcceptBudget({ perSecond: finiteOption( 'SyncSocket', 'maxFramesPerSecond', options.maxFramesPerSecond ?? DEFAULT_MAX_FRAMES_PER_SECOND, ), burst: finiteOption('SyncSocket', 'frameBurst', options.frameBurst ?? DEFAULT_FRAME_BURST), clock: this.#clock, }); // Two clocks on purpose: `openedAt` is an instant a human reads, `lastSeenMonotonicMs` is the // start of a duration only this process compares. this.openedAt = this.#clock.now().getTime(); this.lastSeenMonotonicMs = this.#clock.monotonic(); } get actorId(): string | null { return actorIdOf(this.actor); } get closed(): boolean { return this.#closed; } /** The build the client last claimed: the dial's `?build=`, then whatever its `hello` said. */ get clientBuildId(): string { return this.#clientBuildId; } /** * The `hello` frame is the documented place a client names its build, and until 2026-09-07 the * node never read it: `clientBuildId` came from the dial's `?build=` alone and defaulted to this * node's OWN id when the query was absent — so a client that said `hello` from any build at all * was deemed current forever, and `update-available` never came. Measured on one adopter: a page * sending `buildId: "dev"` in every hello to a node on `46db23f57d6ef969`. The last word wins, * and the hello is the later one; `?build=` still works for a dial that carries it. */ sawHello(buildId: string): void { this.#clientBuildId = buildId; } /** A skewed client gets an `update-available` frame; it is never silently served a new shape. */ get skewed(): boolean { return this.#clientBuildId !== this.serverBuildId; } /** `false` means the frame was dropped by backpressure — the caller must mark state stale. */ send(frame: Frame): boolean { return this.sendEncoded(encode(frame)); } /** An `encode()`d frame — the fan-outs encode once for every socket. Adds no validation. */ sendEncoded(text: string): boolean { if (this.#closed) return false; if (this.#ws.getBufferedAmount() > this.#maxBufferedBytes) { this.#dropped(); return false; } // Bun answers `0` for a message it DROPPED (the socket closed after the check above) — the one // drop. `-1` means QUEUED under backpressure, and it is delivered: counted as a drop it sent a // spurious `replay-gap`, desynced a healthy subscriber, and closed the socket after 33. if (this.#ws.send(text) === 0) { this.#dropped(); return false; } this.sentFrames += 1; return true; } /** One frame that never left: counted for life, judged per `DROP_WINDOW_MS` (`socket-drops.ts`). */ #dropped(): void { this.droppedFrames += 1; if (this.#drops.overflowed(this.#clock.monotonic())) this.close(CLOSE.overloaded, 'backpressure'); } /** Record a dropped or invalidated subscription so the next flush re-snapshots it. */ markDesynced(sid: string): void { this.desynced.add(sid); } clearDesynced(sid: string): void { this.desynced.delete(sid); } /** * This socket's own membership, and nothing else. It used to also call Bun's `ws.subscribe`, * which built a second per-topic index nothing ever published to — the fanout is * `SocketRegistry.deliver`, one filtered `send` per socket, because that is the only path that * can count a dropped frame or close a socket that is drowning in them. */ subscribeTopic(topic: string): void { this.topics.add(topic); } unsubscribeTopic(topic: string): void { this.topics.delete(topic); this.gaps.delete(topic); } touch(): void { this.lastSeenMonotonicMs = this.#clock.monotonic(); } /** `nowMonotonicMs` comes from the SAME clock — `Clock.monotonic()`, never `now().getTime()`. */ idleFor(nowMonotonicMs: number): number { return nowMonotonicMs - this.lastSeenMonotonicMs; } close(code: number = CLOSE.normal, reason = ''): void { if (this.#closed) return; this.#closed = true; this.#ws.close(code, reason); } } export interface SocketRegistryOptions { readonly clock?: Clock; /** Bun's own `idleTimeout` is renewed by its ping/pong; this budget counts routed FRAMES. */ readonly idleTimeoutMs?: number; } /** Per-node socket table. Intentionally the only in-memory map on a `sync` node. */ export class SocketRegistry { readonly #sockets = new Map(); /** * Who is on each channel topic. `deliver` walked every socket on the node asking each whether * it held the topic, so one message with one legitimate subscriber cost as many iterations as * this node has connections — 50,000 at the scale this framework benchmarks. It lives here * rather than on the hub because this is the only object that sees a socket die: a close, a * drain and the idle sweep all pass through `remove`, and an index nobody cleans on those paths * retains a dead socket per topic forever. */ readonly #byTopic = new Map>(); readonly #clock: Clock; readonly #idleTimeoutMs: number; #droppedChannelFrames = 0; /** The repair side of `SyncSocket.gaps`: `repairAll(socket)` is what Bun's `drain` calls. */ readonly gapRepairs = new GapRepairs(); constructor(options: SocketRegistryOptions = {}) { this.#clock = options.clock ?? systemClock; this.#idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS; finiteOption('SocketRegistry', 'idleTimeoutMs', this.#idleTimeoutMs); } /** * This package's ONE metrics call site, and it is here rather than in `sync-node.ts` because * this map is the only definition of "a live connection on this node": a socket ends on the WS * close callback, on the idle sweep, on the drain and on a duplicate id, and every one of those * paths already had to come through `add`/`remove`. A gauge moved from the callers instead would * leak on whichever path a later change forgets — and a connections gauge that only counts up is * an HPA that only scales up. */ add(socket: SyncSocket): void { const replacing = this.#sockets.has(socket.id); this.#sockets.set(socket.id, socket); // A re-added id replaces one connection with another; the count did not change. if (!replacing) recordConnection(1); } remove(id: string): void { const socket = this.#sockets.get(id); // `Map.delete` answers "was it actually there", so a double close cannot decrement twice. if (!this.#sockets.delete(id)) return; recordConnection(-1); if (!socket) return; // Leaving this table IS the close, whoever noticed first. Bun's `close` callback reports a // connection that has already gone, so nothing called `close()` on this object and // `socket.closed` stayed false — leaving a subscribe still awaiting its snapshot read with no // way to tell that the socket it is about to attach to was torn down while it read. socket.close(CLOSE.goingAway, 'connection closed'); for (const name of socket.topics) this.#dropFrom(name, socket); } /** * Join a topic: the socket's own set, Bun's native pub/sub and this node's delivery index, in * one call. `ChannelHub` is its only caller, and calls nothing else — two call sites for one * membership is how an index goes wrong. */ joinTopic(socket: SyncSocket, topic: string): void { socket.subscribeTopic(topic); const members = this.#byTopic.get(topic); if (members) members.add(socket); else this.#byTopic.set(topic, new Set([socket])); } leaveTopic(socket: SyncSocket, topic: string): void { socket.unsubscribeTopic(topic); this.#dropFrom(topic, socket); } /** Sockets this node would deliver `topic` to. */ subscriberCount(topic: string): number { return this.#byTopic.get(topic)?.size ?? 0; } get(id: string): SyncSocket | undefined { return this.#sockets.get(id); } all(): Iterable { return this.#sockets.values(); } get count(): number { return this.#sockets.size; } /** The budget `idle()` answers against, so a caller can size its own sweep from one number. */ get idleTimeoutMs(): number { return this.#idleTimeoutMs; } /** * Everything past the idle budget. A QUERY, and deliberately not an eviction: this table is three * of the five things a socket holds, and the other two — its live subscriptions and its presence * membership on the SHARED set — are only reachable from `sync-node`'s `teardown`. A sweep that * closed and `remove`d here left a member every other node renders until its TTL and a * `QueryEntry` whose `subscribers` map never empties. `sync-node` is the one caller and it * releases each one the way the close callback does. */ idle(): SyncSocket[] { // Monotonic, because this is the one comparison an operator's clock could otherwise decide: // `sync-node` hands this registry and every socket it builds the same `Clock`. const now = this.#clock.monotonic(); return [...this.#sockets.values()].filter( (socket) => socket.idleFor(now) > this.#idleTimeoutMs, ); } /** * Local delivery for a channel topic — every channel message on this node comes through here, * so it reads the per-topic index rather than the socket table. A socket that closed without * an unsubscribe is dropped as it is met, so the index cannot outlive the connection even on a * path that forgot to `remove` it. */ deliver(topic: string, frame: Frame): number { const members = this.#byTopic.get(topic); if (!members) return 0; // Encoded ONCE for every member: per socket it was 16.9 ms against 0.6 ms for a 2 kB frame to // 10,000 sockets, measured. const text = encode(frame); let sent = 0; let dropped = 0; for (const socket of members) { if (socket.closed) { members.delete(socket); continue; } if (socket.sendEncoded(text)) sent += 1; else dropped += 1; } if (members.size === 0) this.#byTopic.delete(topic); if (dropped > 0) this.#countDropped(topic, dropped); return sent; } /** * A `records` delivery. An owed `replay-gap` goes out first; a socket that then drops the frame is * marked for the next one. `deliver`'s twin, because only a records stream can be repaired. A * member `to` does not admit is sent `to.withheld` instead (`channel-tenant.ts`). */ deliverRecords(topic: string, epoch: string, frame: ChannelRecordsFrame, to?: Audience): number { const members = this.#byTopic.get(topic); if (!members) return 0; const text = encode(frame); const other = to === undefined ? text : encode(to.withheld); let sent = 0; let dropped = 0; for (const socket of members) { if (socket.closed) { members.delete(socket); continue; } this.gapRepairs.repair(socket, topic); if (socket.sendEncoded(to === undefined || to.admits(socket.actor) ? text : other)) { sent += 1; continue; } dropped += 1; socket.gaps.set(topic, epoch); } if (members.size === 0) this.#byTopic.delete(topic); if (dropped > 0) this.#countDropped(topic, dropped); return sent; } /** Every member owes a re-read (a TRUNCATE): one `replay-gap` each now, or kept as a mark. */ announceGap(topic: string, epoch: string): number { const members = this.#byTopic.get(topic); if (!members) return 0; let announced = 0; for (const socket of members) { if (socket.closed) continue; socket.gaps.set(topic, epoch); if (this.gapRepairs.repair(socket, topic)) announced += 1; } return announced; } #countDropped(topic: string, dropped: number): void { this.#droppedChannelFrames += dropped; // Two readers, one event, one spelling: the series an operator alerts on and the line that // says which topic it was. channelFramesDropped.add(dropped); logger.warn('channel.frames_dropped', { topic, dropped, total: this.#droppedChannelFrames }); } /** * Channel frames backpressure refused since boot, node-wide and cumulative — the in-process read * of `channel_frames_dropped_total`, for a test or a benchmark that cannot scrape. * * Node-wide on purpose: a socket past `maxDroppedFrames` is closed and removed, so a per-socket * count leaves with the socket exactly when loss is worst. Distinct from `SyncSocket.droppedFrames`, * which counts every kind of frame one connection lost, channel and live-query patch alike. */ get droppedChannelFrames(): number { return this.#droppedChannelFrames; } #dropFrom(topic: string, socket: SyncSocket): void { const members = this.#byTopic.get(topic); if (!members) return; members.delete(socket); if (members.size === 0) this.#byTopic.delete(topic); } }