import type { Database } from "bun:sqlite"; import { getDatabase } from "../db/connection.js"; import type { CacheEntry, CacheOptions, ICache } from "./types.js"; const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 分钟 interface CacheRow { namespace: string; key: string; value: string; expires_at: number; updated_at: number; } export class SqliteCache implements ICache { private db: Database; constructor(db?: Database) { this.db = db ?? getDatabase(); } public get(key: string, namespace = "default"): T | undefined { const entry = this.getEntry(key, namespace); return entry ? entry.value : undefined; } public getEntry(key: string, namespace = "default"): CacheEntry | undefined { try { const row = this.db .query( "SELECT namespace, key, value, expires_at, updated_at FROM cache_entries WHERE namespace = ? AND key = ?" ) .get(namespace, key) as CacheRow | null; if (!row) return undefined; const now = Date.now(); if (row.expires_at <= now) { this.delete(key, namespace); return undefined; } const parsedValue = JSON.parse(row.value) as T; return { value: parsedValue, expiresAt: row.expires_at, updatedAt: row.updated_at, namespace: row.namespace, }; } catch { // 容错处理损坏数据 this.delete(key, namespace); return undefined; } } public set(key: string, value: T, options?: CacheOptions): void { if (value === undefined) { // MIN-05: undefined 语义等同于清除该键 this.delete(key, options?.namespace); return; } const now = Date.now(); const ttl = options?.ttlMs ?? DEFAULT_TTL_MS; const namespace = options?.namespace ?? "default"; const expiresAt = now + ttl; try { const serialized = JSON.stringify(value); this.db.run( ` INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(namespace, key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at, updated_at = excluded.updated_at `, [namespace, key, serialized, expiresAt, now] ); } catch (err) { if (process.env.DEBUG || process.env.NODE_ENV === "development") { console.error(`[cache] SqliteCache.set error for ${namespace}:${key}:`, err); } } } public delete(key: string, namespace = "default"): void { try { this.db.run( "DELETE FROM cache_entries WHERE namespace = ? AND key = ?", [namespace, key] ); } catch { // 容错 } } public clear(namespace?: string): void { try { if (namespace) { this.db.run("DELETE FROM cache_entries WHERE namespace = ?", [namespace]); } else { this.db.run("DELETE FROM cache_entries"); } } catch { // 容错 } } public has(key: string, namespace = "default"): boolean { return this.get(key, namespace) !== undefined; } /** * 主动清理数据库中所有过期缓存记录 */ public pruneExpired(): number { try { const result = this.db.run( "DELETE FROM cache_entries WHERE expires_at <= ?", [Date.now()] ); return result.changes; } catch { return 0; } } }