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,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);
}