refactor: 归整工作流执行与差异比较

This commit is contained in:
gitea committed 2026-10-30 17:48:22 +08:00
1 parent f4f34a83b4
commit c989e544e4
15 files changed
+41 -32

No files matched your search

@@ -0,0 +1,7 @@
# 工作流执行与调试
- [tree.ts](./tree.ts):执行树展开、失败识别和节点查找,也提供工作流任务树展开。
- [context.ts](./context.ts):构建执行实例索引,供条件解释与 Job 差异比较复用。
- [debug.ts](./debug.ts):调试输入、发起 Job、轮询和诊断汇总。
执行监听位于同级 [watch](../watch/README.watch.md),条件解释位于 `branch/`;HTTP 传输位于上级 `api.ts`。
@@ -0,0 +1,45 @@
import type { WorkflowTaskExecution } from "../types.js";
export interface ExecutionContext {
node: WorkflowTaskExecution;
key: string;
scope: string[];
loopPath: string;
}
/** Index real executions by parent task path, loop context and repeated occurrence. */
export function indexExecutionContexts(tree: WorkflowTaskExecution[]): ExecutionContext[] {
const result: ExecutionContext[] = [];
const entries = new Map<string, { node: WorkflowTaskExecution; parentId?: string }>();
const occurrences = new Map<string, number>();
function collect(node: WorkflowTaskExecution, parentId?: string) {
if (!node || !node.id || entries.has(node.id)) return;
entries.set(node.id, { node, parentId: String(node.parentId || parentId || "") || undefined });
for (const key of ["children", "subTasks", "items", "tasks"]) {
const children = node[key];
if (Array.isArray(children)) for (const child of children) collect(child, node.id);
}
}
for (const node of tree) collect(node);
const scopes = new Map<string, { parts: string[]; loopPath: string }>();
function scopeOf(id: string, visited = new Set<string>()): { parts: string[]; loopPath: string } {
const cached = scopes.get(id);
if (cached) return cached;
const entry = entries.get(id);
if (!entry || visited.has(id)) return { parts: [JSON.stringify(["unresolved-parent", id])], loopPath: "" };
visited.add(id);
const parent = entry.parentId ? scopeOf(entry.parentId, visited) : { parts: [], loopPath: "" };
const loopPath = String(entry.node.currentLoopPath ?? parent.loopPath);
const scope = { parts: [...parent.parts, JSON.stringify([entry.node.name || entry.node.type || "unnamed", loopPath])], loopPath };
scopes.set(id, scope);
return scope;
}
for (const { node } of entries.values()) {
const { parts, loopPath } = scopeOf(node.id);
const base = JSON.stringify(parts);
const occurrence = occurrences.get(base) ?? 0;
occurrences.set(base, occurrence + 1);
result.push({ node, key: `${base}#${occurrence}`, scope: parts.slice(0, -1), loopPath });
}
return result;
}
@@ -0,0 +1,151 @@
import * as api from "../api.js";
import { ValidationError } from "../../../../core/errors.js";
import { explainConditionBranches } from "../branch/index.js";
import { WorkflowJobDetail } from "../types.js";
import { extractFailureExecutions } from "./tree.js";
export function getWebhookInfo(...args: Parameters<typeof api.getWebhookInfo>) {
return api.getWebhookInfo(...args);
}
export function sampleWorkflowData(...args: Parameters<typeof api.sampleWorkflowData>) {
return api.sampleWorkflowData(...args);
}
export function getWorkflowDebugSource(...args: Parameters<typeof api.getWorkflowDebugSource>) {
return api.getWorkflowDebugSource(...args);
}
export function triggerWorkflowDebug(...args: Parameters<typeof api.triggerWorkflowDebug>) {
return api.triggerWorkflowDebug(...args);
}
export async function runWorkflowDebugTest(
client: import("ky").KyInstance,
pipelineId: string,
options: {
flowCodeOrId?: string;
data?: Record<string, any>;
triggerCategory?: import("../types.js").WorkflowTriggerCategory;
triggerType?: string;
triggerLabel?: string;
autoPublish?: boolean;
timeoutMs?: number;
pollIntervalMs?: number;
} = {}
): Promise<import("../types.js").WorkflowTestReport> {
if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) {
throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数");
}
let targetEntityId = options.flowCodeOrId ?? "";
const code = options.flowCodeOrId;
const isDirectCode = !code || code.includes("-") || code.startsWith("ID01");
if (code && !isDirectCode) {
try {
const source = await api.getWorkflowDebugSource(client, pipelineId, {
page: 1,
pageSize: 10,
keywords: code,
});
const matched = source.items.find(
(item) => item.id === code || (item as any).code === code || item.title?.includes(code) || (item as any).name?.includes(code)
);
if (matched) {
targetEntityId = matched.id;
}
} catch {
// 关键字搜索超时或失败时直接回退使用传入值
}
}
const jobId = await api.triggerWorkflowDebug(client, pipelineId, {
entityId: targetEntityId || undefined,
data: options.data,
autoPublish: options.autoPublish ?? false,
});
const timeoutMs = options.timeoutMs ?? 15000;
const pollIntervalMs = options.pollIntervalMs ?? 500;
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;
while (Date.now() - start < timeoutMs) {
try {
const job = await api.getJob(client, jobId);
finalJob = job;
if (terminal.has(jobState(job))) break;
} catch (error) {
// 任务刚创建可能存在短延时,继续轮询
const status = (error as { status?: number; response?: { status?: number } } | null)?.status
?? (error as { response?: { status?: number } } | null)?.response?.status;
if (status !== 404) {
recordError("job", error);
pollingFailed = true;
break;
}
}
await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(0, timeoutMs - (Date.now() - start)))));
}
if (!finalJob && !pollingFailed) {
try { finalJob = await api.getJob(client, jobId); }
catch (error) { recordError("job", error); pollingFailed = true; }
}
const timedOut = !pollingFailed && !terminal.has(jobState(finalJob));
const [treeResult, failuresResult] = await Promise.allSettled([
api.getJobExecutionTree(client, jobId),
api.getJobFailedExecutions(client, jobId),
]);
const tree = treeResult.status === "fulfilled" ? treeResult.value : [];
const failedItems = failuresResult.status === "fulfilled" ? failuresResult.value.items : [];
if (treeResult.status === "rejected") recordError("executionTree", treeResult.reason);
if (failuresResult.status === "rejected") recordError("failedExecutions", failuresResult.reason);
const rawFailed = extractFailureExecutions(tree, failedItems);
const diagnosticsComplete = diagnosticsErrors.length === 0;
const status = jobState(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 (status === "COMPLETED" && diagnosticsComplete) outcome = "completed";
const conditionDiagnoses = explainConditionBranches(tree);
return {
jobId,
pipelineId,
status,
outcome,
timedOut,
diagnosticsComplete,
diagnosticsErrors,
runType: finalJob?.runType || "DEBUG",
durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined,
targetEntityId,
triggerCategory: options.triggerCategory,
triggerType: options.triggerType,
triggerLabel: options.triggerLabel,
executionTree: tree,
failedExecutions: rawFailed,
conditionDiagnoses,
};
}
export async function getWorkflowSampleData(
client: import("ky").KyInstance,
pipelineId: string,
type = "webhook"
): Promise<import("../types.js").WorkflowSampleDataResult> {
return api.getWorkflowSampleData(client, pipelineId, type);
}
@@ -0,0 +1,81 @@
import { describe, expect, it } from "bun:test";
import type { KyInstance } from "ky";
import { z } from "zod";
import { AuthenticationError, EkbApiError } from "../../../../core/errors.js";
import { classifyCliError } from "../../../../cli/errors.js";
import { listRunningJobs, unwrap } from "../api.js";
import { watchWorkflowPipeline } from "../watch/pipeline-watcher.js";
const responding = (body: unknown) => ({ get: async () => Response.json(body) }) as unknown as KyInstance;
describe("running jobs response contract", () => {
for (const code of [401, 403, "401", "403"]) {
it(`rejects business authentication failure ${JSON.stringify(code)} before empty-data normalization`, async () => {
await expect(listRunningJobs(responding({ code, data: null, msg: "session expired" }), "wf"))
.rejects.toBeInstanceOf(AuthenticationError);
await expect(listRunningJobs(responding({ code, data: { id: "job" } }), "wf"))
.rejects.toBeInstanceOf(AuthenticationError);
});
}
it("preserves the API error category and server message for other business failures", async () => {
await expect(listRunningJobs(responding({ code: 500, data: null, errorMessage: "backend failed" }), "wf"))
.rejects.toMatchObject({ name: "EkbApiError", code: "EASO_API_ERROR", status: 500, message: expect.stringContaining("backend failed") });
});
it("preserves successful null, missing, single-job and array responses", async () => {
for (const body of [{ code: 200, data: null }, { code: 200 }, { data: [] }]) {
expect(await listRunningJobs(responding(body), "wf")).toEqual([]);
}
const single = await listRunningJobs(responding({ code: 200, data: { jobId: "job" } }), "wf");
expect(single.map((job) => job.id)).toEqual(["job"]);
const array = await listRunningJobs(responding({ code: "200", data: [{ id: "one" }, { id: "two" }] }), "wf");
expect(array.map((job) => job.id)).toEqual(["one", "two"]);
});
it("does not relax unwrap's nonempty-detail requirement", async () => {
await expect(unwrap(Response.json({ code: 200, data: null }), z.unknown())).rejects.toBeInstanceOf(EkbApiError);
await expect(unwrap(Response.json({ code: "401", data: [] }), z.array(z.unknown()))).rejects.toBeInstanceOf(AuthenticationError);
expect(await unwrap(Response.json({ code: 200, value: { id: "detail" } }), z.object({ id: z.string() })))
.toEqual({ id: "detail" });
});
});
describe("running job watcher error propagation", () => {
function watcherClient(running: unknown, otherFailure = false) {
let logCalls = 0;
const client = { get: async (path: string) => {
if (path === "api/easo/jobs/running") return Response.json(running);
if (path.endsWith("/log")) {
logCalls++;
return Response.json({ code: 200, data: { jobList: logCalls > 1 || otherFailure ? [{ jobId: "job", status: "COMPLETED" }] : [] } });
}
if (path.endsWith("/execution/level/failed")) return Response.json({ data: { items: [] } });
if (path.endsWith("/execution")) return Response.json({ data: [] });
if (path === "api/easo/jobs/job") return Response.json({ data: { id: "job", pipelineId: "wf", status: "COMPLETED" } });
return Response.json({ data: { id: "wf", label: "workflow" } });
} } as unknown as KyInstance;
return { client, logCalls: () => logCalls };
}
for (const once of [true, false]) {
it(`propagates running-job authentication failure in ${once ? "snapshot" : "continuous"} mode`, async () => {
const fixture = watcherClient({ code: 401, data: null });
try {
await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
throw new Error("watcher unexpectedly succeeded");
} catch (error) {
expect(error).toBeInstanceOf(AuthenticationError);
expect(classifyCliError(error).exitCode).toBe(11);
}
expect(fixture.logCalls()).toBe(once ? 0 : 1);
});
it(`retains non-authentication log fallback in ${once ? "snapshot" : "continuous"} mode`, async () => {
const fixture = watcherClient({ code: 500, data: null }, once);
const report = await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
expect(report.totalJobsWatched).toBe(1);
expect(report.jobs[0]?.jobId).toBe("job");
});
}
});
@@ -0,0 +1,135 @@
import { WorkflowTask, WorkflowTaskExecution } from "../types.js";
/**
* 递归扁平化执行树节点(展开 children / tasks / items 等嵌套数组)
*/
export function flattenExecutionTree(nodes: WorkflowTaskExecution[]): WorkflowTaskExecution[] {
const result: WorkflowTaskExecution[] = [];
function visit(node: any) {
if (!node || typeof node !== "object") return;
result.push(node as WorkflowTaskExecution);
const children = node.children || node.tasks || node.subTasks || node.items;
if (Array.isArray(children)) {
for (const child of children) {
visit(child);
}
}
}
for (const node of nodes) {
visit(node);
}
return result;
}
/**
* 精准判定某个节点是否执行异常或报错
*/
export function isTaskExecutionFailed(node: WorkflowTaskExecution): boolean {
if (!node) return false;
const anyNode = node as any;
if (node.error?.message || anyNode.errorMessage) return true;
if (node.status === "FAILED" || anyNode.state === "FAILED" || anyNode.state === 2) return true;
if (typeof anyNode.errorTaskCount === "number" && anyNode.errorTaskCount > 0) return true;
if (anyNode.outputs && typeof anyNode.outputs === "object" && anyNode.outputs.error) return true;
if (anyNode.output && typeof anyNode.output === "object" && anyNode.output.error) return true;
return false;
}
/**
* 提取并去重执行树中的全部异常失败节点
*/
export function extractFailureExecutions(
tree: WorkflowTaskExecution[],
failedItems: WorkflowTaskExecution[] = []
): WorkflowTaskExecution[] {
const flattened = flattenExecutionTree(tree);
const map = new Map<string, WorkflowTaskExecution>();
for (const item of failedItems) {
if (item?.id) {
map.set(item.id, item);
}
}
for (const node of flattened) {
if (node?.id && isTaskExecutionFailed(node)) {
const existing = map.get(node.id);
if (!existing) {
map.set(node.id, node);
} else {
map.set(node.id, {
...node,
...existing,
error: existing.error ?? node.error,
inputs: existing.inputs ?? (node as any).inputs,
outputs: existing.outputs ?? (node as any).outputs,
});
}
}
}
return Array.from(map.values());
}
/**
* 按 ID、name、displayName 或 label 查找节点
*/
export function findExecutionNode(
tree: WorkflowTaskExecution[],
query: string
): WorkflowTaskExecution | undefined {
const flattened = flattenExecutionTree(tree);
const q = query.trim().toLowerCase();
if (!q) return undefined;
// 1. 精确匹配 ID 或 name
const exact = flattened.find(
(n) =>
n.id?.toLowerCase() === q ||
n.name?.toLowerCase() === q ||
n.displayName?.toLowerCase() === q
);
if (exact) return exact;
// 2. 包含匹配 name、label、displayName
return flattened.find(
(n) =>
n.name?.toLowerCase().includes(q) ||
n.label?.toLowerCase().includes(q) ||
n.displayName?.toLowerCase().includes(q)
);
}
// ── 工作流快照与 Job 差异比对核心算法 ──────────────────────────────────────────
/**
* 递归展开工作流配置节点(包括 condition 与 every 内嵌的子节点)
*/
export function flattenWorkflowTasks(tasks?: WorkflowTask[] | null): WorkflowTask[] {
if (!tasks || !Array.isArray(tasks)) return [];
const result: WorkflowTask[] = [];
function walk(list: WorkflowTask[]) {
for (const t of list) {
if (!t) continue;
result.push(t);
if (Array.isArray(t.tasks) && t.tasks.length > 0) {
walk(t.tasks);
}
}
}
walk(tasks);
return result;
}
@@ -0,0 +1,78 @@
import { describe, expect, it } from "bun:test";
import { runWorkflowDebugTest } from "../services.js";
function setup(status = "COMPLETED", errors: string[] = []) {
const posts: string[] = [];
const response = (data: unknown) => new Response(JSON.stringify({ code: 200, data }));
const client = {
post: async (path: string) => { posts.push(path); return response("job"); },
get: async (path: string) => {
if (path.endsWith("/level/failed")) {
if (errors.includes("failures")) throw new Error("403 failures unavailable");
return response([]);
}
if (path.endsWith("/execution")) {
if (errors.includes("tree")) throw new Error("403 execution unavailable");
return response([]);
}
if (errors.includes("job")) throw new Error("403 job unavailable");
return response({ id: "job", status });
},
} as any;
return { client, posts };
}
describe("workflow debug completion evidence", () => {
it("reports completed only when all diagnostics were fetched", async () => {
const { client } = setup();
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
expect(result.outcome).toBe("completed");
expect(result.timedOut).toBe(false);
expect(result.diagnosticsComplete).toBe(true);
});
it("reports a failed terminal job", async () => {
const { client } = setup("FAILED");
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
expect(result.outcome).toBe("failed");
});
it("keeps timed-out jobs queryable and exposes missing diagnostic evidence", async () => {
const { client } = setup("RUNNING", ["tree", "failures"]);
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 0 });
expect(result.jobId).toBe("job");
expect(result.status).toBe("RUNNING");
expect(result.outcome).toBe("timed_out");
expect(result.timedOut).toBe(true);
expect(result.diagnosticsComplete).toBe(false);
expect(result.diagnosticsErrors.map(error => error.source)).toEqual(["executionTree", "failedExecutions"]);
});
it("marks partial diagnostic reads as incomplete rather than clean success", async () => {
const { client } = setup("COMPLETED", ["tree"]);
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
expect(result.outcome).toBe("incomplete");
expect(result.diagnosticsErrors[0]?.message).toContain("403");
});
it("preserves job identity when polling fails and does not hide the error", async () => {
const { client } = setup("RUNNING", ["job"]);
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
expect(result.jobId).toBe("job");
expect(result.outcome).toBe("incomplete");
expect(result.diagnosticsErrors[0]?.source).toBe("job");
});
it("rejects invalid timing options before creating a mutating job", async () => {
const { client, posts } = setup();
await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs");
expect(posts).toEqual([]);
});
it("retries a newly created job's HTTP 404 instead of reporting an authorization failure", async () => {
const { client } = setup();
const get = client.get;
let jobReads = 0;
client.get = async (path: string) => {
if (path.endsWith("/job") && jobReads++ === 0) throw { response: { status: 404 } };
return get(path);
};
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 100, pollIntervalMs: 1 });
expect(result.outcome).toBe("completed");
expect(jobReads).toBe(2);
});
});