// Append-only event log on disk (JSON Lines). // // Two properties matter more than anything else here: // - Append-only. Existing lines are never rewritten. History the model has seen stays exactly // as it was, and a crash can only ever damage the last line. // - Durable. Each append is flushed to disk (fdatasync) before it returns, so an event that was // reported as written survives a power cut or `kill -9`. import { appendFile, mkdir, open, readFile, stat } from 'node:fs/promises'; import path from 'node:path'; import { LOG_FORMAT_VERSION, SessionEventSchema, type NewSessionEvent, type SessionEvent, } from './events.ts'; export interface ReadResult { events: SessionEvent[]; /** Lines that could not be parsed (for example a write torn by a crash). */ skipped: { line: number; reason: string }[]; } export class EventLog { readonly file: string; private readonly clock: () => Date; constructor(file: string, clock: () => Date = () => new Date()) { this.file = file; this.clock = clock; } async append(event: NewSessionEvent): Promise { const full = { v: LOG_FORMAT_VERSION, ts: this.clock().toISOString(), ...event, } as SessionEvent; await mkdir(path.dirname(this.file), { recursive: true }); const handle = await open(this.file, 'a'); try { await handle.appendFile(JSON.stringify(full) + '\n', 'utf8'); await handle.datasync(); } finally { await handle.close(); } return full; } async read(): Promise { let text: string; try { text = await readFile(this.file, 'utf8'); } catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { events: [], skipped: [] }; throw err; } const events: SessionEvent[] = []; const skipped: ReadResult['skipped'] = []; const lines = text.split('\n'); lines.forEach((line, index) => { if (line.trim() === '') return; let json: unknown; try { json = JSON.parse(line); } catch { skipped.push({ line: index + 1, reason: 'not valid JSON (torn write?)' }); return; } const parsed = SessionEventSchema.safeParse(json); if (parsed.success) events.push(parsed.data); else skipped.push({ line: index + 1, reason: 'unknown or malformed event' }); }); return { events, skipped }; } /** * If the last write was torn (the file does not end with a newline), end that line, so the * next append starts on a fresh line instead of being glued to the broken one. */ async sealTornTail(): Promise { let size: number; try { size = (await stat(this.file)).size; } catch { return false; } if (size === 0) return false; const handle = await open(this.file, 'r'); try { const last = Buffer.alloc(1); await handle.read(last, 0, 1, size - 1); if (last.toString('utf8') === '\n') return false; } finally { await handle.close(); } await appendFile(this.file, '\n', 'utf8'); return true; } }