- 数据库表规范化与原子事务版本迁移机制 (_schema_migrations) - 增加 SQLite 复合主键、PRAGMA busy_timeout 与索引覆盖 - 构建统一两级协同缓存 (L1 Memory LRU + L2 SQLite 持久化) - withCache 增加 In-flight Promise 去重并发防击穿 (单飞机制) - 收敛 dimension、role、bill 与 token-store 缓存逻辑 - 100% 保持现有 API 契约与零功能删除
105 lines
2.6 KiB
TypeScript
105 lines
2.6 KiB
TypeScript
import { Database } from "bun:sqlite";
|
|
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { dirname, join } from "node:path";
|
|
import { runMigrations } from "./migrations.js";
|
|
import type { DatabaseConnectionOptions } from "./types.js";
|
|
|
|
export const DEFAULT_DB_PATH = join(
|
|
homedir(),
|
|
".config",
|
|
"hose-use",
|
|
"approval.db"
|
|
);
|
|
|
|
export function resolveDatabasePath(): string {
|
|
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
|
|
if (envPath) {
|
|
return envPath;
|
|
}
|
|
return DEFAULT_DB_PATH;
|
|
}
|
|
|
|
let activeDb: Database | null = null;
|
|
let currentDbPath: string | null = null;
|
|
|
|
/**
|
|
* 获取或创建 SQLite 数据库连接单例,自动执行版本迁移
|
|
*/
|
|
export function getDatabase(options?: DatabaseConnectionOptions | string): Database {
|
|
const customPath = typeof options === "string" ? options : options?.customPath;
|
|
const targetPath = customPath ?? resolveDatabasePath();
|
|
|
|
if (activeDb && currentDbPath === targetPath) {
|
|
return activeDb;
|
|
}
|
|
|
|
// 若存在旧的不同路径连接,先优雅关闭释放文件句柄 (MAJ-12)
|
|
if (activeDb && currentDbPath !== targetPath) {
|
|
closeDatabase();
|
|
}
|
|
|
|
// 内存数据库无需创建物理目录
|
|
if (targetPath !== ":memory:") {
|
|
const dir = dirname(targetPath);
|
|
if (!existsSync(dir)) {
|
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
}
|
|
try {
|
|
chmodSync(dir, 0o700);
|
|
} catch {}
|
|
}
|
|
|
|
const db = new Database(targetPath);
|
|
|
|
if (targetPath !== ":memory:") {
|
|
// 保护敏感业务规则、缓存、会话与审计数据 (0o600)
|
|
try {
|
|
chmodSync(targetPath, 0o600);
|
|
} catch {
|
|
// 容错处理
|
|
}
|
|
}
|
|
|
|
// 启用 WAL 模式与并发优化
|
|
db.run("PRAGMA journal_mode = WAL;");
|
|
db.run("PRAGMA foreign_keys = ON;");
|
|
// 关键:避免 0ms 锁超时崩溃,允许并发等待 5000ms (MAJ-02)
|
|
db.run("PRAGMA busy_timeout = 5000;");
|
|
db.run("PRAGMA synchronous = NORMAL;");
|
|
|
|
try {
|
|
// 自动执行结构化原子迁移
|
|
runMigrations(db);
|
|
} catch (err) {
|
|
// CRIT-03: 若迁移失败,坚决不激活单例缓存,关闭句柄并向外抛出错误
|
|
try {
|
|
db.close();
|
|
} catch {}
|
|
activeDb = null;
|
|
currentDbPath = null;
|
|
throw err;
|
|
}
|
|
|
|
// 迁移彻底成功后,才正式激活单例
|
|
currentDbPath = targetPath;
|
|
activeDb = db;
|
|
|
|
return db;
|
|
}
|
|
|
|
/**
|
|
* 关闭并清理当前活跃数据库连接
|
|
*/
|
|
export function closeDatabase(): void {
|
|
if (activeDb) {
|
|
try {
|
|
activeDb.close();
|
|
} catch {
|
|
// 容错
|
|
}
|
|
activeDb = null;
|
|
currentDbPath = null;
|
|
}
|
|
}
|