- 数据库表规范化与原子事务版本迁移机制 (_schema_migrations) - 增加 SQLite 复合主键、PRAGMA busy_timeout 与索引覆盖 - 构建统一两级协同缓存 (L1 Memory LRU + L2 SQLite 持久化) - withCache 增加 In-flight Promise 去重并发防击穿 (单飞机制) - 收敛 dimension、role、bill 与 token-store 缓存逻辑 - 100% 保持现有 API 契约与零功能删除
163 lines
5.9 KiB
TypeScript
163 lines
5.9 KiB
TypeScript
import { Database } from "bun:sqlite";
|
|
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
|
import { closeDatabase, getDatabase } from "../db/connection.js";
|
|
import { MemoryCache } from "./memory.js";
|
|
import { MultiLevelCache } from "./multi-level.js";
|
|
import { SqliteCache } from "./sqlite.js";
|
|
|
|
describe("Core Cache - 多级缓存架构与淘汰机制 (加固测试)", () => {
|
|
let db: Database;
|
|
|
|
beforeEach(() => {
|
|
db = getDatabase(":memory:");
|
|
});
|
|
|
|
afterEach(() => {
|
|
closeDatabase();
|
|
});
|
|
|
|
describe("L1: MemoryCache", () => {
|
|
test("基础读写、删除与命名空间隔离", () => {
|
|
const cache = new MemoryCache();
|
|
cache.set("100", { name: "用户A" }, { namespace: "users" });
|
|
cache.set("100", { title: "角色B" }, { namespace: "roles" });
|
|
|
|
// CRIT-02 验证:相同 key 在不同命名空间下完全隔离、互不覆写
|
|
expect(cache.get<{ name: string }>("100", "users")).toEqual({ name: "用户A" });
|
|
expect(cache.get<{ title: string }>("100", "roles")).toEqual({ title: "角色B" });
|
|
expect(cache.has("100", "users")).toBe(true);
|
|
expect(cache.has("100", "departments")).toBe(false);
|
|
|
|
// 按 namespace 清理
|
|
cache.clear("users");
|
|
expect(cache.get("100", "users")).toBeUndefined();
|
|
expect(cache.get<{ title: string }>("100", "roles")).toEqual({ title: "角色B" });
|
|
|
|
// 单条删除
|
|
cache.delete("100", "roles");
|
|
expect(cache.get("100", "roles")).toBeUndefined();
|
|
});
|
|
|
|
test("TTL 过期检查", async () => {
|
|
const cache = new MemoryCache();
|
|
cache.set("temp", "value", { ttlMs: 10 });
|
|
expect(cache.get<string>("temp")).toBe("value");
|
|
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
expect(cache.get("temp")).toBeUndefined();
|
|
});
|
|
|
|
test("严格 LRU 访问热度调整与容量淘汰 (MAJ-08 & MAJ-09)", () => {
|
|
const cache = new MemoryCache(3);
|
|
cache.set("k1", "v1");
|
|
cache.set("k2", "v2");
|
|
cache.set("k3", "v3");
|
|
|
|
// 访问 k1,使 k1 成为最热的条目(移至队尾)
|
|
expect(cache.get<string>("k1")).toBe("v1");
|
|
|
|
// 此时最冷的是 k2。插入 k4 触发容量超限(容量 3)
|
|
cache.set("k4", "v4");
|
|
|
|
// 验证 k2 被淘汰,而最近被访问的 k1 依然存活
|
|
expect(cache.get("k2")).toBeUndefined();
|
|
expect(cache.get<string>("k1")).toBe("v1");
|
|
expect(cache.get<string>("k3")).toBe("v3");
|
|
expect(cache.get<string>("k4")).toBe("v4");
|
|
|
|
// 更新已有键不会增加容量,也不会误伤淘汰其他键
|
|
cache.set("k1", "v1_updated");
|
|
expect(cache.size()).toBe(3);
|
|
expect(cache.get<string>("k1")).toBe("v1_updated");
|
|
});
|
|
});
|
|
|
|
describe("L2: SqliteCache", () => {
|
|
test("复合主键 (namespace, key) 跨域存储与隔离 (CRIT-02)", () => {
|
|
const cache = new SqliteCache(db);
|
|
cache.set("id_1", { type: "dim" }, { namespace: "dimensions" });
|
|
cache.set("id_1", { type: "role" }, { namespace: "roles" });
|
|
|
|
const dim = cache.get<{ type: string }>("id_1", "dimensions");
|
|
const role = cache.get<{ type: string }>("id_1", "roles");
|
|
|
|
expect(dim?.type).toBe("dim");
|
|
expect(role?.type).toBe("role");
|
|
|
|
// 验证底层 SQLite 表结构行记录
|
|
const rows = db.query("SELECT namespace, key FROM cache_entries WHERE key = 'id_1'").all() as any[];
|
|
expect(rows.length).toBe(2);
|
|
|
|
// 按 namespace 清除
|
|
cache.clear("dimensions");
|
|
expect(cache.get("id_1", "dimensions")).toBeUndefined();
|
|
expect(cache.get("id_1", "roles")).toBeDefined();
|
|
});
|
|
|
|
test("TTL 过期与 pruneExpired 清理", async () => {
|
|
const cache = new SqliteCache(db);
|
|
cache.set("expire_soon", "data", { ttlMs: 15 });
|
|
expect(cache.get<string>("expire_soon")).toBe("data");
|
|
|
|
await new Promise((r) => setTimeout(r, 25));
|
|
expect(cache.get("expire_soon")).toBeUndefined();
|
|
|
|
cache.set("stale", "foo", { ttlMs: 5 });
|
|
await new Promise((r) => setTimeout(r, 15));
|
|
const pruned = cache.pruneExpired();
|
|
expect(pruned).toBeGreaterThanOrEqual(1);
|
|
});
|
|
});
|
|
|
|
describe("MultiLevelCache 两级协同与防击穿 (MAJ-01)", () => {
|
|
test("L1 miss 后从 L2 命中并自动回填至 L1", () => {
|
|
const l1 = new MemoryCache();
|
|
const l2 = new SqliteCache(db);
|
|
const multi = new MultiLevelCache({ l1, l2 });
|
|
|
|
multi.set("order:100", { amount: 888 }, { namespace: "orders" });
|
|
|
|
// 手动清空 L1 模拟内存冷启动
|
|
l1.clear();
|
|
expect(l1.get("order:100", "orders")).toBeUndefined();
|
|
|
|
// 从多级缓存读取:从 L2 命中,并回填至 L1
|
|
const val = multi.get<{ amount: number }>("order:100", "orders");
|
|
expect(val).toEqual({ amount: 888 });
|
|
|
|
// 验证 L1 已被自动回填
|
|
expect(l1.get<{ amount: number }>("order:100", "orders")).toEqual({ amount: 888 });
|
|
});
|
|
|
|
test("并发防击穿 (Thundering Herd Protection / In-flight Deduplication)", async () => {
|
|
const multi = new MultiLevelCache({ l2: new SqliteCache(db) });
|
|
let fetchCount = 0;
|
|
|
|
const slowFetcher = async () => {
|
|
fetchCount++;
|
|
await new Promise((r) => setTimeout(r, 20)); // 模拟慢网络
|
|
return { data: "fresh", fetchCount };
|
|
};
|
|
|
|
// 模拟 10 个并发请求在缓存冷启动时同时调用 withCache
|
|
const promises = Array.from({ length: 10 }).map(() =>
|
|
multi.withCache("concurrent_key", slowFetcher, {
|
|
namespace: "test_herd",
|
|
ttlMs: 5000,
|
|
})
|
|
);
|
|
|
|
const results = await Promise.all(promises);
|
|
|
|
// 验证:所有并发请求获取到相同的数据
|
|
expect(results.length).toBe(10);
|
|
for (const res of results) {
|
|
expect(res.fetchCount).toBe(1);
|
|
}
|
|
|
|
// 核心断言:底层 slowFetcher 严格只被调用了 1 次!彻底防御了缓存击穿
|
|
expect(fetchCount).toBe(1);
|
|
});
|
|
});
|
|
});
|