import { MemoryCache } from "./memory.js"; import { SqliteCache } from "./sqlite.js"; import type { CacheOptions, ICache, WithCacheOptions } from "./types.js"; export interface MultiLevelCacheOptions { l1?: MemoryCache; l2?: SqliteCache | null; } export class MultiLevelCache implements ICache { private l1: MemoryCache; private l2: SqliteCache | null; // MAJ-01: 防击穿 / 单飞并发请求去重表 (In-flight Promise Deduplication) private inFlight = new Map>(); constructor(options?: MultiLevelCacheOptions) { this.l1 = options?.l1 ?? new MemoryCache(); this.l2 = options?.l2 !== undefined ? options.l2 : new SqliteCache(); } public get(key: string, namespace = "default"): T | undefined { // 1. 优先从 L1 (Memory) 获取 const l1Value = this.l1.get(key, namespace); if (l1Value !== undefined) { return l1Value; } // 2. L1 穿透,查询 L2 (SQLite 持久化) if (this.l2) { const l2Entry = this.l2.getEntry(key, namespace); if (l2Entry !== undefined) { // 回填至 L1,保持相同的到期时间与命名空间 this.l1.setEntry(key, l2Entry); return l2Entry.value; } } return undefined; } public set(key: string, value: T, options?: CacheOptions): void { // 同时写入 L1 与 L2 this.l1.set(key, value, options); if (this.l2) { this.l2.set(key, value, options); } } public delete(key: string, namespace = "default"): void { this.l1.delete(key, namespace); if (this.l2) { this.l2.delete(key, namespace); } } public clear(namespace?: string): void { this.l1.clear(namespace); if (this.l2) { this.l2.clear(namespace); } } public has(key: string, namespace = "default"): boolean { return this.get(key, namespace) !== undefined; } /** * MAJ-01: 业务透明包装器,自动多级缓存查验 + In-flight 请求合并防击穿 */ public async withCache( key: string, fetcher: () => Promise, options?: WithCacheOptions ): Promise { const namespace = options?.namespace ?? "default"; const lockKey = `${namespace}:${key}`; if (!options?.forceRefresh) { const cached = this.get(key, namespace); if (cached !== undefined) { return cached; } } // 防击穿:检查是否已有相同命名空间与键的并发请求在执行中 const ongoing = this.inFlight.get(lockKey); if (ongoing) { return ongoing as Promise; } const promise = (async () => { try { const fresh = await fetcher(); this.set(key, fresh, options); return fresh; } finally { this.inFlight.delete(lockKey); } })(); this.inFlight.set(lockKey, promise); return promise; } /** * 清理过期条目(MIN-11: L1 与 L2 同步清理) */ public pruneExpired(): void { if (this.l2) { this.l2.pruneExpired(); } } }