refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固

- 数据库表规范化与原子事务版本迁移机制 (_schema_migrations)
- 增加 SQLite 复合主键、PRAGMA busy_timeout 与索引覆盖
- 构建统一两级协同缓存 (L1 Memory LRU + L2 SQLite 持久化)
- withCache 增加 In-flight Promise 去重并发防击穿 (单飞机制)
- 收敛 dimension、role、bill 与 token-store 缓存逻辑
- 100% 保持现有 API 契约与零功能删除
This commit is contained in:
gitea committed 2026-09-08 15:49:27 +08:00
1 parent 00cbf039eb
commit 3a15b064fe
18 files changed
+1260 -268

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
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<T>(key: string, namespace = "default"): T | undefined {
const entry = this.getEntry<T>(key, namespace);
return entry ? entry.value : undefined;
}
public getEntry<T>(key: string, namespace = "default"): CacheEntry<T> | 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<T>(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) {
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;
}
}
}