Compare commits

...
4 Commits
Author SHA1 Message Date
yunyingk 9a2d4529f5 Merge pull request #58 from yunyingk/release/v0.8.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.0
2026-09-08 15:53:54 +08:00
gitea 3937d3799b chore(release): bump version to v0.8.0 2026-09-08 15:53:41 +08:00
yunyingk bcf8ac0de6 Merge pull request #57 from yunyingk/refactor_db_cache_cleanup
refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
2026-09-08 15:49:57 +08:00
gitea 3a15b064fe refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
- 数据库表规范化与原子事务版本迁移机制 (_schema_migrations)
- 增加 SQLite 复合主键、PRAGMA busy_timeout 与索引覆盖
- 构建统一两级协同缓存 (L1 Memory LRU + L2 SQLite 持久化)
- withCache 增加 In-flight Promise 去重并发防击穿 (单飞机制)
- 收敛 dimension、role、bill 与 token-store 缓存逻辑
- 100% 保持现有 API 契约与零功能删除
2026-09-08 15:49:27 +08:00
25 changed files with 1270 additions and 278 deletions

No files matched your search

+2
View File
@@ -46,3 +46,5 @@ data/
# Local roadmaps & scratch notes
*.local.md
.agents/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.7.5",
"version": "0.8.0",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+1 -1
View File
@@ -1,4 +1,4 @@
# hose-use (v0.7.5)
# hose-use (v0.8.0)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.7.5",
"version": "0.8.0",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.7.5
version: 0.8.0
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.7.5",
"version": "0.8.0",
"module": "src/server.ts",
"type": "module",
"bin": {
+4 -4
View File
@@ -1,12 +1,12 @@
---
name: hose-use
description: "v0.7.5: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
description: "v0.8.0: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.7.5
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.5)
version: 0.8.0
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.0)
---
# hose-use (v0.7.5)
# hose-use (v0.8.0)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
+13 -2
View File
@@ -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/` 并注册版本迁移
+72 -13
View File
@@ -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;
}
+162
View File
@@ -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<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);
});
});
});
+35
View File
@@ -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;
}
}
+143
View File
@@ -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<string, CacheEntry<any>>();
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<T>(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<T>(key: string, namespace = "default"): CacheEntry<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;
}
// 命中后移至 Map 末尾保持热度
this.map.delete(compositeKey);
this.map.set(compositeKey, entry);
return entry as CacheEntry<T>;
}
public set<T>(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<T> = {
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<T>(key: string, entry: CacheEntry<T>): 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;
}
}
}
}
+113
View File
@@ -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<string, Promise<any>>();
constructor(options?: MultiLevelCacheOptions) {
this.l1 = options?.l1 ?? new MemoryCache();
this.l2 = options?.l2 !== undefined ? options.l2 : new SqliteCache();
}
public get<T>(key: string, namespace = "default"): T | undefined {
// 1. 优先从 L1 (Memory) 获取
const l1Value = this.l1.get<T>(key, namespace);
if (l1Value !== undefined) {
return l1Value;
}
// 2. L1 穿透,查询 L2 (SQLite 持久化)
if (this.l2) {
const l2Entry = this.l2.getEntry<T>(key, namespace);
if (l2Entry !== undefined) {
// 回填至 L1,保持相同的到期时间与命名空间
this.l1.setEntry(key, l2Entry);
return l2Entry.value;
}
}
return undefined;
}
public set<T>(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<T>(
key: string,
fetcher: () => Promise<T>,
options?: WithCacheOptions
): Promise<T> {
const namespace = options?.namespace ?? "default";
const lockKey = `${namespace}:${key}`;
if (!options?.forceRefresh) {
const cached = this.get<T>(key, namespace);
if (cached !== undefined) {
return cached;
}
}
// 防击穿:检查是否已有相同命名空间与键的并发请求在执行中
const ongoing = this.inFlight.get(lockKey);
if (ongoing) {
return ongoing as Promise<T>;
}
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();
}
}
}
+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;
}
}
}
+32
View File
@@ -0,0 +1,32 @@
export interface CacheOptions {
/**
* 缓存有效时长(毫秒),默认 10 分钟 (600,000 ms)
*/
ttlMs?: number;
/**
* 命名空间,便于按业务模块隔离与批量失效(例如: 'dimensions', 'roles', 'bills')
*/
namespace?: string;
}
export interface CacheEntry<T> {
value: T;
expiresAt: number;
updatedAt: number;
namespace: string;
}
export interface ICache {
get<T>(key: string): Promise<T | undefined> | T | undefined;
set<T>(key: string, value: T, options?: CacheOptions): Promise<void> | void;
delete(key: string): Promise<void> | void;
clear(namespace?: string): Promise<void> | void;
has(key: string): Promise<boolean> | boolean;
}
export interface WithCacheOptions extends CacheOptions {
/**
* 是否强制穿透缓存刷新
*/
forceRefresh?: boolean;
}
+104
View File
@@ -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;
}
}
+72
View File
@@ -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();
});
});
+3
View File
@@ -0,0 +1,3 @@
export * from "./types.js";
export * from "./connection.js";
export * from "./migrations.js";
+211
View File
@@ -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;
}
}
}
}
+12
View File
@@ -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;
}
+16 -181
View File
@@ -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);
}
+39 -30
View File
@@ -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<string, string> = {
ownerAndApproverPrintNodeFlag: "节点打印控制标识",
};
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
// ── 字段元数据与关联目录多级缓存 ─────────────────────────────────────────────
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
type ReferenceCatalog = {
@@ -110,22 +110,20 @@ type ReferenceCatalog = {
feeTypes: Map<string, Record<string, unknown>>;
};
const referenceCatalogCache = new Map<string, ReferenceCatalog>();
export async function getFieldDictionary(
client: KyInstance,
corpId: string,
forceRefresh = false
): Promise<{ dictionary: Map<string, { label: string; type: string }>; 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<string, { label: string; type: string }>();
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<string, unknown> | undefined {
return value && typeof value === "object" ? value as Record<string, unknown> : undefined;
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
}
function flattenDepartments(items: Record<string, unknown>[], parentPath = "", output = new Map<string, { item: Record<string, unknown>; path: string }>()): Map<string, { item: Record<string, unknown>; path: string }> {
function flattenDepartments(
items: Record<string, unknown>[],
parentPath = "",
output = new Map<string, { item: Record<string, unknown>; path: string }>()
): Map<string, { item: Record<string, unknown>; 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<string, unknown>[], parentPath = "", o
return output;
}
function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<string, Record<string, unknown>>()): Map<string, Record<string, unknown>> {
function flattenFeeTypes(
items: Record<string, unknown>[],
output = new Map<string, Record<string, unknown>>()
): Map<string, Record<string, unknown>> {
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<string, unknown>[], output = new Map<stri
}
async function getReferenceCatalog(client: KyInstance, corpId: string): Promise<ReferenceCatalog> {
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<string, Record<string, unknown>>();
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(
+40 -20
View File
@@ -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<string, { timestamp: number; catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }>();
const CACHE_TTL_MS = 10 * 60 * 1000;
async function getCached(client: KyInstance, corpId: string): Promise<{ catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }> {
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<string, DimensionItem[]>() };
cache.set(corpId, result);
return result;
async function getCachedCatalogs(client: KyInstance, corpId: string): Promise<DimensionCatalog[]> {
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<DimensionCatalog[]> {
const { catalogs } = await getCached(client, corpId);
export async function searchDimensions(
client: KyInstance,
corpId: string,
query: DimensionQuery = {}
): Promise<DimensionCatalog[]> {
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<DimensionItem[]> {
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<DimensionItem[]> {
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) };
},
},
+63 -22
View File
@@ -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<string, { timestamp: number; roles: Role[]; groups: RoleGroup[] }>();
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<Role[]> {
export async function searchRoles(
client: KyInstance,
corpId: string,
query: RoleQuery = {}
): Promise<Role[]> {
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<RoleGroup[]> { return (await getCatalog(client, corpId)).groups; }
export async function resolveRole(client: KyInstance, corpId: string, target: string): Promise<Role | undefined> {
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> {
return (await getCatalog(client, corpId)).groups;
}
export async function resolveRole(
client: KyInstance,
corpId: string,
target: string
): Promise<Role | undefined> {
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<RoleMemberReport | undefined> {
const role = await resolveRole(client, corpId, target); if (!role) return undefined;
export async function getRoleMembers(
client: KyInstance,
corpId: string,
target: string
): Promise<RoleMemberReport | undefined> {
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) };
},
},
}];
];
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.7.5";
export const VERSION = "0.8.0";