import type { WsCloseInfo, WsInputFrame, WsProtocolErrorInfo, WsRecoveryStartedInfo, } from '../../../ws-client.js'; export type ClawclawGameTransportStopReason = | 'manual' | 'game_over' | 'user_left' | 'reconcile' | 'replaced' | 'error' | 'shutdown'; export interface ClawclawGameTransportOutcome { reason: ClawclawGameTransportStopReason; error?: unknown; queueState?: Record; } export interface ClawclawGameServerDiscoveryResult { readonly routeChanged: boolean; readonly queue?: Record; } export interface ClawclawGameTransportClient { readonly wsConnected: boolean; readonly wsConnectionActive: boolean; readonly wsConnectionId: string | null; discoverGameServer(): Promise; connectWs(): Promise; reconnectWsToGameServer(): Promise; disconnectWs(options?: { preserveGameSyncResumeState?: boolean }): void; acknowledgeGameSync(ackToken: string, immediate?: boolean): void; onInputFrame(handler: (frame: WsInputFrame) => void): () => void; onWsConnectionOpened(handler: (connectionId: string) => void): () => void; onWsLiveness(handler: (connectionId: string, atMs: number) => void): () => void; onWsClose(handler: (info: WsCloseInfo) => void): () => void; onWsProtocolError(handler: (info: WsProtocolErrorInfo) => void): () => void; onWsRecoveryStarted(handler: (info: WsRecoveryStartedInfo) => void): () => void; } export interface ClawclawGameTransportOptions { client: ClawclawGameTransportClient; onFrame(frame: WsInputFrame): Promise | ClawclawGameTransportStopReason | void; onConnectionOpened(connectionId: string, reconnected: boolean): Promise | void; onLiveness(connectionId: string, atMs: number): void; onClose( connectionId: string, info: WsCloseInfo, ): Promise | ClawclawGameTransportStopReason | void; onConnectAttemptFailed(error: unknown): void; onParticipationProbe?( queue: Record, ): Promise | ClawclawGameTransportStopReason | void; onProtocolError(info: WsProtocolErrorInfo): void; onRecoveryStarted?(info: WsRecoveryStartedInfo): Promise | void; routePollMs?: number; livenessTimeoutMs?: number; reconcileAfterMs?: number; clock?: () => number; } export interface ClawclawGameTransportPort { start(): Promise; waitForOutcome(): Promise; waitForFirstState(options?: { timeoutMs?: number; signal?: AbortSignal }): Promise>; flush(): Promise; stop(reason?: ClawclawGameTransportStopReason): Promise; } interface StateWaiter { resolve(state: Record): void; reject(error: Error): void; timer?: ReturnType; signal?: AbortSignal; onAbort?: () => void; } /** Owns one Game WS generation and reports lifecycle decisions to the aggregate Source. */ export class ClawclawGameTransport implements ClawclawGameTransportPort { private readonly routePollMs: number; private readonly livenessTimeoutMs: number; private readonly reconcileAfterMs: number; private readonly clock: () => number; private readonly unsubscribers: Array<() => void> = []; private readonly stateWaiters = new Set(); private operationTail: Promise = Promise.resolve(); private pollTimer?: ReturnType; private firstState: Record | null = null; private openedConnections = 0; private stopped = false; private connectAttemptActive = false; private disconnectedSince = 0; private lastLivenessAt = 0; private resolveOutcome!: (outcome: ClawclawGameTransportOutcome) => void; private readonly outcomePromise: Promise; constructor(private readonly options: ClawclawGameTransportOptions) { this.routePollMs = options.routePollMs ?? 3_000; this.livenessTimeoutMs = options.livenessTimeoutMs ?? 35_000; this.reconcileAfterMs = options.reconcileAfterMs ?? 30_000; this.clock = options.clock ?? Date.now; this.outcomePromise = new Promise((resolve) => { this.resolveOutcome = resolve; }); } async start(): Promise { if (this.stopped) throw new Error('Game transport is already stopped.'); const { client } = this.options; this.disconnectedSince = this.clock(); this.unsubscribers.push( client.onInputFrame((frame) => { this.lastLivenessAt = this.clock(); this.options.onLiveness(frame.meta.connectionId, this.lastLivenessAt); this.enqueue(async () => { const reason = await this.options.onFrame(frame); if (frame.kind === 'state') this.resolveFirstState(frame.state); if (reason) this.finish({ reason }); }); }), client.onWsConnectionOpened((connectionId) => { const reconnected = this.openedConnections > 0; this.openedConnections += 1; this.disconnectedSince = 0; this.lastLivenessAt = this.clock(); this.enqueue(() => this.options.onConnectionOpened(connectionId, reconnected)); }), client.onWsLiveness((connectionId, atMs) => { this.lastLivenessAt = Math.max(this.lastLivenessAt, atMs); this.options.onLiveness(connectionId, atMs); }), client.onWsProtocolError((info) => this.options.onProtocolError(info)), client.onWsRecoveryStarted((info) => { this.enqueue(() => this.options.onRecoveryStarted?.(info)); }), client.onWsClose((info) => { const connectionId = client.wsConnectionId ?? 'unknown-game-connection'; if (!this.disconnectedSince) this.disconnectedSince = this.clock(); this.enqueue(async () => { const reason = await this.options.onClose(connectionId, info); if (reason) this.finish({ reason }); }); }), ); await this.ensureConnected(); if (this.stopped) return; this.pollTimer = setInterval(() => { void this.ensureConnected(); }, this.routePollMs); this.pollTimer.unref?.(); } waitForOutcome(): Promise { return this.outcomePromise; } waitForFirstState(options: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise> { if (this.firstState) return Promise.resolve(structuredClone(this.firstState)); if (this.stopped) return Promise.reject(new Error('Game transport stopped before the first State.')); if (options.signal?.aborted) return Promise.reject(this.abortError(options.signal)); return new Promise((resolve, reject) => { const waiter: StateWaiter = { resolve, reject, signal: options.signal }; if (options.timeoutMs !== undefined) { const timeoutMs = Math.max(0, options.timeoutMs); waiter.timer = setTimeout(() => { this.removeWaiter(waiter); reject(new Error(`Timed out waiting ${timeoutMs}ms for the first Game WebSocket State.`)); }, timeoutMs); waiter.timer.unref?.(); } if (options.signal) { waiter.onAbort = () => { this.removeWaiter(waiter); reject(this.abortError(options.signal!)); }; options.signal.addEventListener('abort', waiter.onAbort, { once: true }); } this.stateWaiters.add(waiter); }); } async flush(): Promise { while (true) { const pending = this.operationTail; await pending; if (pending === this.operationTail) return; } } async stop(reason: ClawclawGameTransportStopReason = 'manual'): Promise { this.finish({ reason }); await this.flush(); } private async ensureConnected(): Promise { const { client } = this.options; if (this.stopped || this.connectAttemptActive) return; const now = this.clock(); if ( client.wsConnected && this.lastLivenessAt > 0 && now - this.lastLivenessAt >= this.livenessTimeoutMs ) { this.connectAttemptActive = true; try { const discovery = await client.discoverGameServer(); if (await this.applyParticipationProbe(discovery)) return; if (!discovery.routeChanged) await client.reconnectWsToGameServer(); } catch (error) { this.options.onConnectAttemptFailed(error); } finally { this.connectAttemptActive = false; } return; } if (client.wsConnected) return; if (this.disconnectedSince && now - this.disconnectedSince >= this.reconcileAfterMs) { this.finish({ reason: 'reconcile' }); return; } this.connectAttemptActive = true; try { // This call is required even while WsClient is auto-reconnecting: the // authoritative GameServer route may have changed underneath it. const discovery = await client.discoverGameServer(); if (await this.applyParticipationProbe(discovery)) return; if (!client.wsConnectionActive) await client.connectWs(); if (!client.wsConnectionActive) { this.options.onConnectAttemptFailed(new Error('Game WebSocket connection is unavailable.')); } } catch (error) { this.options.onConnectAttemptFailed(error); } finally { this.connectAttemptActive = false; } } private async applyParticipationProbe( discovery: ClawclawGameServerDiscoveryResult, ): Promise { if (!discovery.queue || !this.options.onParticipationProbe) return false; // Preserve the per-attempt disconnect Event before a Lobby probe can end // this transport generation. await this.flush(); if (this.stopped) return true; const reason = await this.options.onParticipationProbe(structuredClone(discovery.queue)); if (!reason) return false; this.finish({ reason, queueState: structuredClone(discovery.queue) }); return true; } private enqueue(operation: () => void | Promise): void { if (this.stopped) return; this.operationTail = this.operationTail.then(async () => { // An earlier queued operation may have accepted a terminal frame and // stopped the transport. Do not process a close callback that was // already queued behind that frame as a second, contradictory outcome. if (this.stopped) return; await operation(); }).catch((error) => { if (!this.stopped) this.finish({ reason: 'error', error }); }); } private resolveFirstState(state: Record): void { if (this.firstState) return; this.firstState = structuredClone(state); for (const waiter of [...this.stateWaiters]) { this.removeWaiter(waiter); waiter.resolve(structuredClone(this.firstState)); } } private finish(outcome: ClawclawGameTransportOutcome): void { if (this.stopped) return; this.stopped = true; if (this.pollTimer) clearInterval(this.pollTimer); this.pollTimer = undefined; for (const unsubscribe of this.unsubscribers.splice(0)) unsubscribe(); this.options.client.disconnectWs({ // A reconcile creates a new transport generation for the same game. // Keep its continuously reduced baseline so the next physical socket // can use GameSync resume. Every terminal outcome clears it. preserveGameSyncResumeState: outcome.reason === 'reconcile', }); const error = outcome.error instanceof Error ? outcome.error : new Error(`Game transport stopped before the first State: ${outcome.reason}.`); for (const waiter of [...this.stateWaiters]) { this.removeWaiter(waiter); waiter.reject(error); } this.resolveOutcome(outcome); } private removeWaiter(waiter: StateWaiter): void { if (!this.stateWaiters.delete(waiter)) return; if (waiter.timer) clearTimeout(waiter.timer); if (waiter.signal && waiter.onAbort) waiter.signal.removeEventListener('abort', waiter.onAbort); } private abortError(signal: AbortSignal): Error { return signal.reason instanceof Error ? signal.reason : new Error('Waiting for Game State was aborted.'); } }