diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index f8e0f24..2a0feba 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -340,7 +340,7 @@ export const COMMAND_METADATA: Record = { "outbound-message": "outbound" }, - flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } + flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } }, "bill": { diff --git a/src/cli/commands/platform.test.ts b/src/cli/commands/platform.test.ts index 966347b..902246a 100644 --- a/src/cli/commands/platform.test.ts +++ b/src/cli/commands/platform.test.ts @@ -572,5 +572,85 @@ describe("CLI - platform 命令与 record 动作", () => { expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";'); expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"'); }); + + it("platform records 支持仅传单参数业务对象名称,全局反查其所属应用", async () => { + spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); + // 按应用名称查未找到 + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined)); + // 列出所有平台 + spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([ + { id: "platform-lease", name: "租赁摊销业务" } as any, + { id: "platform-other", name: "其他应用" } as any, + ])); + // 模拟应用详情与对象列表 + spies.push(spyOn(servicesApplications, "getPlatform").mockResolvedValue({ + id: "platform-lease", + name: "租赁摊销业务", + } as any)); + spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => { + if (platformId === "platform-lease") { + return [ + { id: "ent-track", name: "付款发票跟踪", code: "TRACK", fields: [{ name: "name", label: "名称", type: "text" }] } as any, + ]; + } + return []; + })); + spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({ + total: 1, + data: [ + { + id: "rec-1", + dataLink: { id: "rec-1", name: "记录1", code: "R1", active: true, updateTime: "2026-10-22" }, + }, + ], + actions: [], + components: [], + path: null, + template: null, + })); + + const res = await handlePlatformCommand( + { area: "platform", action: "records", args: ["付款发票跟踪"], options: { count: 1 }, raw: [] }, + dummyRuntime + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("记录1"); + }); + + it("platform records 单参数业务对象在多个应用重名时抛出明确指导错误", async () => { + spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined)); + spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([ + { id: "app-1", name: "应用一" } as any, + { id: "app-2", name: "应用二" } as any, + ])); + spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => { + return [{ id: `ent-${platformId}`, name: "重名对象", code: "DUP" } as any]; + })); + + await expect( + handlePlatformCommand( + { area: "platform", action: "records", args: ["重名对象"], options: {}, raw: [] }, + dummyRuntime + ) + ).rejects.toThrow("在多个自建应用中找到同名业务对象 [重名对象],请显式指定应用名称"); + }); + + it("platform records 单参数既不是应用也不是业务对象时返回明确 NOT FOUND 错误", async () => { + spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined)); + spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([ + { id: "app-1", name: "应用一" } as any, + ])); + spies.push(spyOn(services, "listPlatformEntities").mockResolvedValue([])); + + await expect( + handlePlatformCommand( + { area: "platform", action: "records", args: ["未知目标"], options: {}, raw: [] }, + dummyRuntime + ) + ).rejects.toThrow("[NOT FOUND] 当前企业下未找到名为 [未知目标] 的自建应用或业务对象"); + }); }); diff --git a/src/cli/commands/platform/records.ts b/src/cli/commands/platform/records.ts index f4c0b65..2c54251 100644 --- a/src/cli/commands/platform/records.ts +++ b/src/cli/commands/platform/records.ts @@ -243,8 +243,8 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): }; if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; - const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name")); - const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code")); + const nameField = resolved.entity.fields?.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name")); + const codeField = resolved.entity.fields?.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code")); const rows = data.map((item, i): Array => { const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record) : item; const id = source.id ?? item.id; diff --git a/src/cli/commands/platform/shared.ts b/src/cli/commands/platform/shared.ts index 3261c8d..2785953 100644 --- a/src/cli/commands/platform/shared.ts +++ b/src/cli/commands/platform/shared.ts @@ -1,5 +1,8 @@ -import { resolveEntity } from "../../../domains/platform/datalink/services.js"; -import { resolvePlatform } from "../../../domains/platform/applications/services.js"; +import type { KyInstance } from "ky"; +import { listPlatformEntities, resolveEntity } from "../../../domains/platform/datalink/services.js"; +import { getPlatform, listPlatforms, resolvePlatform } from "../../../domains/platform/applications/services.js"; +import type { DatalinkEntity } from "../../../domains/platform/datalink/types.js"; +import type { DatalinkPlatformDetail } from "../../../domains/platform/applications/types.js"; import { createClientsForCorp } from "../../helpers.js"; import type { CliParsedArgs, CliRuntime } from "../../types.js"; @@ -19,16 +22,81 @@ export function cell(value: unknown): string { return String(value); } +/** + * 在企业全量自建应用中智能反查指定业务对象,避免强制用户/Agent 手动查询并记忆 platformId + */ +async function resolveEntityGlobally( + client: KyInstance, + corpId: string, + target: string +): Promise<{ platform: DatalinkPlatformDetail; entity: DatalinkEntity } | undefined> { + const platforms = await listPlatforms(client, corpId); + const matches: Array<{ platform: any; entity: DatalinkEntity }> = []; + + const results = await Promise.allSettled( + platforms.map(async (p) => { + const entities = await listPlatformEntities(client, corpId, p.id); + const found = entities.find((e) => + [e.id, e.name, e.code].some((val) => typeof val === "string" && val.toLowerCase() === target.toLowerCase()) + ); + if (found) { + return { platform: p, entity: found }; + } + return null; + }) + ); + + for (const r of results) { + if (r.status === "fulfilled" && r.value) { + matches.push(r.value); + } + } + + if (matches.length === 1) { + const fullPlatform = await getPlatform(client, corpId, matches[0].platform.id); + return { platform: fullPlatform || matches[0].platform, entity: matches[0].entity }; + } + + if (matches.length > 1) { + const names = matches.map((m) => `[${m.platform.name}] (${m.platform.id})`).join(", "); + throw new Error(`在多个自建应用中找到同名业务对象 [${target}],请显式指定应用名称: ${names}`); + } + + return undefined; +} + export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) { - const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>"); + const targetA = parsed.args[appIndex]?.trim(); + const targetB = parsed.args[entityIndex]?.trim(); + + if (!targetA) { + throw new Error("请提供自建应用或业务对象参数: hose-use platform <子命令> [应用] <业务对象>"); + } + const clients = await createClientsForCorp(runtime.selectedCorp!); const corpId = runtime.selectedCorp!.credentials.corpId; - const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget); - if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`); - const entityTarget = parsed.args[entityIndex]?.trim(); - if (!entityTarget) return { clients, corpId, platform, entity: undefined }; - const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget); - if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`); - return { clients, corpId, platform, entity }; + // 1. 若提供了两个位置参数,严格按「应用 ➔ 对象」标准两级解析 + if (targetB) { + const platform = await resolvePlatform(clients.ekbClient, corpId, targetA); + if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${targetA}`); + const entity = await resolveEntity(clients.ekbClient, corpId, platform, targetB); + if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${targetB}`); + return { clients, corpId, platform, entity }; + } + + // 2. 若仅提供了一个位置参数:优先尝试按「应用」解析(兼容查看应用级信息,如 entities/audit 等) + const platform = await resolvePlatform(clients.ekbClient, corpId, targetA); + if (platform) { + return { clients, corpId, platform, entity: undefined }; + } + + // 3. 若按应用未找到,自动降维为「业务对象」在企业全量自建应用中智能反查 (Zero-Config Search) + const globalMatch = await resolveEntityGlobally(clients.ekbClient, corpId, targetA); + if (globalMatch) { + return { clients, corpId, platform: globalMatch.platform, entity: globalMatch.entity }; + } + + throw new Error(`[NOT FOUND] 当前企业下未找到名为 [${targetA}] 的自建应用或业务对象`); } + diff --git a/src/cli/commands/workflow/history.ts b/src/cli/commands/workflow/history.ts index daea04f..fe6c7e7 100644 --- a/src/cli/commands/workflow/history.ts +++ b/src/cli/commands/workflow/history.ts @@ -1,4 +1,4 @@ -import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/workflow/services.js"; +import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots, searchWorkflowJobByFlowCode } from "../../../domains/platform/workflow/services.js"; import { stringOption, numberOption, booleanOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; @@ -28,8 +28,52 @@ export async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); - if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 }; + if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs [--flow=<单号>] [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 }; const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + + // 优先支持按单号精准定位 Job(本地 SQLite 缓存秒级直达 + 流式熔断探查) + const flowFilter = stringOption(parsed.options, ["flow", "flowCode", "code"]); + if (flowFilter) { + const corpId = runtime.selectedCorp?.credentials.corpId || ""; + const searchResult = await searchWorkflowJobByFlowCode(client, corpId, pipelineId, flowFilter, { + maxScanPages: numberOption(parsed.options, ["max-pages", "maxPages", "page-limit"]) ?? 10, + }); + + if (runtime.jsonMode) { + return { + stdout: printJson(searchResult, runtime.outputOptions), + stderr: "", + exitCode: searchResult.found ? 0 : 1, + }; + } + + if (!searchResult.found) { + return { + stdout: `未找到单号 [${flowFilter}] 对应的工作流执行记录 (已探查 ${searchResult.totalScanned || 0} 笔 Job)\n`, + stderr: "", + exitCode: 1, + }; + } + + const job = searchResult.job!; + const hitInfo = searchResult.source === "cache" ? "⚡ 本地 SQLite 缓存秒级命中" : "🔍 远端流式探查并自动建立本地缓存"; + const out = [ + `====== 工作流单据定位成功 [${pipelineId}] ======`, + printKeyValue({ + "定位来源": hitInfo, + "触发单号": searchResult.flowCode || "-", + "实例 ID (jobId)": job.id, + "运行状态 (status)": job.status || "-", + "提交人": job.inputs?.userInfo?.name || "-", + "创建时间": job.createTime ? new Date(job.createTime).toLocaleString() : "-", + }), + "", + `提示: 可执行 hose-use workflow job ${job.id} 查看该单据的完整节点执行树与代码运算日志。`, + ].join("\n"); + + return { stdout: `${out}\n`, stderr: "", exitCode: 0 }; + } + const rawResult = await listWorkflowLogs(client, pipelineId, { state: stringOption(parsed.options, ["state"]), page: numberOption(parsed.options, ["page"]), diff --git a/src/core/README.core.md b/src/core/README.core.md index 6dd2646..a692650 100644 --- a/src/core/README.core.md +++ b/src/core/README.core.md @@ -28,8 +28,9 @@ src/core/ │ ├── multi-level.ts # 多级联动门面与 in-flight 并发防击穿包装器 │ └── types.ts ├── db/ # 统一 SQLite 数据库与结构化版本迁移 -│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护 -│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations) +│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护 +│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations) +│ ├── workflow-job-cache.ts # 工作流 Job 索引缓存与单据触发单号秒级检索 │ └── types.ts ├── config/ # 企业配置管理 │ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化) diff --git a/src/core/db/db.test.ts b/src/core/db/db.test.ts index dd4d377..57f2891 100644 --- a/src/core/db/db.test.ts +++ b/src/core/db/db.test.ts @@ -39,6 +39,7 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", () expect(tableNames.has("cache_entries")).toBe(true); expect(tableNames.has("observed_events")).toBe(true); expect(tableNames.has("workflow_error_alerts")).toBe(true); + expect(tableNames.has("workflow_job_index")).toBe(true); // 检查加固索引:UPPER(short_id)、findings(rule_id) const indices = db @@ -55,6 +56,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", () expect(indexNames.has("idx_cache_expires_at")).toBe(true); expect(indexNames.has("idx_observed_events_scope")).toBe(true); expect(indexNames.has("idx_workflow_alerts_scope")).toBe(true); + expect(indexNames.has("idx_wf_jobs_corp_pipeline_code")).toBe(true); + expect(indexNames.has("idx_wf_jobs_code_upper")).toBe(true); }); test("cache_entries 具备复合主键 (namespace, key) 约束", () => { diff --git a/src/core/db/index.ts b/src/core/db/index.ts index 9964084..406b1f2 100644 --- a/src/core/db/index.ts +++ b/src/core/db/index.ts @@ -1,3 +1,4 @@ export * from "./types.js"; export * from "./connection.js"; export * from "./migrations.js"; +export * from "./workflow-job-cache.js"; diff --git a/src/core/db/migrations.ts b/src/core/db/migrations.ts index 4a9a0e6..6de751e 100644 --- a/src/core/db/migrations.ts +++ b/src/core/db/migrations.ts @@ -242,6 +242,30 @@ export const migrations: DatabaseMigration[] = [ ); }, }, + { + version: 5, + name: "005_workflow_job_cache", + up(db: Database): void { + db.run(` + CREATE TABLE IF NOT EXISTS workflow_job_index ( + corp_id TEXT NOT NULL, + pipeline_id TEXT NOT NULL, + job_id TEXT NOT NULL, + flow_code TEXT, + flow_id TEXT, + execute_time INTEGER, + status TEXT, + user_name TEXT, + updated_at INTEGER NOT NULL, + PRIMARY KEY (corp_id, pipeline_id, job_id) + ); + `); + db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_code ON workflow_job_index(corp_id, flow_code);"); + db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_pipeline ON workflow_job_index(corp_id, pipeline_id);"); + db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_corp_pipeline_code ON workflow_job_index(corp_id, pipeline_id, flow_code);"); + db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_code_upper ON workflow_job_index(corp_id, pipeline_id, UPPER(flow_code));"); + }, + }, ]; function seedDefaultPreference(db: Database): void { diff --git a/src/core/db/workflow-job-cache.test.ts b/src/core/db/workflow-job-cache.test.ts new file mode 100644 index 0000000..043126e --- /dev/null +++ b/src/core/db/workflow-job-cache.test.ts @@ -0,0 +1,130 @@ +import { Database } from "bun:sqlite"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { closeDatabase, getDatabase } from "./connection.js"; +import { + getCachedWorkflowJobByCode, + upsertWorkflowJobIndex, + type WorkflowJobCacheRecord, +} from "./workflow-job-cache.js"; + +describe("Core DB - Workflow Job 本地缓存与索引检索 (workflow_job_index)", () => { + let db: Database; + + beforeEach(() => { + db = getDatabase(":memory:"); + }); + + afterEach(() => { + closeDatabase(); + }); + + test("批量插入 Job 缓存并支持单号精准与大小写不敏感检索", () => { + const records: WorkflowJobCacheRecord[] = [ + { + corpId: "corp_winner", + pipelineId: "pipe_101", + jobId: "job_001", + flowCode: "XZ2610474", + flowId: "flow_abc", + executeTime: 1700000000000, + status: "COMPLETED", + userName: "欧阳亚玲", + }, + { + corpId: "corp_winner", + pipelineId: "pipe_101", + jobId: "job_002", + flowCode: "XZ2610475", + status: "RUNNING", + }, + ]; + + upsertWorkflowJobIndex(records, ":memory:"); + + // 精确匹配 + const hitExact = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:"); + expect(hitExact).not.toBeNull(); + expect(hitExact?.jobId).toBe("job_001"); + expect(hitExact?.userName).toBe("欧阳亚玲"); + expect(hitExact?.status).toBe("COMPLETED"); + + // 小写模糊匹配 + const hitLower = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "xz2610474", ":memory:"); + expect(hitLower).not.toBeNull(); + expect(hitLower?.jobId).toBe("job_001"); + + // 不存在的单号或不同企业/工作流应返回 null + expect(getCachedWorkflowJobByCode("corp_winner", "pipe_101", "NON_EXISTENT", ":memory:")).toBeNull(); + expect(getCachedWorkflowJobByCode("other_corp", "pipe_101", "XZ2610474", ":memory:")).toBeNull(); + expect(getCachedWorkflowJobByCode("corp_winner", "other_pipe", "XZ2610474", ":memory:")).toBeNull(); + }); + + test("同单号存在多笔记录时,按 execute_time DESC 优先返回最新执行的一笔", () => { + const records: WorkflowJobCacheRecord[] = [ + { + corpId: "corp_winner", + pipelineId: "pipe_101", + jobId: "job_old", + flowCode: "XZ2610474", + executeTime: 1000, + status: "FAILED", + }, + { + corpId: "corp_winner", + pipelineId: "pipe_101", + jobId: "job_new", + flowCode: "XZ2610474", + executeTime: 2000, + status: "COMPLETED", + }, + ]; + + upsertWorkflowJobIndex(records, ":memory:"); + + const hit = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:"); + expect(hit).not.toBeNull(); + expect(hit?.jobId).toBe("job_new"); + expect(hit?.status).toBe("COMPLETED"); + }); + + test("相同主键冲突时,执行增量更新并保持已有非空字段 (COALESCE)", () => { + upsertWorkflowJobIndex( + [ + { + corpId: "corp_winner", + pipelineId: "pipe_101", + jobId: "job_001", + flowCode: "XZ2610474", + userName: "欧阳亚玲", + status: "RUNNING", + executeTime: 1000, + }, + ], + ":memory:" + ); + + // 再次写入,只更新 status,未传 userName + upsertWorkflowJobIndex( + [ + { + corpId: "corp_winner", + pipelineId: "pipe_101", + jobId: "job_001", + status: "COMPLETED", + }, + ], + ":memory:" + ); + + const hit = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:"); + expect(hit).not.toBeNull(); + expect(hit?.jobId).toBe("job_001"); + expect(hit?.status).toBe("COMPLETED"); + // userName 依然保留 + expect(hit?.userName).toBe("欧阳亚玲"); + }); + + test("空数组调用 upsert 不抛异常", () => { + expect(() => upsertWorkflowJobIndex([], ":memory:")).not.toThrow(); + }); +}); diff --git a/src/core/db/workflow-job-cache.ts b/src/core/db/workflow-job-cache.ts new file mode 100644 index 0000000..6c897de --- /dev/null +++ b/src/core/db/workflow-job-cache.ts @@ -0,0 +1,80 @@ +import { getDatabase } from "./connection.js"; + +export interface WorkflowJobCacheRecord { + corpId: string; + pipelineId: string; + jobId: string; + flowCode?: string; + flowId?: string; + executeTime?: number; + status?: string; + userName?: string; + updatedAt?: number; +} + +/** + * 按企业 + 工作流 + 单号快速从本地 SQLite 缓存中检索匹配的 Job 记录 + */ +export function getCachedWorkflowJobByCode( + corpId: string, + pipelineId: string, + flowCode: string, + dbPath?: string +): WorkflowJobCacheRecord | null { + const db = getDatabase(dbPath); + const normalizedCode = flowCode.trim(); + const row = db + .query( + `SELECT corp_id AS corpId, pipeline_id AS pipelineId, job_id AS jobId, + flow_code AS flowCode, flow_id AS flowId, execute_time AS executeTime, + status, user_name AS userName, updated_at AS updatedAt + FROM workflow_job_index + WHERE corp_id = ? AND pipeline_id = ? AND (flow_code = ? OR UPPER(flow_code) = UPPER(?)) + ORDER BY execute_time DESC, updated_at DESC + LIMIT 1` + ) + .get(corpId, pipelineId, normalizedCode, normalizedCode) as WorkflowJobCacheRecord | null; + + return row ?? null; +} + +/** + * 批量插入或更新 Job 缓存索引 + */ +export function upsertWorkflowJobIndex( + records: WorkflowJobCacheRecord[], + dbPath?: string +): void { + if (!records.length) return; + const db = getDatabase(dbPath); + const now = Date.now(); + + const insertStmt = db.prepare(` + INSERT INTO workflow_job_index ( + corp_id, pipeline_id, job_id, flow_code, flow_id, execute_time, status, user_name, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(corp_id, pipeline_id, job_id) DO UPDATE SET + flow_code = COALESCE(excluded.flow_code, workflow_job_index.flow_code), + flow_id = COALESCE(excluded.flow_id, workflow_job_index.flow_id), + execute_time = COALESCE(excluded.execute_time, workflow_job_index.execute_time), + status = COALESCE(excluded.status, workflow_job_index.status), + user_name = COALESCE(excluded.user_name, workflow_job_index.user_name), + updated_at = excluded.updated_at + `); + + db.transaction(() => { + for (const r of records) { + insertStmt.run( + r.corpId, + r.pipelineId, + r.jobId, + r.flowCode || null, + r.flowId || null, + r.executeTime || null, + r.status || null, + r.userName || null, + now + ); + } + })(); +} diff --git a/src/domains/platform/datalink/README.datalink.md b/src/domains/platform/datalink/README.datalink.md index 11269c1..6851c94 100644 --- a/src/domains/platform/datalink/README.datalink.md +++ b/src/domains/platform/datalink/README.datalink.md @@ -33,7 +33,7 @@ hose-use platform list hose-use platform get <应用 ID|名称> hose-use platform entities <应用 ID|名称> hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>] -hose-use platform records <应用 ID|名称> <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats] +hose-use platform records [应用 ID|名称] <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats] hose-use platform record get [<应用> <业务对象>] <记录ID> hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes] hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes] @@ -47,6 +47,8 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称> 也可以使用 `datalink` / `data-link` 作为同义命令域。 +- `records <业务对象>`(单参数免应用查询):当企业自建应用较多时,无需事先查询 platformId。直接输入业务对象名称或编码,CLI 自动遍历企业全量自建应用进行智能反查与寻址;若跨应用重名则抛出精准候选项提示,避免人工心智负担。 + - `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。 - 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o ` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。 - MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。 diff --git a/src/domains/platform/workflow/README.workflow.md b/src/domains/platform/workflow/README.workflow.md index dc73667..12ff329 100644 --- a/src/domains/platform/workflow/README.workflow.md +++ b/src/domains/platform/workflow/README.workflow.md @@ -19,7 +19,7 @@ hose-use workflow list [--platform-id=|--app-id=] [-q|--keyword=<关键 hose-use workflow get hose-use workflow enum [thirdId] [--third-id=] [--json] hose-use workflow analyze [--json] -hose-use workflow logs [--has-error] [--state=FAILED] +hose-use workflow logs [--flow=<单号>] [--has-error] [--state=FAILED] hose-use workflow job [--failed] [--node=] [--verbose] hose-use workflow diff [--pipelineId=] hose-use workflow diff-job [--json] @@ -44,6 +44,7 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}' ``` - `workflow list [-q|--keyword=<关键词>] [--full]`:工作流列表。默认采用**轻量化紧凑模式**,自动剥离每个流程内部包含的庞大 `tasks` 节点树与 MVEL/JS 脚本代码(仅保留 `nodeCount` 统计与核心元数据),将输出报文体积削减 97%(从数兆降至几十 KB),彻底解决上下文截断。传入 `--full` 或 `--with-tasks` 时恢复输出完整节点树。支持 `-q / --keyword` 模糊匹配工作流名称、ID 与应用名称。 +- `workflow logs --flow=<单号>`:按业务单号(如报销单/销账单号)秒级定位对应的 Job 实例。由于外部 Piper API 原生无单号索引,CLI 引入「本地 SQLite 缓存 + 流式探查早停熔断」机制:首次探查边扫描边建立本地单号索引,后续命中直接 0ms 返回,避免全表盲目拉取。 ## 触发器分类与调测路径分支 (Path Branching) diff --git a/src/domains/platform/workflow/execution/search-by-flow.test.ts b/src/domains/platform/workflow/execution/search-by-flow.test.ts new file mode 100644 index 0000000..4b23be8 --- /dev/null +++ b/src/domains/platform/workflow/execution/search-by-flow.test.ts @@ -0,0 +1,171 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { closeDatabase, getDatabase } from "../../../../core/db/connection.js"; +import { + extractJobFlowCode, + searchWorkflowJobByFlowCode, +} from "./search-by-flow.js"; + +describe("Workflow - 按单号查找运行实例 (searchWorkflowJobByFlowCode)", () => { + const originalDbEnv = process.env.HOSE_APPROVAL_DB; + + beforeEach(() => { + process.env.HOSE_APPROVAL_DB = ":memory:"; + getDatabase(":memory:"); + }); + + afterEach(() => { + closeDatabase(); + if (originalDbEnv !== undefined) { + process.env.HOSE_APPROVAL_DB = originalDbEnv; + } else { + delete process.env.HOSE_APPROVAL_DB; + } + }); + + test("extractJobFlowCode 能准确从各类 inputs 结构或顶层字段解析出单号", () => { + expect(extractJobFlowCode(null)).toBeUndefined(); + expect(extractJobFlowCode({})).toBeUndefined(); + expect(extractJobFlowCode({ inputs: { code: " XZ2610474 " } })).toBe("XZ2610474"); + expect(extractJobFlowCode({ inputs: { flowCode: "BX20261101" } })).toBe("BX20261101"); + expect(extractJobFlowCode({ code: "JK20260901" })).toBe("JK20260901"); + }); + + test("空单号直接返回未找到", async () => { + const dummyClient = {} as any; + const res = await searchWorkflowJobByFlowCode(dummyClient, "corp1", "pipe1", " "); + expect(res.found).toBe(false); + }); + + test("流式翻页探查:命中目标单号并自动写入本地 SQLite 缓存,后续查询秒级命中缓存", async () => { + const mockJobsDetail: Record = { + job_001: { + id: "job_001", + status: "COMPLETED", + inputs: { + code: "XZ2610474", + flowId: "flow_xz_01", + userInfo: { name: "欧阳亚玲" }, + }, + }, + job_002: { + id: "job_002", + status: "RUNNING", + inputs: { + code: "OTHER_999", + }, + }, + }; + + let logCalls = 0; + let jobCalls = 0; + + const mockClient = { + get: async (path: string, options?: any) => { + if (path.includes("/log")) { + logCalls++; + return new Response( + JSON.stringify({ + code: 200, + data: { + totalCount: 2, + totalPages: 1, + jobList: [ + { jobId: "job_002", status: "RUNNING", executeTime: 1700000000000 }, + { jobId: "job_001", status: "COMPLETED", executeTime: 1700000050000 }, + ], + }, + }) + ); + } + if (path.includes("/jobs/")) { + jobCalls++; + const jobId = path.split("/jobs/")[1]?.split("?")[0]; + return new Response( + JSON.stringify({ + code: 200, + data: mockJobsDetail[jobId] || { id: jobId }, + }) + ); + } + return new Response(JSON.stringify({ code: 404 })); + }, + } as any; + + // 第一次调用:缓存未命中,执行流式远端嗅探 + const res1 = await searchWorkflowJobByFlowCode( + mockClient, + "corp_winner", + "pipe_win", + "XZ2610474", + { maxScanPages: 5 } + ); + + expect(res1.found).toBe(true); + expect(res1.source).toBe("scan"); + expect(res1.jobId).toBe("job_001"); + expect(res1.job?.id).toBe("job_001"); + expect(logCalls).toBe(1); + expect(jobCalls).toBe(2); + + // 第二次调用:应当直接命中本地 SQLite 缓存,不调 /log 接口 + const prevLogCalls = logCalls; + const prevJobCalls = jobCalls; + + const res2 = await searchWorkflowJobByFlowCode( + mockClient, + "corp_winner", + "pipe_win", + "xz2610474" // 测试大小写模糊命中 + ); + + expect(res2.found).toBe(true); + expect(res2.source).toBe("cache"); + expect(res2.jobId).toBe("job_001"); + // 不应再请求 /log + expect(logCalls).toBe(prevLogCalls); + // 仅通过 getJob 校验最新状态 + expect(jobCalls).toBe(prevJobCalls + 1); + }); + + test("扫描达最大页数仍未找到时安全熔断并返回未找到", async () => { + const mockClient = { + get: async (path: string) => { + if (path.includes("/log")) { + return new Response( + JSON.stringify({ + code: 200, + data: { + totalCount: 10, + totalPages: 10, + jobList: [ + { jobId: "job_x", status: "COMPLETED" }, + ], + }, + }) + ); + } + if (path.includes("/jobs/")) { + return new Response( + JSON.stringify({ + code: 200, + data: { id: "job_x", inputs: { code: "NO_MATCH" } }, + }) + ); + } + return new Response(JSON.stringify({ code: 404 })); + }, + } as any; + + const res = await searchWorkflowJobByFlowCode( + mockClient, + "corp1", + "pipe1", + "WANT_THIS", + { maxScanPages: 2 } + ); + + expect(res.found).toBe(false); + expect(res.scannedPages).toBe(2); + expect(res.totalScanned).toBe(2); + }); +}); diff --git a/src/domains/platform/workflow/execution/search-by-flow.ts b/src/domains/platform/workflow/execution/search-by-flow.ts new file mode 100644 index 0000000..e5f5a97 --- /dev/null +++ b/src/domains/platform/workflow/execution/search-by-flow.ts @@ -0,0 +1,168 @@ +import type { KyInstance } from "ky"; +import { getCachedWorkflowJobByCode, upsertWorkflowJobIndex, type WorkflowJobCacheRecord } from "../../../../core/db/index.js"; +import { getJob } from "./queries.js"; +import { listWorkflowLogs } from "../transport/pipeline/api.js"; +import type { WorkflowJobDetail } from "../types.js"; + +export interface SearchJobByFlowOptions { + maxScanPages?: number; + pageSize?: number; +} + +export interface SearchJobByFlowResult { + found: boolean; + source?: "cache" | "scan"; + job?: WorkflowJobDetail; + jobId?: string; + flowCode?: string; + scannedPages?: number; + totalScanned?: number; +} + +/** + * 提取工作流 Job 内部携带的触发单号 + */ +export function extractJobFlowCode(job: any): string | undefined { + if (!job) return undefined; + const inputs = job.inputs || {}; + if (inputs.code && typeof inputs.code === "string") return inputs.code.trim(); + if (inputs.flowCode && typeof inputs.flowCode === "string") return inputs.flowCode.trim(); + if (job.code && typeof job.code === "string") return job.code.trim(); + return undefined; +} + +/** + * 根据单据编号 (flowCode) 高效查找对应的工作流运行实例 (Job) + * 采用【本地 SQLite 缓存命中 ➔ 未命中流式翻页探查并写入缓存】的双层机制 + */ +export async function searchWorkflowJobByFlowCode( + client: KyInstance, + corpId: string, + pipelineId: string, + flowCode: string, + options: SearchJobByFlowOptions = {} +): Promise { + const targetCode = flowCode.trim(); + if (!targetCode) { + return { found: false, flowCode: targetCode }; + } + + // 1. 本地 SQLite 缓存优先探查 (0ms 命中) + try { + const cached = getCachedWorkflowJobByCode(corpId, pipelineId, targetCode); + if (cached?.jobId) { + try { + const fullJob = await getJob(client, cached.jobId); + if (fullJob) { + return { + found: true, + source: "cache", + job: fullJob, + jobId: cached.jobId, + flowCode: targetCode, + }; + } + } catch { + // 若远程已清理或失效,平滑回退至实时扫描 + } + } + } catch {} + + // 2. 本地未命中,启动流式嗅探拉取(带本地边拉边存与早停熔断) + const maxPages = options.maxScanPages ?? 10; + const pageSize = options.pageSize ?? 20; + let totalScanned = 0; + + for (let page = 1; page <= maxPages; page++) { + const logPage = await listWorkflowLogs(client, pipelineId, { + page, + pageSize, + }); + + const jobs = logPage.jobList || []; + if (!jobs.length) { + break; + } + + // 并发提取当前页所有 Job 详情以解析其单号 + const batchDetails = await Promise.allSettled( + jobs.map(async (j) => { + try { + const detail = await getJob(client, j.jobId); + return { summary: j, detail }; + } catch { + return { summary: j, detail: null }; + } + }) + ); + + const cacheBatch: WorkflowJobCacheRecord[] = []; + let matchedJob: WorkflowJobDetail | null = null; + + for (const item of batchDetails) { + if (item.status !== "fulfilled") continue; + const { summary, detail } = item.value; + totalScanned++; + + const parsedCode = detail ? extractJobFlowCode(detail) : undefined; + const parsedFlowId = detail?.inputs?.flowId || undefined; + const userName = detail?.inputs?.userInfo?.name || undefined; + + let recordTime: number | undefined; + if (summary.executeTime) { + const t = typeof summary.executeTime === "number" ? summary.executeTime : new Date(summary.executeTime).getTime(); + recordTime = Number.isNaN(t) ? undefined : t; + } else if (detail?.startTime) { + const t = typeof detail.startTime === "number" ? detail.startTime : new Date(detail.startTime).getTime(); + recordTime = Number.isNaN(t) ? undefined : t; + } + + cacheBatch.push({ + corpId, + pipelineId, + jobId: summary.jobId, + flowCode: parsedCode, + flowId: parsedFlowId, + executeTime: recordTime, + status: summary.status || detail?.status, + userName, + }); + + if ( + parsedCode && + (parsedCode === targetCode || parsedCode.toUpperCase() === targetCode.toUpperCase()) + ) { + matchedJob = detail; + } + } + + // 将拉取到的索引批量落盘至本地 SQLite 缓存 + try { + upsertWorkflowJobIndex(cacheBatch); + } catch {} + + // 一旦命中立即短路熔断,返回目标单据的完整 Job 记录 + if (matchedJob) { + return { + found: true, + source: "scan", + job: matchedJob, + jobId: matchedJob.id, + flowCode: targetCode, + scannedPages: page, + totalScanned, + }; + } + + if (page >= (logPage.totalPages || 0)) { + break; + } + } + + return { + found: false, + flowCode: targetCode, + scannedPages: maxPages, + totalScanned, + }; +} diff --git a/src/domains/platform/workflow/services.ts b/src/domains/platform/workflow/services.ts index b8f5195..a0f3ca5 100644 --- a/src/domains/platform/workflow/services.ts +++ b/src/domains/platform/workflow/services.ts @@ -18,6 +18,12 @@ export { getJobExecutionLevel, getExecutionLogs, } from "./execution/queries.js"; +export { + searchWorkflowJobByFlowCode, + extractJobFlowCode, + type SearchJobByFlowOptions, + type SearchJobByFlowResult, +} from "./execution/search-by-flow.js"; export type { WorkflowClients, ListAllWorkflowsOptions,