import { randomUUID } from 'node:crypto'; import WebSocket from 'ws'; import { lobbyHostHeaders, type LobbyHostContext } from '../../../../lib/lobby-host-context.js'; import { normalizeRoomSnapshot, type RoomSnapshot, } from '../../../../lib/room.js'; export interface ClawclawRoomGameStarted { game_id?: string; game_server_name?: string; ws_url?: string; } export type ClawclawRoomTransportStopReason = | 'manual' | 'game_started' | 'self_left' | 'room_destroyed' | 'maintenance' | 'reconcile' | 'replaced' | 'fatal' | 'normal' | 'error' | 'shutdown'; export type ClawclawRoomTransportOutcome = | { reason: 'game_started'; event: ClawclawRoomGameStarted; roomCode?: string } | { reason: Exclude; error?: unknown }; export interface ClawclawRoomCloseInfo { code?: number; reason: string; } export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'maintenance' | 'reconcile' | 'replaced' | 'fatal' | 'normal'; export interface ClawclawRoomTransportFrameMeta { connectionId: string; receivedAt: string; sourceSeq: number | string; sourceEventId?: string; replay?: boolean; } export interface ClawclawRoomTransportOptions { url: string; apiKey: string; hostContext?: LobbyHostContext; onOpened(connectionId: string, reconnected: boolean): Promise | void; onLiveness(connectionId: string, atMs: number): void; onConnectionChanged(connectionId: string, state: 'reconnecting' | 'disconnected'): Promise | void; onClosed( connectionId: string, info: ClawclawRoomCloseInfo, ): Promise | ClawclawRoomCloseDecision; onFrame(input: { type: string; data: Record; snapshot: RoomSnapshot | null; terminalPhase?: 'room_left'; meta: ClawclawRoomTransportFrameMeta; }): Promise | void; onDiagnostic(name: string, attributes?: Record): void; webSocketFactory?: ( url: string, options: { headers: Record }, ) => WebSocket; heartbeatIntervalMs?: number; pongTimeoutMs?: number; reconnectMs?: number; maxHandshakeFailures?: number; initialSnapshotTimeoutMs?: number; /** Maximum time to attach or reattach before the aggregate Source reconciles through Lobby HTTP. */ reconcileAfterMs?: number; } export interface ClawclawRoomTransportPort { start(): Promise; snapshot(): RoomSnapshot | null; waitForOutcome(): Promise; flush(): Promise; stop(reason?: ClawclawRoomTransportStopReason): Promise; } function messageText(data: WebSocket.RawData): 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 closeReason(value: Buffer | ArrayBuffer | Buffer[] | undefined): string { if (value === undefined) return ''; if (Buffer.isBuffer(value)) return value.toString('utf8'); if (value instanceof ArrayBuffer) return Buffer.from(value).toString('utf8'); return Buffer.concat(value).toString('utf8'); } export function gameStartedFromRoomSnapshot( snapshot: RoomSnapshot | null | undefined, ): ClawclawRoomGameStarted | null { if (!snapshot || snapshot.status !== 'playing') return null; const gameServerName = typeof snapshot.game_server_name === 'string' && snapshot.game_server_name.length > 0 ? snapshot.game_server_name : undefined; const wsUrl = typeof snapshot.ws_url === 'string' && snapshot.ws_url.length > 0 ? snapshot.ws_url : undefined; if (!gameServerName && !wsUrl) return null; return { game_id: typeof snapshot.game_id === 'string' ? snapshot.game_id : undefined, game_server_name: gameServerName, ws_url: wsUrl, }; } /** Lobby room WS with bounded attach, heartbeat and explicit close classification. */ export class ClawclawRoomTransport implements ClawclawRoomTransportPort { private readonly webSocketFactory: NonNullable; private readonly heartbeatIntervalMs: number; private readonly pongTimeoutMs: number; private readonly reconnectMs: number; private readonly initialSnapshotTimeoutMs: number; private readonly reconcileAfterMs: number; private ws: WebSocket | null = null; private connectionId = ''; private heartbeatTimer?: ReturnType; private pongTimer?: ReturnType; private reconnectTimer?: ReturnType; private snapshotTimer?: ReturnType; private attachTimer?: ReturnType; private latestSnapshot: RoomSnapshot | null = null; private operationTail: Promise = Promise.resolve(); private openedConnections = 0; private physicalFrameSeq = 0; private gameStartedEmitted = false; private replacementReceived = false; private handshakeFailures = 0; private socketOpened = false; private reconnectAttempts = 0; private readonly hostHeaders: Record; private stopped = false; private resolveOutcome!: (outcome: ClawclawRoomTransportOutcome) => void; private readonly outcomePromise: Promise; constructor(private readonly options: ClawclawRoomTransportOptions) { this.hostHeaders = options.hostContext ? lobbyHostHeaders(options.hostContext) : {}; this.webSocketFactory = options.webSocketFactory ?? ((url, init) => new WebSocket(url, init)); this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? 15_000; this.pongTimeoutMs = options.pongTimeoutMs ?? 10_000; this.reconnectMs = options.reconnectMs ?? 2_000; this.initialSnapshotTimeoutMs = options.initialSnapshotTimeoutMs ?? 10_000; this.reconcileAfterMs = options.reconcileAfterMs ?? 30_000; this.outcomePromise = new Promise((resolve) => { this.resolveOutcome = resolve; }); } async start(): Promise { if (this.stopped) throw new Error('Room transport is already stopped.'); this.startAttachDeadline(); this.openSocket(); } snapshot(): RoomSnapshot | null { return this.latestSnapshot ? structuredClone(this.latestSnapshot) : null; } waitForOutcome(): Promise { return this.outcomePromise; } async flush(): Promise { while (true) { const pending = this.operationTail; await pending; if (pending === this.operationTail) return; } } async stop(reason: ClawclawRoomTransportStopReason = 'manual'): Promise { this.finish(reason === 'game_started' ? { reason: 'game_started', event: gameStartedFromRoomSnapshot(this.latestSnapshot) ?? {}, roomCode: this.latestSnapshot?.room_code, } : { reason }); await this.flush(); } private openSocket(): void { if (this.stopped) return; this.clearSocket(); const connectionId = randomUUID(); this.connectionId = connectionId; this.physicalFrameSeq = 0; this.socketOpened = false; let ws: WebSocket; try { ws = this.webSocketFactory(this.options.url, { headers: { Authorization: `Bearer ${this.options.apiKey}`, ...this.hostHeaders }, }); } catch (error) { this.options.onDiagnostic('runtime.source.connect_failed', { transport: 'room_ws', error: error instanceof Error ? error.message : String(error), }); if (!this.recordHandshakeFailure()) this.scheduleReconnect(); return; } this.ws = ws; ws.once('open', () => { if (this.stopped || this.ws !== ws) return; this.socketOpened = true; this.handshakeFailures = 0; const reconnected = this.openedConnections > 0; this.openedConnections += 1; this.enqueue(() => this.options.onOpened(connectionId, reconnected)); this.startHeartbeat(connectionId, ws); this.startSnapshotDeadline(connectionId, ws); }); ws.on('message', (data) => this.handleRawMessage(data, connectionId, ws)); ws.once('error', (error) => { if (this.stopped || this.ws !== ws) return; this.options.onDiagnostic('runtime.source.connect_failed', { transport: 'room_ws', error: error.message, }); }); ws.once('close', (code, reason) => { this.handleClose(connectionId, ws, { code: typeof code === 'number' ? code : undefined, reason: closeReason(reason), }); }); } private handleRawMessage(raw: WebSocket.RawData, connectionId: string, ws: WebSocket): void { if (this.stopped || this.ws !== ws || this.connectionId !== connectionId) return; let message: any; try { message = JSON.parse(messageText(raw)); } catch { this.options.onDiagnostic('runtime.input.rejected', { reason: 'invalid_room_ws_json' }); return; } if (this.pongTimer) clearTimeout(this.pongTimer); this.pongTimer = undefined; this.options.onLiveness(connectionId, Date.now()); if (message?.type === 'ping') { this.send({ type: 'pong' }, ws); return; } if (message?.type === 'pong') { if (this.pongTimer) clearTimeout(this.pongTimer); this.pongTimer = undefined; this.options.onLiveness(connectionId, Date.now()); return; } const type = typeof message?.type === 'string' ? message.type : ''; if (type === 'replaced') { this.handleClose(connectionId, ws, { code: 4002, reason: typeof message.message === 'string' ? message.message : 'Lobby connection replaced', }); return; } if (!type) { this.options.onDiagnostic('runtime.input.rejected', { reason: 'room_ws_message_without_type' }); return; } const data = message?.data && typeof message.data === 'object' && !Array.isArray(message.data) ? message.data : {}; const backendSequence = message?.source_seq ?? message?.sequence ?? message?.seq ?? data.source_seq ?? data.sequence ?? data.seq; const physicalFrameSeq = ++this.physicalFrameSeq; const meta: ClawclawRoomTransportFrameMeta = { connectionId, receivedAt: new Date().toISOString(), sourceSeq: backendSequence ?? physicalFrameSeq, sourceEventId: message?.event_id ?? message?.eventId ?? data.event_id ?? data.eventId, replay: type === 'room.snapshot', }; this.enqueue(async () => { if (this.replacementReceived) return; let terminalPhase: 'room_left' | undefined; if (type === 'room.snapshot') { this.reconnectAttempts = 0; this.clearSnapshotDeadline(); this.clearAttachDeadline(); this.latestSnapshot = normalizeRoomSnapshot(data); } else { this.applyIncremental(type, data); if (type === 'room.self_left') { this.latestSnapshot = null; terminalPhase = 'room_left'; } } await this.options.onFrame({ type, data: structuredClone(data), snapshot: this.latestSnapshot ? structuredClone(this.latestSnapshot) : null, terminalPhase, meta, }); if (this.replacementReceived) return; const started = gameStartedFromRoomSnapshot(this.latestSnapshot); if (started && !this.gameStartedEmitted) { this.gameStartedEmitted = true; this.finish({ reason: 'game_started', event: started, roomCode: this.latestSnapshot?.room_code, }); } else if (type === 'room.self_left') { this.finish({ reason: 'self_left' }); } }); } private applyIncremental(type: string, data: Record): void { if (type === 'room.game_started') { this.latestSnapshot = { ...(this.latestSnapshot ?? {}), status: 'playing', ...data }; return; } if (type === 'room.game_starting') { this.latestSnapshot = { ...(this.latestSnapshot ?? {}), status: 'starting', ...data }; return; } if (type === 'room.game_finished') { const { game_id: _gameId, game_server_name: _server, ws_url: _ws, ...room } = this.latestSnapshot ?? {}; this.latestSnapshot = { ...room, status: 'waiting' }; this.gameStartedEmitted = false; return; } if (type === 'room.cooldown') { this.latestSnapshot = { ...(this.latestSnapshot ?? {}), status: 'waiting', cooldown_seconds: data.seconds_remaining ?? data.cooldown_seconds, }; return; } if (!this.latestSnapshot) return; if (type === 'room.member_joined' && Array.isArray(this.latestSnapshot.members)) { if (!this.latestSnapshot.members.some((member) => member.agent_id === data.agent_id)) { this.latestSnapshot.members = [...this.latestSnapshot.members, data]; } } else if (type === 'room.member_left' && Array.isArray(this.latestSnapshot.members)) { this.latestSnapshot.members = this.latestSnapshot.members.filter((member) => member.agent_id !== data.agent_id); } else if (type === 'room.owner_changed' && Array.isArray(this.latestSnapshot.members)) { this.latestSnapshot.members = this.latestSnapshot.members.map((member) => ({ ...member, is_owner: member.agent_id === data.agent_id, })); } else if ( type === 'room.member_status_changed' && (data.status === 'online' || data.status === 'offline' || data.status === 'in_game') && Array.isArray(this.latestSnapshot.members) ) { this.latestSnapshot.members = this.latestSnapshot.members.map((member) => ( member.agent_id === data.agent_id ? { ...member, status: data.status } : member )); } else if (type === 'room.idle_warning' && typeof data.destroy_at === 'number') { this.latestSnapshot.idle_destroy_at = data.destroy_at; } } private startHeartbeat(connectionId: string, ws: WebSocket): void { if (this.heartbeatTimer) clearInterval(this.heartbeatTimer); this.heartbeatTimer = setInterval(() => { if (this.stopped || this.ws !== ws || this.connectionId !== connectionId) return; this.send({ type: 'ping' }, ws); if (this.pongTimer) clearTimeout(this.pongTimer); this.pongTimer = setTimeout(() => { this.options.onDiagnostic('runtime.source.input_gap', { reason: 'room_heartbeat_timeout', connection_id: connectionId, recoverable: true, }); this.handleClose(connectionId, ws, { reason: 'heartbeat_timeout' }); }, this.pongTimeoutMs); this.pongTimer.unref?.(); }, this.heartbeatIntervalMs); this.heartbeatTimer.unref?.(); } private startSnapshotDeadline(connectionId: string, ws: WebSocket): void { this.clearSnapshotDeadline(); this.snapshotTimer = setTimeout(() => { if (this.stopped || this.ws !== ws || this.connectionId !== connectionId) return; this.options.onDiagnostic('runtime.source.snapshot_timeout', { transport: 'room_ws', connection_id: connectionId, timeout_ms: this.initialSnapshotTimeoutMs, }); this.finish({ reason: 'reconcile' }); }, this.initialSnapshotTimeoutMs); this.snapshotTimer.unref?.(); } private handleClose( connectionId: string, ws: WebSocket, info: ClawclawRoomCloseInfo, ): void { if (this.stopped || this.ws !== ws || this.connectionId !== connectionId) return; if (info.code === 4002) this.replacementReceived = true; const handshakeFailed = !this.socketOpened; this.clearTimers(); this.clearSocket(); this.enqueue(async () => { const classified = await this.options.onClosed(connectionId, info); const decision = this.replacementReceived ? 'replaced' : classified; await this.options.onConnectionChanged(connectionId, decision === 'retry' ? 'reconnecting' : 'disconnected'); if (decision === 'retry') { if (handshakeFailed && this.recordHandshakeFailure()) return; this.options.onDiagnostic('runtime.source.input_gap', { reason: 'room_ws_disconnected', connection_id: connectionId, close_code: info.code, close_reason: info.reason, recoverable: true, }); this.scheduleReconnect(); return; } this.finish({ reason: decision, ...(decision === 'fatal' ? { error: new Error(`Lobby WebSocket closed (${info.code ?? 'unknown'}): ${info.reason}`) } : {}) }); }); } private scheduleReconnect(): void { if (this.stopped || this.replacementReceived || this.reconnectTimer) return; this.startAttachDeadline(); this.clearSocket(); const delay = Math.min(30_000, this.reconnectMs * 2 ** Math.min(this.reconnectAttempts++, 5)); this.reconnectTimer = setTimeout(() => { this.reconnectTimer = undefined; this.openSocket(); }, delay); this.reconnectTimer.unref?.(); } private recordHandshakeFailure(): boolean { if (++this.handshakeFailures < (this.options.maxHandshakeFailures ?? 3)) return false; this.finish({ reason: 'fatal', error: new Error('Lobby WebSocket handshake repeatedly failed; check credentials and host context before retrying.') }); return true; } private send(message: Record, ws = this.ws): void { if (!ws || ws !== this.ws || ws.readyState !== WebSocket.OPEN) return; ws.send(JSON.stringify(message)); } private enqueue(operation: () => void | Promise): void { if (this.stopped) return; this.operationTail = this.operationTail.then(() => { if (!this.stopped) return operation(); }).catch((error) => { this.finish({ reason: 'error', error }); }); } private clearSnapshotDeadline(): void { if (this.snapshotTimer) clearTimeout(this.snapshotTimer); this.snapshotTimer = undefined; } private startAttachDeadline(): void { if (this.stopped || this.attachTimer || this.reconcileAfterMs <= 0) return; this.attachTimer = setTimeout(() => { if (this.stopped) return; this.options.onDiagnostic('runtime.source.attach_timeout', { transport: 'room_ws', connection_id: this.connectionId || undefined, timeout_ms: this.reconcileAfterMs, }); this.finish({ reason: 'reconcile' }); }, this.reconcileAfterMs); this.attachTimer.unref?.(); } private clearAttachDeadline(): void { if (this.attachTimer) clearTimeout(this.attachTimer); this.attachTimer = undefined; } private clearTimers(): void { if (this.heartbeatTimer) clearInterval(this.heartbeatTimer); if (this.pongTimer) clearTimeout(this.pongTimer); if (this.reconnectTimer) clearTimeout(this.reconnectTimer); this.clearSnapshotDeadline(); this.heartbeatTimer = undefined; this.pongTimer = undefined; this.reconnectTimer = undefined; } private clearSocket(): void { if (!this.ws) return; this.ws.removeAllListeners(); try { this.ws.close(); } catch {} this.ws = null; } private finish(outcome: ClawclawRoomTransportOutcome): void { if (this.stopped) return; this.stopped = true; this.clearTimers(); this.clearAttachDeadline(); this.clearSocket(); this.resolveOutcome(outcome); } }