import { Worker } from 'node:worker_threads'; import { EventEmitter } from 'node:events'; import { WsConnectionState } from '../sdk/types.js'; import { gameSyncPerceptionReportMessage, gameSyncRuntimeReportMessage, type GameSyncPerceptionReport, type GameSyncRuntimeReport } from './game-sync-protocol.js'; import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js'; import type { GameSyncResumeState, WsClient, WsClientConfig, WsInputFrame, WsCloseInfo, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js'; export interface ThreadedWsClientConfig extends Omit { rawLog?: GameSyncIngressConfig['rawLog']; /** Complete-frame delivery credits. Raw reception/ACK continues when these are exhausted. */ maxInFlightFrames?: number; maxPendingBytes?: number; transportGeneration?: number; } /** Source-owned facade. Socket/heartbeat/delta work runs exclusively in the ingress Worker. */ export class ThreadedWsClient implements Pick { private readonly events = new EventEmitter(); private worker?: Worker; private stateValue = WsConnectionState.Disconnected; private connectionIdValue = ''; private lastLivenessAt: string | null = null; private committed?: GameSyncResumeState; private readonly pending = new Map(); private pendingReports = 0; private stopped = false; private connectedTask?: Promise; private resolveConnect?: () => void; private rejectConnect?: (error: Error) => void; private closeTask: Promise = Promise.resolve(); private resolveClose?: () => void; private closeTimer?: ReturnType; private startupTimer?: ReturnType; constructor(private readonly config: ThreadedWsClientConfig) { const frames = config.maxInFlightFrames ?? 10; const bytes = config.maxPendingBytes ?? 32 * 1024 * 1024; if (!Number.isSafeInteger(frames) || frames < 1 || frames > 1000) throw new Error('GAME_SYNC_FRAME_LIMIT_INVALID'); if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > 32 * 1024 * 1024) throw new Error('GAME_SYNC_BYTE_LIMIT_INVALID'); this.committed = config.resumeState ? structuredClone(config.resumeState) : undefined; } get connected(): boolean { return this.stateValue === WsConnectionState.Connected; } get state(): WsConnectionState { return this.stateValue; } get connectionId(): string { return this.connectionIdValue; } get lastPongAt(): string | null { return this.lastLivenessAt; } get resumeState(): GameSyncResumeState | undefined { return this.committed ? structuredClone(this.committed) : undefined; } connect(): Promise { if (this.connectedTask) return this.connectedTask; if (this.stopped) return Promise.reject(new Error('GAME_SYNC_INGRESS_STOPPED')); this.stateValue = WsConnectionState.Connecting; this.connectedTask = new Promise((resolve, reject) => { this.resolveConnect = resolve; this.rejectConnect = reject; }); this.closeTask = new Promise(resolve => { this.resolveClose = resolve; }); this.startupTimer = setTimeout(() => this.fail('GAME_SYNC_INGRESS_START_TIMEOUT'), 20_000); this.startupTimer.unref(); const config: GameSyncIngressConfig = { url: this.config.url, apiKey: this.config.apiKey, resumeState: this.committed, reconnectMaxMs: this.config.reconnectMaxMs, ackIntervalMs: this.config.ackIntervalMs, maxInFlightFrames: this.config.maxInFlightFrames ?? 10, maxPendingBytes: this.config.maxPendingBytes ?? 32 * 1024 * 1024, rawLog: this.config.rawLog, }; try { this.worker = new Worker(new URL('./framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), { execArgv: [], stdout: true, stderr: true, resourceLimits: { maxOldGenerationSizeMb: 128 }, workerData: { config, runtimeModuleBootstrap: { hostUrl: new URL('./game-sync-ingress-worker.ts', import.meta.url).href, hooksUrl: new URL('./framework/modules/runtime-module-loader-hooks.mjs', import.meta.url).href, sdkAliases: {}, esmModuleRoots: [], } }, }); this.worker.stdout?.on('data', () => {}); this.worker.stderr?.on('data', () => {}); this.worker.on('message', (message: IngressEvent) => this.receive(message)); this.worker.on('error', () => this.fail('GAME_SYNC_INGRESS_WORKER_FAILED')); this.worker.on('exit', (code) => { if (!this.stopped) this.fail('GAME_SYNC_INGRESS_WORKER_EXITED'); if (this.closeTimer) clearTimeout(this.closeTimer); this.resolveClose?.(); this.diagnostic('runtime.ws.ingress_stopped', { exit_code: code }); }); } catch { this.fail('GAME_SYNC_INGRESS_START_FAILED'); this.resolveClose?.(); } return this.connectedTask; } private receive(message: IngressEvent): void { if (message.type === 'telemetry') { const a = message.attributes; const at = Number(a.last_liveness_at_ms); if (at > 0 && !this.stopped) { this.lastLivenessAt = new Date(at).toISOString(); this.events.emit('liveness', String(a.connection_id), at); } this.diagnostic('runtime.ws.ingress_window', { ...a, owner_observed_at_ms: Date.now() }, Number(a.overload_count) ? 'warn' : 'info'); this.post({ type: 'telemetry_ack' }); return; } if (message.type === 'stopped') { if (message.rawStats) this.diagnostic('runtime.raw_ws.capture_stopped', { ...message.rawStats }); return; } if (this.stopped) return; switch (message.type) { case 'connected': if (this.startupTimer) clearTimeout(this.startupTimer); this.resolveConnect?.(); break; case 'failed': this.fail(message.code); break; case 'state': this.stateValue = message.state; this.events.emit('state', message.state); break; case 'opened': this.connectionIdValue = message.connectionId; this.events.emit('opened', message.connectionId); break; case 'close': this.connectionIdValue = message.connectionId; this.diagnostic('runtime.ws.ingress_disconnected', { code: message.info.code, reason: message.info.reason, pending_frames: this.pending.size }, 'warn'); this.events.emit('close', message.info); break; case 'protocol': this.events.emit('protocol', message.info); break; case 'recovery': this.events.emit('recovery', message.info); break; case 'report_done': this.pendingReports = Math.max(0, this.pendingReports - 1); break; case 'frame': { const frame = message.frame; frame.meta.ingress = { ...frame.meta.ingress!, ownerReceivedAtMs: Date.now(), transportGeneration: this.config.transportGeneration ?? 1 }; this.pending.set(frame.meta.ackToken, frame); this.lastLivenessAt = frame.meta.receivedAt; this.events.emit('liveness', frame.meta.connectionId, Date.parse(frame.meta.receivedAt)); this.events.emit('frame', frame); break; } } } acknowledge(token: string, _immediate = false): void { const frame = this.pending.get(token); if (this.stopped || !frame || frame.meta.connectionId !== this.connectionIdValue) return; const seq = Number(frame.meta.sourceSeq); if (!this.committed || seq >= this.committed.seq) { const { game_id: _gameId, tick: _tick, ...state } = frame.state; this.committed = { gameId: frame.meta.gameId, seq, tick: frame.meta.domainTick, locale: frame.meta.locale ?? 'zh-CN', state: structuredClone(state) }; } // A snapshot/resume barrier can share a seq with an earlier frame. Only // consume the delivered prefix through this token, not later same-seq input. for (const key of this.pending.keys()) { this.pending.delete(key); if (key === token) break; } // Source consumption releases delivery credits/cache, not the network ACK. // Keep this baseline Source-owned for recovery if the ingress Worker is lost. this.post({ type: 'consumed', token }); } reportPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean { if (!this.connected || this.stopped || this.pendingReports >= 16) return false; const message = gameSyncPerceptionReportMessage(perceptions); if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false; this.pendingReports++; this.post({ type: 'report', perceptions: message.data.perceptions, connectionId: this.connectionId }); return true; } reportRuntime(report: GameSyncRuntimeReport): boolean { if (!this.connected || this.stopped || this.pendingReports >= 16) return false; const message = gameSyncRuntimeReportMessage(report); if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false; this.pendingReports++; this.post({ type: 'runtime_report', report: message.data, connectionId: this.connectionId }); return true; } private post(message: IngressCommand): void { try { this.worker?.postMessage(message); } catch { if (!this.stopped) this.fail('GAME_SYNC_INGRESS_PORT_FAILED'); } } private diagnostic(name: string, attributes: Record, severity: 'debug' | 'info' | 'warn' = 'info'): void { try { this.config.diagnostic?.(name, { transport_generation: this.config.transportGeneration ?? 1, ...attributes }, severity); } catch {} } private fail(code: string): void { if (this.stopped) return; this.rejectConnect?.(new Error(code)); this.diagnostic('runtime.ws.ingress_failed', { error_code: code }, 'warn'); this.stateValue = WsConnectionState.Disconnected; this.events.emit('close', { code: 1013, reason: code, wasClean: false } satisfies WsCloseInfo); this.disconnect(); } disconnect(): void { if (this.stopped) return; this.stopped = true; if (this.startupTimer) clearTimeout(this.startupTimer); this.stateValue = WsConnectionState.Disconnected; this.rejectConnect?.(new Error('GAME_SYNC_INGRESS_STOPPED')); this.post({ type: 'stop' }); this.pending.clear(); this.events.emit('state', this.stateValue); if (this.worker) { this.closeTimer = setTimeout(() => { this.diagnostic('runtime.ws.ingress_stop_timeout', {}, 'warn'); void this.worker?.terminate(); }, 5000); this.closeTimer.unref(); } } async close(): Promise { this.disconnect(); await this.closeTask; } clearHandlers(): void { this.events.removeAllListeners(); } private on(event: string, handler: (...args: any[]) => void): () => void { this.events.on(event, handler); return () => { this.events.off(event, handler); }; } onInputFrame(handler: (frame: WsInputFrame) => void): () => void { return this.on('frame', handler); } onConnectionOpened(handler: (connectionId: string) => void): () => void { return this.on('opened', handler); } onLiveness(handler: (connectionId: string, atMs: number) => void): () => void { return this.on('liveness', handler); } onProtocolError(handler: (info: WsProtocolErrorInfo) => void): () => void { return this.on('protocol', handler); } onRecoveryStarted(handler: (info: WsRecoveryStartedInfo) => void): () => void { return this.on('recovery', handler); } onStateChange(handler: (state: WsConnectionState) => void): () => void { return this.on('state', handler); } onDisconnect(handler: (info: WsCloseInfo) => void): () => void { return this.on('close', handler); } }