505 lines
17 KiB
TypeScript
505 lines
17 KiB
TypeScript
import {
|
|
extractFailureExecutions,
|
|
findExecutionNode,
|
|
flattenExecutionTree,
|
|
getExecutionLogs,
|
|
getJob,
|
|
getJobExecutionLevel,
|
|
getJobExecutionTree,
|
|
getJobFailedExecutions,
|
|
isTaskExecutionFailed,
|
|
listPlatforms,
|
|
explainConditionBranches,
|
|
} from "../../../domains/platform/services.js";
|
|
import type { WorkflowTaskExecution } from "../../../domains/platform/types.js";
|
|
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
|
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
|
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
|
import { PLATFORM_ID_OPTION_KEYS } from "./shared.js";
|
|
|
|
async function createJobPiperClient(
|
|
parsed: CliParsedArgs,
|
|
runtime: CliRuntime
|
|
): Promise<Awaited<ReturnType<typeof createPiperClientForCorp>>> {
|
|
const corp = runtime.selectedCorp!;
|
|
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
|
if (explicit) {
|
|
return createPiperClientForCorp(corp, explicit);
|
|
}
|
|
const clients = await createClientsForCorp(corp);
|
|
try {
|
|
const corpId = corp.corpId || corp.id;
|
|
const platforms = await listPlatforms(clients.ekbClient, corpId);
|
|
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
|
|
if (firstActive?.id) {
|
|
return await createPiperClientForCorp(corp, firstActive.id);
|
|
}
|
|
} catch {
|
|
// Fall back to default easoClient
|
|
}
|
|
return clients.easoClient;
|
|
}
|
|
|
|
async function enrichFailedExecutions(
|
|
client: Awaited<ReturnType<typeof createPiperClientForCorp>>,
|
|
jobId: string,
|
|
items: WorkflowTaskExecution[]
|
|
): Promise<WorkflowTaskExecution[]> {
|
|
const parentCache = new Map<string, WorkflowTaskExecution[]>();
|
|
const enriched: WorkflowTaskExecution[] = [];
|
|
|
|
for (const item of items) {
|
|
if (item.parentId && (!item.currentLoopPath || !item.name || !item.form)) {
|
|
let siblings = parentCache.get(item.parentId);
|
|
if (!siblings) {
|
|
try {
|
|
const level = await getJobExecutionLevel(client, jobId, {
|
|
parentId: item.parentId,
|
|
page: 1,
|
|
pageSize: 100,
|
|
});
|
|
siblings = level.items;
|
|
} catch {
|
|
siblings = [];
|
|
}
|
|
parentCache.set(item.parentId, siblings);
|
|
}
|
|
const matched = siblings.find((s) => s.id === item.id);
|
|
if (matched) {
|
|
const itemInputs = item.inputs;
|
|
const matchedInputs = matched.inputs;
|
|
const hasItemInputs = Array.isArray(itemInputs)
|
|
? itemInputs.length > 0
|
|
: Boolean(itemInputs && typeof itemInputs === "object" && Object.keys(itemInputs as Record<string, unknown>).length > 0);
|
|
const itemOutputs = item.outputs;
|
|
const matchedOutputs = matched.outputs;
|
|
const hasItemOutputs = Boolean(
|
|
itemOutputs && typeof itemOutputs === "object" && Object.keys(itemOutputs as Record<string, unknown>).length > 0
|
|
);
|
|
enriched.push({
|
|
...matched,
|
|
...item,
|
|
name: item.name || matched.name,
|
|
label: item.label || matched.label,
|
|
displayName: item.displayName || matched.displayName,
|
|
type: item.type || matched.type,
|
|
status: item.status || matched.status,
|
|
currentLoopPath: item.currentLoopPath || matched.currentLoopPath,
|
|
levelIndex: item.levelIndex?.length ? item.levelIndex : matched.levelIndex,
|
|
form: item.form ?? matched.form,
|
|
details: item.details ?? matched.details,
|
|
inputs: hasItemInputs ? itemInputs : matchedInputs,
|
|
outputs: hasItemOutputs ? itemOutputs : matchedOutputs,
|
|
error: item.error ?? matched.error,
|
|
});
|
|
continue;
|
|
}
|
|
}
|
|
enriched.push(item);
|
|
}
|
|
return enriched;
|
|
}
|
|
|
|
export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const jobId = parsed.args[0] || stringOption(parsed.options, ["id", "job-id", "jobId"]);
|
|
if (!jobId) {
|
|
return {
|
|
stdout: "",
|
|
stderr: "用法: hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose] [--parent=<executionId>] [--logs=<executionId>]\n",
|
|
exitCode: 1,
|
|
};
|
|
}
|
|
|
|
const client = await createJobPiperClient(parsed, runtime);
|
|
const page = numberOption(parsed.options, ["page"]) || 1;
|
|
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100;
|
|
const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]);
|
|
const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
|
|
const nodeQuery = stringOption(parsed.options, ["node", "task", "node-id", "nodeId"]);
|
|
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
|
|
const verbose = booleanOption(parsed.options, ["verbose", "v"]);
|
|
|
|
// 1. --logs=<executionId>
|
|
if (logsExecutionId) {
|
|
const logs = await getExecutionLogs(client, logsExecutionId);
|
|
if (runtime.jsonMode) {
|
|
return {
|
|
stdout: printJson({ jobId, executionId: logsExecutionId, logs }, runtime.outputOptions),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
const rows = logs.map((log, i) => [
|
|
i + 1,
|
|
String(log.id ?? "-"),
|
|
String(log.createAt ?? (log as Record<string, unknown>).createTime ?? (log as Record<string, unknown>).timestamp ?? "-"),
|
|
String(log.level || "INFO"),
|
|
String(log.message || JSON.stringify(log)),
|
|
]);
|
|
return {
|
|
stdout: [
|
|
`====== 节点执行日志 (Job: ${jobId} | Execution: ${logsExecutionId}) ======`,
|
|
rows.length ? printTable(["#", "日志 ID", "时间", "级别", "内容"], rows) : "该节点暂无输出日志",
|
|
"",
|
|
].join("\n"),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
// 2. --parent=<executionId>
|
|
if (parentExecutionId) {
|
|
const levelPage = await getJobExecutionLevel(client, jobId, {
|
|
parentId: parentExecutionId,
|
|
page,
|
|
pageSize,
|
|
});
|
|
if (runtime.jsonMode) {
|
|
return {
|
|
stdout: printJson(
|
|
{
|
|
jobId,
|
|
parentId: parentExecutionId,
|
|
...levelPage,
|
|
},
|
|
runtime.outputOptions
|
|
),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
const rows = levelPage.items.map((item, idx) => [
|
|
idx + 1,
|
|
item.id,
|
|
item.name || "-",
|
|
item.label || item.displayName || "-",
|
|
item.type || "-",
|
|
item.status || "-",
|
|
item.currentLoopPath || "-",
|
|
item.error?.message || "-",
|
|
]);
|
|
const extraDetails: string[] = [];
|
|
for (const item of levelPage.items) {
|
|
if (item.form !== undefined || item.error?.message) {
|
|
extraDetails.push(
|
|
`\n── 节点明细 [${item.id}] (${item.name || "-"} | loop=${item.currentLoopPath || "-"} | status=${item.status}) ──`
|
|
);
|
|
if (item.error?.message) {
|
|
extraDetails.push(` 错误原因: ${item.error.message}`);
|
|
}
|
|
if (item.form !== undefined) {
|
|
extraDetails.push(` 传入表单 (form): ${JSON.stringify(item.form)}`);
|
|
}
|
|
if (item.details !== undefined) {
|
|
extraDetails.push(` 明细数据 (details): ${JSON.stringify(item.details)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
stdout: [
|
|
`====== 子节点执行层级明细 (Job: ${jobId} | Parent: ${parentExecutionId} | 共 ${levelPage.totalItems} 项) ======`,
|
|
rows.length
|
|
? printTable(
|
|
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因"],
|
|
rows
|
|
)
|
|
: "暂无子节点执行记录",
|
|
...extraDetails,
|
|
"",
|
|
].join("\n"),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
// 3. --node=<name|id>
|
|
if (nodeQuery) {
|
|
const tree = await getJobExecutionTree(client, jobId);
|
|
const matchedNode = findExecutionNode(tree, nodeQuery);
|
|
if (!matchedNode) {
|
|
return {
|
|
stdout: "",
|
|
stderr: `未在 Job [${jobId}] 的执行树中找到匹配 "${nodeQuery}" 的节点。请核对节点名称或 Execution ID。\n`,
|
|
exitCode: 1,
|
|
};
|
|
}
|
|
|
|
if (runtime.jsonMode) {
|
|
return {
|
|
stdout: printJson({ jobId, node: matchedNode }, runtime.outputOptions),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
const anyNode = matchedNode as any;
|
|
const inputPayload = anyNode.inputs ?? anyNode.form ?? anyNode.params;
|
|
const outputPayload = anyNode.outputs ?? anyNode.output ?? anyNode.details;
|
|
const lines = [
|
|
`====== 工作流节点执行详情 [${matchedNode.id}] (Job: ${jobId}) ======`,
|
|
printKeyValue({
|
|
"Execution ID": matchedNode.id,
|
|
"Parent ID": matchedNode.parentId || "-",
|
|
"节点标识 (name)": matchedNode.name || "-",
|
|
"节点名称": matchedNode.displayName || matchedNode.label || "-",
|
|
"节点类型 (type)": matchedNode.type || "-",
|
|
"执行状态 (status)": matchedNode.status || anyNode.state || "-",
|
|
"耗时(ms)": String(matchedNode.executionTime ?? anyNode.durationTime ?? "-"),
|
|
"开始时间": String(matchedNode.startTime || anyNode.createTime || "-"),
|
|
"结束时间": String(matchedNode.endTime || "-"),
|
|
"循环路径": matchedNode.currentLoopPath || "-",
|
|
...(matchedNode.error?.message ? { "错误信息": matchedNode.error.message } : {}),
|
|
}),
|
|
];
|
|
|
|
if (matchedNode.error?.message) {
|
|
lines.push("");
|
|
lines.push("── ❌ 错误堆栈 / 原因 ──");
|
|
lines.push(matchedNode.error.message);
|
|
if (anyNode.error?.stack) {
|
|
lines.push(anyNode.error.stack);
|
|
}
|
|
}
|
|
|
|
if (inputPayload !== undefined) {
|
|
lines.push("");
|
|
lines.push("── 📥 节点入参报文 (inputs / form) ──");
|
|
lines.push(typeof inputPayload === "string" ? inputPayload : JSON.stringify(inputPayload, null, 2));
|
|
}
|
|
|
|
if (outputPayload !== undefined) {
|
|
lines.push("");
|
|
lines.push("── 📤 节点出参 / 响应结果 (outputs) ──");
|
|
lines.push(typeof outputPayload === "string" ? outputPayload : JSON.stringify(outputPayload, null, 2));
|
|
}
|
|
|
|
lines.push("");
|
|
return {
|
|
stdout: `${lines.join("\n")}\n`,
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
// 4. --failed
|
|
if (onlyFailed) {
|
|
const [job, tree, failedPage] = await Promise.all([
|
|
getJob(client, jobId).catch(() => undefined),
|
|
getJobExecutionTree(client, jobId).catch(() => []),
|
|
getJobFailedExecutions(client, jobId).catch(() => ({
|
|
number: 1,
|
|
size: 100,
|
|
totalPages: 0,
|
|
totalItems: 0,
|
|
items: [] as WorkflowTaskExecution[],
|
|
})),
|
|
]);
|
|
|
|
const rawFailed = extractFailureExecutions(tree, failedPage.items);
|
|
const enrichedItems = await enrichFailedExecutions(client, jobId, rawFailed);
|
|
|
|
if (runtime.jsonMode) {
|
|
return {
|
|
stdout: printJson(
|
|
{
|
|
jobId,
|
|
job: job ?? null,
|
|
totalFailed: enrichedItems.length,
|
|
failedNodes: enrichedItems,
|
|
},
|
|
runtime.outputOptions
|
|
),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
const rows = enrichedItems.map((item: any, idx) => [
|
|
idx + 1,
|
|
item.id,
|
|
item.parentId || "-",
|
|
item.name || "-",
|
|
item.displayName || item.label || item.type || "-",
|
|
item.status || item.state || "-",
|
|
String(item.executionTime ?? item.durationTime ?? "-"),
|
|
item.error?.message || item.errorMessage || item.outputs?.error || "-",
|
|
]);
|
|
|
|
const nodeDetailBlocks: string[] = [];
|
|
const shouldExpand = verbose || enrichedItems.length <= 5;
|
|
|
|
for (const item of enrichedItems) {
|
|
const anyItem = item as any;
|
|
const errMsg = item.error?.message || anyItem.errorMessage || anyItem.outputs?.error;
|
|
const inputPayload = anyItem.inputs ?? anyItem.form ?? anyItem.params;
|
|
const outputPayload = anyItem.outputs ?? anyItem.output ?? anyItem.details;
|
|
|
|
if (errMsg || inputPayload !== undefined || outputPayload !== undefined) {
|
|
nodeDetailBlocks.push(
|
|
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | ${item.displayName || item.label || item.type || "-"} | status=${item.status || anyItem.state}) ──`
|
|
);
|
|
if (errMsg) {
|
|
nodeDetailBlocks.push(` ❌ 错误原因: ${errMsg}`);
|
|
}
|
|
if (shouldExpand) {
|
|
if (inputPayload !== undefined) {
|
|
const inStr = typeof inputPayload === "string" ? inputPayload : JSON.stringify(inputPayload, null, 2);
|
|
nodeDetailBlocks.push(` 📥 节点入参 (inputs/form):\n${inStr.split("\n").map((l: string) => " " + l).join("\n")}`);
|
|
}
|
|
if (outputPayload !== undefined) {
|
|
const outStr = typeof outputPayload === "string" ? outputPayload : JSON.stringify(outputPayload, null, 2);
|
|
nodeDetailBlocks.push(` 📤 节点出参 (outputs/details):\n${outStr.split("\n").map((l: string) => " " + l).join("\n")}`);
|
|
}
|
|
} else {
|
|
if (inputPayload !== undefined) {
|
|
nodeDetailBlocks.push(` 📥 节点入参: [已省略,使用 --verbose 查看完整 JSON]`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
stdout: [
|
|
`====== Job 异常/失败执行节点透视 (Job: ${jobId}) ======`,
|
|
job
|
|
? printKeyValue({
|
|
"Job ID": job.id,
|
|
"工作流 ID": job.pipelineId,
|
|
"Job 状态": job.state ?? job.status,
|
|
"开始时间": job.startTime || "-",
|
|
"耗时(ms)": String(job.durationTime ?? "-"),
|
|
"失败节点数": enrichedItems.length,
|
|
})
|
|
: "",
|
|
"",
|
|
rows.length
|
|
? printTable(
|
|
["#", "Execution ID", "Parent ID", "节点标识 (name)", "节点名称/类型", "状态", "耗时(ms)", "错误原因"],
|
|
rows
|
|
)
|
|
: "✅ 未发现任何异常或报错失败的执行节点",
|
|
...nodeDetailBlocks,
|
|
"",
|
|
].filter(Boolean).join("\n"),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
// 4. Default mode: Job overview + top-level tree + failed executions
|
|
const [job, tree, failedPage] = await Promise.all([
|
|
getJob(client, jobId),
|
|
getJobExecutionTree(client, jobId),
|
|
getJobFailedExecutions(client, jobId).catch(() => ({
|
|
number: 1,
|
|
size: 100,
|
|
totalPages: 0,
|
|
totalItems: 0,
|
|
items: [] as WorkflowTaskExecution[],
|
|
})),
|
|
]);
|
|
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
|
|
|
const conditionDiagnoses = explainConditionBranches(tree);
|
|
|
|
if (runtime.jsonMode) {
|
|
return {
|
|
stdout: printJson(
|
|
{
|
|
jobId,
|
|
job,
|
|
executionTree: tree,
|
|
failedExecutions,
|
|
conditionDiagnoses,
|
|
},
|
|
runtime.outputOptions
|
|
),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
const treeRows = tree.map((node, idx) => [
|
|
idx + 1,
|
|
node.id,
|
|
node.name || "-",
|
|
node.label || node.displayName || "-",
|
|
node.type || "-",
|
|
node.status || "-",
|
|
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
|
|
node.error?.message || "-",
|
|
]);
|
|
|
|
const failedRows = failedExecutions.map((item, idx) => [
|
|
idx + 1,
|
|
item.id,
|
|
item.parentId || "-",
|
|
item.name || "-",
|
|
item.type || "-",
|
|
item.status || "-",
|
|
item.currentLoopPath || "-",
|
|
item.error?.message || "-",
|
|
]);
|
|
|
|
const outLines = [
|
|
`====== 工作流 Job 执行详情 [${job.id}] ======`,
|
|
printKeyValue({
|
|
"Job ID": job.id,
|
|
"工作流 ID (pipelineId)": job.pipelineId,
|
|
"Job 状态 (state)": job.state ?? job.status,
|
|
"开始时间": job.startTime || "-",
|
|
"结束时间": job.endTime || "-",
|
|
"耗时(ms)": String(job.durationTime ?? "-"),
|
|
"顶层节点数": tree.length,
|
|
"异常/跳过节点数": failedExecutions.length,
|
|
}),
|
|
"",
|
|
"── 顶层节点执行树 ──",
|
|
treeRows.length
|
|
? printTable(
|
|
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
|
|
treeRows
|
|
)
|
|
: "暂无顶层节点执行记录",
|
|
];
|
|
|
|
if (failedRows.length > 0) {
|
|
outLines.push("");
|
|
outLines.push("── ⚠️ 失败/报错跳过节点明细 (含循环子项) ──");
|
|
outLines.push(
|
|
printTable(
|
|
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
|
failedRows
|
|
)
|
|
);
|
|
}
|
|
|
|
if (conditionDiagnoses.length > 0) {
|
|
outLines.push("");
|
|
outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──");
|
|
for (const diag of conditionDiagnoses) {
|
|
outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`);
|
|
outLines.push(` • 判定结论: ${diag.summary}`);
|
|
outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`);
|
|
if (diag.rules.length > 0) {
|
|
outLines.push(" • 规则比对明细:");
|
|
for (const r of diag.rules) {
|
|
const statusIcon = r.matched ? "✅" : "❌";
|
|
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
|
|
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
|
|
outLines.push(` ↳ ${r.detail}`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
stdout: `${outLines.join("\n")}\n`,
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|