Files
hose-use/src/domains/role/tools.ts
T
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

82 lines
2.7 KiB
TypeScript

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_TTL_MS = 10 * 60 * 1000;
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[]> {
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)
)
);
}
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]
);
}
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) };
},
},
];