From 71aa9b54a71582eeed879c4ca2400e98ba2e3947 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 1 Nov 2026 22:02:06 +0800 Subject: [PATCH] =?UTF-8?q?refactor(workflow):=20=E6=94=B6=E6=95=9B=20Job?= =?UTF-8?q?=20=E7=8A=B6=E6=80=81=E8=AF=AD=E4=B9=89=E4=B8=8E=E7=9B=91?= =?UTF-8?q?=E5=90=AC=E4=BA=8B=E4=BB=B6=E8=BF=87=E6=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 同一份逻辑在两个地方各写一遍,必然在某次修改后漂移: - Job 状态判定:watch/helpers.ts 与 execution/debug.ts 各有一份终态集合, 且对数字 state 的解释相反——watch 把 state:0 视为 COMPLETED, debug 把它当成未知继续轮询到超时,同一个 Job 在两条路径上结论相反。 统一到 execution/job-status.ts(watch 已依赖 execution,方向单向), helpers 保留转发导出,debug 删除本地实现;新增两条用例固定该语义。 - --failed-only 事件过滤:pipeline-watcher.ts 与 single-job.ts 逐字重复, 抽为 watch/helpers.ts 的 shouldEmitWatchEvent(),两处调用点同步瘦身。 同步更新 execution 模块 README,说明状态语义的两个入口必须一起考虑。 --- .../workflow/execution/README.execution.md | 8 ++++ .../platform/workflow/execution/debug.ts | 11 +++-- .../platform/workflow/execution/job-status.ts | 36 +++++++++++++++++ .../workflow/execution/workflow-debug.test.ts | 29 ++++++++++++++ .../platform/workflow/watch/helpers.ts | 40 +++++++++---------- .../workflow/watch/pipeline-watcher.ts | 13 +----- .../platform/workflow/watch/single-job.ts | 13 +----- 7 files changed, 102 insertions(+), 48 deletions(-) create mode 100644 src/domains/platform/workflow/execution/job-status.ts diff --git a/src/domains/platform/workflow/execution/README.execution.md b/src/domains/platform/workflow/execution/README.execution.md index e6d0b9c..d26ab75 100644 --- a/src/domains/platform/workflow/execution/README.execution.md +++ b/src/domains/platform/workflow/execution/README.execution.md @@ -2,7 +2,15 @@ - [tree.ts](./tree.ts):执行树展开、失败识别和节点查找,也提供工作流任务树展开。 - [context.ts](./context.ts):构建执行实例索引,供条件解释与 Job 差异比较复用。 +- [job-status.ts](./job-status.ts):Job 状态归一化与终态判定,**watch 监听与 debug 轮询共用同一实现**。 - [debug.ts](./debug.ts):调试输入、发起 Job、轮询和诊断汇总。 - [queries.ts](./queries.ts):Job、执行树与日志读取服务出口。 执行监听位于同级 [watch](../watch/README.watch.md),条件解释位于 `branch/`;HTTP 传输位于上级 `api.ts`。 + +## Job 状态语义 + +Job 可能只返回字符串 `status`,也可能只返回数字 `state`(0 完成、1 运行中、2 失败)。 +归一化逻辑只在 `job-status.ts` 定义一次:过去 debug 侧自行判定时把 `state: 0` 当成未知而继续轮询, +watch 侧却视为已完成,同一个 Job 在两条路径上会得到相反的结论。 +修改状态时必须同时考虑这两个入口,并在两侧补回归用例。 diff --git a/src/domains/platform/workflow/execution/debug.ts b/src/domains/platform/workflow/execution/debug.ts index cbce7d2..f47a5a0 100644 --- a/src/domains/platform/workflow/execution/debug.ts +++ b/src/domains/platform/workflow/execution/debug.ts @@ -3,6 +3,7 @@ import { ValidationError } from "../../../../core/errors.js"; import { explainConditionBranches } from "../branch/index.js"; import { WorkflowJobDetail } from "../types.js"; import { extractFailureExecutions } from "./tree.js"; +import { normalizeJobStatus, isJobTerminal } from "./job-status.js"; export function getWebhookInfo(...args: Parameters) { @@ -74,8 +75,6 @@ export async function runWorkflowDebugTest( const start = Date.now(); const diagnosticsErrors: Array<{ source: string; message: string }> = []; const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) }); - const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]); - const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase(); let finalJob: WorkflowJobDetail | undefined; let pollingFailed = false; @@ -83,7 +82,7 @@ export async function runWorkflowDebugTest( try { const job = await api.getJob(client, jobId); finalJob = job; - if (terminal.has(jobState(job))) break; + if (isJobTerminal(normalizeJobStatus(job))) break; } catch (error) { // 任务刚创建可能存在短延时,继续轮询 const status = (error as { status?: number; response?: { status?: number } } | null)?.status @@ -101,7 +100,7 @@ export async function runWorkflowDebugTest( try { finalJob = await api.getJob(client, jobId); } catch (error) { recordError("job", error); pollingFailed = true; } } - const timedOut = !pollingFailed && !terminal.has(jobState(finalJob)); + const timedOut = !pollingFailed && !isJobTerminal(normalizeJobStatus(finalJob)); const [treeResult, failuresResult] = await Promise.allSettled([ api.getJobExecutionTree(client, jobId), api.getJobFailedExecutions(client, jobId), @@ -113,11 +112,11 @@ export async function runWorkflowDebugTest( const rawFailed = extractFailureExecutions(tree, failedItems); const diagnosticsComplete = diagnosticsErrors.length === 0; - const status = jobState(finalJob); + const status = normalizeJobStatus(finalJob); const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0; let outcome: import("../types.js").WorkflowTestReport["outcome"] = "incomplete"; if (timedOut) outcome = "timed_out"; - else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed"; + else if (isJobTerminal(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed"; else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed"; const conditionDiagnoses = explainConditionBranches(tree); diff --git a/src/domains/platform/workflow/execution/job-status.ts b/src/domains/platform/workflow/execution/job-status.ts new file mode 100644 index 0000000..bdddd6d --- /dev/null +++ b/src/domains/platform/workflow/execution/job-status.ts @@ -0,0 +1,36 @@ +import type { WorkflowJobDetail } from "../types.js"; + +/** + * Job 状态归一化。Job 可能只返回字符串 `status`,也可能只返回数字 `state`, + * 两个入口(watch 监听与 debug 轮询)必须给出一致的解释,否则同一个 Job + * 在一处被视为已完成、在另一处被视为仍在运行。 + * + * 数字 state 的语义:0 完成、1 运行中、2 失败(与 watch 侧既有约定一致)。 + */ +export const TERMINAL_JOB_STATES = new Set([ + "COMPLETED", + "FAILED", + "STOP", + "STOPPED", + "CANCELLED", + "CANCELED", +]); + +export function normalizeJobStatus(job?: Partial | Record | null): string { + if (!job) return "UNKNOWN"; + const rawStatus = (job as Record).status; + const rawState = (job as Record).state; + if (typeof rawStatus === "string" && rawStatus.trim()) { + const normalized = rawStatus.trim().toUpperCase(); + return normalized === "STARTED" ? "RUNNING" : normalized; + } + if (rawState === 1 || rawState === "1") return "RUNNING"; + if (rawState === 2 || rawState === "2") return "FAILED"; + if (rawState === 0 || rawState === "0") return "COMPLETED"; + if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase(); + return "UNKNOWN"; +} + +export function isJobTerminal(status: string): boolean { + return TERMINAL_JOB_STATES.has(status.toUpperCase()); +} diff --git a/src/domains/platform/workflow/execution/workflow-debug.test.ts b/src/domains/platform/workflow/execution/workflow-debug.test.ts index d87bc40..33b646d 100644 --- a/src/domains/platform/workflow/execution/workflow-debug.test.ts +++ b/src/domains/platform/workflow/execution/workflow-debug.test.ts @@ -63,6 +63,35 @@ describe("workflow debug completion evidence", () => { await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs"); expect(posts).toEqual([]); }); + + describe("numeric job state must agree with the watch pipeline", () => { + const withState = (state: number) => { + const { client } = setup(); + const get = client.get; + client.get = async (path: string) => { + if (path.endsWith("/job")) { + return new Response(JSON.stringify({ code: 200, data: { id: "job", state } }), { + headers: { "content-type": "application/json" }, + }); + } + return get(path); + }; + return client; + }; + + it("reads state 0 as completed instead of polling until timeout", async () => { + const result = await runWorkflowDebugTest(withState(0), "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 100, pollIntervalMs: 1 }); + expect(result.status).toBe("COMPLETED"); + expect(result.outcome).toBe("completed"); + expect(result.timedOut).toBe(false); + }); + + it("reads state 1 as still running", async () => { + const result = await runWorkflowDebugTest(withState(1), "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 0 }); + expect(result.status).toBe("RUNNING"); + expect(result.outcome).toBe("timed_out"); + }); + }); it("retries a newly created job's HTTP 404 instead of reporting an authorization failure", async () => { const { client } = setup(); const get = client.get; diff --git a/src/domains/platform/workflow/watch/helpers.ts b/src/domains/platform/workflow/watch/helpers.ts index 14a7d0b..fce0173 100644 --- a/src/domains/platform/workflow/watch/helpers.ts +++ b/src/domains/platform/workflow/watch/helpers.ts @@ -1,25 +1,25 @@ -import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js"; +import type { WorkflowTaskExecution } from "../types.js"; +import type { WatchWorkflowOptions, WorkflowWatchEvent } from "./types.js"; -export const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]); +// Job 状态判定统一来自 execution/job-status.ts,watch 与 debug 共用同一套语义。 +export { normalizeJobStatus, isJobTerminal, TERMINAL_JOB_STATES } from "../execution/job-status.js"; -export function normalizeJobStatus(job?: Partial | Record | null): string { - if (!job) return "UNKNOWN"; - const rawStatus = (job as any).status; - const rawState = (job as any).state; - if (typeof rawStatus === "string" && rawStatus.trim()) { - const s = rawStatus.trim().toUpperCase(); - if (s === "STARTED") return "RUNNING"; - return s; - } - if (rawState === 1 || rawState === "1") return "RUNNING"; - if (rawState === 2 || rawState === "2") return "FAILED"; - if (rawState === 0 || rawState === "0") return "COMPLETED"; - if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase(); - return "UNKNOWN"; -} - -export function isJobTerminal(status: string): boolean { - return TERMINAL_STATES.has(status.toUpperCase()); +/** + * `--failed-only` 的事件过滤。此前的实现在两个监听入口各写了一份且逐字相同, + * 任一侧漏改都会让两种监听模式给出不同的结果。 + */ +export function shouldEmitWatchEvent( + event: WorkflowWatchEvent, + options: Pick +): boolean { + if (!options.failedOnly) return true; + return ( + event.type === "task_failed" || + (event.type === "task_skipped" && Boolean(event.error)) || + event.type === "job_completed" || + event.type === "timeout" || + event.type === "cancelled" + ); } /** diff --git a/src/domains/platform/workflow/watch/pipeline-watcher.ts b/src/domains/platform/workflow/watch/pipeline-watcher.ts index 0247673..a9b4b2b 100644 --- a/src/domains/platform/workflow/watch/pipeline-watcher.ts +++ b/src/domains/platform/workflow/watch/pipeline-watcher.ts @@ -2,7 +2,7 @@ import type { KyInstance } from "ky"; import { AuthenticationError } from "../../../../core/errors.js"; import * as api from "../api.js"; import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js"; -import { normalizeJobStatus, isJobTerminal } from "./helpers.js"; +import { normalizeJobStatus, isJobTerminal, shouldEmitWatchEvent } from "./helpers.js"; import { watchSingleJob } from "./single-job.js"; /** @@ -21,16 +21,7 @@ export async function watchWorkflowPipeline( const seenJobIds = new Set(); 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" && event.type !== "cancelled" - ) { - return; - } - } + if (!shouldEmitWatchEvent(event, options)) return; if (options.onEvent) { await options.onEvent(event); } diff --git a/src/domains/platform/workflow/watch/single-job.ts b/src/domains/platform/workflow/watch/single-job.ts index a820430..7204fdc 100644 --- a/src/domains/platform/workflow/watch/single-job.ts +++ b/src/domains/platform/workflow/watch/single-job.ts @@ -2,7 +2,7 @@ import type { KyInstance } from "ky"; import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js"; import * as api from "../api.js"; import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchEvent } from "./types.js"; -import { normalizeJobStatus, isJobTerminal } from "./helpers.js"; +import { normalizeJobStatus, isJobTerminal, shouldEmitWatchEvent } from "./helpers.js"; import { TaskExecutionTracker } from "./tracker.js"; /** @@ -20,16 +20,7 @@ export async function watchSingleJob( 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" && event.type !== "cancelled" - ) { - return; - } - } + if (!shouldEmitWatchEvent(event, options)) return; events.push(event); if (options.onEvent) { await options.onEvent(event);