// Internal GameSync v2 WebSocket client. It owns ordered reduction, ACK and // reconnect aggregation; Runtime never sees a partial replay. import WebSocket from 'ws'; import { randomUUID } from 'crypto'; import { performance } from 'node:perf_hooks'; import { WsConnectionState } from '../sdk/types.js'; import type { RawWsMessageSink } from './raw-ws-log.js'; import { applyGameSyncDelta, gameSyncPerceptionReportMessage, gameSyncUrl, parseGameSyncMessage, type GameSyncErrorData, type GameSyncPerceptionReport, gameSyncRuntimeReportMessage, type GameSyncRuntimeReport, } from './game-sync-protocol.js'; export interface GameSyncResumeState { readonly gameId: string; readonly seq: number; readonly tick: number; readonly locale: 'zh-CN' | 'en-US'; readonly state: Record; } export interface WsClientConfig { /** Base `/api/v1/game/sync` URL. Protocol and resume query params are owned here. */ url: string; apiKey: string; reconnectMaxMs?: number; ackIntervalMs?: number; /** Non-blocking raw server-frame capture owned and closed by the caller. */ rawMessageSink?: RawWsMessageSink; resumeState?: GameSyncResumeState; maxPayloadBytes?: number; handshakeTimeoutMs?: number; /** Optional reconnect gate for consumers that cannot retain input independently. */ reconnectReady?: () => boolean; /** Optional ingress-owned raw cache. Reserve before applying/ACKing a valid message. */ retainInputMessage?: (raw: string) => boolean; /** Release only an incomplete replay; already dispatched frames remain owned by the cache. */ discardUnappliedMessages?: () => void; diagnostic?: (name: string, attributes: Record, severity?: 'debug' | 'info' | 'warn') => void; } export interface WsCloseInfo { code?: number; reason: string; wasClean?: boolean; } export interface WsProtocolErrorInfo { connectionId: string; reason: | 'invalid_json' | 'invalid_game_sync_message' | 'update_without_snapshot' | 'game_id_changed' | 'seq_gap' | 'invalid_resume' | 'server_error'; details?: Record; } export interface WsRecoveryStartedInfo { connectionId: string; reason: string; expectedSeq?: number; receivedSeq?: number; } export interface WsFrameMeta { connectionId: string; receivedAt: string; origin: 'snapshot' | 'update' | 'resume'; sourceSeq: number | string; sourceEventId?: string; gameId: string; domainTick: number; replayed: boolean; /** Opaque authority token for this exact physical frame application. */ ackToken: string; snapshotFallback?: boolean; replayedEventCount?: number; /** Local transport clocks, not backend production timestamps. */ ingress?: { socketReceivedAtMs: number; decodedAtMs: number; decodeDurationMs: number; workerPostedAtMs?: number; ownerReceivedAtMs?: number; outstandingFrames?: number; outstandingBytes?: number; transportGeneration?: number; }; locale?: 'zh-CN' | 'en-US'; } export type WsInputFrame = { kind: 'state'; state: Record; events: Record[]; meta: WsFrameMeta; }; const DEFAULT_ACK_INTERVAL_MS = 10_000; const MAX_SEEN_EVENT_IDS = 20_000; function wsMessageToString(data: WebSocket.Data): string { if (typeof data === 'string') return data; if (Buffer.isBuffer(data)) return data.toString('utf8'); if (data instanceof ArrayBuffer) return Buffer.from(data).toString('utf8'); return Buffer.concat(data).toString('utf8'); } function closeIsTerminal(code: number | undefined): boolean { return code === 1000 || code === 1002 || code === 4000 || code === 4001 || code === 4002 || code === 4003; } interface PendingBaseline { readonly connectionId: string; readonly baseline: GameSyncResumeState; } export class WsClient { private ws: WebSocket | null = null; private _state = WsConnectionState.Disconnected; private shouldReconnect = false; private reconnectAttempt = 0; private reconnectTimer: ReturnType | null = null; private ackTimer: ReturnType | null = null; private connectionIdValue = ''; private lastPongAtValue: string | null = null; private baseline: GameSyncResumeState | null; /** Last baseline accepted by the consumer (Source or the ingress memory cache). */ private committedBaseline: GameSyncResumeState | null; private recovering = false; private awaitingSnapshot = false; private recoveryStartSeq: number | null = null; private recoveryFirstSeq: number | null = null; private recoveryFrameCount = 0; private recoveryEvents: Record[] = []; private readonly pendingBaselines = new Map(); private readonly pendingEventIds = new Map(); private readonly inFlightEventIds = new Set(); private ackDirty = false; private lastAckSent = 0; private readonly seenEventIds = new Set(); private readonly rawMessageSink?: RawWsMessageSink; private socketReceivedAtMs = 0; private decodeStartedAt = 0; private readonly inputFrameHandlers = new Set<(frame: WsInputFrame) => void>(); private readonly connectionOpenedHandlers = new Set<(connectionId: string) => void>(); private readonly livenessHandlers = new Set<(connectionId: string, atMs: number) => void>(); private readonly protocolErrorHandlers = new Set<(info: WsProtocolErrorInfo) => void>(); private readonly recoveryStartedHandlers = new Set<(info: WsRecoveryStartedInfo) => void>(); private readonly disconnectHandlers = new Set<(info: WsCloseInfo) => void>(); private readonly stateChangeHandlers = new Set<(state: WsConnectionState) => void>(); constructor(private readonly config: WsClientConfig) { this.baseline = config.resumeState ? structuredClone(config.resumeState) : null; this.committedBaseline = config.resumeState ? structuredClone(config.resumeState) : null; this.rawMessageSink = config.rawMessageSink; } get connected(): boolean { return this._state === WsConnectionState.Connected; } get state(): WsConnectionState { return this._state; } get connectionId(): string { return this.connectionIdValue; } get lastPongAt(): string | null { return this.lastPongAtValue; } get resumeState(): GameSyncResumeState | undefined { return this.committedBaseline ? structuredClone(this.committedBaseline) : undefined; } /** Best-effort perception output; the server intentionally sends no acknowledgement. */ reportPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean { return this.send(gameSyncPerceptionReportMessage(perceptions)); } reportRuntime(report: GameSyncRuntimeReport): boolean { return this.send(gameSyncRuntimeReportMessage(report)); } /** * Advance the resume/ACK watermark after the consumer has accepted the frame. * The threaded consumer retains it in memory before ACK; this is not a disk flush. */ acknowledge(ackToken: string, immediate = false): void { if (!ackToken) return; const pending = this.pendingBaselines.get(ackToken); if (!pending || pending.connectionId !== this.connectionIdValue) return; const committed = pending.baseline; const { seq, tick } = committed; if (!this.committedBaseline || seq >= this.committedBaseline.seq) { this.committedBaseline = structuredClone(committed); } for (const [pendingSeq, ids] of [...this.pendingEventIds]) { if (pendingSeq > seq) continue; for (const eventId of ids) { this.inFlightEventIds.delete(eventId); this.seenEventIds.add(eventId); } this.pendingEventIds.delete(pendingSeq); } for (const [key, candidate] of [...this.pendingBaselines]) { const candidateBaseline = candidate.baseline; if ( candidate.connectionId === pending.connectionId && candidateBaseline.gameId === committed.gameId && (candidateBaseline.seq < seq || (candidateBaseline.seq === seq && candidateBaseline.tick <= tick)) ) { this.pendingBaselines.delete(key); } } this.trimSeenEventIds(); this.ackDirty = true; if (immediate) this.sendAck(); } connect(): Promise { this.shouldReconnect = true; this.reconnectAttempt = 0; this.setState(WsConnectionState.Connecting); return this.openSocket(); } private openSocket(): Promise { return new Promise((resolve, reject) => { // Discard input not accepted by the consumer. The threaded consumer // keeps ACKed raw input across socket reconnects in its own memory cache. this.baseline = this.committedBaseline ? structuredClone(this.committedBaseline) : null; this.clearPendingApplication(); this.config.discardUnappliedMessages?.(); this.connectionIdValue = randomUUID(); this.recovering = this.baseline !== null; this.awaitingSnapshot = false; this.recoveryStartSeq = this.baseline?.seq ?? null; this.recoveryFirstSeq = null; this.recoveryFrameCount = 0; this.recoveryEvents = []; const url = gameSyncUrl(this.config.url, this.baseline?.seq); const ws = new WebSocket(url, { autoPong: false, ...(this.config.handshakeTimeoutMs === undefined ? {} : { handshakeTimeout: this.config.handshakeTimeoutMs }), ...(this.config.maxPayloadBytes === undefined ? {} : { maxPayload: this.config.maxPayloadBytes }), headers: { Authorization: `Bearer ${this.config.apiKey}`, 'Accept-Language': this.baseline?.locale ?? 'zh-CN', }, }); this.ws = ws; ws.onopen = () => { if (this.ws !== ws) return; this.setState(WsConnectionState.Connected); this.reconnectAttempt = 0; this.startAckTimer(); for (const handler of this.connectionOpenedHandlers) { try { handler(this.connectionIdValue); } catch {} } resolve(); }; ws.onerror = (error) => reject(error); ws.on('ping', (data) => { if (this.ws !== ws) return; const receivedAtMs = Date.now(); this.recordLiveness(); this.config.diagnostic?.('runtime.ws.ping_received', { received_at_ms: receivedAtMs, bytes: data.length }); // Reply in the socket-owning isolate, independently of Source/Runtime work. ws.pong(data, true, (error) => this.config.diagnostic?.('runtime.ws.pong_written', { ping_received_at_ms: receivedAtMs, written_at_ms: Date.now(), duration_ms: Math.max(0, Date.now() - receivedAtMs), success: !error, }, error ? 'warn' : 'debug')); }); (ws as any).on?.('pong', () => this.recordLiveness()); ws.onmessage = (event) => { if (this.ws !== ws) return; this.socketReceivedAtMs = Date.now(); this.decodeStartedAt = performance.now(); const raw = wsMessageToString(event.data); try { this.rawMessageSink?.enqueue(raw); } catch {} this.recordLiveness(); let parsed: unknown; try { parsed = JSON.parse(raw); } catch { this.reportProtocolError('invalid_json'); return; } try { this.handleMessage(parsed, raw); } catch (error) { this.reportProtocolError('invalid_game_sync_message', { error: error instanceof Error ? error.message : String(error), }); } }; ws.onclose = (event: { code?: number; reason?: string; wasClean?: boolean }) => { if (this.ws !== ws) return; this.stopAckTimer(); const info: WsCloseInfo = { code: typeof event.code === 'number' ? event.code : undefined, reason: event.reason ?? '', wasClean: typeof event.wasClean === 'boolean' ? event.wasClean : undefined, }; for (const handler of this.disconnectHandlers) handler(info); if (closeIsTerminal(info.code)) this.shouldReconnect = false; if (this.shouldReconnect) { this.setState(WsConnectionState.Reconnecting); this.scheduleReconnect(); } else { this.setState(WsConnectionState.Disconnected); } }; }); } private handleMessage(raw: unknown, wire = JSON.stringify(raw)): void { const message = parseGameSyncMessage(raw); if (message.type === 'game.sync.snapshot') { this.config.discardUnappliedMessages?.(); if (this.config.retainInputMessage?.(wire) === false) return; const wasRecovering = this.recovering; const previousGameId = this.baseline?.gameId; if (previousGameId !== undefined && previousGameId !== message.data.game_id) { this.seenEventIds.clear(); } this.baseline = { gameId: message.data.game_id, seq: message.data.seq, tick: message.data.tick, locale: message.data.locale, state: structuredClone(message.data.state), }; this.recovering = false; this.awaitingSnapshot = false; this.recoveryStartSeq = null; this.recoveryFirstSeq = null; this.recoveryFrameCount = 0; this.recoveryEvents = []; this.clearPendingApplication(); const events = this.newEvents(message.data.events, message.data.seq); const ackToken = this.recordPendingBaseline(this.baseline); this.dispatch(this.baseline, events, { origin: 'snapshot', replayed: false, ackToken, ...(wasRecovering ? { snapshotFallback: true } : {}), }); return; } if (message.type === 'game.sync.update') { const baseline = this.baseline; if (!baseline || this.awaitingSnapshot) { this.reportProtocolError('update_without_snapshot', { received_seq: message.data.seq }); this.requestResync('missing_baseline', undefined, message.data.seq); return; } if (message.data.game_id !== baseline.gameId) { this.reportProtocolError('game_id_changed', { expected_game_id: baseline.gameId, received_game_id: message.data.game_id, }); this.requestResync('game_id_changed', baseline.seq + 1, message.data.seq); return; } if (message.data.seq <= baseline.seq) return; const expectedSeq = baseline.seq + 1; if (message.data.seq !== expectedSeq) { this.reportProtocolError('seq_gap', { expected_seq: expectedSeq, received_seq: message.data.seq, }); this.requestResync('seq_gap', expectedSeq, message.data.seq); return; } if (this.config.retainInputMessage?.(wire) === false) return; this.baseline = { ...baseline, seq: message.data.seq, tick: message.data.tick, state: applyGameSyncDelta(baseline.state, message.data.state_delta), }; const events = this.newEvents(message.data.events, message.data.seq); if (this.recovering) { if (this.recoveryFrameCount === 0) this.recoveryFirstSeq = message.data.seq; this.recoveryFrameCount += 1; this.recoveryEvents.push(...events); return; } const ackToken = this.recordPendingBaseline(this.baseline); this.dispatch(this.baseline, events, { origin: 'update', replayed: false, ackToken }); return; } if (message.type === 'game.sync.resume') { const baseline = this.baseline; const expectedToSeq = this.recoveryStartSeq === null ? undefined : this.recoveryStartSeq + this.recoveryFrameCount; if ( !this.recovering || !baseline || message.data.to_seq !== baseline.seq || message.data.tick < baseline.tick || message.data.replayed_count !== this.recoveryFrameCount || message.data.to_seq !== expectedToSeq || (this.recoveryFrameCount === 0 && message.data.from_seq != null) || (this.recoveryFrameCount > 0 && message.data.from_seq !== this.recoveryFirstSeq) ) { this.reportProtocolError('invalid_resume', { from_seq: message.data.from_seq, applied_from_seq: this.recoveryFirstSeq, to_seq: message.data.to_seq, applied_seq: baseline?.seq, replayed_count: message.data.replayed_count, applied_count: this.recoveryFrameCount, resume_tick: message.data.tick, applied_tick: baseline?.tick, }); this.requestResync('invalid_resume', baseline ? baseline.seq + 1 : undefined, message.data.to_seq); return; } if (this.config.retainInputMessage?.(wire) === false) return; const events = this.recoveryEvents; const replayedEventCount = events.length; this.recoveryEvents = []; this.recoveryStartSeq = null; this.recoveryFirstSeq = null; this.recoveryFrameCount = 0; this.recovering = false; this.awaitingSnapshot = false; // A quiet phase can advance the backend tick without producing a frame. this.baseline = { ...baseline, tick: message.data.tick }; const ackToken = this.recordPendingBaseline(this.baseline); // Do not expose a partial replay. Once the barrier validates, publish all // recovered Events with the authoritative current State. Intermediate // visual frames intentionally are not reconstructed after a disconnect. this.dispatch(this.baseline, events, { origin: 'resume', replayed: true, ackToken, replayedEventCount, }); return; } this.handleServerError(message.data); } private handleServerError(error: GameSyncErrorData): void { this.reportProtocolError('server_error', { code: error.code, recoverable: error.recoverable, ...(error.message ? { message: error.message } : {}), }); if (!error.recoverable) { this.shouldReconnect = false; this.ws?.close(1002, error.code); } } private requestResync(reason: string, expectedSeq?: number, receivedSeq?: number): void { if (this.awaitingSnapshot) return; this.config.discardUnappliedMessages?.(); this.awaitingSnapshot = true; this.recovering = true; this.recoveryStartSeq = this.baseline?.seq ?? null; this.recoveryFirstSeq = null; this.recoveryFrameCount = 0; this.recoveryEvents = []; const recovery: WsRecoveryStartedInfo = { connectionId: this.connectionIdValue, reason, ...(expectedSeq === undefined ? {} : { expectedSeq }), ...(receivedSeq === undefined ? {} : { receivedSeq }), }; for (const handler of this.recoveryStartedHandlers) { try { handler(recovery); } catch {} } this.send({ type: 'game.sync.resync', data: { reason, ...(expectedSeq === undefined ? {} : { expected_seq: expectedSeq }), ...(receivedSeq === undefined ? {} : { received_seq: receivedSeq }), }, }); } private newEvents(events: readonly Record[], seq: number): Record[] { const result: Record[] = []; const eventIds: string[] = []; for (const event of events) { const eventId = String(event.event_id); if (this.seenEventIds.has(eventId) || this.inFlightEventIds.has(eventId)) continue; this.inFlightEventIds.add(eventId); eventIds.push(eventId); result.push(structuredClone(event)); } if (eventIds.length > 0) this.pendingEventIds.set(seq, eventIds); return result; } private trimSeenEventIds(): void { while (this.seenEventIds.size > MAX_SEEN_EVENT_IDS) { const oldest = this.seenEventIds.values().next().value as string | undefined; if (oldest === undefined) break; this.seenEventIds.delete(oldest); } } private dispatch( baseline: GameSyncResumeState, events: Record[], meta: Pick< WsFrameMeta, 'origin' | 'replayed' | 'ackToken' | 'snapshotFallback' | 'replayedEventCount' >, ): void { const frame: WsInputFrame = { kind: 'state', state: { ...structuredClone(baseline.state), game_id: baseline.gameId, tick: baseline.tick, }, events: structuredClone(events), meta: { connectionId: this.connectionIdValue, receivedAt: new Date().toISOString(), locale: baseline.locale, ingress: { socketReceivedAtMs: this.socketReceivedAtMs, decodedAtMs: Date.now(), decodeDurationMs: Math.max(0, performance.now() - this.decodeStartedAt), }, origin: meta.origin, sourceSeq: baseline.seq, gameId: baseline.gameId, domainTick: baseline.tick, replayed: meta.replayed, ackToken: meta.ackToken, ...(meta.snapshotFallback ? { snapshotFallback: true } : {}), ...(meta.replayedEventCount === undefined ? {} : { replayedEventCount: meta.replayedEventCount }), }, }; for (const handler of this.inputFrameHandlers) handler(frame); } private recordPendingBaseline(baseline: GameSyncResumeState): string { const ackToken = randomUUID(); this.pendingBaselines.set(ackToken, { connectionId: this.connectionIdValue, baseline: structuredClone(baseline), }); return ackToken; } private clearPendingApplication(): void { this.pendingBaselines.clear(); this.pendingEventIds.clear(); this.inFlightEventIds.clear(); } private sendAck(): void { const seq = this.committedBaseline?.seq; if (!this.ackDirty || seq === undefined || seq <= this.lastAckSent) return; if (this.send({ type: 'game.sync.ack', data: { seq } })) { this.lastAckSent = seq; this.ackDirty = false; this.config.diagnostic?.('runtime.ws.ack_submitted', { source_seq: seq, submitted_at_ms: Date.now() }); } } private send(value: unknown): boolean { if (!this.ws || this._state !== WsConnectionState.Connected) return false; try { this.ws.send(JSON.stringify(value)); return true; } catch { return false; } } private startAckTimer(): void { this.stopAckTimer(); const intervalMs = this.config.ackIntervalMs ?? DEFAULT_ACK_INTERVAL_MS; if (intervalMs <= 0) return; this.ackTimer = setInterval(() => this.sendAck(), intervalMs); this.ackTimer.unref?.(); } private stopAckTimer(): void { if (!this.ackTimer) return; clearInterval(this.ackTimer); this.ackTimer = null; } private recordLiveness(): void { const atMs = Date.now(); this.lastPongAtValue = new Date(atMs).toISOString(); for (const handler of this.livenessHandlers) { try { handler(this.connectionIdValue, atMs); } catch {} } } private reportProtocolError( reason: WsProtocolErrorInfo['reason'], details?: Record, ): void { const info: WsProtocolErrorInfo = { connectionId: this.connectionIdValue, reason, ...(details ? { details } : {}), }; for (const handler of this.protocolErrorHandlers) { try { handler(info); } catch {} } } private setState(next: WsConnectionState): void { if (next === this._state) return; this._state = next; for (const handler of this.stateChangeHandlers) handler(next); } private scheduleReconnect(): void { const delay = Math.min(1_000 * (2 ** this.reconnectAttempt), this.config.reconnectMaxMs ?? 30_000); this.reconnectAttempt += 1; this.reconnectTimer = setTimeout(() => { if (!this.shouldReconnect) return; if (this.config.reconnectReady?.() === false) { this.reconnectAttempt = Math.max(0, this.reconnectAttempt - 1); this.scheduleReconnect(); return; } this.setState(WsConnectionState.Connecting); void this.openSocket().catch(() => {}); }, delay); } onInputFrame(handler: (frame: WsInputFrame) => void): () => void { this.inputFrameHandlers.add(handler); return () => this.inputFrameHandlers.delete(handler); } onConnectionOpened(handler: (connectionId: string) => void): () => void { this.connectionOpenedHandlers.add(handler); return () => this.connectionOpenedHandlers.delete(handler); } onLiveness(handler: (connectionId: string, atMs: number) => void): () => void { this.livenessHandlers.add(handler); return () => this.livenessHandlers.delete(handler); } onProtocolError(handler: (info: WsProtocolErrorInfo) => void): () => void { this.protocolErrorHandlers.add(handler); return () => this.protocolErrorHandlers.delete(handler); } onRecoveryStarted(handler: (info: WsRecoveryStartedInfo) => void): () => void { this.recoveryStartedHandlers.add(handler); return () => this.recoveryStartedHandlers.delete(handler); } onStateChange(handler: (state: WsConnectionState) => void): () => void { this.stateChangeHandlers.add(handler); return () => this.stateChangeHandlers.delete(handler); } onDisconnect(handler: (info: WsCloseInfo) => void): () => void { this.disconnectHandlers.add(handler); return () => this.disconnectHandlers.delete(handler); } clearHandlers(): void { this.inputFrameHandlers.clear(); this.connectionOpenedHandlers.clear(); this.livenessHandlers.clear(); this.protocolErrorHandlers.clear(); this.recoveryStartedHandlers.clear(); this.stateChangeHandlers.clear(); this.disconnectHandlers.clear(); } disconnect(): void { this.shouldReconnect = false; this.sendAck(); this.stopAckTimer(); if (this.reconnectTimer) clearTimeout(this.reconnectTimer); this.reconnectTimer = null; const ws = this.ws; this.ws = null; if (ws) { ws.onclose = null; ws.close(); } this.setState(WsConnectionState.Disconnected); } }