import type { Db } from './db'; /** * Pluggable cache contract. The SQLite implementation below is the default for * the adapter-node deployment; a Redis-backed implementation can be swapped in * later without touching callers. Async by design so that swap stays invisible. */ export interface Cache { get(key: string): Promise; set(key: string, value: T, ttlMs?: number): Promise; delete(key: string): Promise; /** Fetch from cache, or run `load`, store the result, and return it. */ getOrLoad(key: string, ttlMs: number, load: () => Promise): Promise; } /** SQLite-backed cache. Replaces Blento's Cloudflare KV `CacheService`. */ export class SqliteCache implements Cache { #db: Db; constructor(db: Db) { this.#db = db; } async get(key: string): Promise { const row = this.#db.prepare('SELECT value, expires_at FROM cache WHERE key = ?').get(key) as | { value: string; expires_at: number | null } | undefined; if (!row) return undefined; if (row.expires_at !== null && row.expires_at <= Date.now()) { this.#db.prepare('DELETE FROM cache WHERE key = ?').run(key); return undefined; } return JSON.parse(row.value) as T; } async set(key: string, value: T, ttlMs?: number): Promise { const expiresAt = ttlMs === undefined ? null : Date.now() + ttlMs; this.#db .prepare( 'INSERT INTO cache (key, value, expires_at) VALUES (?, ?, ?) ' + 'ON CONFLICT(key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at' ) .run(key, JSON.stringify(value), expiresAt); } async delete(key: string): Promise { this.#db.prepare('DELETE FROM cache WHERE key = ?').run(key); } async getOrLoad(key: string, ttlMs: number, load: () => Promise): Promise { const cached = await this.get(key); if (cached !== undefined) return cached; const fresh = await load(); await this.set(key, fresh, ttlMs); return fresh; } /** Remove expired rows. Safe to call periodically; not required for correctness. */ prune(): void { this.#db .prepare('DELETE FROM cache WHERE expires_at IS NOT NULL AND expires_at <= ?') .run(Date.now()); } }