- 数据库迁移与本地缓存:在 `core/db/migrations.ts` 新增 version 5 迁移 (`005_workflow_job_cache`),创建 `workflow_job_index` 缓存表及高效复合索引;实现 `core/db/workflow-job-cache.ts`,支持按企业+工作流+单号快速检索与幂等增量缓存; - 流式早停探查与业务编排:在 `domains/platform/workflow/execution/search-by-flow.ts` 实现 `searchWorkflowJobByFlowCode`,采用「本地 SQLite 缓存 0ms 直达 ➔ 远端流式探查早停熔断并自动建立本地索引」机制,彻底解决云端 Piper API 无单号索引导致的排查低效问题; - CLI 命令层升级: - `workflow logs <pipelineId> --flow=<单号>`:直接秒级定位单据关联 Job 实例; - `platform records <业务对象>`:支持单参数业务对象名称,自动在企业全量自建应用中全局反查与智能寻址,若跨应用重名则抛出精准候选; - 命令行元数据对齐:在 `command-metadata.ts` 为 `workflow` 补齐 `--max-pages`、`--maxPages` 与 `--page-limit` 选项注册,满足严格参数词汇表静态检查; - 测试与文档:新增并更新 `workflow-job-cache.test.ts`、`search-by-flow.test.ts`、`platform.test.ts` 与 `db.test.ts`,更新核心与域层文档,全量 1126 个测试与类型检查全部通过。
209 lines
9.0 KiB
TypeScript
209 lines
9.0 KiB
TypeScript
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";
|
|
import { createWorkflowDetailClient } from "./shared.js";
|
|
|
|
export async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
|
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow history <pipelineId> [--page=1] [--page-size=10]\n", exitCode: 1 };
|
|
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
|
const page = numberOption(parsed.options, ["page"]) || 1;
|
|
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 10;
|
|
const result = await listWorkflowSnapshots(client, pipelineId, page, pageSize);
|
|
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
|
const rows = result.items.map((snapshot, index) => [
|
|
(page - 1) * pageSize + index + 1,
|
|
snapshot.version,
|
|
snapshot.id,
|
|
snapshot.updateTime,
|
|
snapshot.staffName || snapshot.staffId || "-",
|
|
]);
|
|
return {
|
|
stdout: `====== 工作流版本历史 [${pipelineId}](共 ${result.totalItems} 个) ======\n${printTable(["#", "版本", "快照 ID", "更新时间", "操作者"], rows)}\n`,
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
|
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--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"]),
|
|
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size", "limit", "count", "n"]),
|
|
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
|
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
|
});
|
|
const stateOption = stringOption(parsed.options, ["state"]);
|
|
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
|
const hasJobError = (job: any): boolean => {
|
|
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
|
|
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
|
|
if (job.state === "FAILED" || job.status === "FAILED") return true;
|
|
return false;
|
|
};
|
|
// Preserve the existing terminal-state filters while --has-error also sees in-flight errors.
|
|
const isJobError = (job: any): boolean => {
|
|
const s = (job.status || "").toUpperCase();
|
|
return s !== "STARTED" && s !== "RUNNING" && hasJobError(job);
|
|
};
|
|
|
|
let filteredJobList = rawResult.jobList;
|
|
if (hasErrorFilter) {
|
|
filteredJobList = filteredJobList.filter(hasJobError);
|
|
} else if (stateOption) {
|
|
const norm = stateOption.trim().toUpperCase();
|
|
if (norm === "FAILED" || norm === "FAIL" || norm === "ERROR") {
|
|
filteredJobList = filteredJobList.filter(isJobError);
|
|
} else if (norm === "COMPLETED" || norm === "SUCCESS") {
|
|
filteredJobList = filteredJobList.filter((j: any) => (j.status || "").toUpperCase() === "COMPLETED" && !isJobError(j));
|
|
} else if (norm === "RUNNING" || norm === "STARTED" || norm === "IN_PROGRESS") {
|
|
filteredJobList = filteredJobList.filter((j: any) => {
|
|
const s = (j.status || "").toUpperCase();
|
|
return s === "STARTED" || s === "RUNNING";
|
|
});
|
|
}
|
|
}
|
|
|
|
const inProgressCount = Math.max(
|
|
0,
|
|
(rawResult.executeCount ?? 0) - (rawResult.successCount ?? 0) - (rawResult.errorCount ?? 0)
|
|
);
|
|
|
|
const result = {
|
|
...rawResult,
|
|
jobList: filteredJobList,
|
|
inProgressCount,
|
|
};
|
|
|
|
let workflowName = rawResult.jobList[0]?.jobName;
|
|
let workflowState: string | undefined;
|
|
try {
|
|
const detail = await getWorkflowDetail(client, pipelineId);
|
|
if (detail) {
|
|
workflowName = detail.pipelineName || detail.label || workflowName;
|
|
workflowState = detail.state === 1 ? "🟢 启用中" : "⚪ 已停用";
|
|
}
|
|
} catch {}
|
|
|
|
if (runtime.jsonMode) {
|
|
return {
|
|
stdout: printJson({ ...result, workflowName, workflowState }, runtime.outputOptions),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
const formatRunType = (runType?: string): string => {
|
|
if (!runType) return "-";
|
|
const upper = runType.toUpperCase();
|
|
if (upper === "DEBUG") return "🧪 调试";
|
|
if (upper === "RUN") return "🏃 运行";
|
|
return runType;
|
|
};
|
|
|
|
const formatJobStatus = (status?: string, state?: unknown): string => {
|
|
const s = (status || "").toUpperCase();
|
|
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中";
|
|
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成";
|
|
if (s === "FAILED" || s === "ERROR") return "❌ 失败";
|
|
if (s === "STOP" || s === "STOPPED") return "🛑 终止";
|
|
if (s === "CANCELLED" || s === "CANCELED") return "🚫 取消";
|
|
if (!s && (state === 0 || state === "0")) return "COMPLETED";
|
|
return s || String(state ?? "-");
|
|
};
|
|
|
|
const formatErrorColumn = (job: any): string => {
|
|
const s = (job.status || "").toUpperCase();
|
|
if (hasJobError(job)) return "⚠️ 包含错误";
|
|
if (s === "STARTED" || s === "RUNNING") return "⏳ 执行中";
|
|
return "正常";
|
|
};
|
|
|
|
const rows = result.jobList.map((job: any, idx) => [
|
|
idx + 1,
|
|
job.jobId || job.id || "-",
|
|
formatRunType(job.runType),
|
|
formatJobStatus(job.status, job.state),
|
|
job.successTaskCount ?? 0,
|
|
job.errorTaskCount ?? 0,
|
|
formatErrorColumn(job),
|
|
job.durationTime ?? "-",
|
|
job.executeTime || job.startTime || "-",
|
|
]);
|
|
const tableStr = rows.length
|
|
? printTable(
|
|
["#", "Job ID", "类型 (runType)", "状态 (state)", "成功节点", "失败节点", "有错误", "耗时(ms)", "开始时间"],
|
|
rows
|
|
)
|
|
: "暂无匹配的运行记录";
|
|
|
|
return {
|
|
stdout: [
|
|
`====== 工作流运行日志 [${pipelineId}]${workflowName ? ` · ${workflowName}` : ""}${workflowState ? ` (${workflowState})` : ""} ======`,
|
|
printKeyValue({
|
|
...(workflowName ? { "工作流名称": workflowName } : {}),
|
|
...(workflowState ? { "当前状态": workflowState } : {}),
|
|
"执行次数": result.executeCount,
|
|
"成功次数": result.successCount,
|
|
"错误次数": result.errorCount,
|
|
...(result.inProgressCount > 0 ? { "运行中/延时": `${result.inProgressCount} (正在执行或延时等待中)` } : {}),
|
|
"日志条数": result.totalItems,
|
|
"当前返回记录": result.jobList.length,
|
|
}),
|
|
"",
|
|
tableStr,
|
|
"\n提示: 运行 hose-use workflow job <jobId> [--failed] 下钻查看单次 Job 节点级报错与入参明细\n",
|
|
].join("\n"),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|