refactor(workflow): 收敛 Job 状态语义与监听事件过滤
同一份逻辑在两个地方各写一遍,必然在某次修改后漂移: - 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,说明状态语义的两个入口必须一起考虑。
This commit is contained in:
1 parent
a0058c1c66
commit
71aa9b54a7
7 files changed
+102
-48
No files matched your search
@@ -2,7 +2,15 @@
|
|||||||
|
|
||||||
- [tree.ts](./tree.ts):执行树展开、失败识别和节点查找,也提供工作流任务树展开。
|
- [tree.ts](./tree.ts):执行树展开、失败识别和节点查找,也提供工作流任务树展开。
|
||||||
- [context.ts](./context.ts):构建执行实例索引,供条件解释与 Job 差异比较复用。
|
- [context.ts](./context.ts):构建执行实例索引,供条件解释与 Job 差异比较复用。
|
||||||
|
- [job-status.ts](./job-status.ts):Job 状态归一化与终态判定,**watch 监听与 debug 轮询共用同一实现**。
|
||||||
- [debug.ts](./debug.ts):调试输入、发起 Job、轮询和诊断汇总。
|
- [debug.ts](./debug.ts):调试输入、发起 Job、轮询和诊断汇总。
|
||||||
- [queries.ts](./queries.ts):Job、执行树与日志读取服务出口。
|
- [queries.ts](./queries.ts):Job、执行树与日志读取服务出口。
|
||||||
|
|
||||||
执行监听位于同级 [watch](../watch/README.watch.md),条件解释位于 `branch/`;HTTP 传输位于上级 `api.ts`。
|
执行监听位于同级 [watch](../watch/README.watch.md),条件解释位于 `branch/`;HTTP 传输位于上级 `api.ts`。
|
||||||
|
|
||||||
|
## Job 状态语义
|
||||||
|
|
||||||
|
Job 可能只返回字符串 `status`,也可能只返回数字 `state`(0 完成、1 运行中、2 失败)。
|
||||||
|
归一化逻辑只在 `job-status.ts` 定义一次:过去 debug 侧自行判定时把 `state: 0` 当成未知而继续轮询,
|
||||||
|
watch 侧却视为已完成,同一个 Job 在两条路径上会得到相反的结论。
|
||||||
|
修改状态时必须同时考虑这两个入口,并在两侧补回归用例。
|
||||||
@@ -3,6 +3,7 @@ import { ValidationError } from "../../../../core/errors.js";
|
|||||||
import { explainConditionBranches } from "../branch/index.js";
|
import { explainConditionBranches } from "../branch/index.js";
|
||||||
import { WorkflowJobDetail } from "../types.js";
|
import { WorkflowJobDetail } from "../types.js";
|
||||||
import { extractFailureExecutions } from "./tree.js";
|
import { extractFailureExecutions } from "./tree.js";
|
||||||
|
import { normalizeJobStatus, isJobTerminal } from "./job-status.js";
|
||||||
|
|
||||||
|
|
||||||
export function getWebhookInfo(...args: Parameters<typeof api.getWebhookInfo>) {
|
export function getWebhookInfo(...args: Parameters<typeof api.getWebhookInfo>) {
|
||||||
@@ -74,8 +75,6 @@ export async function runWorkflowDebugTest(
|
|||||||
const start = Date.now();
|
const start = Date.now();
|
||||||
const diagnosticsErrors: Array<{ source: string; message: string }> = [];
|
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 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 finalJob: WorkflowJobDetail | undefined;
|
||||||
let pollingFailed = false;
|
let pollingFailed = false;
|
||||||
|
|
||||||
@@ -83,7 +82,7 @@ export async function runWorkflowDebugTest(
|
|||||||
try {
|
try {
|
||||||
const job = await api.getJob(client, jobId);
|
const job = await api.getJob(client, jobId);
|
||||||
finalJob = job;
|
finalJob = job;
|
||||||
if (terminal.has(jobState(job))) break;
|
if (isJobTerminal(normalizeJobStatus(job))) break;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// 任务刚创建可能存在短延时,继续轮询
|
// 任务刚创建可能存在短延时,继续轮询
|
||||||
const status = (error as { status?: number; response?: { status?: number } } | null)?.status
|
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); }
|
try { finalJob = await api.getJob(client, jobId); }
|
||||||
catch (error) { recordError("job", error); pollingFailed = true; }
|
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([
|
const [treeResult, failuresResult] = await Promise.allSettled([
|
||||||
api.getJobExecutionTree(client, jobId),
|
api.getJobExecutionTree(client, jobId),
|
||||||
api.getJobFailedExecutions(client, jobId),
|
api.getJobFailedExecutions(client, jobId),
|
||||||
@@ -113,11 +112,11 @@ export async function runWorkflowDebugTest(
|
|||||||
|
|
||||||
const rawFailed = extractFailureExecutions(tree, failedItems);
|
const rawFailed = extractFailureExecutions(tree, failedItems);
|
||||||
const diagnosticsComplete = diagnosticsErrors.length === 0;
|
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;
|
const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0;
|
||||||
let outcome: import("../types.js").WorkflowTestReport["outcome"] = "incomplete";
|
let outcome: import("../types.js").WorkflowTestReport["outcome"] = "incomplete";
|
||||||
if (timedOut) outcome = "timed_out";
|
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";
|
else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed";
|
||||||
const conditionDiagnoses = explainConditionBranches(tree);
|
const conditionDiagnoses = explainConditionBranches(tree);
|
||||||
|
|
||||||
|
|||||||
@@ -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<WorkflowJobDetail> | Record<string, unknown> | null): string {
|
||||||
|
if (!job) return "UNKNOWN";
|
||||||
|
const rawStatus = (job as Record<string, unknown>).status;
|
||||||
|
const rawState = (job as Record<string, unknown>).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());
|
||||||
|
}
|
||||||
@@ -63,6 +63,35 @@ describe("workflow debug completion evidence", () => {
|
|||||||
await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs");
|
await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs");
|
||||||
expect(posts).toEqual([]);
|
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 () => {
|
it("retries a newly created job's HTTP 404 instead of reporting an authorization failure", async () => {
|
||||||
const { client } = setup();
|
const { client } = setup();
|
||||||
const get = client.get;
|
const get = client.get;
|
||||||
|
|||||||
@@ -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<WorkflowJobDetail> | Record<string, unknown> | null): string {
|
/**
|
||||||
if (!job) return "UNKNOWN";
|
* `--failed-only` 的事件过滤。此前的实现在两个监听入口各写了一份且逐字相同,
|
||||||
const rawStatus = (job as any).status;
|
* 任一侧漏改都会让两种监听模式给出不同的结果。
|
||||||
const rawState = (job as any).state;
|
*/
|
||||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
export function shouldEmitWatchEvent(
|
||||||
const s = rawStatus.trim().toUpperCase();
|
event: WorkflowWatchEvent,
|
||||||
if (s === "STARTED") return "RUNNING";
|
options: Pick<WatchWorkflowOptions, "failedOnly">
|
||||||
return s;
|
): boolean {
|
||||||
}
|
if (!options.failedOnly) return true;
|
||||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
return (
|
||||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
event.type === "task_failed" ||
|
||||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
(event.type === "task_skipped" && Boolean(event.error)) ||
|
||||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
event.type === "job_completed" ||
|
||||||
return "UNKNOWN";
|
event.type === "timeout" ||
|
||||||
}
|
event.type === "cancelled"
|
||||||
|
);
|
||||||
export function isJobTerminal(status: string): boolean {
|
|
||||||
return TERMINAL_STATES.has(status.toUpperCase());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
|
|||||||
import { AuthenticationError } from "../../../../core/errors.js";
|
import { AuthenticationError } from "../../../../core/errors.js";
|
||||||
import * as api from "../api.js";
|
import * as api from "../api.js";
|
||||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.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";
|
import { watchSingleJob } from "./single-job.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -21,16 +21,7 @@ export async function watchWorkflowPipeline(
|
|||||||
const seenJobIds = new Set<string>();
|
const seenJobIds = new Set<string>();
|
||||||
|
|
||||||
const emit = async (event: WorkflowWatchEvent) => {
|
const emit = async (event: WorkflowWatchEvent) => {
|
||||||
if (options.failedOnly) {
|
if (!shouldEmitWatchEvent(event, options)) return;
|
||||||
if (
|
|
||||||
event.type !== "task_failed" &&
|
|
||||||
!(event.type === "task_skipped" && event.error) &&
|
|
||||||
event.type !== "job_completed" &&
|
|
||||||
event.type !== "timeout" && event.type !== "cancelled"
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (options.onEvent) {
|
if (options.onEvent) {
|
||||||
await options.onEvent(event);
|
await options.onEvent(event);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
|
|||||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
|
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
|
||||||
import * as api from "../api.js";
|
import * as api from "../api.js";
|
||||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchEvent } from "./types.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";
|
import { TaskExecutionTracker } from "./tracker.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,16 +20,7 @@ export async function watchSingleJob(
|
|||||||
const events: WorkflowWatchEvent[] = [];
|
const events: WorkflowWatchEvent[] = [];
|
||||||
|
|
||||||
const emit = async (event: WorkflowWatchEvent) => {
|
const emit = async (event: WorkflowWatchEvent) => {
|
||||||
if (options.failedOnly) {
|
if (!shouldEmitWatchEvent(event, options)) return;
|
||||||
if (
|
|
||||||
event.type !== "task_failed" &&
|
|
||||||
!(event.type === "task_skipped" && event.error) &&
|
|
||||||
event.type !== "job_completed" &&
|
|
||||||
event.type !== "timeout" && event.type !== "cancelled"
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
events.push(event);
|
events.push(event);
|
||||||
if (options.onEvent) {
|
if (options.onEvent) {
|
||||||
await options.onEvent(event);
|
await options.onEvent(event);
|
||||||
|
|||||||
Reference in new issue
Block a user