diff --git a/.gitignore b/.gitignore index 891383c..7ba29a8 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,5 @@ data/ # Local roadmaps & scratch notes *.local.md +.agents/ + diff --git a/.zcode-plugin/plugin.json b/.zcode-plugin/plugin.json index 709f1ca..1cf0b00 100644 --- a/.zcode-plugin/plugin.json +++ b/.zcode-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "hose-use", - "version": "0.7.4", + "version": "0.7.5", "description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。", "author": { "name": "yingqing" diff --git a/README.md b/README.md index c68d5d0..5ccb51a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# hose-use (v0.7.4) +# hose-use (v0.7.5) 合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。 diff --git a/dist/openapi.json b/dist/openapi.json index 200c6a2..1f7d86f 100644 --- a/dist/openapi.json +++ b/dist/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "hose-use API & MCP Tools Specification", - "version": "0.7.4", + "version": "0.7.5", "description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows." }, "servers": [ diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index 4c63af2..ec81ece 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.1.0 info: title: hose-use API & MCP Tools Specification - version: 0.7.4 + version: 0.7.5 description: >- Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows. servers: diff --git a/package.json b/package.json index ba7983c..ae7228b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hose-use", - "version": "0.7.4", + "version": "0.7.5", "module": "src/server.ts", "type": "module", "bin": { diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index 8270eaf..c44131e 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -1,12 +1,12 @@ --- name: hose-use -description: "v0.7.4: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。" +description: "v0.7.5: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。" metadata: - version: 0.7.4 - short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.4) + version: 0.7.5 + short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.5) --- -# hose-use (v0.7.4) +# hose-use (v0.7.5) 在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。 本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。 diff --git a/src/core/README.core.md b/src/core/README.core.md index 7815577..4b2275b 100644 --- a/src/core/README.core.md +++ b/src/core/README.core.md @@ -1,6 +1,6 @@ # Core 层说明 -Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、HTTP 客户端工厂、统一异常语义。 +Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、统一数据库与版本迁移、多级协同缓存、HTTP 客户端工厂、统一异常语义。 ## 代码结构 @@ -13,7 +13,16 @@ src/core/ │ ├── ekb.ts # 快报主站三 Header 认证 │ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证 │ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证 -│ ├── token-store.ts # 动态 Token 缓存(~/.cache/ekb-mcp/tokens.json) +│ ├── token-store.ts # 动态 Token 缓存(兼容 ~/.config/hose-use/tokens.json 与历史路径) +│ └── types.ts +├── cache/ # 统一多级协同缓存 +│ ├── memory.ts # L1 内存缓存(TTL、容量限制、按命名空间清理) +│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用) +│ ├── multi-level.ts # 多级联动门面与 withCache 透明包装器 +│ └── types.ts +├── db/ # 统一 SQLite 数据库与结构化版本迁移 +│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护 +│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations) │ └── types.ts ├── config/ # 企业配置管理 │ ├── loader.ts @@ -29,3 +38,5 @@ src/core/ - `domains/*/api.ts` 只通过 `core/http/factory.ts` 或 `core/auth/*` 获取客户端 - `domains/*` 层只抛 `EkbError` 子类 - `server.ts` 负责把 `EkbError` 映射为 MCP error +- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面 +- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移 diff --git a/src/core/auth/token-store.ts b/src/core/auth/token-store.ts index 09cab16..06b044c 100644 --- a/src/core/auth/token-store.ts +++ b/src/core/auth/token-store.ts @@ -1,31 +1,82 @@ -import { readFileSync, writeFileSync, mkdirSync } from "fs"; -import { join, dirname } from "path"; +import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs"; import { homedir } from "os"; +import { dirname, join } from "path"; import { TokenStore, TokenStoreSchema } from "./types"; -const TOKEN_CACHE_PATH = join( +export const PRIMARY_TOKEN_CACHE_PATH = join( + homedir(), + ".config", + "hose-use", + "tokens.json" +); + +export const LEGACY_TOKEN_CACHE_PATH = join( homedir(), ".cache", "ekb-mcp", "tokens.json" ); -function ensureDir(path: string): void { - mkdirSync(dirname(path), { recursive: true }); +function resolveTokenCachePath(): string { + if (existsSync(PRIMARY_TOKEN_CACHE_PATH)) { + return PRIMARY_TOKEN_CACHE_PATH; + } + if (existsSync(LEGACY_TOKEN_CACHE_PATH)) { + return LEGACY_TOKEN_CACHE_PATH; + } + return PRIMARY_TOKEN_CACHE_PATH; } -export function loadTokenStore(): TokenStore { - try { - const content = readFileSync(TOKEN_CACHE_PATH, "utf-8"); - return TokenStoreSchema.parse(JSON.parse(content)); - } catch { - return {}; +function ensureDir(path: string): void { + const dir = dirname(path); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true, mode: 0o700 }); } + try { + chmodSync(dir, 0o700); + } catch {} +} + +let memoryTokenCache: TokenStore | null = null; +let lastMtimeMs = 0; + +export function loadTokenStore(): TokenStore { + const filePath = resolveTokenCachePath(); + + if (existsSync(filePath)) { + try { + const stats = statSync(filePath); + if (memoryTokenCache && stats.mtimeMs === lastMtimeMs) { + return memoryTokenCache; + } + const content = readFileSync(filePath, "utf-8"); + const parsed = TokenStoreSchema.parse(JSON.parse(content)); + memoryTokenCache = parsed; + lastMtimeMs = stats.mtimeMs; + return parsed; + } catch { + // 若已有内存缓存则保留,避免解析失败直接冲刷为 {} + return memoryTokenCache ?? {}; + } + } + + return memoryTokenCache ?? {}; } export function saveTokenStore(store: TokenStore): void { - ensureDir(TOKEN_CACHE_PATH); - writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(store, null, 2)); + memoryTokenCache = store; + const targetPath = PRIMARY_TOKEN_CACHE_PATH; + ensureDir(targetPath); + + // MAJ-03: 强制写入 0o600 保护敏感凭证 + writeFileSync(targetPath, JSON.stringify(store, null, 2), { + encoding: "utf-8", + mode: 0o600, + }); + try { + chmodSync(targetPath, 0o600); + lastMtimeMs = statSync(targetPath).mtimeMs; + } catch {} } export function getCorpTokens(corpId: string): TokenStore[string] | undefined { @@ -44,3 +95,11 @@ export function clearCorpTokens(corpId: string): void { delete store[corpId]; saveTokenStore(store); } + +/** + * 重置内存 Token 缓存(测试隔离用) + */ +export function resetTokenStoreMemory(): void { + memoryTokenCache = null; + lastMtimeMs = 0; +} diff --git a/src/core/cache/cache.test.ts b/src/core/cache/cache.test.ts new file mode 100644 index 0000000..9bb72a1 --- /dev/null +++ b/src/core/cache/cache.test.ts @@ -0,0 +1,162 @@ +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("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("k1")).toBe("v1"); + + // 此时最冷的是 k2。插入 k4 触发容量超限(容量 3) + cache.set("k4", "v4"); + + // 验证 k2 被淘汰,而最近被访问的 k1 依然存活 + expect(cache.get("k2")).toBeUndefined(); + expect(cache.get("k1")).toBe("v1"); + expect(cache.get("k3")).toBe("v3"); + expect(cache.get("k4")).toBe("v4"); + + // 更新已有键不会增加容量,也不会误伤淘汰其他键 + cache.set("k1", "v1_updated"); + expect(cache.size()).toBe(3); + expect(cache.get("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("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); + }); + }); +}); diff --git a/src/core/cache/index.ts b/src/core/cache/index.ts new file mode 100644 index 0000000..c54171a --- /dev/null +++ b/src/core/cache/index.ts @@ -0,0 +1,35 @@ +import { MultiLevelCache, type MultiLevelCacheOptions } from "./multi-level.js"; + +export * from "./types.js"; +export * from "./memory.js"; +export * from "./sqlite.js"; +export * from "./multi-level.js"; + +let defaultCacheInstance: MultiLevelCache | null = null; + +/** + * 获取全局默认多级缓存实例(单例) + */ +export function getGlobalCache(): MultiLevelCache { + if (!defaultCacheInstance) { + defaultCacheInstance = new MultiLevelCache(); + } + return defaultCacheInstance; +} + +/** + * 创建独立的多级缓存实例 + */ +export function createMultiLevelCache(options?: MultiLevelCacheOptions): MultiLevelCache { + return new MultiLevelCache(options); +} + +/** + * 重置全局缓存实例(测试清理用) + */ +export function resetGlobalCache(): void { + if (defaultCacheInstance) { + defaultCacheInstance.clear(); + defaultCacheInstance = null; + } +} diff --git a/src/core/cache/memory.ts b/src/core/cache/memory.ts new file mode 100644 index 0000000..21e981e --- /dev/null +++ b/src/core/cache/memory.ts @@ -0,0 +1,143 @@ +import type { CacheEntry, CacheOptions, ICache } from "./types.js"; + +const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 分钟 +const DEFAULT_MAX_ENTRIES = 2000; + +export class MemoryCache implements ICache { + // Map 保持键的插入顺序,结合重新插入机制实现高效的 O(1) LRU 淘汰 + private map = new Map>(); + private maxEntries: number; + + constructor(maxEntries = DEFAULT_MAX_ENTRIES) { + this.maxEntries = maxEntries; + } + + /** + * CRIT-02: 构建命名空间隔离的复合内存键,彻底规避跨域碰撞 + */ + private toCompositeKey(key: string, namespace?: string): string { + const ns = namespace || "default"; + return `${ns}:${key}`; + } + + public get(key: string, namespace = "default"): T | undefined { + const compositeKey = this.toCompositeKey(key, namespace); + const entry = this.map.get(compositeKey); + if (!entry) return undefined; + + const now = Date.now(); + if (entry.expiresAt <= now) { + this.map.delete(compositeKey); + return undefined; + } + + // MAJ-09: 真正 LRU 访问刷新 —— 命中后移至 Map 末尾 + this.map.delete(compositeKey); + this.map.set(compositeKey, entry); + + return entry.value as T; + } + + public getEntry(key: string, namespace = "default"): CacheEntry | undefined { + const compositeKey = this.toCompositeKey(key, namespace); + const entry = this.map.get(compositeKey); + if (!entry) return undefined; + + const now = Date.now(); + if (entry.expiresAt <= now) { + this.map.delete(compositeKey); + return undefined; + } + + // 命中后移至 Map 末尾保持热度 + this.map.delete(compositeKey); + this.map.set(compositeKey, entry); + + return entry as CacheEntry; + } + + public set(key: string, value: T, options?: CacheOptions): void { + const namespace = options?.namespace ?? "default"; + const compositeKey = this.toCompositeKey(key, namespace); + const now = Date.now(); + const ttl = options?.ttlMs ?? DEFAULT_TTL_MS; + + const entry: CacheEntry = { + value, + expiresAt: now + ttl, + updatedAt: now, + namespace, + }; + + // MAJ-08: 更新已有键时,先删后插调至末尾,不应误触发 LRU 淘汰 + if (this.map.has(compositeKey)) { + this.map.delete(compositeKey); + this.map.set(compositeKey, entry); + return; + } + + // 若达到容量限制,执行 LRU 淘汰 + if (this.map.size >= this.maxEntries) { + this.evict(); + } + + this.map.set(compositeKey, entry); + } + + public setEntry(key: string, entry: CacheEntry): void { + const compositeKey = this.toCompositeKey(key, entry.namespace); + if (this.map.has(compositeKey)) { + this.map.delete(compositeKey); + } else if (this.map.size >= this.maxEntries) { + this.evict(); + } + this.map.set(compositeKey, entry); + } + + public delete(key: string, namespace = "default"): void { + const compositeKey = this.toCompositeKey(key, namespace); + this.map.delete(compositeKey); + } + + public clear(namespace?: string): void { + if (!namespace) { + this.map.clear(); + return; + } + + const prefix = `${namespace}:`; + for (const k of this.map.keys()) { + if (k.startsWith(prefix)) { + this.map.delete(k); + } + } + } + + public has(key: string, namespace = "default"): boolean { + return this.get(key, namespace) !== undefined; + } + + public size(): number { + return this.map.size; + } + + private evict(): void { + const now = Date.now(); + // 1. 优先剔除已过期的死键 + for (const [k, v] of this.map.entries()) { + if (v.expiresAt <= now) { + this.map.delete(k); + } + } + + // 2. 若仍然超限,按真正的 LRU(头部为最久未访问的条目)淘汰最早的条目 + while (this.map.size >= this.maxEntries) { + const oldestKey = this.map.keys().next().value; + if (oldestKey !== undefined) { + this.map.delete(oldestKey); + } else { + break; + } + } + } +} diff --git a/src/core/cache/multi-level.ts b/src/core/cache/multi-level.ts new file mode 100644 index 0000000..ba192d0 --- /dev/null +++ b/src/core/cache/multi-level.ts @@ -0,0 +1,113 @@ +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(); + } + } +} diff --git a/src/core/cache/sqlite.ts b/src/core/cache/sqlite.ts new file mode 100644 index 0000000..5b3c3b3 --- /dev/null +++ b/src/core/cache/sqlite.ts @@ -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(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) { + 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; + } + } +} diff --git a/src/core/cache/types.ts b/src/core/cache/types.ts new file mode 100644 index 0000000..4745e09 --- /dev/null +++ b/src/core/cache/types.ts @@ -0,0 +1,32 @@ +export interface CacheOptions { + /** + * 缓存有效时长(毫秒),默认 10 分钟 (600,000 ms) + */ + ttlMs?: number; + /** + * 命名空间,便于按业务模块隔离与批量失效(例如: 'dimensions', 'roles', 'bills') + */ + namespace?: string; +} + +export interface CacheEntry { + value: T; + expiresAt: number; + updatedAt: number; + namespace: string; +} + +export interface ICache { + get(key: string): Promise | T | undefined; + set(key: string, value: T, options?: CacheOptions): Promise | void; + delete(key: string): Promise | void; + clear(namespace?: string): Promise | void; + has(key: string): Promise | boolean; +} + +export interface WithCacheOptions extends CacheOptions { + /** + * 是否强制穿透缓存刷新 + */ + forceRefresh?: boolean; +} diff --git a/src/core/db/connection.ts b/src/core/db/connection.ts new file mode 100644 index 0000000..291a4e2 --- /dev/null +++ b/src/core/db/connection.ts @@ -0,0 +1,104 @@ +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; + } +} diff --git a/src/core/db/db.test.ts b/src/core/db/db.test.ts new file mode 100644 index 0000000..2828471 --- /dev/null +++ b/src/core/db/db.test.ts @@ -0,0 +1,72 @@ +import { Database } from "bun:sqlite"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { closeDatabase, getDatabase } from "./connection.js"; +import { runMigrations } from "./migrations.js"; + +describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", () => { + let db: Database; + + beforeEach(() => { + db = getDatabase(":memory:"); + }); + + afterEach(() => { + closeDatabase(); + }); + + test("数据库初始化时自动应用所有版本迁移并记录到 _schema_migrations", () => { + const rows = db.query("SELECT version, name FROM _schema_migrations ORDER BY version ASC").all() as Array<{ + version: number; + name: string; + }>; + expect(rows.length).toBeGreaterThanOrEqual(1); + expect(rows[0].version).toBe(1); + expect(rows[0].name).toBe("001_core_schema_and_approval_tables"); + }); + + test("核心数据表与新增的多级缓存表结构完备且索引有效", () => { + // 检查表是否存在 + const tables = db + .query("SELECT name FROM sqlite_master WHERE type = 'table'") + .all() as Array<{ name: string }>; + const tableNames = new Set(tables.map((t) => t.name)); + + expect(tableNames.has("rules")).toBe(true); + expect(tableNames.has("preferences")).toBe(true); + expect(tableNames.has("approval_runs")).toBe(true); + expect(tableNames.has("approval_findings")).toBe(true); + expect(tableNames.has("aipro_logs")).toBe(true); + expect(tableNames.has("cache_entries")).toBe(true); + + // 检查加固索引:UPPER(short_id)、findings(rule_id) + const indices = db + .query("SELECT name FROM sqlite_master WHERE type = 'index'") + .all() as Array<{ name: string }>; + const indexNames = new Set(indices.map((i) => i.name)); + + expect(indexNames.has("idx_runs_corp_id")).toBe(true); + expect(indexNames.has("idx_runs_expires_at")).toBe(true); + expect(indexNames.has("idx_runs_flow_id")).toBe(true); + expect(indexNames.has("idx_runs_short_id_upper")).toBe(true); + expect(indexNames.has("idx_findings_rule_id")).toBe(true); + expect(indexNames.has("idx_cache_namespace")).toBe(true); + expect(indexNames.has("idx_cache_expires_at")).toBe(true); + }); + + test("cache_entries 具备复合主键 (namespace, key) 约束", () => { + db.run( + "INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES ('n1', 'k1', 'v1', 9999, 1000)" + ); + // 相同 key 但不同 namespace 可以成功插入 + db.run( + "INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES ('n2', 'k1', 'v2', 9999, 1000)" + ); + + const countRow = db.query("SELECT COUNT(*) AS c FROM cache_entries WHERE key = 'k1'").get() as { c: number }; + expect(countRow.c).toBe(2); + }); + + test("再次执行 runMigrations 保证幂等且不抛错", () => { + expect(() => runMigrations(db)).not.toThrow(); + }); +}); diff --git a/src/core/db/index.ts b/src/core/db/index.ts new file mode 100644 index 0000000..9964084 --- /dev/null +++ b/src/core/db/index.ts @@ -0,0 +1,3 @@ +export * from "./types.js"; +export * from "./connection.js"; +export * from "./migrations.js"; diff --git a/src/core/db/migrations.ts b/src/core/db/migrations.ts new file mode 100644 index 0000000..c0b4a36 --- /dev/null +++ b/src/core/db/migrations.ts @@ -0,0 +1,211 @@ +import type { Database } from "bun:sqlite"; +import type { DatabaseMigration } from "./types.js"; + +function hasColumn(db: Database, tableName: string, columnName: string): boolean { + try { + const rows = db.query(`PRAGMA table_info(${tableName})`).all() as Array<{ name: string }>; + return rows.some((r) => r.name === columnName); + } catch { + return false; + } +} + +export const migrations: DatabaseMigration[] = [ + { + version: 1, + name: "001_core_schema_and_approval_tables", + up(db: Database): void { + // 1. 规约主表 + db.run(` + CREATE TABLE IF NOT EXISTS rules ( + id TEXT PRIMARY KEY, + code INTEGER NOT NULL UNIQUE, + scope TEXT NOT NULL, + body TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active', + version INTEGER NOT NULL DEFAULT 1, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + `); + db.run("CREATE INDEX IF NOT EXISTS idx_rules_scope ON rules(scope);"); + db.run("CREATE INDEX IF NOT EXISTS idx_rules_status ON rules(status);"); + + // 2. 风格偏好表 + db.run(` + CREATE TABLE IF NOT EXISTS preferences ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + is_default INTEGER NOT NULL DEFAULT 0, + rules_reject TEXT NOT NULL, + rules_review TEXT NOT NULL, + rules_pass_note TEXT NOT NULL, + rules_approve TEXT NOT NULL, + updated_at INTEGER NOT NULL + ); + `); + + // 3. 审批运行执行记录表 + db.run(` + CREATE TABLE IF NOT EXISTS approval_runs ( + id TEXT PRIMARY KEY, + short_id TEXT, + expires_at INTEGER, + flow_id TEXT, + document_sn TEXT NOT NULL, + corp_id TEXT, + scope TEXT, + decision TEXT NOT NULL, + decision_summary TEXT, + matched_rules_count INTEGER NOT NULL DEFAULT 0, + failed_rules_count INTEGER NOT NULL DEFAULT 0, + document_snapshot TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + `); + + // 增量兼容老库缺省列 + if (!hasColumn(db, "approval_runs", "scope")) { + try { db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;"); } catch {} + } + if (!hasColumn(db, "approval_runs", "short_id")) { + try { db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;"); } catch {} + } + if (!hasColumn(db, "approval_runs", "expires_at")) { + try { db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;"); } catch {} + } + + db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);"); + db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);"); + // MAJ-06: 支持 UPPER(short_id) 大小写不敏感快速定位 + db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id_upper ON approval_runs(UPPER(short_id));"); + db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);"); + db.run("CREATE INDEX IF NOT EXISTS idx_runs_corp_id ON approval_runs(corp_id);"); + db.run("CREATE INDEX IF NOT EXISTS idx_runs_flow_id ON approval_runs(flow_id);"); + db.run("CREATE INDEX IF NOT EXISTS idx_runs_expires_at ON approval_runs(expires_at);"); + + // 4. 审批要点事实记录表 + db.run(` + CREATE TABLE IF NOT EXISTS approval_findings ( + id TEXT PRIMARY KEY, + run_id TEXT NOT NULL REFERENCES approval_runs(id) ON DELETE CASCADE, + rule_id TEXT REFERENCES rules(id) ON DELETE SET NULL, + clause_text TEXT NOT NULL, + strictness TEXT NOT NULL, + check_status TEXT NOT NULL, + evidence TEXT, + reasoning TEXT, + created_at INTEGER NOT NULL + ); + `); + db.run("CREATE INDEX IF NOT EXISTS idx_findings_run_id ON approval_findings(run_id);"); + // MAJ-07: 补充外键索引,防止外键删除全表扫描 + db.run("CREATE INDEX IF NOT EXISTS idx_findings_rule_id ON approval_findings(rule_id);"); + + // 5. 全流程操作与审计流水表 + db.run(` + CREATE TABLE IF NOT EXISTS aipro_logs ( + id TEXT PRIMARY KEY, + run_id TEXT, + action TEXT NOT NULL, + document_sn TEXT, + operator TEXT, + args TEXT, + status TEXT NOT NULL, + decision TEXT, + summary TEXT, + created_at INTEGER NOT NULL + ); + `); + if (!hasColumn(db, "aipro_logs", "run_id")) { + try { db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;"); } catch {} + } + db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);"); + db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);"); + db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);"); + + // 6. 多级缓存持久化表 (L2 Persistent Cache) + // CRIT-02: 采用复合主键 (namespace, key),彻底杜绝跨命名空间键碰撞 + db.run(` + CREATE TABLE IF NOT EXISTS cache_entries ( + namespace TEXT NOT NULL, + key TEXT NOT NULL, + value TEXT NOT NULL, + expires_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + PRIMARY KEY (namespace, key) + ); + `); + db.run("CREATE INDEX IF NOT EXISTS idx_cache_namespace ON cache_entries(namespace);"); + db.run("CREATE INDEX IF NOT EXISTS idx_cache_expires_at ON cache_entries(expires_at);"); + + // 种子数据:初始化默认偏好(CRIT-05: 使用 INSERT OR IGNORE 保证多进程启动绝对幂等) + seedDefaultPreference(db); + }, + }, +]; + +function seedDefaultPreference(db: Database): void { + const now = Date.now(); + // CRIT-05: 使用 INSERT OR IGNORE 消除多进程并发启动 UNIQUE 冲突 + db.run( + ` + INSERT OR IGNORE INTO preferences ( + id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `, + [ + "default", + "标准财务审批偏好", + 1, + "确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)", + "触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则", + "未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)", + "所有条款全部满足,秒级免审全自动通过", + now, + ] + ); +} + +/** + * 执行迁移:自动检测并按序原子执行未应用的 migration (CRIT-04) + */ +export function runMigrations(db: Database): void { + // 创建迁移历史版本表 + db.run(` + CREATE TABLE IF NOT EXISTS _schema_migrations ( + version INTEGER PRIMARY KEY, + name TEXT NOT NULL, + applied_at INTEGER NOT NULL + ); + `); + + const appliedRows = db + .query("SELECT version FROM _schema_migrations ORDER BY version ASC") + .all() as Array<{ version: number }>; + const appliedVersions = new Set(appliedRows.map((r) => r.version)); + + // 按版本号升序排列依次执行 + const sortedMigrations = [...migrations].sort((a, b) => a.version - b.version); + + for (const migration of sortedMigrations) { + if (!appliedVersions.has(migration.version)) { + // CRIT-04: 使用 BEGIN IMMEDIATE 事务原子包裹 + db.run("BEGIN IMMEDIATE;"); + try { + migration.up(db); + db.run( + "INSERT INTO _schema_migrations (version, name, applied_at) VALUES (?, ?, ?)", + [migration.version, migration.name, Date.now()] + ); + db.run("COMMIT;"); + } catch (err) { + try { + db.run("ROLLBACK;"); + } catch {} + throw err; + } + } + } +} diff --git a/src/core/db/types.ts b/src/core/db/types.ts new file mode 100644 index 0000000..c0fd01d --- /dev/null +++ b/src/core/db/types.ts @@ -0,0 +1,12 @@ +import type { Database } from "bun:sqlite"; + +export interface DatabaseMigration { + version: number; + name: string; + up: (db: Database) => void; +} + +export interface DatabaseConnectionOptions { + customPath?: string; + readOnly?: boolean; +} diff --git a/src/domains/approval/db.ts b/src/domains/approval/db.ts index 8c4f45b..b18449f 100644 --- a/src/domains/approval/db.ts +++ b/src/domains/approval/db.ts @@ -1,200 +1,35 @@ -import { Database } from "bun:sqlite"; -import { chmodSync, existsSync, mkdirSync } from "node:fs"; -import { homedir } from "node:os"; -import { dirname, join } from "node:path"; +import type { Database } from "bun:sqlite"; +import { + DEFAULT_DB_PATH, + closeDatabase, + getDatabase, + resolveDatabasePath, + runMigrations, +} from "../../core/db/index.js"; -export const DEFAULT_APPROVAL_DB_PATH = join( - homedir(), - ".config", - "hose-use", - "approval.db" -); +export const DEFAULT_APPROVAL_DB_PATH = DEFAULT_DB_PATH; export function resolveApprovalDbPath(): string { - const envPath = process.env.HOSE_APPROVAL_DB?.trim(); - if (envPath) { - return envPath; - } - return DEFAULT_APPROVAL_DB_PATH; + return resolveDatabasePath(); } -let activeDb: Database | null = null; -let currentDbPath: string | null = null; - /** - * 获取或创建 SQLite 数据库连接单例 + * 获取或创建 SQLite 数据库连接单例(兼容原接口,底层使用 core/db) */ export function getApprovalDatabase(customPath?: string): Database { - const targetPath = customPath ?? resolveApprovalDbPath(); - - if (activeDb && currentDbPath === targetPath) { - return activeDb; - } - - // 内存数据库无需创建目录 - if (targetPath !== ":memory:") { - const dir = dirname(targetPath); - if (!existsSync(dir)) { - mkdirSync(dir, { recursive: true, mode: 0o700 }); - } - } - - const db = new Database(targetPath); - if (targetPath !== ":memory:") { - // 规则、单据快照、审核证据和审计日志都可能包含敏感信息。 - // SQLite 默认文件权限受 umask 影响,不能依赖默认值保护凭证与业务数据。 - chmodSync(targetPath, 0o600); - } - currentDbPath = targetPath; - activeDb = db; - - initDatabaseSchema(db); - return db; + return getDatabase(customPath); } /** - * 关闭并清理当前数据库连接(用于测试重置或进程退出) + * 关闭并清理当前数据库连接 */ export function closeApprovalDatabase(): void { - if (activeDb) { - activeDb.close(); - activeDb = null; - currentDbPath = null; - } + closeDatabase(); } /** - * 初始化表结构与默认数据 + * 初始化表结构与默认数据(兼容原接口,委托给 runMigrations) */ export function initDatabaseSchema(db: Database): void { - // 启用 WAL 模式提高并发性能与数据安全性 - db.run("PRAGMA journal_mode = WAL;"); - db.run("PRAGMA foreign_keys = ON;"); - - // 1. 规约主表 - db.run(` - CREATE TABLE IF NOT EXISTS rules ( - id TEXT PRIMARY KEY, - code INTEGER NOT NULL UNIQUE, - scope TEXT NOT NULL, - body TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'active', - version INTEGER NOT NULL DEFAULT 1, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL - ); - `); - db.run("CREATE INDEX IF NOT EXISTS idx_rules_scope ON rules(scope);"); - db.run("CREATE INDEX IF NOT EXISTS idx_rules_status ON rules(status);"); - - // 2. 风格偏好表 - db.run(` - CREATE TABLE IF NOT EXISTS preferences ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - is_default INTEGER NOT NULL DEFAULT 0, - rules_reject TEXT NOT NULL, - rules_review TEXT NOT NULL, - rules_pass_note TEXT NOT NULL, - rules_approve TEXT NOT NULL, - updated_at INTEGER NOT NULL - ); - `); - - // 3. 审批运行执行记录表 - db.run(` - CREATE TABLE IF NOT EXISTS approval_runs ( - id TEXT PRIMARY KEY, - short_id TEXT, - expires_at INTEGER, - flow_id TEXT, - document_sn TEXT NOT NULL, - corp_id TEXT, - scope TEXT, - decision TEXT NOT NULL, - decision_summary TEXT, - matched_rules_count INTEGER NOT NULL DEFAULT 0, - failed_rules_count INTEGER NOT NULL DEFAULT 0, - document_snapshot TEXT, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL - ); - `); - try { - db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;"); - } catch {} - try { - db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;"); - } catch {} - try { - db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;"); - } catch {} - db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);"); - db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);"); - db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);"); - - // 4. 审批要点事实记录表 - db.run(` - CREATE TABLE IF NOT EXISTS approval_findings ( - id TEXT PRIMARY KEY, - run_id TEXT NOT NULL REFERENCES approval_runs(id) ON DELETE CASCADE, - rule_id TEXT REFERENCES rules(id) ON DELETE SET NULL, - clause_text TEXT NOT NULL, - strictness TEXT NOT NULL, - check_status TEXT NOT NULL, - evidence TEXT, - reasoning TEXT, - created_at INTEGER NOT NULL - ); - `); - db.run("CREATE INDEX IF NOT EXISTS idx_findings_run_id ON approval_findings(run_id);"); - - // 5. AI PRO 全流程操作与审计监控流水表 - db.run(` - CREATE TABLE IF NOT EXISTS aipro_logs ( - id TEXT PRIMARY KEY, - run_id TEXT, - action TEXT NOT NULL, - document_sn TEXT, - operator TEXT, - args TEXT, - status TEXT NOT NULL, - decision TEXT, - summary TEXT, - created_at INTEGER NOT NULL - ); - `); - try { - db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;"); - } catch {} - db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);"); - db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);"); - db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);"); - - // 种子数据:初始化默认偏好 - seedDefaultPreference(db); -} - -function seedDefaultPreference(db: Database): void { - const existing = db.query("SELECT id FROM preferences WHERE id = 'default'").get(); - if (!existing) { - const now = Date.now(); - db.run( - ` - INSERT INTO preferences ( - id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) - `, - [ - "default", - "标准财务审批偏好", - 1, - "确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)", - "触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则", - "未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)", - "所有条款全部满足,秒级免审全自动通过", - now - ] - ); - } + runMigrations(db); } diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index a0bc763..0a71a11 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -3,6 +3,7 @@ import { KyInstance } from "ky"; import { existsSync } from "node:fs"; import { mkdir, writeFile } from "node:fs/promises"; import { basename, extname, join, resolve } from "node:path"; +import { getGlobalCache } from "../../core/cache/index.js"; import { searchRawBills, getRawBillsByIds, @@ -98,9 +99,8 @@ const COMMON_FIELD_LABELS: Record = { ownerAndApproverPrintNodeFlag: "节点打印控制标识", }; -// ── 字段元数据内存缓存 ───────────────────────────────────────────────────────── +// ── 字段元数据与关联目录多级缓存 ───────────────────────────────────────────── -const schemaCache = new Map; entities: EntityMeta[] }>(); const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存 type ReferenceCatalog = { @@ -110,22 +110,20 @@ type ReferenceCatalog = { feeTypes: Map>; }; -const referenceCatalogCache = new Map(); - export async function getFieldDictionary( client: KyInstance, corpId: string, forceRefresh = false ): Promise<{ dictionary: Map; entities: EntityMeta[] }> { - const cached = schemaCache.get(corpId); - if (!forceRefresh && cached && Date.now() - cached.timestamp < CACHE_TTL_MS) { - return cached; - } + const cache = getGlobalCache(); + const rawEntities = await cache.withCache( + `bill:entities:${corpId}`, + () => listEntitySchemas(client, corpId, { start: 0, count: 100 }), + { namespace: "bills", ttlMs: CACHE_TTL_MS, forceRefresh } + ); - const entities = await listEntitySchemas(client, corpId, { start: 0, count: 100 }); const dictionary = new Map(); - - for (const entity of entities) { + for (const entity of rawEntities) { for (const field of entity.fields) { if (field.name && field.label) { dictionary.set(field.name, { label: field.label, type: field.type }); @@ -133,9 +131,7 @@ export async function getFieldDictionary( } } - const result = { timestamp: Date.now(), dictionary, entities }; - schemaCache.set(corpId, result); - return result; + return { dictionary, entities: rawEntities }; } function referenceId(value: unknown): string | undefined { @@ -146,10 +142,14 @@ function referenceId(value: unknown): string | undefined { } function referenceObject(value: unknown): Record | undefined { - return value && typeof value === "object" ? value as Record : undefined; + return value && typeof value === "object" ? (value as Record) : undefined; } -function flattenDepartments(items: Record[], parentPath = "", output = new Map; path: string }>()): Map; path: string }> { +function flattenDepartments( + items: Record[], + parentPath = "", + output = new Map; path: string }>() +): Map; path: string }> { for (const item of items) { const name = typeof item.name === "string" ? item.name : ""; const path = name ? (parentPath ? `${parentPath}/${name}` : name) : parentPath; @@ -163,7 +163,10 @@ function flattenDepartments(items: Record[], parentPath = "", o return output; } -function flattenFeeTypes(items: Record[], output = new Map>()): Map> { +function flattenFeeTypes( + items: Record[], + output = new Map>() +): Map> { for (const item of items) { const feeType = referenceObject(item.feeType) ?? item; const id = typeof feeType.id === "string" ? feeType.id : undefined; @@ -177,29 +180,35 @@ function flattenFeeTypes(items: Record[], output = new Map { - const cached = referenceCatalogCache.get(corpId); - if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) return cached; - const [staffs, departments, feeTypes] = await Promise.all([ - listActiveStaffCatalog(client, corpId), - getDepartmentTree(client, corpId), - getFeeTypeTree(client, corpId), - ]); + const cache = getGlobalCache(); + const raw = await cache.withCache( + `bill:ref_raw:${corpId}`, + async () => { + const [staffs, departments, feeTypes] = await Promise.all([ + listActiveStaffCatalog(client, corpId), + getDepartmentTree(client, corpId), + getFeeTypeTree(client, corpId), + ]); + return { staffs, departments, feeTypes }; + }, + { namespace: "bills", ttlMs: CACHE_TTL_MS } + ); + const staff = new Map>(); - for (const item of staffs) { + for (const item of raw.staffs) { if (typeof item.id === "string") { staff.set(item.id, item); const userId = typeof item.userId === "string" ? item.userId : undefined; if (userId) staff.set(userId, item); } } - const result = { + + return { timestamp: Date.now(), staff, - departments: flattenDepartments(departments), - feeTypes: flattenFeeTypes(feeTypes), + departments: flattenDepartments(raw.departments), + feeTypes: flattenFeeTypes(raw.feeTypes), }; - referenceCatalogCache.set(corpId, result); - return result; } function toReference( diff --git a/src/domains/dimension/tools.ts b/src/domains/dimension/tools.ts index 393ec4b..c5b4fa8 100644 --- a/src/domains/dimension/tools.ts +++ b/src/domains/dimension/tools.ts @@ -1,37 +1,53 @@ import { z } from "zod"; import type { KyInstance } from "ky"; +import { getGlobalCache } from "../../core/cache/index.js"; import { listDimensionCatalogs, listDimensionItems } from "./api.js"; import type { DimensionCatalog, DimensionItem, DimensionQuery } from "./types.js"; -const cache = new Map }>(); const CACHE_TTL_MS = 10 * 60 * 1000; -async function getCached(client: KyInstance, corpId: string): Promise<{ catalogs: DimensionCatalog[]; items: Map }> { - const existing = cache.get(corpId); - if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing; - const catalogs = await listDimensionCatalogs(client, corpId); - const result = { timestamp: Date.now(), catalogs, items: new Map() }; - cache.set(corpId, result); - return result; +async function getCachedCatalogs(client: KyInstance, corpId: string): Promise { + const cache = getGlobalCache(); + return cache.withCache( + `dimensions:catalogs:${corpId}`, + () => listDimensionCatalogs(client, corpId), + { namespace: "dimensions", ttlMs: CACHE_TTL_MS } + ); } -export async function searchDimensions(client: KyInstance, corpId: string, query: DimensionQuery = {}): Promise { - const { catalogs } = await getCached(client, corpId); +export async function searchDimensions( + client: KyInstance, + corpId: string, + query: DimensionQuery = {} +): Promise { + const catalogs = await getCachedCatalogs(client, corpId); const keyword = (query.name || query.code || query.id || "").trim().toLowerCase(); if (!keyword) return catalogs; - return catalogs.filter((item) => [item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword))); + return catalogs.filter((item) => + [item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword)) + ); } -export async function getDimensionItems(client: KyInstance, corpId: string, dimension: DimensionCatalog, start = 0, count = 100): Promise { - const catalog = await getCached(client, corpId); - const cached = catalog.items.get(dimension.id); - if (cached && start === 0 && count >= cached.length) return cached; - const items = await listDimensionItems(client, corpId, dimension.id, start, count); - if (start === 0) catalog.items.set(dimension.id, items); - return items; +export async function getDimensionItems( + client: KyInstance, + corpId: string, + dimension: DimensionCatalog, + start = 0, + count = 100 +): Promise { + const cache = getGlobalCache(); + return cache.withCache( + `dimensions:items:${corpId}:${dimension.id}:${start}:${count}`, + () => listDimensionItems(client, corpId, dimension.id, start, count), + { namespace: "dimensions", ttlMs: CACHE_TTL_MS } + ); } -export async function resolveDimension(client: KyInstance, corpId: string, target: string): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> { +export async function resolveDimension( + client: KyInstance, + corpId: string, + target: string +): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> { const matches = await searchDimensions(client, corpId, { id: target, code: target, name: target }); const dimension = matches[0]; if (!dimension) return undefined; @@ -46,7 +62,11 @@ export const dimensionTools = [ handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => { const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文"); - const items = await searchDimensions(await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)), corp.corpId || corp.id, { name: params.keyword }); + const items = await searchDimensions( + await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)), + corp.corpId || corp.id, + { name: params.keyword } + ); return { count: items.length, dimensions: items.slice(0, params.count ?? 100) }; }, }, diff --git a/src/domains/role/tools.ts b/src/domains/role/tools.ts index 60d2998..3626a14 100644 --- a/src/domains/role/tools.ts +++ b/src/domains/role/tools.ts @@ -1,40 +1,81 @@ import { z } from "zod"; import type { KyInstance } from "ky"; +import { getGlobalCache } from "../../core/cache/index.js"; import { listRoleGroups, listRoleMembers, listRoles } from "./api.js"; import type { Role, RoleGroup, RoleMemberReport, RoleQuery } from "./types.js"; -const cache = new Map(); const CACHE_TTL_MS = 10 * 60 * 1000; -async function getCatalog(client: KyInstance, corpId: string): Promise<{ roles: Role[]; groups: RoleGroup[] }> { - const existing = cache.get(corpId); - if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing; - const [roles, groups] = await Promise.all([listRoles(client, corpId), listRoleGroups(client, corpId)]); - const result = { timestamp: Date.now(), roles, groups }; cache.set(corpId, result); return result; + +async function getCatalog( + client: KyInstance, + corpId: string +): Promise<{ roles: Role[]; groups: RoleGroup[] }> { + const cache = getGlobalCache(); + return cache.withCache( + `roles:catalog:${corpId}`, + async () => { + const [roles, groups] = await Promise.all([ + listRoles(client, corpId), + listRoleGroups(client, corpId), + ]); + return { roles, groups }; + }, + { namespace: "roles", ttlMs: CACHE_TTL_MS } + ); } -export async function searchRoles(client: KyInstance, corpId: string, query: RoleQuery = {}): Promise { +export async function searchRoles( + client: KyInstance, + corpId: string, + query: RoleQuery = {} +): Promise { const { roles } = await getCatalog(client, corpId); const keyword = (query.keyword || query.id || query.code || query.name || "").trim().toLowerCase(); if (!keyword) return roles; - return roles.filter((role) => [role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) => value.toLowerCase().includes(keyword))); + return roles.filter((role) => + [role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) => + value.toLowerCase().includes(keyword) + ) + ); } -export async function getRoleGroups(client: KyInstance, corpId: string): Promise { return (await getCatalog(client, corpId)).groups; } -export async function resolveRole(client: KyInstance, corpId: string, target: string): Promise { + +export async function getRoleGroups(client: KyInstance, corpId: string): Promise { + return (await getCatalog(client, corpId)).groups; +} + +export async function resolveRole( + client: KyInstance, + corpId: string, + target: string +): Promise { const matches = await searchRoles(client, corpId, { keyword: target }); - return matches.find((role) => role.id === target || role.code === target || role.name === target) || matches[0]; + return ( + matches.find((role) => role.id === target || role.code === target || role.name === target) || + matches[0] + ); } -export async function getRoleMembers(client: KyInstance, corpId: string, target: string): Promise { - const role = await resolveRole(client, corpId, target); if (!role) return undefined; + +export async function getRoleMembers( + client: KyInstance, + corpId: string, + target: string +): Promise { + const role = await resolveRole(client, corpId, target); + if (!role) return undefined; return { role, members: await listRoleMembers(client, corpId, role.id) }; } -export const roleTools = [{ - name: "role_list", description: "列出当前企业角色定义与角色组", - parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }), - handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => { - const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文"); - const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)); - const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword }); - return { count: roles.length, roles: roles.slice(0, params.count ?? 100) }; +export const roleTools = [ + { + name: "role_list", + description: "列出当前企业角色定义与角色组", + parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }), + handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => { + const corp = corpContext.getCurrent(); + if (!corp) throw new Error("未配置活跃企业上下文"); + const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)); + const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword }); + return { count: roles.length, roles: roles.slice(0, params.count ?? 100) }; + }, }, -}]; +]; diff --git a/src/version.ts b/src/version.ts index ee51168..1491e83 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "0.7.4"; +export const VERSION = "0.7.5";