import { error as logError, log } from '../logger' import { getDb } from '../db/sqlite' import type { SessionEvent } from '../transport/event-bus' import { indexEventForSearch } from './search' /** * Durable event persistence — mirrors non-transient EventBus events into the * `session_events` SQLite table. * * The in-memory bus is the hot path (SSE fan-out, WS replay); SQLite is the * cold path (history after restart, sessions longer than the 5000-event * window). Writes are synchronous prepared-statement inserts — WAL mode * keeps them in the tens of microseconds, and event volume (excluding * transient streaming deltas) is a few per second at most. */ const INSERT_SQL = 'INSERT OR REPLACE INTO session_events (id, session_id, seq_num, type, payload, direction, created_at) VALUES ($id, $session_id, $seq_num, $type, $payload, $direction, $created_at)' type RunQuery = { run(...params: unknown[]): unknown } // Cache the prepared statement bound to the Database instance it was created // from — `getDb()` is a singleton in production (never swaps), but test // suites call freshDb() per file to get a brand-new Database; without the // binding the stale statement would keep writing into the previous temp file. let stmtCache: { db: unknown; stmt: RunQuery } | null = null function getInsertStmt(): RunQuery | null { const db = getDb() as unknown if (stmtCache && stmtCache.db === db) return stmtCache.stmt try { const stmt = (db as ReturnType).query( INSERT_SQL, ) as unknown as RunQuery stmtCache = { db, stmt } return stmt } catch (err) { stmtCache = null logError('[event-persistence] prepare insert failed:', err) return null } } /** Persist one non-transient event. Best-effort: failures are logged, never thrown — * persistence must not break the live event path. */ export function persistSessionEvent(event: SessionEvent): void { const stmt = getInsertStmt() if (!stmt) return try { stmt.run({ $id: event.id, $session_id: event.sessionId, $seq_num: event.seqNum, $type: event.type, $payload: JSON.stringify(event.payload ?? null), $direction: event.direction, $created_at: event.createdAt, }) // Cross-session FTS index (Web Dashboard search) — same best-effort contract indexEventForSearch(event) } catch (err) { logError( `[event-persistence] insert failed session=${event.sessionId} type=${event.type}:`, err, ) } } interface PersistedRow { id: string session_id: string seq_num: number type: string payload: string direction: string created_at: number } /** Load all persisted events for a session, oldest first. */ export function loadPersistedEvents( sessionId: string, limit = 5000, ): SessionEvent[] { try { const rows = getDb() .query( 'SELECT id, session_id, seq_num, type, payload, direction, created_at FROM session_events WHERE session_id = $sid ORDER BY rowid ASC LIMIT $limit', ) .all({ $sid: sessionId, $limit: limit }) as unknown as PersistedRow[] return rows.map(row => ({ id: row.id, sessionId: row.session_id, seqNum: row.seq_num, type: row.type, payload: safeParse(row.payload), direction: row.direction === 'outbound' ? 'outbound' : 'inbound', createdAt: row.created_at, })) } catch (err) { logError(`[event-persistence] load failed session=${sessionId}:`, err) return [] } } /** Delete persisted events for a session (data-retention cleanup). */ export function deletePersistedEvents(sessionId: string): void { try { getDb() .query('DELETE FROM session_events WHERE session_id = $sid') .run({ $sid: sessionId }) } catch (err) { logError(`[event-persistence] delete failed session=${sessionId}:`, err) } } function safeParse(raw: string): unknown { try { return JSON.parse(raw) } catch { return null } }