Merge pull request #114 from yunyingk/feat/workflow-tail-and-watch
feat(workflow): implement real-time workflow tail and watch commands
This commit is contained in:
11 files changed
+1310
-7
No files matched your search
@@ -210,6 +210,10 @@ hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指
|
||||
hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code="return items;" --yes # 声明式追加节点 (--after/--parent 插入)
|
||||
hose-use workflow node edit wf_01k83y... <节点name或#序号> --label="新标题" --yes # 定向修改节点配置
|
||||
hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
|
||||
hose-use workflow tail wf_01k83y... # 类似 tail -f 实时监听新任务派发与节点执行日志流 (别名 watch, follow)
|
||||
hose-use workflow tail wf_01k83y... --job=<jobId> # 针对单个执行中的 Job 实时跟踪直至终态
|
||||
hose-use workflow tail wf_01k83y... --failed-only # 仅在有报错或异常跳过 (SKIPPED) 时即时打印详情
|
||||
hose-use workflow tail wf_01k83y... --once --json # 检视最新或当前运行中的 Job 进度快照并返回结构化数据
|
||||
|
||||
# 6. OpenAPI 密钥与应用中心
|
||||
hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏
|
||||
|
||||
@@ -302,7 +302,33 @@ hose-use workflow node rm <pipelineId> 3 --yes
|
||||
|
||||
---
|
||||
|
||||
## 16. 工作流排障与创单排错三大黄金法则(必读)
|
||||
## 16. 实时任务监听与执行日志流 (`workflow tail` / `watch` / `follow`)
|
||||
|
||||
类似 Unix `tail -f` 实时监听工作流在合思云端的任务派发与节点执行树跃迁。当有外部 Webhook 推送、定时 CRON 调度或业务单据流转触发工作流时,无需反复手动敲 `workflow logs` 或 `workflow job` 轮询,即时流式打出节点状态跃迁与详细报错:
|
||||
|
||||
```bash
|
||||
# 1. 类似 tail -f 实时监听流水线任务派发与各节点执行状态跃迁 (别名: watch, follow)
|
||||
hose-use workflow tail <pipelineId>
|
||||
hose-use workflow watch <pipelineId> --interval=1
|
||||
|
||||
# 2. 针对指定单次运行中的 Job 进行实时跟踪直至执行完成
|
||||
hose-use workflow tail <pipelineId> --job=<jobId>
|
||||
hose-use workflow tail 898268773466365973 --job=898577624451395602
|
||||
|
||||
# 3. 仅在有报错或异常跳过 (SKIPPED) 节点时即时告警并打出底层错误
|
||||
hose-use workflow tail <pipelineId> --failed-only
|
||||
|
||||
# 4. 检视最新或当前运行中的 Job 进度快照 (不进入持续循环,适合脚本快速检查)
|
||||
hose-use workflow tail <pipelineId> --once
|
||||
hose-use workflow tail <pipelineId> --once --json
|
||||
|
||||
# 5. 设置最长监听超时 (秒)
|
||||
hose-use workflow tail <pipelineId> --timeout=60
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 17. 工作流排障与创单排错三大黄金法则(必读)
|
||||
|
||||
在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则:
|
||||
|
||||
|
||||
@@ -1683,4 +1683,141 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
)
|
||||
).rejects.toThrow("触发源节点");
|
||||
});
|
||||
|
||||
it("handles workflow tail and watch commands for real-time streaming and snapshots", async () => {
|
||||
// 1. Missing target -> usage
|
||||
const noArgRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "tail",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["workflow", "tail"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(noArgRes.exitCode).toBe(1);
|
||||
expect(noArgRes.stderr).toContain("用法: hose-use workflow tail");
|
||||
|
||||
const mockJobDetail = {
|
||||
id: "job_tail_101",
|
||||
pipelineId: "pipe_tail_test",
|
||||
label: "实时监控流程",
|
||||
status: "COMPLETED",
|
||||
runType: "DEBUG",
|
||||
durationTime: 850,
|
||||
successTaskCount: 2,
|
||||
errorTaskCount: 0,
|
||||
hasError: false,
|
||||
};
|
||||
|
||||
const mockExecutions = [
|
||||
{
|
||||
id: "ex_node_1",
|
||||
name: "trigger_webhook",
|
||||
label: "发票接入",
|
||||
type: "webhook",
|
||||
status: "COMPLETED",
|
||||
executionTime: 15,
|
||||
},
|
||||
{
|
||||
id: "ex_node_2",
|
||||
name: "action_clean",
|
||||
label: "数据清洗",
|
||||
type: "code-js2",
|
||||
status: "COMPLETED",
|
||||
executionTime: 120,
|
||||
},
|
||||
];
|
||||
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("api/easo/pipelines/pipe_tail_test/log")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
jobList: [{ jobId: "job_tail_101", status: "COMPLETED" }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/jobs/running")) {
|
||||
return { json: async () => ({ code: 200, data: [] }) };
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_tail_101/execution/level/failed")) {
|
||||
return { json: async () => ({ code: 200, data: { items: [] } }) };
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_tail_101/execution")) {
|
||||
return { json: async () => ({ code: 200, data: mockExecutions }) };
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_tail_101")) {
|
||||
return { json: async () => ({ code: 200, data: mockJobDetail }) };
|
||||
}
|
||||
if (url.includes("api/easo/pipelines/pipe_tail_test")) {
|
||||
return { json: async () => ({ code: 200, data: { id: "pipe_tail_test", label: "实时监控流程" } }) };
|
||||
}
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
ekbClient: mockClient as any,
|
||||
easoClient: mockClient as any,
|
||||
corp: mockCorp,
|
||||
} as any)
|
||||
);
|
||||
spies.push(
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any)
|
||||
);
|
||||
|
||||
// 2. tail --once snapshot
|
||||
const onceRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "tail",
|
||||
args: ["pipe_tail_test"],
|
||||
options: { once: true },
|
||||
raw: ["workflow", "tail", "pipe_tail_test", "--once"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(onceRes.exitCode).toBe(0);
|
||||
expect(onceRes.stdout).toContain("trigger_webhook");
|
||||
expect(onceRes.stdout).toContain("action_clean");
|
||||
expect(onceRes.stdout).toContain("Job [job_tail_101] 执行结束");
|
||||
|
||||
// 3. tail --once --json
|
||||
const onceJsonRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "tail",
|
||||
args: ["pipe_tail_test"],
|
||||
options: { once: true },
|
||||
raw: ["workflow", "tail", "pipe_tail_test", "--once"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
expect(onceJsonRes.exitCode).toBe(0);
|
||||
const parsedReport = JSON.parse(onceJsonRes.stdout);
|
||||
expect(parsedReport.totalJobsWatched).toBe(1);
|
||||
expect(parsedReport.jobs[0].jobId).toBe("job_tail_101");
|
||||
expect(parsedReport.jobs[0].successCount).toBe(2);
|
||||
|
||||
// 4. watch alias targeting specific job
|
||||
const watchJobRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "watch",
|
||||
args: ["pipe_tail_test"],
|
||||
options: { job: "job_tail_101", interval: 1, once: true },
|
||||
raw: ["workflow", "watch", "pipe_tail_test", "--job=job_tail_101", "--once"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(watchJobRes.exitCode).toBe(0);
|
||||
expect(watchJobRes.stdout).toContain("Job [job_tail_101]");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import { handleCopy } from "./copy.js";
|
||||
import { handleDelete } from "./delete.js";
|
||||
import { handleCreate } from "./create.js";
|
||||
import { handleNodeCommand } from "./node.js";
|
||||
import { handleWorkflowTailCommand } from "./tail.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -93,10 +94,14 @@ export async function handleWorkflowCommand(
|
||||
case "node":
|
||||
case "nodes":
|
||||
return handleNodeCommand(parsed, runtime);
|
||||
case "tail":
|
||||
case "watch":
|
||||
case "follow":
|
||||
return handleWorkflowTailCommand(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
watchWorkflowPipeline,
|
||||
formatWatchEvent,
|
||||
type WorkflowWatchEvent,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleWorkflowTailCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const targetArg = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "workflowId", "job", "jobId"]);
|
||||
|
||||
if (!targetArg) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow tail <pipelineId> [选项]",
|
||||
"别名: hose-use workflow watch, hose-use workflow follow",
|
||||
"",
|
||||
"说明:",
|
||||
" 类似 tail -f 实时监听工作流在云端的任务派发与节点执行树跃迁,即时捕获错误与异常跳过 (SKIPPED)。",
|
||||
"",
|
||||
"选项:",
|
||||
" --job=<jobId> 定向实时监听指定 Job 直至其运行结束",
|
||||
" --interval=<秒> 轮询检查间隔秒数 (默认 2 秒,最小 1 秒)",
|
||||
" --timeout=<秒> 最长监听秒数 (超时后退出)",
|
||||
" --max-jobs=<数量> 最多持续跟踪的 Job 个数后退出",
|
||||
" --once 仅检视最新或当前运行中的 Job 进度快照,不进入持续监听循环",
|
||||
" --failed-only 仅打印报错或异常跳过的节点与失败摘要",
|
||||
" --follow, -f 持续监听 (即使单个 Job 完成后也继续等待后续新任务)",
|
||||
" --json 以 JSON 结构或 JSONL 事件流输出",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow tail 898268773466365973",
|
||||
" hose-use workflow tail 898268773466365973 --job=898577624451395602",
|
||||
" hose-use workflow watch 898268773466365973 --failed-only",
|
||||
" hose-use workflow tail 898268773466365973 --once --json",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// 允许将特定 jobId 直接作为参数,或通过 --job 指定
|
||||
const explicitJob = stringOption(parsed.options, ["job", "jobId"]);
|
||||
let pipelineId = targetArg;
|
||||
let jobId = explicitJob;
|
||||
|
||||
const intervalSec = numberOption(parsed.options, ["interval", "i"]) ?? 2;
|
||||
const timeoutSec = numberOption(parsed.options, ["timeout", "t"]);
|
||||
const maxJobs = numberOption(parsed.options, ["max-jobs", "maxJobs", "count"]);
|
||||
const once = booleanOption(parsed.options, ["once", "snapshot"], false);
|
||||
const follow = booleanOption(parsed.options, ["follow", "f"], !once && !jobId);
|
||||
const failedOnly = booleanOption(parsed.options, ["failed-only", "failedOnly", "errors"], false);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
const outputChunks: string[] = [];
|
||||
const eventsCollected: WorkflowWatchEvent[] = [];
|
||||
|
||||
const emit = async (chunk: string) => {
|
||||
outputChunks.push(chunk);
|
||||
if (runtime.writeStdout) {
|
||||
await runtime.writeStdout(chunk);
|
||||
}
|
||||
};
|
||||
|
||||
const report = await watchWorkflowPipeline(client, pipelineId, {
|
||||
jobId,
|
||||
intervalMs: Math.max(intervalSec, 1) * 1000,
|
||||
timeoutMs: timeoutSec !== undefined ? timeoutSec * 1000 : undefined,
|
||||
maxJobs,
|
||||
once,
|
||||
follow,
|
||||
failedOnly,
|
||||
onEvent: async (ev) => {
|
||||
eventsCollected.push(ev);
|
||||
if (runtime.jsonMode) {
|
||||
if (!once) {
|
||||
await emit(JSON.stringify(ev) + "\n");
|
||||
}
|
||||
} else {
|
||||
const line = formatWatchEvent(ev);
|
||||
await emit(line + "\n");
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
if (once) {
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: runtime.writeStdout ? "" : outputChunks.join(""),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: runtime.writeStdout ? "" : outputChunks.join(""),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -39,7 +39,7 @@ export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
},
|
||||
},
|
||||
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
|
||||
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", diff: "对比两个工作流快照的结构与脚本差异", "diff-job": "对比两次执行的节点分支与报错发散点", test: "端到端一键调试单据(替代前端手工调测)", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--flow=<单号> 指定测试单据", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志", "--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", diff: "对比两个工作流快照的结构与脚本差异", "diff-job": "对比两次执行的节点分支与报错发散点", test: "端到端一键调试单据(替代前端手工调测)", node: "声明式节点编排与增删改 (list|get|add|edit|rm)", tail: "实时监听任务派发与节点执行日志流 (watch|follow)", create: "从零新建工作流草稿", copy: "复制克隆工作流", delete: "删除工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--flow=<单号> 指定测试单据", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志", "--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all / --ndjson 流式 / --stats 画像)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--ndjson 流式逐行下发 JSON Lines ($O(1)内存)", "--flat 剥离底层实体动态字段前缀并提取引用", "--stats 输出总数/启停/重名/编码规则聚类画像", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
|
||||
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
|
||||
+1
-1
@@ -179,7 +179,7 @@ export function printHelp(target: string[] = []): string {
|
||||
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, job, toggle, publish, patch, save, history, logs, check)
|
||||
workflow 工作流管理 (list, get, find, analyze, node, tail, job, create, copy, delete, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索、模板规格与审批动作 (list, get <单号|ID> [--risk], spec <模板ID>, approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
|
||||
@@ -10,6 +10,7 @@ src/domains/platform/
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
├── workflow-nodes.ts # 节点树展平、树形索引定位、声明式增删改与索引重排 SDK
|
||||
├── workflow-watch.ts # 实时任务监听、增量状态跃迁追踪与执行日志流引擎
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
```
|
||||
|
||||
@@ -33,6 +34,7 @@ hose-use workflow node get <pipelineId> <节点name或#序号>
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
|
||||
hose-use workflow node edit <pipelineId> <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes]
|
||||
hose-use workflow node rm <pipelineId> <节点name或#序号> [--dry-run|--yes]
|
||||
hose-use workflow tail <pipelineId> [--job=<jobId>] [--once] [--failed-only] [--interval=2] [--json]
|
||||
```
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
|
||||
@@ -941,6 +941,4 @@ export async function getWorkflowSampleData(
|
||||
}
|
||||
|
||||
export * from "./workflow-nodes.js";
|
||||
|
||||
|
||||
|
||||
export * from "./workflow-watch.js";
|
||||
@@ -0,0 +1,374 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
TaskExecutionTracker,
|
||||
formatWatchEvent,
|
||||
normalizeJobStatus,
|
||||
isJobTerminal,
|
||||
extractTaskErrorMessage,
|
||||
watchSingleJob,
|
||||
watchWorkflowPipeline,
|
||||
type WorkflowWatchEvent,
|
||||
} from "./workflow-watch.js";
|
||||
import type { WorkflowTaskExecution } from "./types.js";
|
||||
|
||||
describe("workflow-watch - 实时监控与日志流跟踪引擎", () => {
|
||||
describe("TaskExecutionTracker", () => {
|
||||
it("tracks new nodes and produces correct initial events", () => {
|
||||
const tracker = new TaskExecutionTracker("job_123");
|
||||
const mockNodes: WorkflowTaskExecution[] = [
|
||||
{
|
||||
id: "exec_1",
|
||||
name: "trigger_clock",
|
||||
type: "clock",
|
||||
label: "定时触发",
|
||||
status: "COMPLETED",
|
||||
executionTime: 12,
|
||||
},
|
||||
{
|
||||
id: "exec_2",
|
||||
name: "action_js",
|
||||
type: "code-js2",
|
||||
label: "数据清洗",
|
||||
status: "RUNNING",
|
||||
},
|
||||
{
|
||||
id: "exec_3",
|
||||
name: "action_http",
|
||||
type: "http",
|
||||
status: "FAILED",
|
||||
executionTime: 450,
|
||||
error: { message: "HTTP 502 Bad Gateway", stackTrace: [] },
|
||||
},
|
||||
{
|
||||
id: "exec_4",
|
||||
name: "action_create",
|
||||
type: "flow-create-task",
|
||||
status: "SKIPPED",
|
||||
executionTime: 120,
|
||||
currentLoopPath: "every_1:0",
|
||||
output: { error: "送审失败: 缺失经办人" },
|
||||
},
|
||||
];
|
||||
|
||||
const events = tracker.processExecutions(mockNodes);
|
||||
expect(events).toHaveLength(4);
|
||||
|
||||
expect(events[0].type).toBe("task_completed");
|
||||
expect(events[0].name).toBe("trigger_clock");
|
||||
expect(events[0].durationMs).toBe(12);
|
||||
|
||||
expect(events[1].type).toBe("task_started");
|
||||
expect(events[1].name).toBe("action_js");
|
||||
expect(events[1].status).toBe("RUNNING");
|
||||
|
||||
expect(events[2].type).toBe("task_failed");
|
||||
expect(events[2].name).toBe("action_http");
|
||||
expect(events[2].error).toBe("HTTP 502 Bad Gateway");
|
||||
|
||||
expect(events[3].type).toBe("task_skipped");
|
||||
expect(events[3].name).toBe("action_create");
|
||||
expect(events[3].error).toBe("送审失败: 缺失经办人");
|
||||
expect(events[3].loopPath).toBe("every_1:0");
|
||||
});
|
||||
|
||||
it("does not re-emit events if node status has not changed on subsequent poll", () => {
|
||||
const tracker = new TaskExecutionTracker("job_123");
|
||||
const mockNodes: WorkflowTaskExecution[] = [
|
||||
{
|
||||
id: "exec_1",
|
||||
name: "trigger_clock",
|
||||
type: "clock",
|
||||
status: "COMPLETED",
|
||||
},
|
||||
{
|
||||
id: "exec_2",
|
||||
name: "action_js",
|
||||
type: "code-js2",
|
||||
status: "RUNNING",
|
||||
},
|
||||
];
|
||||
|
||||
const initialEvents = tracker.processExecutions(mockNodes);
|
||||
expect(initialEvents).toHaveLength(2);
|
||||
|
||||
// 相同状态再次轮询
|
||||
const repeatEvents = tracker.processExecutions(mockNodes);
|
||||
expect(repeatEvents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("detects status transitions from RUNNING to COMPLETED", () => {
|
||||
const tracker = new TaskExecutionTracker("job_123");
|
||||
const initialNodes: WorkflowTaskExecution[] = [
|
||||
{
|
||||
id: "exec_2",
|
||||
name: "action_js",
|
||||
type: "code-js2",
|
||||
status: "RUNNING",
|
||||
},
|
||||
];
|
||||
tracker.processExecutions(initialNodes);
|
||||
|
||||
// 节点完成
|
||||
const updatedNodes: WorkflowTaskExecution[] = [
|
||||
{
|
||||
id: "exec_2",
|
||||
name: "action_js",
|
||||
type: "code-js2",
|
||||
status: "COMPLETED",
|
||||
executionTime: 230,
|
||||
},
|
||||
];
|
||||
const transitionedEvents = tracker.processExecutions(updatedNodes);
|
||||
expect(transitionedEvents).toHaveLength(1);
|
||||
expect(transitionedEvents[0].type).toBe("task_completed");
|
||||
expect(transitionedEvents[0].status).toBe("COMPLETED");
|
||||
expect(transitionedEvents[0].durationMs).toBe(230);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractTaskErrorMessage", () => {
|
||||
it("extracts error from error.message", () => {
|
||||
const node: WorkflowTaskExecution = {
|
||||
id: "e1",
|
||||
status: "FAILED",
|
||||
type: "code",
|
||||
error: { message: "Syntax error at line 3", stackTrace: [] },
|
||||
};
|
||||
expect(extractTaskErrorMessage(node)).toBe("Syntax error at line 3");
|
||||
});
|
||||
|
||||
it("extracts error from outputs.error", () => {
|
||||
const node: any = {
|
||||
id: "e2",
|
||||
status: "SKIPPED",
|
||||
type: "http",
|
||||
outputs: { error: "Connection timed out" },
|
||||
};
|
||||
expect(extractTaskErrorMessage(node)).toBe("Connection timed out");
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeJobStatus and isJobTerminal", () => {
|
||||
it("normalizes various string and numeric states", () => {
|
||||
expect(normalizeJobStatus({ status: "running" })).toBe("RUNNING");
|
||||
expect(normalizeJobStatus({ state: 0 })).toBe("COMPLETED");
|
||||
expect(normalizeJobStatus({ state: 1 })).toBe("RUNNING");
|
||||
expect(normalizeJobStatus({ state: 2 })).toBe("FAILED");
|
||||
expect(normalizeJobStatus(null)).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("checks terminal states", () => {
|
||||
expect(isJobTerminal("COMPLETED")).toBe(true);
|
||||
expect(isJobTerminal("FAILED")).toBe(true);
|
||||
expect(isJobTerminal("STOP")).toBe(true);
|
||||
expect(isJobTerminal("RUNNING")).toBe(false);
|
||||
expect(isJobTerminal("UNKNOWN")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatWatchEvent", () => {
|
||||
it("formats various watch events cleanly", () => {
|
||||
const now = new Date("2026-10-15T16:00:00.000Z").getTime();
|
||||
|
||||
const startEv: WorkflowWatchEvent = {
|
||||
type: "pipeline_watch_start",
|
||||
pipelineId: "pipe_100",
|
||||
pipelineLabel: "发票自动归档",
|
||||
timestamp: now,
|
||||
};
|
||||
expect(formatWatchEvent(startEv)).toContain("开始监听工作流 [发票自动归档]");
|
||||
|
||||
const jobEv: WorkflowWatchEvent = {
|
||||
type: "job_detected",
|
||||
jobId: "job_999",
|
||||
status: "RUNNING",
|
||||
runType: "DEBUG",
|
||||
timestamp: now,
|
||||
};
|
||||
expect(formatWatchEvent(jobEv)).toContain("捕获新运行任务 Job [job_999]");
|
||||
|
||||
const completedEv: WorkflowWatchEvent = {
|
||||
type: "task_completed",
|
||||
jobId: "job_999",
|
||||
name: "action_js",
|
||||
label: "清洗数据",
|
||||
taskType: "code-js2",
|
||||
durationMs: 88,
|
||||
timestamp: now,
|
||||
};
|
||||
expect(formatWatchEvent(completedEv)).toContain("✓ [code-js2] action_js (清洗数据) COMPLETED (88ms)");
|
||||
|
||||
const failedEv: WorkflowWatchEvent = {
|
||||
type: "task_failed",
|
||||
jobId: "job_999",
|
||||
name: "action_http",
|
||||
taskType: "http",
|
||||
durationMs: 500,
|
||||
error: "网络连接失败",
|
||||
timestamp: now,
|
||||
};
|
||||
const formattedFailed = formatWatchEvent(failedEv);
|
||||
expect(formattedFailed).toContain("❌ [http] action_http FAILED");
|
||||
expect(formattedFailed).toContain("网络连接失败");
|
||||
|
||||
const skippedEv: WorkflowWatchEvent = {
|
||||
type: "task_skipped",
|
||||
jobId: "job_999",
|
||||
name: "action_create",
|
||||
taskType: "flow-create-task",
|
||||
durationMs: 120,
|
||||
loopPath: "every_1:0",
|
||||
error: "金额超标跳过",
|
||||
timestamp: now,
|
||||
};
|
||||
const formattedSkipped = formatWatchEvent(skippedEv);
|
||||
expect(formattedSkipped).toContain("⚠️ [flow-create-task] action_create SKIPPED");
|
||||
expect(formattedSkipped).toContain("金额超标跳过");
|
||||
|
||||
const endEv: WorkflowWatchEvent = {
|
||||
type: "job_completed",
|
||||
jobId: "job_999",
|
||||
timestamp: now,
|
||||
jobSummary: {
|
||||
status: "COMPLETED",
|
||||
durationMs: 1500,
|
||||
successCount: 5,
|
||||
errorCount: 1,
|
||||
hasError: true,
|
||||
},
|
||||
};
|
||||
expect(formatWatchEvent(endEv)).toContain("Job [job_999] 执行结束: 状态 [COMPLETED]");
|
||||
expect(formatWatchEvent(endEv)).toContain("存在错误: 是");
|
||||
});
|
||||
});
|
||||
|
||||
describe("watchSingleJob and watchWorkflowPipeline with Mock Client", () => {
|
||||
it("watchSingleJob tracks a job through completion", async () => {
|
||||
const mockJob = {
|
||||
id: "job_test_1",
|
||||
pipelineId: "pipe_1",
|
||||
status: "COMPLETED",
|
||||
runType: "DEBUG",
|
||||
durationTime: 1200,
|
||||
successTaskCount: 2,
|
||||
errorTaskCount: 0,
|
||||
hasError: false,
|
||||
};
|
||||
|
||||
const mockExecutions: WorkflowTaskExecution[] = [
|
||||
{
|
||||
id: "ex_1",
|
||||
name: "trigger_1",
|
||||
type: "webhook",
|
||||
status: "COMPLETED",
|
||||
executionTime: 10,
|
||||
},
|
||||
{
|
||||
id: "ex_2",
|
||||
name: "action_2",
|
||||
type: "code-js2",
|
||||
status: "COMPLETED",
|
||||
executionTime: 200,
|
||||
},
|
||||
];
|
||||
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("api/easo/jobs/job_test_1/execution/level/failed")) {
|
||||
return { json: async () => ({ code: 200, data: { items: [] } }) };
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_test_1/execution")) {
|
||||
return { json: async () => ({ code: 200, data: mockExecutions }) };
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_test_1")) {
|
||||
return { json: async () => ({ code: 200, data: mockJob }) };
|
||||
}
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
};
|
||||
|
||||
const emitted: WorkflowWatchEvent[] = [];
|
||||
const res = await watchSingleJob(mockClient as any, "job_test_1", {
|
||||
intervalMs: 50,
|
||||
timeoutMs: 1000,
|
||||
onEvent: (ev) => {
|
||||
emitted.push(ev);
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.status).toBe("COMPLETED");
|
||||
expect(res.successCount).toBe(2);
|
||||
expect(res.hasError).toBe(false);
|
||||
expect(emitted.length).toBeGreaterThanOrEqual(3); // 2 tasks + 1 job_completed
|
||||
expect(emitted.some((e) => e.type === "job_completed")).toBe(true);
|
||||
});
|
||||
|
||||
it("watchWorkflowPipeline with once=true inspects the latest job snapshot", async () => {
|
||||
const mockJobDetail = {
|
||||
id: "job_recent_1",
|
||||
pipelineId: "pipe_1",
|
||||
status: "COMPLETED",
|
||||
successTaskCount: 1,
|
||||
errorTaskCount: 0,
|
||||
};
|
||||
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("api/easo/pipelines/pipe_1/log")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
jobList: [{ jobId: "job_recent_1", status: "COMPLETED" }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/jobs/running")) {
|
||||
return { json: async () => ({ code: 200, data: [] }) };
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_recent_1/execution/level/failed")) {
|
||||
return { json: async () => ({ code: 200, data: { items: [] } }) };
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_recent_1/execution")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "ex_10",
|
||||
name: "action_clean",
|
||||
type: "code",
|
||||
status: "COMPLETED",
|
||||
executionTime: 50,
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_recent_1")) {
|
||||
return { json: async () => ({ code: 200, data: mockJobDetail }) };
|
||||
}
|
||||
if (url.includes("api/easo/pipelines/pipe_1")) {
|
||||
return { json: async () => ({ code: 200, data: { id: "pipe_1", label: "测试流水线" } }) };
|
||||
}
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
};
|
||||
|
||||
const emitted: WorkflowWatchEvent[] = [];
|
||||
const report = await watchWorkflowPipeline(mockClient as any, "pipe_1", {
|
||||
once: true,
|
||||
onEvent: (ev) => {
|
||||
emitted.push(ev);
|
||||
},
|
||||
});
|
||||
|
||||
expect(report.totalJobsWatched).toBe(1);
|
||||
expect(report.hasFailures).toBe(false);
|
||||
expect(emitted.some((e) => e.type === "pipeline_watch_start")).toBe(true);
|
||||
expect(emitted.some((e) => e.type === "task_completed" && e.name === "action_clean")).toBe(true);
|
||||
expect(emitted.some((e) => e.type === "job_completed")).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,645 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "./types.js";
|
||||
import * as api from "./api.js";
|
||||
import { flattenExecutionTree, isTaskExecutionFailed } from "./services.js";
|
||||
|
||||
export type WorkflowWatchEventType =
|
||||
| "pipeline_watch_start"
|
||||
| "job_detected"
|
||||
| "task_started"
|
||||
| "task_completed"
|
||||
| "task_failed"
|
||||
| "task_skipped"
|
||||
| "job_completed"
|
||||
| "idle"
|
||||
| "timeout";
|
||||
|
||||
export interface WorkflowWatchEvent {
|
||||
type: WorkflowWatchEventType;
|
||||
pipelineId?: string;
|
||||
pipelineLabel?: string;
|
||||
jobId?: string;
|
||||
runType?: string;
|
||||
executionId?: string;
|
||||
name?: string;
|
||||
displayName?: string;
|
||||
label?: string;
|
||||
taskType?: string;
|
||||
status?: string;
|
||||
durationMs?: number;
|
||||
startTime?: string;
|
||||
loopPath?: string;
|
||||
error?: string;
|
||||
jobSummary?: {
|
||||
status: string;
|
||||
durationMs?: number;
|
||||
successCount: number;
|
||||
errorCount: number;
|
||||
hasError: boolean;
|
||||
};
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface WatchWorkflowOptions {
|
||||
jobId?: string;
|
||||
intervalMs?: number;
|
||||
timeoutMs?: number;
|
||||
maxJobs?: number;
|
||||
once?: boolean;
|
||||
follow?: boolean;
|
||||
failedOnly?: boolean;
|
||||
onEvent?: (event: WorkflowWatchEvent) => Promise<void> | void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface WatchedJobResult {
|
||||
jobId: string;
|
||||
pipelineId: string;
|
||||
status: string;
|
||||
runType?: string;
|
||||
durationMs?: number;
|
||||
successCount: number;
|
||||
errorCount: number;
|
||||
hasError: boolean;
|
||||
events: WorkflowWatchEvent[];
|
||||
}
|
||||
|
||||
export interface WorkflowWatchReport {
|
||||
pipelineId: string;
|
||||
totalJobsWatched: number;
|
||||
jobs: WatchedJobResult[];
|
||||
timedOut: boolean;
|
||||
hasFailures: boolean;
|
||||
}
|
||||
|
||||
const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
||||
|
||||
export function normalizeJobStatus(job?: Partial<WorkflowJobDetail> | Record<string, unknown> | null): string {
|
||||
if (!job) return "UNKNOWN";
|
||||
const rawStatus = (job as any).status;
|
||||
const rawState = (job as any).state;
|
||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
||||
return rawStatus.trim().toUpperCase();
|
||||
}
|
||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
export function isJobTerminal(status: string): boolean {
|
||||
return TERMINAL_STATES.has(status.toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取节点执行失败或跳过时的具体错误原因
|
||||
*/
|
||||
export function extractTaskErrorMessage(node: WorkflowTaskExecution): string | undefined {
|
||||
if (!node) return undefined;
|
||||
const anyNode = node as any;
|
||||
if (node.error?.message && String(node.error.message).trim()) {
|
||||
return String(node.error.message).trim();
|
||||
}
|
||||
if (anyNode.errorMessage && String(anyNode.errorMessage).trim()) {
|
||||
return String(anyNode.errorMessage).trim();
|
||||
}
|
||||
const outputs = anyNode.outputs ?? anyNode.output;
|
||||
if (outputs && typeof outputs === "object") {
|
||||
if (outputs.error) {
|
||||
return typeof outputs.error === "string" ? outputs.error.trim() : JSON.stringify(outputs.error);
|
||||
}
|
||||
if (outputs.message && typeof outputs.message === "string") {
|
||||
return outputs.message.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点状态追踪器:比对并生成增量任务状态变更事件,避免轮询时重复日志刷屏
|
||||
*/
|
||||
export class TaskExecutionTracker {
|
||||
private seenStatuses = new Map<string, string>();
|
||||
|
||||
constructor(public readonly jobId: string) {}
|
||||
|
||||
public processExecutions(executions: WorkflowTaskExecution[]): WorkflowWatchEvent[] {
|
||||
const flattened = flattenExecutionTree(executions);
|
||||
const events: WorkflowWatchEvent[] = [];
|
||||
const now = Date.now();
|
||||
|
||||
for (const node of flattened) {
|
||||
if (!node?.id) continue;
|
||||
const executionId = node.id;
|
||||
const rawStatus = (node.status || "UNKNOWN").toUpperCase();
|
||||
const previousStatus = this.seenStatuses.get(executionId);
|
||||
|
||||
const name = node.name || executionId;
|
||||
const label = node.label || node.displayName || undefined;
|
||||
const displayName = node.displayName || undefined;
|
||||
const taskType = node.type || "unknown";
|
||||
const durationMs = typeof node.executionTime === "number" ? node.executionTime : undefined;
|
||||
const loopPath = node.currentLoopPath || undefined;
|
||||
const error = extractTaskErrorMessage(node);
|
||||
const isFailed = isTaskExecutionFailed(node) || rawStatus === "FAILED";
|
||||
const isSkipped = rawStatus === "SKIPPED" || rawStatus === "SKIP";
|
||||
|
||||
if (previousStatus === undefined) {
|
||||
// 第一次发现该节点
|
||||
this.seenStatuses.set(executionId, rawStatus);
|
||||
|
||||
if (isSkipped) {
|
||||
events.push({
|
||||
type: "task_skipped",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error,
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (isFailed) {
|
||||
events.push({
|
||||
type: "task_failed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error: error || "执行异常或未通过规则校验",
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (rawStatus === "COMPLETED" || rawStatus === "SUCCESS") {
|
||||
events.push({
|
||||
type: "task_completed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
} else {
|
||||
events.push({
|
||||
type: "task_started",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
}
|
||||
} else if (previousStatus !== rawStatus) {
|
||||
// 状态发生跃迁(例如从 RUNNING -> COMPLETED 或 FAILED)
|
||||
this.seenStatuses.set(executionId, rawStatus);
|
||||
|
||||
if (isSkipped) {
|
||||
events.push({
|
||||
type: "task_skipped",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error,
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (isFailed) {
|
||||
events.push({
|
||||
type: "task_failed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error: error || "执行异常或未通过规则校验",
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (rawStatus === "COMPLETED" || rawStatus === "SUCCESS") {
|
||||
events.push({
|
||||
type: "task_completed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将事件格式化为带时间戳的清晰控制台文本行
|
||||
*/
|
||||
export function formatWatchEvent(event: WorkflowWatchEvent): string {
|
||||
const timeStr = new Date(event.timestamp).toTimeString().slice(0, 8);
|
||||
const tag = `[${timeStr}]`;
|
||||
|
||||
switch (event.type) {
|
||||
case "pipeline_watch_start":
|
||||
return `${tag} 🔍 开始监听工作流 [${event.pipelineLabel || event.pipelineId}] 运行动态 (按 Ctrl+C 退出)...`;
|
||||
|
||||
case "job_detected":
|
||||
return `${tag} 🚀 捕获新运行任务 Job [${event.jobId}] (${event.runType || "RUN"}, 状态: ${event.status || "RUNNING"})`;
|
||||
|
||||
case "task_started":
|
||||
return ` ⏳ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} 开始运行...${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}`;
|
||||
|
||||
case "task_completed":
|
||||
return ` ✓ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} COMPLETED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}`;
|
||||
|
||||
case "task_skipped": {
|
||||
const errHint = event.error ? `\n ↳ ⚠️ 异常跳过原因: ${event.error}` : "";
|
||||
return ` ⚠️ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} SKIPPED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}${errHint}`;
|
||||
}
|
||||
|
||||
case "task_failed":
|
||||
return ` ❌ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} FAILED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}\n ↳ 错误详情: ${event.error || "未捕获明确错误信息"}`;
|
||||
|
||||
case "job_completed": {
|
||||
const summary = event.jobSummary;
|
||||
const isOk = summary?.status === "COMPLETED" && !summary.hasError && summary.errorCount === 0;
|
||||
const icon = isOk ? "🏁" : "❌";
|
||||
const statusText = summary?.status || "COMPLETED";
|
||||
return `${tag} ${icon} Job [${event.jobId}] 执行结束: 状态 [${statusText}] | 耗时: ${summary?.durationMs ?? "-"}ms | 成功: ${summary?.successCount ?? 0} | 失败: ${summary?.errorCount ?? 0} | 存在错误: ${summary?.hasError ? "是" : "否"}`;
|
||||
}
|
||||
|
||||
case "timeout":
|
||||
return `${tag} ⏱️ 监听超时,未在指定时间内捕获到新的任务状态变更。`;
|
||||
|
||||
case "idle":
|
||||
return `${tag} 💤 暂无新运行实例,继续等待中...`;
|
||||
|
||||
default:
|
||||
return `${tag} [${event.type}]`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听指定单个 Job 的实时执行,直至其达到终态或超时
|
||||
*/
|
||||
export async function watchSingleJob(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: WatchWorkflowOptions = {}
|
||||
): Promise<WatchedJobResult> {
|
||||
const intervalMs = Math.max(options.intervalMs ?? 1500, 500);
|
||||
const timeoutMs = options.timeoutMs ?? 60000;
|
||||
const startTime = Date.now();
|
||||
const tracker = new TaskExecutionTracker(jobId);
|
||||
const events: WorkflowWatchEvent[] = [];
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
events.push(event);
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
}
|
||||
};
|
||||
|
||||
let latestJob: WorkflowJobDetail | undefined;
|
||||
let isTerminal = false;
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (options.signal?.aborted) break;
|
||||
|
||||
try {
|
||||
latestJob = await api.getJob(client, jobId);
|
||||
} catch {
|
||||
// 任务初创可能存在 404/延迟,忽略单次瞬态
|
||||
}
|
||||
|
||||
const currentStatus = normalizeJobStatus(latestJob);
|
||||
|
||||
// 获取当前执行树并比对增量事件
|
||||
try {
|
||||
const tree = await api.getJobExecutionTree(client, jobId);
|
||||
const deltaEvents = tracker.processExecutions(tree);
|
||||
for (const ev of deltaEvents) {
|
||||
await emit(ev);
|
||||
}
|
||||
} catch {
|
||||
// 忽略执行树瞬态读取异常
|
||||
}
|
||||
|
||||
if (isJobTerminal(currentStatus)) {
|
||||
isTerminal = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (options.once) {
|
||||
break;
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const remaining = timeoutMs - elapsed;
|
||||
if (remaining <= 0) break;
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
|
||||
}
|
||||
|
||||
// 终态最后同步一次失败节点信息
|
||||
let failureItems: WorkflowTaskExecution[] = [];
|
||||
try {
|
||||
const failedPage = await api.getJobFailedExecutions(client, jobId);
|
||||
failureItems = failedPage.items || [];
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
const finalStatus = normalizeJobStatus(latestJob);
|
||||
const anyJob = latestJob as any;
|
||||
const successCount = Number(anyJob?.successTaskCount ?? 0);
|
||||
const errorCount = Math.max(Number(anyJob?.errorTaskCount ?? 0), failureItems.length);
|
||||
const hasError = anyJob?.hasError === true || anyJob?.hasError === "存在" || errorCount > 0 || finalStatus === "FAILED";
|
||||
const durationMs = typeof anyJob?.durationTime === "number" ? anyJob.durationTime : undefined;
|
||||
|
||||
const completionEvent: WorkflowWatchEvent = {
|
||||
type: "job_completed",
|
||||
jobId,
|
||||
status: finalStatus,
|
||||
timestamp: Date.now(),
|
||||
jobSummary: {
|
||||
status: finalStatus,
|
||||
durationMs,
|
||||
successCount,
|
||||
errorCount,
|
||||
hasError,
|
||||
},
|
||||
};
|
||||
await emit(completionEvent);
|
||||
|
||||
return {
|
||||
jobId,
|
||||
pipelineId: latestJob?.pipelineId || "",
|
||||
status: finalStatus,
|
||||
runType: latestJob?.runType,
|
||||
durationMs,
|
||||
successCount,
|
||||
errorCount,
|
||||
hasError,
|
||||
events,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听工作流流水线:持续捕获新派发的 Job,并实时输出其节点执行动态
|
||||
*/
|
||||
export async function watchWorkflowPipeline(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
options: WatchWorkflowOptions = {}
|
||||
): Promise<WorkflowWatchReport> {
|
||||
const intervalMs = Math.max(options.intervalMs ?? 2000, 500);
|
||||
const timeoutMs = options.timeoutMs ?? (options.once || options.jobId ? 60000 : Infinity);
|
||||
const maxJobs = options.jobId ? 1 : (options.maxJobs ?? (options.follow ? Infinity : 1));
|
||||
const startTime = Date.now();
|
||||
const watchedJobs: WatchedJobResult[] = [];
|
||||
const seenJobIds = new Set<string>();
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
}
|
||||
};
|
||||
|
||||
// 1. 如果用户显式指定了 --job=<jobId>
|
||||
if (options.jobId) {
|
||||
const jobResult = await watchSingleJob(client, options.jobId, {
|
||||
...options,
|
||||
onEvent: emit,
|
||||
});
|
||||
watchedJobs.push(jobResult);
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 1,
|
||||
jobs: watchedJobs,
|
||||
timedOut: false,
|
||||
hasFailures: jobResult.hasError || jobResult.status === "FAILED",
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 发出监听开始事件
|
||||
let pipelineLabel = "";
|
||||
try {
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
pipelineLabel = detail.label || "";
|
||||
} catch {
|
||||
// 忽略标签读取失败
|
||||
}
|
||||
|
||||
await emit({
|
||||
type: "pipeline_watch_start",
|
||||
pipelineId,
|
||||
pipelineLabel,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 如果是一次性快照检视 (--once)
|
||||
if (options.once) {
|
||||
let targetJobId: string | undefined;
|
||||
|
||||
// 先查是否有正在运行的任务
|
||||
try {
|
||||
const running = await api.listRunningJobs(client, pipelineId, "DEBUG");
|
||||
if (running.length > 0) targetJobId = running[0].id;
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
if (!targetJobId) {
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 1 });
|
||||
if (logs.jobList && logs.jobList.length > 0) {
|
||||
const first = logs.jobList[0];
|
||||
targetJobId = first.jobId || first.id;
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetJobId) {
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 0,
|
||||
jobs: [],
|
||||
timedOut: false,
|
||||
hasFailures: false,
|
||||
};
|
||||
}
|
||||
|
||||
const singleRes = await watchSingleJob(client, targetJobId, {
|
||||
...options,
|
||||
once: true,
|
||||
onEvent: emit,
|
||||
});
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 1,
|
||||
jobs: [singleRes],
|
||||
timedOut: false,
|
||||
hasFailures: singleRes.hasError || singleRes.status === "FAILED",
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 持续监听循环
|
||||
let timedOut = false;
|
||||
|
||||
// 记录初次启动时的最新已知 JobId,避免将老历史任务当作新触发任务(除非有处于 RUNNING 状态的任务)
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 5 });
|
||||
for (const j of logs.jobList || []) {
|
||||
const jid = j.jobId || j.id;
|
||||
const status = normalizeJobStatus(j);
|
||||
// 如果不是运行中,标为已知历史
|
||||
if (jid && !isJobTerminal(status)) {
|
||||
// 运行中的保留待观察
|
||||
} else if (jid) {
|
||||
seenJobIds.add(jid);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (options.signal?.aborted) break;
|
||||
|
||||
let candidateJob: { id: string; status: string; runType?: string } | undefined;
|
||||
|
||||
// 优先检查 running 接口
|
||||
try {
|
||||
const runningJobs = await api.listRunningJobs(client, pipelineId, "DEBUG");
|
||||
const found = runningJobs.find((j) => !seenJobIds.has(j.id));
|
||||
if (found) {
|
||||
candidateJob = { id: found.id, status: found.status || "RUNNING", runType: "DEBUG" };
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
// 其次检查流水线最新 log
|
||||
if (!candidateJob) {
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 3 });
|
||||
for (const j of logs.jobList || []) {
|
||||
const jid = j.jobId || j.id;
|
||||
if (jid && !seenJobIds.has(jid)) {
|
||||
candidateJob = { id: jid, status: normalizeJobStatus(j), runType: j.runType };
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
if (candidateJob) {
|
||||
seenJobIds.add(candidateJob.id);
|
||||
|
||||
await emit({
|
||||
type: "job_detected",
|
||||
pipelineId,
|
||||
jobId: candidateJob.id,
|
||||
status: candidateJob.status,
|
||||
runType: candidateJob.runType,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 实时跟踪该 Job 执行
|
||||
const jobResult = await watchSingleJob(client, candidateJob.id, {
|
||||
...options,
|
||||
onEvent: emit,
|
||||
});
|
||||
|
||||
watchedJobs.push(jobResult);
|
||||
|
||||
if (watchedJobs.length >= maxJobs) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const remaining = timeoutMs - elapsed;
|
||||
if (remaining <= 0) {
|
||||
timedOut = true;
|
||||
break;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
|
||||
}
|
||||
|
||||
if (Date.now() - startTime >= timeoutMs && watchedJobs.length === 0) {
|
||||
timedOut = true;
|
||||
await emit({
|
||||
type: "timeout",
|
||||
pipelineId,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const hasFailures = watchedJobs.some((j) => j.hasError || j.status === "FAILED");
|
||||
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: watchedJobs.length,
|
||||
jobs: watchedJobs,
|
||||
timedOut,
|
||||
hasFailures,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user