/** * SQLite Event Store * * Implements the EventStore interface from @frontmcp/protocol for SSE resumability. * Stores events in SQLite with TTL-based expiration and max event limits. */ import type Database from 'better-sqlite3'; import { decryptValue, deriveEncryptionKey, encryptValue } from './encryption'; import { withBusyRetry } from './open-database'; import { acquireConnection, type SqliteConnection } from './sqlite-connection'; import type { SqliteDatabase, SqliteStatement } from './sqlite-driver'; import type { SqliteStorageOptions } from './sqlite.options'; /** * Event store interface matching @frontmcp/protocol EventStore. * Redeclared here to avoid hard dependency on @frontmcp/protocol. */ export interface EventStoreInterface { storeEvent(streamId: string, message: unknown): Promise; replayEventsAfter( lastEventId: string, callbacks: { send: (eventId: string, message: unknown) => Promise }, ): Promise; /** * Resolve the stream an event belongs to. Optional upstream, but the * transport's 409-conflict guard is dead code without it * (GHSA-84j6-jc92-77jm). */ getStreamIdForEventId?(eventId: string): Promise; } export interface SqliteEventStoreOptions extends SqliteStorageOptions { /** Maximum number of events to store before eviction. @default 10000 */ maxEvents?: number; /** TTL in milliseconds for stored events. @default 300000 (5 minutes) */ ttlMs?: number; } /** Bundled prepared statements - all-or-nothing initialization. */ interface PreparedStatements { insert: SqliteStatement; getAfter: SqliteStatement; getStreamId: SqliteStatement; count: SqliteStatement; evictOldest: SqliteStatement; evictExpired: SqliteStatement; getLastId: SqliteStatement; } /** * SQLite-backed event store for SSE resumability. * * Schema: * ```sql * CREATE TABLE IF NOT EXISTS events ( * id TEXT PRIMARY KEY, * stream_id TEXT NOT NULL, * message TEXT NOT NULL, * created_at INTEGER NOT NULL * ); * ``` */ export class SqliteEventStore implements EventStoreInterface { private readonly connection: SqliteConnection; private readonly db: SqliteDatabase; private maxEvents: number; private ttlMs: number; private counters = new Map(); private cleanupTimer: ReturnType | null = null; private stmts: PreparedStatements | null = null; /** AES-256-GCM key derived from `options.encryption.secret`, applied to each stored message. */ private readonly encryptionKey: Uint8Array | null = null; constructor(options: SqliteEventStoreOptions) { this.connection = acquireConnection(options.path, 'SqliteEventStore', { busyTimeoutMs: options.busyTimeoutMs, walMode: options.walMode !== false, }); this.db = this.connection.db; this.maxEvents = options.maxEvents ?? 10000; this.ttlMs = options.ttlMs ?? 300000; if (options.encryption?.secret) { this.encryptionKey = deriveEncryptionKey(options.encryption.secret); } try { withBusyRetry(() => this.initSchema()); this.prepareStatements(); } catch (error) { this.connection.release(); throw error; } // Periodic cleanup of expired events, queued so another process's lock does not block or throw const cleanupInterval = options.ttlCleanupIntervalMs ?? 60000; if (cleanupInterval > 0) { this.cleanupTimer = setInterval( () => void this.connection.write(() => this.evictExpired()).catch(() => undefined), cleanupInterval, ); if (this.cleanupTimer.unref) { this.cleanupTimer.unref(); } } } private initSchema(): void { this.db.exec(` CREATE TABLE IF NOT EXISTS events ( id TEXT PRIMARY KEY, stream_id TEXT NOT NULL, message TEXT NOT NULL, created_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_events_stream ON events(stream_id, created_at); CREATE INDEX IF NOT EXISTS idx_events_created ON events(created_at); `); } private prepareStatements(): void { this.stmts = { insert: this.db.prepare('INSERT INTO events (id, stream_id, message, created_at) VALUES (?, ?, ?, ?)'), getAfter: this.db.prepare( 'SELECT id, message, created_at FROM events WHERE stream_id = ? AND rowid > (SELECT rowid FROM events WHERE id = ?) AND created_at > ? ORDER BY rowid ASC', ), getStreamId: this.db.prepare('SELECT stream_id FROM events WHERE id = ?'), count: this.db.prepare('SELECT COUNT(*) as count FROM events'), evictOldest: this.db.prepare( 'DELETE FROM events WHERE id IN (SELECT id FROM events ORDER BY created_at ASC LIMIT ?)', ), evictExpired: this.db.prepare('DELETE FROM events WHERE created_at <= ?'), getLastId: this.db.prepare('SELECT id FROM events WHERE stream_id = ? ORDER BY rowid DESC LIMIT 1'), }; } /** * Return prepared statements, throwing if not yet initialized. */ private prepared(): PreparedStatements { if (!this.stmts) { throw new Error('SqliteEventStore: prepared statements not initialized. Was prepareStatements() called?'); } return this.stmts; } /** * Get the next counter value for a stream, rehydrating from SQLite on first use. */ private getNextCounter(streamId: string): number { let counter = this.counters.get(streamId); if (counter === undefined) { // Rehydrate from SQLite: find the last event ID for this stream const stmts = this.prepared(); const row = stmts.getLastId.get(streamId) as { id: string } | undefined; if (row) { const lastSegment = row.id.split(':').pop(); counter = lastSegment ? parseInt(lastSegment, 10) : 0; if (isNaN(counter)) counter = 0; } else { counter = 0; } } counter += 1; this.counters.set(streamId, counter); return counter; } async storeEvent(streamId: string, message: unknown): Promise { const stmts = this.prepared(); this.evictExpired(); const counter = this.getNextCounter(streamId); const id = `${streamId}:${counter}`; const now = Date.now(); const json = JSON.stringify(message); stmts.insert.run(id, streamId, this.encryptionKey ? encryptValue(this.encryptionKey, json) : json, now); // Evict oldest if over max const countRow = stmts.count.get() as { count: number }; if (countRow.count > this.maxEvents) { const excess = countRow.count - this.maxEvents; stmts.evictOldest.run(excess); } return id; } async getStreamIdForEventId(eventId: string): Promise { const row = this.prepared().getStreamId.get(eventId) as { stream_id: string } | undefined; return row?.stream_id; } async replayEventsAfter( lastEventId: string, { send }: { send: (eventId: string, message: unknown) => Promise }, ): Promise { const stmts = this.prepared(); // Find the stream for this event const streamRow = stmts.getStreamId.get(lastEventId) as { stream_id: string } | undefined; if (!streamRow) { // Unknown lastEventId: return a default stream return 'default-stream'; } const streamId = streamRow.stream_id; const expiryCutoff = Date.now() - this.ttlMs; const rows = stmts.getAfter.all(streamId, lastEventId, expiryCutoff) as { id: string; message: string; created_at: number; }[]; for (const row of rows) { const message = this.readMessage(row.message); if (message !== undefined) await send(row.id, message); } return streamId; } /** * A stored message, decrypted when a secret is set. A message that does not decrypt (stored before * the secret was set, or with another secret) is undefined, and left out of the replay. */ private readMessage(stored: string): unknown { if (!this.encryptionKey) return JSON.parse(stored); try { return JSON.parse(decryptValue(this.encryptionKey, stored)); } catch { return undefined; } } private evictExpired(): void { const stmts = this.prepared(); const cutoff = Date.now() - this.ttlMs; stmts.evictExpired.run(cutoff); } /** * Stop the cleanup timer and release the connection, which closes once no other store on the file uses it. */ close(): void { if (this.cleanupTimer) { clearInterval(this.cleanupTimer); this.cleanupTimer = null; } this.connection.release(); } /** * Get the underlying database instance. * With a driver set by `useSqliteDriver()` it is the driver's database, which has the members of * `SqliteDatabase` only. */ getDatabase(): Database.Database { return this.db as Database.Database; } /** * Get the current number of stored events. */ get size(): number { const stmts = this.prepared(); const row = stmts.count.get() as { count: number }; return row.count; } }