import { gameSyncRuntimeReportMessage, type GameSyncRuntimeReport } from '../../../../game-sync-protocol.js'; import type { RuntimeEpochReady } from '../../../../framework/plugins/index.js'; import type { ClawclawMailboxDriver } from '../mailbox-plugin.js'; export interface GameSyncRuntimeReportBoundary { readonly gameId: string; readonly connectionId: string; readonly resources: GameSyncRuntimeReport; } /** Latest complete resource snapshot; no delivery ACK, gameplay events, or computation backpressure. */ export class GameSyncRuntimeReportAdapter implements ClawclawMailboxDriver { readonly adapter = { id: 'clawclaw.mailbox.adapter.game-sync-runtime-report', acknowledgement: 'none' } as const; private stopped = false; private queued = false; private lastSent?: string; private lastInvalid?: string; private ready?: RuntimeEpochReady; constructor(private readonly options: { snapshot: (ready: RuntimeEpochReady) => GameSyncRuntimeReportBoundary | null; send: (report: GameSyncRuntimeReport, gameId: string, connectionId: string) => boolean; diagnostic?: (name: string, attributes: Record) => void; }) {} afterReady(ready: RuntimeEpochReady): void { if (this.stopped) return; this.ready = ready; if (this.queued) return; this.queued = true; queueMicrotask(() => { this.queued = false; void this.flush(); }); } async flush(): Promise { if (this.stopped || !this.ready) return; try { const boundary = this.options.snapshot(this.ready); if (!boundary) return; const key = JSON.stringify([boundary.gameId, boundary.connectionId, boundary.resources]); if (key === this.lastSent || key === this.lastInvalid) return; let report: GameSyncRuntimeReport; try { report = gameSyncRuntimeReportMessage(boundary.resources).data; } catch (error) { this.lastInvalid = key; this.options.diagnostic?.('runtime.mailbox.runtime_report_invalid', { error: error instanceof Error ? error.message : String(error), }); return; } if (this.options.send(report, boundary.gameId, boundary.connectionId)) this.lastSent = key; } catch (error) { this.options.diagnostic?.('runtime.mailbox.runtime_report_failed', { error: error instanceof Error ? error.message : String(error), }); } } async stop(): Promise { this.stopped = true; this.ready = undefined; } }