import { appendFile, mkdir, readdir, rename, rm, stat } from 'fs/promises'; import { basename, dirname, join } from 'path'; function hasErrorCode(error: unknown, code: string): boolean { return !!error && typeof error === 'object' && (error as NodeJS.ErrnoException).code === code; } export function ownerRawWsLogPath(runtimeStateDir: string): string { return join(runtimeStateDir, 'observability', 'game-sync.raw-ws.jsonl'); } /** * Owner-supplied capture boundary. enqueue() must not wait for disk I/O or * throw into the WebSocket message handler. The owner retains lifecycle * ownership of a supplied sink and closes it after the transport has stopped. */ export interface RawWsMessageSink { enqueue(raw: string): boolean; flush(): Promise; close(): Promise; } export interface BufferedRawWsLogOptions { /** Total queued and in-flight bytes retained in process memory. */ maxBufferedBytes?: number; /** Start a background write after this many records have accumulated. */ batchSize?: number; /** Periodic background flush; zero disables the timer. */ flushIntervalMs?: number; /** Rotate the active file before a batch would exceed this size. */ maxFileBytes?: number; /** Number of rotated history files (`.1`, `.2`, ...) to retain. */ retainedFiles?: number; /** Deterministic timestamp seam for tests. */ now?: () => Date; } export interface RawWsLogStats { accepted: number; dropped: number; written: number; failedBatches: number; bufferedBytes: number; queuedRecords: number; } interface QueuedLine { readonly data: string; readonly bytes: number; } const DEFAULT_MAX_BUFFERED_BYTES = 8 * 1024 * 1024; const DEFAULT_BATCH_SIZE = 100; const DEFAULT_FLUSH_INTERVAL_MS = 500; const DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024; const DEFAULT_RETAINED_FILES = 5; /** * Best-effort raw GameSync journal. WebSocket callbacks only serialize and * enqueue records; all directory, append and rotation work runs asynchronously * on one ordered promise chain. A slow or failed disk therefore cannot delay * parsing, reduction, ACK, strategy, or perception. */ export class BufferedRawWsLog implements RawWsMessageSink { readonly filePath: string; private readonly maxBufferedBytes: number; private readonly batchSize: number; private readonly maxFileBytes: number; private readonly retainedFiles: number; private readonly now: () => Date; private readonly queue: QueuedLine[] = []; private readonly timer?: ReturnType; private operation: Promise = Promise.resolve(); private bufferedBytes = 0; private activeFileBytes: number | null = null; private retentionPrepared = false; private closed = false; private acceptedCount = 0; private droppedCount = 0; private writtenCount = 0; private failedBatchCount = 0; constructor(filePath: string, options: BufferedRawWsLogOptions = {}) { this.filePath = filePath; this.maxBufferedBytes = Math.max(1, options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES); this.batchSize = Math.max(1, options.batchSize ?? DEFAULT_BATCH_SIZE); this.maxFileBytes = Math.max(1, options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES); this.retainedFiles = Math.max(1, options.retainedFiles ?? DEFAULT_RETAINED_FILES); this.now = options.now ?? (() => new Date()); const interval = Math.max(0, options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS); if (interval > 0) { this.timer = setInterval(() => { void this.flush(); }, interval); this.timer.unref?.(); } } enqueue(raw: string): boolean { if (this.closed) { this.droppedCount += 1; return false; } let data: string; try { data = JSON.stringify({ ts: this.now().toISOString(), direction: 'server_to_ccl', raw, }) + '\n'; } catch { this.droppedCount += 1; return false; } const bytes = Buffer.byteLength(data); // Preserve one oversized physical frame when the buffer is otherwise // empty; truncating it would make this cease to be a raw capture. if (this.bufferedBytes > 0 && this.bufferedBytes + bytes > this.maxBufferedBytes) { this.droppedCount += 1; return false; } this.queue.push({ data, bytes }); this.bufferedBytes += bytes; this.acceptedCount += 1; if (this.queue.length >= this.batchSize) void this.flush(); return true; } flush(): Promise { if (this.queue.length === 0) return this.operation; const batch = this.queue.splice(0, this.queue.length); const batchBytes = batch.reduce((sum, line) => sum + line.bytes, 0); const next = this.operation.then(async () => { try { await this.writeBatch(batch); this.writtenCount += batch.length; } catch { // Capture is diagnostic-only. Count and discard failed batches rather // than retrying indefinitely or surfacing failure into gameplay. this.failedBatchCount += 1; } finally { this.bufferedBytes -= batchBytes; } }); // writeBatch failures are contained above; keep one ordered chain alive. this.operation = next.catch(() => {}); return this.operation; } async close(): Promise { if (this.closed) { await this.operation; return; } this.closed = true; if (this.timer) clearInterval(this.timer); await this.flush(); } stats(): RawWsLogStats { return { accepted: this.acceptedCount, dropped: this.droppedCount, written: this.writtenCount, failedBatches: this.failedBatchCount, bufferedBytes: this.bufferedBytes, queuedRecords: this.queue.length, }; } private async writeBatch(batch: readonly QueuedLine[]): Promise { await mkdir(dirname(this.filePath), { recursive: true }); if (!this.retentionPrepared) { await this.pruneExcessHistory(); this.retentionPrepared = true; } if (this.activeFileBytes === null) { try { this.activeFileBytes = (await stat(this.filePath)).size; } catch (error) { if (!hasErrorCode(error, 'ENOENT')) throw error; this.activeFileBytes = 0; } } let chunk: QueuedLine[] = []; let chunkBytes = 0; const appendChunk = async (): Promise => { if (chunk.length === 0) return; await appendFile( this.filePath, chunk.map((line) => line.data).join(''), { encoding: 'utf8', mode: 0o600 }, ); this.activeFileBytes! += chunkBytes; chunk = []; chunkBytes = 0; }; for (const line of batch) { const occupiedBytes = this.activeFileBytes + chunkBytes; if (occupiedBytes > 0 && occupiedBytes + line.bytes > this.maxFileBytes) { await appendChunk(); await this.rotate(); this.activeFileBytes = 0; } chunk.push(line); chunkBytes += line.bytes; // A single physical frame may exceed the file limit because raw capture // must not truncate it. Flush it alone so the next frame rotates first. if (line.bytes >= this.maxFileBytes) await appendChunk(); } await appendChunk(); } private async rotate(): Promise { await rm(`${this.filePath}.${this.retainedFiles}`, { force: true }); for (let index = this.retainedFiles - 1; index >= 1; index -= 1) { try { await rename(`${this.filePath}.${index}`, `${this.filePath}.${index + 1}`); } catch (error) { if (!hasErrorCode(error, 'ENOENT')) throw error; } } try { await rename(this.filePath, `${this.filePath}.1`); } catch (error) { if (!hasErrorCode(error, 'ENOENT')) throw error; } } private async pruneExcessHistory(): Promise { const directory = dirname(this.filePath); const prefix = `${basename(this.filePath)}.`; const entries = await readdir(directory); await Promise.all(entries.map(async (entry) => { if (!entry.startsWith(prefix)) return; const suffix = entry.slice(prefix.length); if (!/^\d+$/.test(suffix) || Number(suffix) <= this.retainedFiles) return; await rm(join(directory, entry), { force: true }); })); } }