import { parentPort, workerData, threadId } from 'node:worker_threads'; import { readFileSync } from 'node:fs'; import { monitorEventLoopDelay } from 'node:perf_hooks'; import { WsConnectionState } from '../sdk/types.js'; import { WsClient } from './ws-client.js'; import { BufferedRawWsLog } from './raw-ws-log.js'; import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js'; import { applyGameSyncDelta, type GameSyncServerMessage } from './game-sync-protocol.js'; import type { GameSyncResumeState, WsFrameMeta, WsInputFrame } from './ws-client.js'; const port = parentPort!; const config = workerData.config as GameSyncIngressConfig; const packageVersion = (JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { version?: string }).version; const raw = config.rawLog ? new BufferedRawWsLog(config.rawLog.path, config.rawLog.options) : undefined; interface CachedFrame { type: 'cached_frame'; messages: Buffer[]; bytes: number; meta: WsFrameMeta; eventIds: Set; } const pending = new Map(); const inFlight = new Map(); let deliveryQueue: Array = []; let deliveryHead = 0; let unappliedMessages: Buffer[] = []; let unappliedBytes = 0; let deliveryBaseline: GameSyncResumeState | undefined = config.resumeState; let pendingBytes = 0; let stopped = false; let overloaded = false; let restartTimer: ReturnType | undefined; let telemetryPending = false; let lastLiveness = 0; let lastReceivedSeq = 0; let acceptedSeq = config.resumeState?.seq ?? 0; let bufferedSeq = config.resumeState?.seq ?? 0; let ackSubmittedSeq = 0; let receivedFrames = 0; let pingCount = 0; let pongCount = 0; let pongErrors = 0; let lastPingAt = 0; let lastPongWrittenAt = 0; let maxPongWriteMs = 0; let maxSourceConsumptionDelayMs = 0; let overloadCount = 0; let maxOutstanding = 0; let maxBufferedBytes = 0; const delay = monitorEventLoopDelay({ resolution: 20 }); delay.enable(); const post = (message: IngressEvent): void => { if (!stopped || message.type === 'stopped') port.postMessage(message); }; const client = new WsClient({ url: config.url, apiKey: config.apiKey, resumeState: config.resumeState, reconnectMaxMs: config.reconnectMaxMs, ackIntervalMs: config.ackIntervalMs, maxPayloadBytes: 32 * 1024 * 1024, rawMessageSink: raw, handshakeTimeoutMs: 10_000, retainInputMessage: retainMessage, discardUnappliedMessages, diagnostic: (name, attributes) => { if (name === 'runtime.ws.ping_received') { pingCount++; lastPingAt = Number(attributes.received_at_ms); } if (name === 'runtime.ws.pong_written') { if (attributes.success) { pongCount++; lastPongWrittenAt = Number(attributes.written_at_ms); } else pongErrors++; maxPongWriteMs = Math.max(maxPongWriteMs, Number(attributes.duration_ms)); } if (name === 'runtime.ws.ack_submitted') ackSubmittedSeq = Number(attributes.source_seq); }, }); function telemetry(force = false): void { if (stopped || (telemetryPending && !force)) return; telemetryPending = true; post({ type: 'telemetry', attributes: { sampled_at_ms: Date.now(), connection_id: client.connectionId, implementation: 'buffered_gamesync_v2', package_version: packageVersion, node_version: process.version, thread_id: threadId, last_liveness_at_ms: lastLiveness, received_frames: receivedFrames, received_seq: lastReceivedSeq, buffered_seq: bufferedSeq, source_accepted_seq: acceptedSeq, ack_submitted_seq: ackSubmittedSeq, outstanding_frames: pending.size, outstanding_bytes: pendingBytes, max_outstanding_frames: maxOutstanding, in_flight_frames: inFlight.size, max_in_flight_frames: config.maxInFlightFrames, buffered_raw_bytes: pendingBytes, max_buffered_raw_bytes: maxBufferedBytes, unapplied_raw_bytes: unappliedBytes, max_pending_bytes: config.maxPendingBytes, received_ping_count: pingCount, written_pong_count: pongCount, pong_write_errors: pongErrors, last_ping_received_at_ms: lastPingAt, last_pong_written_at_ms: lastPongWrittenAt, max_pong_write_ms: maxPongWriteMs, max_source_consumption_delay_ms: maxSourceConsumptionDelayMs, overload_count: overloadCount, worker_event_loop_delay_p95_ms: delay.percentile(95) / 1e6, worker_event_loop_delay_max_ms: delay.max / 1e6, worker_heap_used_bytes: process.memoryUsage().heapUsed, ...(raw ? { raw_log: raw.stats() } : {}), } }); delay.reset(); } function discardUnappliedMessages(): void { pendingBytes -= unappliedBytes; unappliedBytes = 0; unappliedMessages = []; } function retainMessage(message: string): boolean { if (stopped || overloaded) return false; const bytes = Buffer.byteLength(message); if (pendingBytes + bytes > config.maxPendingBytes) { overloadCount++; overloaded = true; // This message has not been applied or ACKed. Retained completed frames // survive; an incomplete replay can be retried from the buffered baseline. discardUnappliedMessages(); client.disconnect(); enqueue({ type: 'close', connectionId: client.connectionId, info: { code: 1013, reason: 'CCL_INGRESS_BACKLOG_LIMIT', wasClean: false, } }); enqueue({ type: 'state', state: WsConnectionState.Reconnecting }); telemetry(true); reconnectWhenDrained(); return false; } unappliedMessages.push(Buffer.from(message)); unappliedBytes += bytes; pendingBytes += bytes; maxBufferedBytes = Math.max(maxBufferedBytes, pendingBytes); return true; } /** Preserve lifecycle ordering across reconnects while old frames await Source. */ function enqueue(message: IngressEvent | CachedFrame): void { deliveryQueue.push(message); pump(); } function materialize(cached: CachedFrame): WsInputFrame { const events: Record[] = []; const emitted = new Set(); for (const bytes of cached.messages) { const message = JSON.parse(bytes.toString('utf8')) as GameSyncServerMessage; if (message.type === 'game.sync.snapshot') { deliveryBaseline = { gameId: message.data.game_id, seq: message.data.seq, tick: message.data.tick, locale: message.data.locale, state: message.data.state, }; } else if (message.type === 'game.sync.update') { if (!deliveryBaseline || message.data.game_id !== deliveryBaseline.gameId || message.data.seq !== deliveryBaseline.seq + 1) throw new Error('INGRESS_CACHE_SEQUENCE_INVALID'); deliveryBaseline = { ...deliveryBaseline, seq: message.data.seq, tick: message.data.tick, state: applyGameSyncDelta(deliveryBaseline.state, message.data.state_delta) }; } else if (message.type === 'game.sync.resume') { if (!deliveryBaseline || deliveryBaseline.seq !== message.data.to_seq) throw new Error('INGRESS_CACHE_RESUME_INVALID'); deliveryBaseline = { ...deliveryBaseline, tick: message.data.tick }; } if (message.type === 'game.sync.snapshot' || message.type === 'game.sync.update') { for (const event of message.data.events ?? []) { const id = String(event.event_id); if (cached.eventIds.has(id) && !emitted.has(id)) { emitted.add(id); events.push(event); } } } } if (!deliveryBaseline) throw new Error('INGRESS_CACHE_BASELINE_MISSING'); return { kind: 'state', state: { ...structuredClone(deliveryBaseline.state), game_id: deliveryBaseline.gameId, tick: deliveryBaseline.tick }, events, meta: { ...cached.meta, ingress: { ...cached.meta.ingress!, workerPostedAtMs: Date.now(), outstandingFrames: pending.size, outstandingBytes: pendingBytes, } }, }; } function pump(): void { if (stopped) return; while (deliveryHead < deliveryQueue.length) { const message = deliveryQueue[deliveryHead]!; if (message.type === 'cached_frame') { if (inFlight.size >= config.maxInFlightFrames) break; const frame = materialize(message); inFlight.set(message.meta.ackToken, message); post({ type: 'frame', frame }); } else { // In particular, do not change the Source connection id ahead of its // pending frames; transport reconnect itself does not wait for this queue. if (inFlight.size) break; post(message); } deliveryQueue[deliveryHead++] = undefined; } if (deliveryHead > 1024 && deliveryHead * 2 > deliveryQueue.length) { deliveryQueue = deliveryQueue.slice(deliveryHead); deliveryHead = 0; } } function reconnectWhenDrained(): void { if (!overloaded || pending.size || restartTimer || stopped) return; restartTimer = setTimeout(() => { restartTimer = undefined; if (stopped) return; overloaded = false; void client.connect().catch(() => {}); }, 1000); } client.onStateChange(state => enqueue({ type: 'state', state })); client.onConnectionOpened(connectionId => { // Socket generation is deliberately separate from monotonically ordered source seq. enqueue({ type: 'opened', connectionId }); }); client.onLiveness((_connection, atMs) => { lastLiveness = atMs; }); client.onDisconnect(info => { discardUnappliedMessages(); enqueue({ type: 'close', connectionId: client.connectionId, info }); }); const reportedProtocolErrors = new Set(); client.onProtocolError(info => { if (reportedProtocolErrors.has(info.reason)) return; reportedProtocolErrors.add(info.reason); enqueue({ type: 'protocol', info }); }); client.onRecoveryStarted(info => enqueue({ type: 'recovery', info })); client.onInputFrame(frame => { if (stopped || overloaded) return; receivedFrames++; lastReceivedSeq = Number(frame.meta.sourceSeq); const cached: CachedFrame = { type: 'cached_frame', messages: unappliedMessages, bytes: unappliedBytes, meta: frame.meta, eventIds: new Set(frame.events.map(event => String(event.event_id))), }; unappliedMessages = []; unappliedBytes = 0; pending.set(frame.meta.ackToken, cached); maxOutstanding = Math.max(maxOutstanding, pending.size); // The entire validated input is now retained independently of the Owner. client.acknowledge(frame.meta.ackToken, true); bufferedSeq = Math.max(bufferedSeq, Number(frame.meta.sourceSeq)); enqueue(cached); }); const timer = setInterval(() => { reportedProtocolErrors.clear(); telemetry(); }, 5000); timer.unref(); port.on('message', (message: IngressCommand) => { if (stopped) return; if (message.type === 'consumed') { const entry = inFlight.get(message.token); if (!entry) return; acceptedSeq = Math.max(acceptedSeq, Number(entry.meta.sourceSeq)); maxSourceConsumptionDelayMs = Math.max(maxSourceConsumptionDelayMs, Date.now() - Date.parse(entry.meta.receivedAt)); for (const [token, item] of inFlight) { inFlight.delete(token); pending.delete(token); pendingBytes -= item.bytes; if (token === message.token) break; } pump(); reconnectWhenDrained(); } else if (message.type === 'report') { try { if (message.connectionId === client.connectionId) client.reportPerceptions(message.perceptions); } finally { post({ type: 'report_done' }); } } else if (message.type === 'runtime_report') { try { if (message.connectionId === client.connectionId) client.reportRuntime(message.report); } finally { post({ type: 'report_done' }); } } else if (message.type === 'telemetry_ack') { telemetryPending = false; } else if (message.type === 'stop') { void (async () => { client.disconnect(); telemetry(true); stopped = true; clearInterval(timer); if (restartTimer) clearTimeout(restartTimer); delay.disable(); await raw?.close(); post({ type: 'stopped', ...(raw ? { rawStats: raw.stats() } : {}) }); port.close(); })().catch(() => { post({ type: 'stopped' }); port.close(); }); } }); void client.connect().then(() => post({ type: 'connected' }), () => post({ type: 'failed', code: 'GAME_SYNC_CONNECT_FAILED' }));