diff --git a/src/__tests__/__snapshots__/options.defaults.test.ts.snap b/src/__tests__/__snapshots__/options.defaults.test.ts.snap index 03bd081a..451ecbf5 100644 --- a/src/__tests__/__snapshots__/options.defaults.test.ts.snap +++ b/src/__tests__/__snapshots__/options.defaults.test.ts.snap @@ -2,6 +2,12 @@ exports[`options defaults should return specific properties: defaults 1`] = ` { + "cacheDb": { + "busyTimeoutMs": 5000, + "dbDefaultFilename": "pfmcp.db", + "dbPath": ":memory:", + "enabled": false, + }, "client": false, "contextManagement": false, "contextPath": "/", diff --git a/src/__tests__/server.db.test.ts b/src/__tests__/server.db.test.ts new file mode 100644 index 00000000..ab59da84 --- /dev/null +++ b/src/__tests__/server.db.test.ts @@ -0,0 +1,432 @@ +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { DatabaseSync } from 'node:sqlite'; +import { memo } from '../server.caching'; +import { memoSettledAdapter } from '../server.cachingAdapter'; +import { + createDb, + quarantineCorruptDb, + resolveCacheDbPath, + verifyDbIntegrity, + type DbInstance +} from '../server.db'; +import { DEFAULT_OPTIONS } from '../options.defaults'; + +describe('createDb', () => { + let dbInstance: DbInstance; + + beforeEach(() => { + dbInstance = createDb(':memory:'); + }); + + afterEach(() => { + dbInstance.close(); + }); + + it('should initialize an in-memory database with configured PRAGMAs', () => { + expect(dbInstance).toBeDefined(); + expect(dbInstance.db).toBeDefined(); + + const journalMode = dbInstance.db.prepare('PRAGMA journal_mode;').get() as { journal_mode: string }; + + // In-memory databases report 'memory' mode for journal_mode in SQLite + expect(journalMode.journal_mode).toBeDefined(); + + const foreignKeys = dbInstance.db.prepare('PRAGMA foreign_keys;').get() as { foreign_keys: number }; + + expect(foreignKeys.foreign_keys).toBe(1); + + const busyTimeout = dbInstance.db.prepare('PRAGMA busy_timeout;').get() as { timeout: number }; + + expect(busyTimeout.timeout).toBe(5000); + }); + + it('should delegate memoStore creation and perform basic operations', () => { + const store = dbInstance.memoStore('test_ns'); + + expect(store).toBeDefined(); + expect(store.size).toBe(0); + + store.set('key1', { status: 'fulfilled', value: 'hello' }); + expect(store.has('key1')).toBe(true); + expect(store.get('key1')).toEqual({ status: 'fulfilled', value: 'hello' }); + expect(store.size).toBe(1); + }); + + it('should allow pruneExpired on a fresh database before any memoStore is created', () => { + expect(dbInstance.pruneExpired()).toBe(0); + }); + + it('should prune expired entries globally and by namespace', () => { + jest.useFakeTimers(); + const now = 500000; + + jest.setSystemTime(now); + + const storeA = dbInstance.memoStore('ns_a', { expire: 5000 }); + const storeB = dbInstance.memoStore('ns_b', { expire: 10000 }); + + storeA.set('k_a', { status: 'fulfilled', value: 'a' }); + storeB.set('k_b', { status: 'fulfilled', value: 'b' }); + + jest.setSystemTime(now + 6000); + + const changesB = dbInstance.pruneExpired('ns_b'); + + expect(changesB).toBe(0); + + const changesA = dbInstance.pruneExpired('ns_a'); + + expect(changesA).toBe(1); + + jest.setSystemTime(now + 12000); + const totalChanges = dbInstance.pruneExpired(); + + expect(totalChanges).toBe(1); + + jest.useRealTimers(); + }); + + it('should close the underlying database connection cleanly', () => { + dbInstance.close(); + + expect(() => { + dbInstance.db.prepare('SELECT 1;').get(); + }).toThrow(); + }); + + it('should checkpoint WAL on close or manual checkpoint call', () => { + expect(() => dbInstance.checkpoint()).not.toThrow(); + }); +}); + +describe('resolveCacheDbPath', () => { + const testDir = join(tmpdir(), `pf-mcp-db-test-${Date.now()}`); + + afterEach(() => { + if (existsSync(testDir)) { + rmSync(testDir, { recursive: true, force: true }); + } + }); + + it('should return :memory: unchanged', () => { + expect(resolveCacheDbPath(':memory:')).toBe(':memory:'); + expect(resolveCacheDbPath('')).toBe(':memory:'); + }); + + it('should auto-append the DB filename when path ends in a trailing slash and create directory', () => { + const dirWithSlash = join(testDir, 'nested', ''); + const resolved = resolveCacheDbPath(`${dirWithSlash}/`); + + expect(resolved).toBe(join(testDir, 'nested', DEFAULT_OPTIONS.cacheDb.dbDefaultFilename)); + expect(existsSync(join(testDir, 'nested'))).toBe(true); + }); + + it('should auto-append the DB filename when path resolves to an existing directory', () => { + mkdirSync(testDir, { recursive: true }); + const resolved = resolveCacheDbPath(testDir); + + expect(resolved).toBe(join(testDir, DEFAULT_OPTIONS.cacheDb.dbDefaultFilename)); + }); + + it('should ensure parent directory exists when given a direct file path', () => { + const filePath = join(testDir, 'subdir', 'custom.db'); + const resolved = resolveCacheDbPath(filePath); + + expect(resolved).toBe(filePath); + expect(existsSync(join(testDir, 'subdir'))).toBe(true); + }); + + it('should respect custom dbDefaultFilename from options', () => { + const customOptions = { + cacheDb: { ...DEFAULT_OPTIONS.cacheDb, dbDefaultFilename: 'custom-name.db' } + } as any; + const resolved = resolveCacheDbPath(`${testDir}/`, customOptions); + + expect(resolved).toBe(join(testDir, 'custom-name.db')); + }); +}); + +describe('verifyDbIntegrity', () => { + it('should pass for a healthy SQLite database', () => { + const rawDb = new DatabaseSync(':memory:'); + + expect(() => verifyDbIntegrity(rawDb)).not.toThrow(); + rawDb.close(); + }); + + it('should throw when unauthorized views or triggers exist', () => { + const rawDb = new DatabaseSync(':memory:'); + + rawDb.exec('CREATE TABLE test (id INT);'); + rawDb.exec('CREATE VIEW unauthorized_view AS SELECT * FROM test;'); + + expect(() => verifyDbIntegrity(rawDb)).toThrow( + /unauthorized schema objects detected: view:unauthorized_view/ + ); + + rawDb.close(); + }); +}); + +describe('quarantineCorruptDb', () => { + const testDir = join(tmpdir(), `pf-mcp-quarantine-test-${Date.now()}`); + + beforeEach(() => { + mkdirSync(testDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(testDir)) { + rmSync(testDir, { recursive: true, force: true }); + } + }); + + it('should rename corrupt file with timestamp suffix', () => { + const filePath = join(testDir, 'corrupt.db'); + + writeFileSync(filePath, 'NOT_A_SQLITE_DATABASE'); + + const quarantinedPath = quarantineCorruptDb(filePath); + + expect(existsSync(filePath)).toBe(false); + expect(existsSync(quarantinedPath)).toBe(true); + expect(quarantinedPath).toMatch(/corrupt\.db\.corrupt\.\d{4}-\d{2}-\d{2}T/); + expect(readFileSync(quarantinedPath, 'utf8')).toBe('NOT_A_SQLITE_DATABASE'); + }); +}); + +describe('createDb file-backed persistence & self-healing', () => { + const testDir = join(tmpdir(), `pf-mcp-filebacked-test-${Date.now()}`); + + beforeEach(() => { + mkdirSync(testDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(testDir)) { + rmSync(testDir, { recursive: true, force: true }); + } + }); + + it('should persist data across separate createDb instances pointing to same file', () => { + const dbFile = join(testDir, 'test.db'); + + const dbInstance1 = createDb(dbFile); + const store1 = dbInstance1.memoStore('persist_ns'); + + store1.set('key1', { status: 'fulfilled', value: 'persisted_val' }); + dbInstance1.close(); + + const dbInstance2 = createDb(dbFile); + const store2 = dbInstance2.memoStore('persist_ns'); + + expect(store2.has('key1')).toBe(true); + expect(store2.get('key1')).toEqual({ status: 'fulfilled', value: 'persisted_val' }); + dbInstance2.close(); + }); + + it('should forward custom options to resolveCacheDbPath when opening a directory path', () => { + const customOptions = { + ...DEFAULT_OPTIONS, + cacheDb: { ...DEFAULT_OPTIONS.cacheDb, dbDefaultFilename: 'custom-forwarded.db' } + } as any; + const dbInstance = createDb(`${testDir}/`, customOptions); + + expect(dbInstance.db.isOpen).toBe(true); + expect(existsSync(join(testDir, 'custom-forwarded.db'))).toBe(true); + + dbInstance.close(); + }); + + it('should quarantine corrupted file on startup and recreate fresh healthy database', () => { + const dbFile = join(testDir, 'corrupted.db'); + + writeFileSync(dbFile, 'GARBAGE_HEADER_CORRUPTING_SQLITE_FORMAT'); + + const dbInstance = createDb(dbFile); + + expect(dbInstance).toBeDefined(); + expect(dbInstance.db.isOpen).toBe(true); + + // Fresh database should be functional + const store = dbInstance.memoStore('healed_ns'); + + store.set('key', { status: 'fulfilled', value: 'recovered' }); + expect(store.get('key')).toEqual({ status: 'fulfilled', value: 'recovered' }); + + dbInstance.close(); + }); + + it('should recreate the database file and re-prepare statements if deleted while open', () => { + const dbFile = join(testDir, 'nested', 'recreate.db'); + const dbInstance = createDb(dbFile); + const store = dbInstance.memoStore('live_ns'); + + store.set('key1', { status: 'fulfilled', value: 'initial' }); + expect(existsSync(dbFile)).toBe(true); + expect(store.get('key1')).toEqual({ status: 'fulfilled', value: 'initial' }); + + // Delete the database file and its parent directory while the connection is active + rmSync(join(testDir, 'nested'), { recursive: true, force: true }); + expect(existsSync(dbFile)).toBe(false); + + // Subsequent store operations should transparently recreate the directory, DB file, and statements + expect(store.get('key1')).toBeUndefined(); + store.set('key2', { status: 'fulfilled', value: 'recreated' }); + expect(existsSync(dbFile)).toBe(true); + expect(store.get('key2')).toEqual({ status: 'fulfilled', value: 'recreated' }); + expect(dbInstance.pruneExpired()).toBe(0); + + dbInstance.close(); + }); +}); + +describe('createDb memoSettledAdapter integration & cold hydration', () => { + const testDir = join(tmpdir(), `pf-mcp-db-hydration-test-${Date.now()}`); + let dbInstance: DbInstance | undefined; + + beforeEach(() => { + mkdirSync(testDir, { recursive: true }); + }); + + afterEach(() => { + dbInstance?.close(); + dbInstance = undefined; + if (existsSync(testDir)) { + rmSync(testDir, { recursive: true, force: true }); + } + }); + + it('should persist settled entries to SQLite and hydrate on cold restart', async () => { + jest.useFakeTimers(); + const dbFile = join(testDir, 'cache.db'); + + // Session 1: Write and persist to SQLite + dbInstance = createDb(dbFile); + const store1 = dbInstance.memoStore('fetch_urls'); + const worker1 = jest.fn(async (url: string) => `content for ${url}`); + const memoized1 = memo(worker1, { + cache: memoSettledAdapter>(store1) + }); + + const result1 = await memoized1('https://example.com/api/v1'); + + expect(result1).toBe('content for https://example.com/api/v1'); + expect(worker1).toHaveBeenCalledTimes(1); + + // Allow asynchronous storeQueue flush to SQLite + await jest.advanceTimersByTimeAsync(0); + + // Verify SQLite row was persisted + const row = dbInstance.db + .prepare('SELECT value, status FROM memo_cache WHERE namespace = ?') + .get('fetch_urls') as { value: string; status: string } | undefined; + + expect(row?.status).toBe('fulfilled'); + dbInstance.close(); + + // Session 2: Cold boot restart with separate DB and memo instance + const dbInstance2 = createDb(dbFile); + const store2 = dbInstance2.memoStore('fetch_urls'); + const worker2 = jest.fn(async (url: string) => `content for ${url}`); + const memoized2 = memo(worker2, { + cache: memoSettledAdapter>(store2) + }); + + // Cold hit should rehydrate from SQLite without invoking worker2 + const result2 = await memoized2('https://example.com/api/v1'); + + expect(result2).toBe('content for https://example.com/api/v1'); + expect(worker2).not.toHaveBeenCalled(); + + dbInstance2.close(); + jest.useRealTimers(); + }); + + it('should forward clear housekeeping to SQLite partition through settled adapter', async () => { + jest.useFakeTimers(); + const mockSystemTime = 0; + + jest.setSystemTime(mockSystemTime); + + dbInstance = createDb(':memory:'); + const store = dbInstance.memoStore('isolated_ns', { expire: 50 }); + const memoized = memo(async (id: string) => `data-${id}`, { + cache: memoSettledAdapter>(store) + }); + + await memoized('item1'); + await memoized('item2'); + await jest.advanceTimersByTimeAsync(0); + expect(store.size).toBe(2); + + // Unexpired entries should be preserved on clear + memoized.clear(); + await jest.advanceTimersByTimeAsync(0); + expect(store.size).toBe(2); + + // Advance time past expiration (50ms), then clear should prune them + jest.setSystemTime(mockSystemTime + 60); + memoized.clear(); + await jest.advanceTimersByTimeAsync(0); + expect(store.size).toBe(0); + + jest.useRealTimers(); + }); +}); + +describe('createDb.memo', () => { + afterEach(() => { + createDb.memo.clear(); + }); + + it('should return identical DbInstance for identical database path', () => { + const db = createDb.memo(':memory:'); + const nextDb = createDb.memo(':memory:'); + + expect(db).toBe(nextDb); + }); + + it('should evict entries from memo cache when clear() is called without forcibly closing open connections', () => { + const db = createDb.memo(':memory:'); + + expect(db.db.isOpen).toBe(true); + + createDb.memo.clear(); + + // Existing consumer's instance remains open + expect(db.db.isOpen).toBe(true); + + // Subsequent call returns a fresh instance + const nextDb = createDb.memo(':memory:'); + + expect(nextDb).not.toBe(db); + + db.close(); + nextDb.close(); + }); + + it('should close evicted DbInstance via onCacheRollout when cacheLimit is exceeded', async () => { + jest.useFakeTimers(); + + const db = createDb.memo(':memory:'); + + expect(db.db.isOpen).toBe(true); + + const nextDb = createDb.memo(':memory:', { + ...DEFAULT_OPTIONS, + cacheDb: { ...DEFAULT_OPTIONS.cacheDb, busyTimeoutMs: 1000 } + }); + + await jest.advanceTimersByTimeAsync(0); + + expect(nextDb).not.toBe(db); + expect(db.db.isOpen).toBe(false); + expect(nextDb.db.isOpen).toBe(true); + + nextDb.close(); + jest.useRealTimers(); + }); +}); diff --git a/src/__tests__/server.dbMemoStore.test.ts b/src/__tests__/server.dbMemoStore.test.ts new file mode 100644 index 00000000..1e94ebe5 --- /dev/null +++ b/src/__tests__/server.dbMemoStore.test.ts @@ -0,0 +1,306 @@ +import { DatabaseSync } from 'node:sqlite'; +import { + createDbMemoStore, + getStatements, + initMemoCacheTable, + prepareStatements +} from '../server.dbMemoStore'; +import type { MemoSettled } from '../server.cachingAdapter'; + +describe('initMemoCacheTable', () => { + it('should idempotently create the memo_cache table and indices', () => { + const rawDb = new DatabaseSync(':memory:'); + + initMemoCacheTable(rawDb); + initMemoCacheTable(rawDb); + + const tableInfo = rawDb + .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='memo_cache'") + .get() as { name: string } | undefined; + + expect(tableInfo?.name).toBe('memo_cache'); + rawDb.close(); + }); + + it('should purge entries that expired while the server was offline on initialization', () => { + const rawDb = new DatabaseSync(':memory:'); + + initMemoCacheTable(rawDb); + + // Manually insert an expired row simulating a previous session + rawDb.prepare(` + INSERT INTO memo_cache (namespace, key_hash, value, status, created_at, expires_at, last_accessed_at) + VALUES ('ns_offline', 'k_old', '{"status":"fulfilled","value":"stale"}', 'fulfilled', 1000, 2000, 1000) + `).run(); + + initMemoCacheTable(rawDb); + + const row = rawDb.prepare('SELECT 1 FROM memo_cache WHERE namespace = ? AND key_hash = ?').get('ns_offline', 'k_old'); + + expect(row).toBeUndefined(); + rawDb.close(); + }); +}); + +describe('prepareStatements & getStatements', () => { + afterEach(() => { + prepareStatements.memo.clear(); + }); + + it('should memoize compiled statements for the same DatabaseSync reference', () => { + const db = new DatabaseSync(':memory:'); + const first = prepareStatements.memo(db); + const second = prepareStatements.memo(db); + + expect(first).toBe(second); + db.close(); + }); + + it('should re-prepare statements when a db getter returns a new DatabaseSync instance', () => { + let activeDb = new DatabaseSync(':memory:'); + const store = createDbMemoStore(() => activeDb, 'dynamic_ns'); + + store.set('k1', { status: 'fulfilled', value: 'v1' }); + expect(store.get('k1')).toEqual({ status: 'fulfilled', value: 'v1' }); + + // Simulate database recreation by swapping the underlying DatabaseSync instance + activeDb.close(); + activeDb = new DatabaseSync(':memory:'); + + expect(store.get('k1')).toBeUndefined(); + store.set('k2', { status: 'fulfilled', value: 'v2' }); + expect(store.get('k2')).toEqual({ status: 'fulfilled', value: 'v2' }); + + activeDb.close(); + }); + + it('should expose bound all, get, and run helpers via getStatements', () => { + const db = new DatabaseSync(':memory:'); + const statements = getStatements(db); + + expect(typeof statements.stmtGet.get).toBe('function'); + expect(typeof statements.stmtSet.run).toBe('function'); + expect(typeof statements.stmtKeys.all).toBe('function'); + + statements.stmtSet.run('ns', 'hash1', '{"status":"fulfilled","value":"ok"}', 'fulfilled', 0, 1000, null, 1000); + expect(statements.stmtHas.get('ns', 'hash1', 1000)).toBeDefined(); + + db.close(); + }); +}); + +describe('createDbMemoStore', () => { + let db: DatabaseSync; + + beforeEach(() => { + db = new DatabaseSync(':memory:'); + }); + + afterEach(() => { + db.close(); + prepareStatements.memo.clear(); + }); + + it('should set, has, and get entries within a namespace', () => { + const store = createDbMemoStore(db, 'ns_test'); + const entry: MemoSettled = { status: 'fulfilled', value: 'hello' }; + + expect(store.has('key1')).toBe(false); + expect(store.get('key1')).toBeUndefined(); + + store.set('key1', entry); + + expect(store.has('key1')).toBe(true); + expect(store.get('key1')).toEqual(entry); + expect(store.size).toBe(1); + }); + + it('should update existing entries and track access count', () => { + const store = createDbMemoStore(db, 'ns_test'); + + store.set('count', { status: 'fulfilled', value: 1 }); + + const firstGet = store.get('count'); + + expect(firstGet).toEqual({ status: 'fulfilled', value: 1 }); + + store.set('count', { status: 'fulfilled', value: 2 }); + const secondGet = store.get('count'); + + expect(secondGet).toEqual({ status: 'fulfilled', value: 2 }); + + const row = db + .prepare('SELECT access_count FROM memo_cache WHERE namespace = ? AND key_hash = ?') + .get('ns_test', 'count') as { access_count: number }; + + expect(row.access_count).toBeGreaterThanOrEqual(2); + }); + + it('should delete entries and return boolean status', () => { + const store = createDbMemoStore(db, 'ns_test'); + + store.set('key1', { status: 'fulfilled', value: 'val1' }); + + expect(store.has('key1')).toBe(true); + const deleted = store.delete?.('key1'); + + expect(deleted).toBe(true); + expect(store.has('key1')).toBe(false); + expect(store.get('key1')).toBeUndefined(); + expect(store.size).toBe(0); + }); + + it('should hash object keys deterministically', () => { + const store = createDbMemoStore(db, 'ns_test'); + const keyA = { url: 'https://example.com', method: 'GET' }; + const keyB = { method: 'GET', url: 'https://example.com' }; + + store.set(keyA, { status: 'fulfilled', value: 'cached' }); + + expect(store.has(keyB)).toBe(true); + expect(store.get(keyB)).toEqual({ status: 'fulfilled', value: 'cached' }); + }); + + it('should isolate keys between namespaces and preserve other namespaces on clear', () => { + const storeA = createDbMemoStore(db, 'ns_a'); + const storeB = createDbMemoStore(db, 'ns_b'); + + storeA.set('shared_key', { status: 'fulfilled', value: 'val_a' }); + storeB.set('shared_key', { status: 'fulfilled', value: 'val_b' }); + + expect(storeA.get('shared_key')).toEqual({ status: 'fulfilled', value: 'val_a' }); + expect(storeB.get('shared_key')).toEqual({ status: 'fulfilled', value: 'val_b' }); + expect(storeA.size).toBe(1); + expect(storeB.size).toBe(1); + + (storeA.clear as (all?: boolean) => void)?.(true); + + expect(storeA.has('shared_key')).toBe(false); + expect(storeA.get('shared_key')).toBeUndefined(); + expect(storeA.size).toBe(0); + + expect(storeB.has('shared_key')).toBe(true); + expect(storeB.get('shared_key')).toEqual({ status: 'fulfilled', value: 'val_b' }); + expect(storeB.size).toBe(1); + }); + + it('should expire entries when expire time has elapsed', () => { + jest.useFakeTimers(); + const now = 100000; + + jest.setSystemTime(now); + + const store = createDbMemoStore(db, 'ns_expire', { expire: 5000 }); + + store.set('temp', { status: 'fulfilled', value: 'expires_soon' }); + + expect(store.has('temp')).toBe(true); + expect(store.get('temp')).toEqual({ status: 'fulfilled', value: 'expires_soon' }); + expect(store.size).toBe(1); + + jest.setSystemTime(now + 5001); + + expect(store.has('temp')).toBe(false); + expect(store.get('temp')).toBeUndefined(); + expect(store.size).toBe(0); + + jest.useRealTimers(); + }); + + it('should interpret clear() as TTL garbage collection of expired entries while preserving active ones', () => { + jest.useFakeTimers(); + const now = 200000; + + jest.setSystemTime(now); + + const store = createDbMemoStore(db, 'ns_gc', { expire: 5000 }); + + store.set('expired_key', { status: 'fulfilled', value: 'old_value' }); + + jest.setSystemTime(now + 6000); + store.set('fresh_key', { status: 'fulfilled', value: 'fresh_value' }); + + // Default clear() performs TTL garbage collection + store.clear?.(); + + // Fresh key must still be present and valid + expect(store.has('fresh_key')).toBe(true); + expect(store.get('fresh_key')).toEqual({ status: 'fulfilled', value: 'fresh_value' }); + + // Expired row has been physically deleted from the table + const expiredRow = db.prepare('SELECT 1 FROM memo_cache WHERE namespace = ? AND key_hash = ?').get('ns_gc', 'expired_key'); + + expect(expiredRow).toBeUndefined(); + + jest.useRealTimers(); + }); + + it('should perform opportunistic TTL pruning on set when prune interval has elapsed', () => { + jest.useFakeTimers(); + const now = 300000; + + jest.setSystemTime(now); + + const store = createDbMemoStore(db, 'ns_opp_gc', { expire: 5000, pruneIntervalMs: 10000 }); + + store.set('first_key', { status: 'fulfilled', value: 'v1' }); + + // Advance time past expiration AND prune interval + jest.setSystemTime(now + 12000); + store.set('second_key', { status: 'fulfilled', value: 'v2' }); + + const staleRow = db.prepare('SELECT 1 FROM memo_cache WHERE namespace = ? AND key_hash = ?').get('ns_opp_gc', 'first_key'); + + expect(staleRow).toBeUndefined(); + + jest.useRealTimers(); + }); + + it('should iterate over keys and entries filtering expired items', () => { + const store = createDbMemoStore(db, 'ns_iter'); + + store.set('k1', { status: 'fulfilled', value: 'v1' }); + store.set('k2', { status: 'fulfilled', value: 'v2' }); + + const keys = Array.from(store.keys?.() ?? []); + + expect(keys).toEqual(['k1', 'k2']); + + const entries = Array.from(store.entries?.() ?? []); + + expect(entries).toEqual([ + ['k1', { status: 'fulfilled', value: 'v1' }], + ['k2', { status: 'fulfilled', value: 'v2' }] + ]); + }); + + it('should persist rejected error envelopes', () => { + const store = createDbMemoStore(db, 'ns_err'); + const errorEntry: MemoSettled = { + status: 'rejected', + reason: new Error('Network timeout'), + isPromise: true + }; + + store.set('failed_call', errorEntry); + + const retrieved = store.get('failed_call'); + + expect(retrieved).toEqual(expect.objectContaining({ + status: 'rejected', + isPromise: true + })); + }); + + it('should safely evict corrupted JSON entries upon get', () => { + const store = createDbMemoStore(db, 'ns_corrupt'); + + store.set('bad', { status: 'fulfilled', value: 'ok' }); + + db.prepare('UPDATE memo_cache SET value = ? WHERE namespace = ? AND key_hash = ?') + .run('{ invalid json', 'ns_corrupt', 'bad'); + + expect(store.get('bad')).toBeUndefined(); + expect(store.has('bad')).toBe(false); + }); +}); diff --git a/src/options.defaults.ts b/src/options.defaults.ts index d3f82843..23a4f6cc 100644 --- a/src/options.defaults.ts +++ b/src/options.defaults.ts @@ -54,6 +54,7 @@ import { getNodeMajorVersion } from './options.helpers'; * @property xhrFetch - XHR and Fetch options. */ interface DefaultOptions { + cacheDb: CacheDbOptions; client: boolean; contextManagement: boolean; contextPath: string; @@ -91,6 +92,25 @@ interface DefaultOptions { xhrFetch: XhrFetchOptions; } +/** + * Database options. + * + * See {@link CACHE_DB_OPTIONS} for defaults. + * + * @interface CacheDbOptions + * + * @property enabled Enable database functionality. + * @property dbPath Full path and filename of the database. + * @property dbDefaultFilename Default filename of the database file. Used when not provided via `dbPath`. + * @property busyTimeoutMs Busy timeout in milliseconds. + */ +interface CacheDbOptions { + enabled: boolean; + dbPath: string; + dbDefaultFilename: string; + busyTimeoutMs: number; +} + /** * HTTP server options. * @@ -349,6 +369,16 @@ interface XhrFetchOptions { sanitizeMessages: boolean; } +/** + * Cache Database options. + */ +const CACHE_DB_OPTIONS: CacheDbOptions = { + enabled: false, + dbPath: ':memory:', + dbDefaultFilename: 'pfmcp.db', + busyTimeoutMs: 5000 +}; + /** * Base logging options. */ @@ -599,6 +629,7 @@ const PLUGIN_ISOLATION: DefaultOptions['pluginIsolation'][] = ['none', 'strict'] * @type {DefaultOptions} Default options object. */ const DEFAULT_OPTIONS: DefaultOptions = { + cacheDb: CACHE_DB_OPTIONS, client: false, contextManagement: false, contextPath: (process.env.NODE_ENV === 'local' && '/') || resolve(process.cwd()), @@ -637,10 +668,12 @@ const DEFAULT_OPTIONS: DefaultOptions = { }; export { + CACHE_DB_OPTIONS, DEFAULT_OPTIONS, CHANNEL_BASENAME, MODE_LEVELS, PLUGIN_ISOLATION, + type CacheDbOptions, type DefaultOptions, type HttpOptions, type LoggingOptions, diff --git a/src/server.db.ts b/src/server.db.ts new file mode 100644 index 00000000..a6782361 --- /dev/null +++ b/src/server.db.ts @@ -0,0 +1,252 @@ +import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { log } from './logger'; +import { createDbMemoStore, initMemoCacheTable, type DbMemoStoreOptions } from './server.dbMemoStore'; +import { memo, type MemoMapLike } from './server.caching'; +import { type MemoSettled } from './server.cachingAdapter'; +import { getOptions } from './options.context'; +import { type GlobalOptions } from './options'; + +/** + * SQLite database instance manager interface. + */ +interface DbInstance { + readonly db: DatabaseSync; + close(): void; + checkpoint(): void; + pruneExpired(namespace?: string): number; + memoStore(namespace: string, options?: DbMemoStoreOptions): MemoMapLike>; +} + +/** + * In-memory default db. + */ +const IN_MEMORY_DB = ':memory:'; + +/** + * Resolve database path, create a parent directory, and appending a default filename if needed. + * + * @param inputPath - Raw database path or {@link IN_MEMORY_DB}. + * @param {GlobalOptions} options - Optional configuration. + * @returns Resolved filesystem path or {@link IN_MEMORY_DB}. + */ +const resolveCacheDbPath = (inputPath: string = IN_MEMORY_DB, options = getOptions()): string => { + const { dbDefaultFilename } = options.cacheDb; + + if (!inputPath || inputPath === IN_MEMORY_DB) { + return IN_MEMORY_DB; + } + + let resolvedPath = resolve(inputPath); + const isDirectoryTarget = inputPath.endsWith('/') || inputPath.endsWith('\\'); + + if (isDirectoryTarget || (existsSync(resolvedPath) && statSync(resolvedPath).isDirectory())) { + resolvedPath = join(resolvedPath, dbDefaultFilename); + } + + const parentDir = dirname(resolvedPath); + + if (!existsSync(parentDir)) { + mkdirSync(parentDir, { recursive: true }); + } + + return resolvedPath; +}; + +/** + * Verify SQLite database integrity, foreign keys, and absence of injected triggers or views. + * + * @param db - The SQLite DatabaseSync instance to verify. + * @throws Error if structural check fails or unauthorized objects are detected. + */ +const verifyDbIntegrity = (db: DatabaseSync): void => { + const quickCheck = db.prepare('PRAGMA quick_check;').get() as { quick_check?: string } | undefined; + + if (quickCheck?.quick_check !== 'ok') { + throw new Error(`Database quick_check failed: ${quickCheck?.quick_check || 'unknown error'}`); + } + + const fkErrors = db.prepare('PRAGMA foreign_key_check;').all(); + + if (fkErrors.length > 0) { + throw new Error(`Database foreign_key_check failed with ${fkErrors.length} violation(s)`); + } + + const injectedObjects = db + .prepare("SELECT type, name FROM sqlite_schema WHERE type IN ('trigger', 'view');") + .all() as Array<{ type: string; name: string }>; + + if (injectedObjects.length > 0) { + const names = injectedObjects.map(item => `${item.type}:${item.name}`).join(', '); + + throw new Error(`Database integrity violation: unauthorized schema objects detected: ${names}`); + } +}; + +/** + * Move corrupted database file aside to preserve evidence and allow clean reinitialization. + * + * @param filePath - Path to the corrupt database file. + * @returns Path to the renamed quarantine file. + */ +const quarantineCorruptDb = (filePath: string): string => { + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + const quarantinePath = `${filePath}.corrupt.${timestamp}`; + + renameSync(filePath, quarantinePath); + log.warn(`Corrupt SQLite database quarantined: ${filePath} -> ${quarantinePath}`); + + return quarantinePath; +}; + +/** + * Open and configure a DatabaseSync instance with standard PRAGMAs. + * + * @param resolvedPath - Filesystem path or {@link IN_MEMORY_DB}. + * @param busyTimeout - Milliseconds to wait before throwing SQLITE_BUSY. + * @returns Open DatabaseSync instance. + */ +const openDatabase = (resolvedPath: string, busyTimeout: number): DatabaseSync => { + if (resolvedPath !== IN_MEMORY_DB) { + const parentDir = dirname(resolvedPath); + + if (!existsSync(parentDir)) { + mkdirSync(parentDir, { recursive: true }); + } + } + + const db = new DatabaseSync(resolvedPath); + + log.debug(`Opening SQLite database (${resolvedPath})`); + + db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + PRAGMA foreign_keys = ON; + PRAGMA trusted_schema = OFF; + PRAGMA busy_timeout = ${busyTimeout}; + `); + initMemoCacheTable(db); + + return db; +}; + +/** + * Create and configure an SQLite database instance. + * + * @param database - File path or {@link IN_MEMORY_DB}. + * @param {GlobalOptions}[options] - Optional configuration options for the DB instance. + * @returns Configured DbInstance. + */ +const createDb = (database: string = IN_MEMORY_DB, options: GlobalOptions = getOptions()): DbInstance => { + const { busyTimeoutMs } = options.cacheDb; + const resolvedPath = resolveCacheDbPath(database, options); + let db: DatabaseSync; + + try { + db = openDatabase(resolvedPath, busyTimeoutMs); + verifyDbIntegrity(db); + } catch (error) { + if (resolvedPath !== IN_MEMORY_DB && existsSync(resolvedPath)) { + quarantineCorruptDb(resolvedPath); + db = openDatabase(resolvedPath, busyTimeoutMs); + verifyDbIntegrity(db); + } else { + throw error; + } + } + + const ensureDb = (): DatabaseSync => { + if (resolvedPath !== IN_MEMORY_DB && db.isOpen && !existsSync(resolvedPath)) { + log.warn(`SQLite database file missing on disk, recreating (${resolvedPath})`); + db.close(); + db = openDatabase(resolvedPath, busyTimeoutMs); + } + + return db; + }; + + const checkpoint = (): void => { + if (db.isOpen) { + const activeDb = ensureDb(); + + try { + activeDb.exec('PRAGMA wal_checkpoint(TRUNCATE);'); + } catch { + // Ignore checkpoint errors during shutdown + } + } + }; + + const pruneExpired = (targetNamespace?: string): number => { + const activeDb = ensureDb(); + const now = Date.now(); + + if (targetNamespace) { + const result = activeDb.prepare(` + DELETE FROM memo_cache WHERE namespace = ? AND expires_at IS NOT NULL AND expires_at <= ?; + `).run(targetNamespace, now); + + return Number(result.changes); + } + const result = activeDb.prepare('DELETE FROM memo_cache WHERE expires_at IS NOT NULL AND expires_at <= ?;').run(now); + + return Number(result.changes); + }; + + return { + get db() { + return ensureDb(); + }, + checkpoint, + pruneExpired, + close(): void { + if (db.isOpen) { + checkpoint(); + db.close(); + } + }, + memoStore(namespace: string, storeOptions?: DbMemoStoreOptions): MemoMapLike> { + return createDbMemoStore(ensureDb, namespace, storeOptions); + } + }; +}; + +/** + * Memoized instance of createDb. + * - Returns the identical database connection handle for matching paths + * - Closes and checkpoints the database when the "database memo" rolls out, not the cached entries themselves + * - Limited to a single active database connection instance + */ +createDb.memo = memo( + (database: string = IN_MEMORY_DB, options: GlobalOptions = getOptions()) => createDb(database, options), + { + cacheLimit: 1, + onCacheRollout: async ({ removed }) => { + const results = await Promise.allSettled(removed.values()); + + for (const result of results) { + if (result.status === 'fulfilled') { + try { + await result.value.close(); + } catch (error) { + // Avoid engaging the contextual log channel on rollout. + console.error(`Error stopping database: ${error}`); + } + } else { + // Avoid engaging the contextual log channel on rollout. + console.error(`Error cleaning up database: ${result?.reason?.message || result?.reason || 'Unknown error'}`); + } + } + } + } +); + +export { + createDb, + quarantineCorruptDb, + resolveCacheDbPath, + verifyDbIntegrity, + type DbInstance +}; diff --git a/src/server.dbMemoStore.ts b/src/server.dbMemoStore.ts new file mode 100644 index 00000000..aa11e6f1 --- /dev/null +++ b/src/server.dbMemoStore.ts @@ -0,0 +1,321 @@ +import { + type DatabaseSync, + type SQLInputValue, + type SQLOutputValue, + type StatementResultingChanges +} from 'node:sqlite'; +import { generateHash } from './server.helpers'; +import { memo, type MemoMapLike } from './server.caching'; +import type { MemoSettled } from './server.cachingAdapter'; + +/** + * Options for configuring a specific memo namespace storage partition. + * + * @property [expire] - Time-to-live in milliseconds for entries in this namespace. + * @property [pruneIntervalMs] - Milliseconds between opportunistic background prune sweeps on set (default: 1 hour). + */ +interface DbMemoStoreOptions { + expire?: number | undefined; + pruneIntervalMs?: number | undefined; +} + +/** + * Internal row representation in the `memo_cache` table. + */ +interface MemoCacheRow { + namespace: string; + key_hash: string; + value: string; + status: 'fulfilled' | 'rejected'; + is_promise: number; + created_at: number; + expires_at: number | null; + access_count: number; + last_accessed_at: number; +} + +/** + * Minimal execution surface of a prepared SQLite statement. + */ +interface BoundStatement { + all: (...params: SQLInputValue[]) => Record[]; + get: (...params: SQLInputValue[]) => Record | undefined; + run: (...params: SQLInputValue[]) => StatementResultingChanges; +} + +/** + * DDL statement for creating the memo_cache table and its indexes. + */ +const MEMO_CACHE_SCHEMA_SQL = ` + CREATE TABLE IF NOT EXISTS memo_cache ( + namespace TEXT NOT NULL, + key_hash TEXT NOT NULL, + value TEXT NOT NULL, + status TEXT NOT NULL, + is_promise INTEGER DEFAULT 0, + created_at INTEGER NOT NULL, + expires_at INTEGER, + access_count INTEGER DEFAULT 1, + last_accessed_at INTEGER NOT NULL, + PRIMARY KEY (namespace, key_hash) + ); + CREATE INDEX IF NOT EXISTS idx_memo_ns ON memo_cache (namespace); + CREATE INDEX IF NOT EXISTS idx_memo_expires ON memo_cache (expires_at); +`; + +/** + * Default interval between opportunistic write-time expiration sweeps (1 hour). + */ +const DEFAULT_PRUNE_INTERVAL_MS = 60 * 60 * 1000; + +/** + * Initialize the memo_cache table schema within the given database instance. + * Automatically executes a startup sweep to purge any entries that expired while the server was offline. + * + * @param db - The SQLite DatabaseSync instance. + */ +const initMemoCacheTable = (db: DatabaseSync): void => { + db.exec(MEMO_CACHE_SCHEMA_SQL); + + db.prepare(` + DELETE FROM memo_cache + WHERE expires_at IS NOT NULL AND expires_at <= ?; + `).run(Date.now()); +}; + +/** + * Compile prepared statements for the memo_cache table on a given DatabaseSync instance. + * + * @param db - The SQLite DatabaseSync instance. + * @returns Object containing compiled StatementSync instances. + */ +const prepareStatements = (db: DatabaseSync) => { + initMemoCacheTable(db); + + return { + stmtHas: db.prepare(` + SELECT 1 FROM memo_cache + WHERE namespace = ? AND key_hash = ? AND (expires_at IS NULL OR expires_at > ?) + LIMIT 1; + `), + stmtGet: db.prepare(` + SELECT value, expires_at FROM memo_cache + WHERE namespace = ? AND key_hash = ? AND (expires_at IS NULL OR expires_at > ?) + LIMIT 1; + `), + stmtUpdateAccess: db.prepare(` + UPDATE memo_cache + SET access_count = access_count + 1, last_accessed_at = ? + WHERE namespace = ? AND key_hash = ?; + `), + stmtSet: db.prepare(` + INSERT INTO memo_cache ( + namespace, key_hash, value, status, is_promise, created_at, expires_at, access_count, last_accessed_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?) + ON CONFLICT(namespace, key_hash) DO UPDATE SET + value = excluded.value, + status = excluded.status, + is_promise = excluded.is_promise, + expires_at = excluded.expires_at, + access_count = memo_cache.access_count + 1, + last_accessed_at = excluded.last_accessed_at; + `), + stmtDelete: db.prepare(` + DELETE FROM memo_cache WHERE namespace = ? AND key_hash = ?; + `), + stmtClear: db.prepare(` + DELETE FROM memo_cache WHERE namespace = ?; + `), + stmtPruneExpiredNamespace: db.prepare(` + DELETE FROM memo_cache + WHERE namespace = ? AND expires_at IS NOT NULL AND expires_at <= ?; + `), + stmtSize: db.prepare(` + SELECT COUNT(*) as count FROM memo_cache + WHERE namespace = ? AND (expires_at IS NULL OR expires_at > ?); + `), + stmtKeys: db.prepare(` + SELECT key_hash FROM memo_cache + WHERE namespace = ? AND (expires_at IS NULL OR expires_at > ?) + ORDER BY created_at ASC; + `), + stmtEntries: db.prepare(` + SELECT key_hash, value FROM memo_cache + WHERE namespace = ? AND (expires_at IS NULL OR expires_at > ?) + ORDER BY created_at ASC; + `) + }; +}; + +/** + * Memoize statement compilation by DatabaseSync instance reference. + */ +prepareStatements.memo = memo(prepareStatements, { + keyHash: ([targetDb]) => targetDb +}); + +/** + * Resolve prepared statements bound to the active DatabaseSync instance. + * + * @param db - DatabaseSync instance or getter returning the active DatabaseSync instance. + * @returns Bound statement helpers matching the StatementSync execution surface. + */ +const getStatements = (db: DatabaseSync | (() => DatabaseSync)) => { + const resolveDb = typeof db === 'function' ? db : () => db; + const initialStatements = prepareStatements.memo(resolveDb()); + + type StatementKey = keyof typeof initialStatements; + + const bindStatement = (key: StatementKey): BoundStatement => { + const getActive = () => prepareStatements.memo(resolveDb())[key]; + + return { + all: (...params) => getActive().all(...params), + get: (...params) => getActive().get(...params), + run: (...params) => getActive().run(...params) + }; + }; + + return Object.fromEntries( + (Object.keys(initialStatements) as StatementKey[]).map(key => [key, bindStatement(key)]) + ) as Record; +}; + +/** + * Create a namespace-partitioned MemoMapLike store backed by the memo_cache table. + * + * @param db - DatabaseSync instance or getter returning the active DatabaseSync instance. + * @param namespace - Partition namespace identifier. + * @param [options] - Partition options such as expire. + * @returns MemoMapLike store compatible with memoSettledAdapter. + */ +const createDbMemoStore = ( + db: DatabaseSync | (() => DatabaseSync), + namespace: string, + options: DbMemoStoreOptions = {} +): MemoMapLike> => { + const { expire, pruneIntervalMs = DEFAULT_PRUNE_INTERVAL_MS } = options; + let lastPrunedAt = Date.now(); + const { + stmtHas, + stmtGet, + stmtUpdateAccess, + stmtSet, + stmtDelete, + stmtClear, + stmtPruneExpiredNamespace, + stmtSize, + stmtKeys, + stmtEntries + } = getStatements(db); + + const toKeyHash = (key: unknown): string => (typeof key === 'string' ? key : generateHash(key)); + + const maybePruneExpired = (now: number): void => { + if (now - lastPrunedAt >= pruneIntervalMs) { + lastPrunedAt = now; + stmtPruneExpiredNamespace.run(namespace, now); + } + }; + + return { + has(key: unknown): boolean { + const keyHash = toKeyHash(key); + const row = stmtHas.get(namespace, keyHash, Date.now()); + + return row !== undefined; + }, + + get(key: unknown): MemoSettled | undefined { + const now = Date.now(); + const keyHash = toKeyHash(key); + const row = stmtGet.get(namespace, keyHash, now) as { value: string; expires_at: number | null } | undefined; + + if (!row) { + return undefined; + } + + stmtUpdateAccess.run(now, namespace, keyHash); + + try { + return JSON.parse(row.value) as MemoSettled; + } catch { + stmtDelete.run(namespace, keyHash); + + return undefined; + } + }, + + set(key: unknown, value: MemoSettled): void { + const now = Date.now(); + + maybePruneExpired(now); + const keyHash = toKeyHash(key); + const expiresAt = expire ? now + expire : null; + const status = value?.status === 'rejected' ? 'rejected' : 'fulfilled'; + const isPromise = value?.isPromise ? 1 : 0; + const serialized = JSON.stringify(value); + + stmtSet.run(namespace, keyHash, serialized, status, isPromise, now, expiresAt, now); + }, + + delete(key: unknown): boolean { + const keyHash = toKeyHash(key); + const result = stmtDelete.run(namespace, keyHash); + + return Number(result.changes) > 0; + }, + + /** + * Clear cache entries. + * By default, performs TTL garbage collection by pruning expired entries in this namespace. + * Pass `true` to forcefully remove all entries (expired and active) in this namespace. + * + * @param [all=false] - Whether to remove all entries or only expired entries. + */ + clear(all = false): void { + if (all) { + stmtClear.run(namespace); + } else { + stmtPruneExpiredNamespace.run(namespace, Date.now()); + } + }, + + get size(): number { + const row = stmtSize.get(namespace, Date.now()) as { count: number } | undefined; + + return Number(row?.count || 0); + }, + + keys(): IterableIterator { + const rows = stmtKeys.all(namespace, Date.now()) as Array<{ key_hash: string }>; + + return rows.map(row => row.key_hash).values(); + }, + + entries(): IterableIterator<[unknown, MemoSettled]> { + const rows = stmtEntries.all(namespace, Date.now()) as Array<{ key_hash: string; value: string }>; + const list: Array<[unknown, MemoSettled]> = []; + + for (const row of rows) { + try { + list.push([row.key_hash, JSON.parse(row.value) as MemoSettled]); + } catch { + // Skip corrupted rows during iteration + } + } + + return list.values(); + } + }; +}; + +export { + createDbMemoStore, + getStatements, + initMemoCacheTable, + MEMO_CACHE_SCHEMA_SQL, + prepareStatements, + type DbMemoStoreOptions, + type MemoCacheRow +};