Files
hose-use/src/domains/platform/workflow-state.test.ts
T

400 lines
15 KiB
TypeScript

import { describe, expect, it } from "bun:test";
import {
beginWorkflowSave,
applyWorkflowPathPatch,
commitWorkflowSave,
createWorkflowDraft,
failWorkflowSave,
hasWorkflowVersionConflict,
patchWorkflowDraft,
} from "./workflow-state.js";
import { WorkflowDetailSchema } from "./types.js";
import type { WorkflowDetail } from "./types.js";
import {
getExecutionLogs,
getJob,
getJobExecutionLevel,
getJobExecutionTree,
getJobFailedExecutions,
getWorkflowDetail,
listWorkflowSnapshots,
listWorkflowLogs,
toggleWorkflow,
updateWorkflow,
} from "./api.js";
import {
extractFailureExecutions,
findExecutionNode,
flattenExecutionTree,
isTaskExecutionFailed,
} from "./services.js";
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
import { WorkflowAlertStore } from "./workflow-alert-store.js";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
const workflow = (overrides: Partial<WorkflowDetail> = {}): WorkflowDetail => WorkflowDetailSchema.parse({
id: "wf-1",
label: "测试流程",
state: 0,
debugState: 0,
runTimes: 0,
errorTimes: 0,
updateTime: "",
version: "1",
dataLimit: 20,
source: 1,
queueJobs: false,
tasksVersion: 3,
tasks: [],
...overrides,
});
describe("workflow draft state machine", () => {
it("patches a nested node field without mutating the source snapshot", () => {
const source = workflow({ tasks: [{ name: "task-1", type: "code", label: "旧值", groupName: "", orderIndex: 0, levelIndex: [0], status: "ok", code: "return 1;" }] });
const patched = applyWorkflowPathPatch(source, "tasks[0].code", "return 2;");
expect(patched.tasks[0]?.code).toBe("return 2;");
expect(source.tasks[0]?.code).toBe("return 1;");
});
it("rejects a path whose parent does not exist", () => {
expect(() => applyWorkflowPathPatch(workflow(), "tasks.0.form.title", "x")).toThrow("路径不存在");
});
it("sends the complete workflow snapshot to the Piper update endpoint", async () => {
let request: { url: string; json: WorkflowDetail } | undefined;
const client = {
put: async (url: string, options: { json: WorkflowDetail }) => {
request = { url, json: options.json };
return { json: async () => ({ data: options.json }) };
},
} as any;
const input = workflow({ inputs: [{ key: "$platformId", value: "platform-1" }], "$snapshot": [{ key: "tasks.0", value: "{}" }] });
const result = await updateWorkflow(client, input);
expect(request?.url).toBe("api/easo/pipelines/wf-1");
expect(request?.json.inputs).toEqual([{ key: "$platformId", value: "platform-1" }]);
expect(result["$snapshot"]).toEqual([{ key: "tasks.0", value: "{}" }]);
});
it("reads snapshot history and accepts the web API's serialized inputs", async () => {
let request: { url: string; options: any } | undefined;
const client = {
get: async (url: string, options: any) => {
request = { url, options };
return new Response(JSON.stringify({ data: {
number: 1,
size: 10,
totalPages: 1,
totalItems: 1,
items: [{
id: "snapshot-1",
pipelineId: "wf-1",
platformId: "platform-1",
inputs: '[{"key":"$platformId","value":"platform-1"}]',
outputs: "[]",
version: "26.2.38",
}],
} }));
},
} as any;
const result = await listWorkflowSnapshots(client, "wf-1", 2, 5);
expect(request?.url).toBe("api/easo/pipelines/wf-1/snapshots");
expect(request?.options.searchParams).toEqual({ number: "2", pageSize: "5" });
expect(result.items[0]?.inputs).toContain("$platformId");
expect(result.items[0]?.version).toBe("26.2.38");
});
it("reads workflow logs with the web query contract", async () => {
let request: { url: string; options: any } | undefined;
const client = {
get: async (url: string, options: any) => {
request = { url, options };
return new Response(JSON.stringify({ data: { number: 1, size: 10, totalItems: 1, items: [{ id: "run-1", state: "FAILED", message: "测试错误" }] } }));
},
} as any;
const result = await listWorkflowLogs(client, "wf-1", { state: "FAILED", startTime: "2026-09-01", endTime: "2026-09-09" });
expect(request?.url).toBe("api/easo/pipelines/wf-1/log");
expect(request?.options.searchParams).toEqual({ state: "FAILED", number: "1", pageSize: "10", startTime: "2026-09-01", endTime: "2026-09-09" });
expect(result.items[0]?.message).toBe("测试错误");
});
it("uses the state endpoint for publishing a workflow", async () => {
let request: { url: string; options: any } | undefined;
const client = {
put: async (url: string, options: any) => {
request = { url, options };
return new Response(JSON.stringify({ code: 200, msg: "更新成功", data: null }), { status: 200 });
},
} as any;
const result = await toggleWorkflow(client, "wf-1", 1);
expect(result.success).toBe(true);
expect(request?.url).toBe("api/easo/pipelines/state/wf-1");
expect(request?.options.searchParams).toEqual({ state: "1" });
});
it("persists workflow alert fingerprints and only reports new counts", () => {
const dir = mkdtempSync("hose-workflow-alert-");
const file = join(dir, "alerts.json");
const store = new WorkflowAlertStore(file);
const alert = { id: "corp:platform:wf-1", pipelineId: "wf-1", platformId: "platform-1", pipelineName: "测试流程", errorCount: 1, state: 0, observedAt: 1 };
expect(store.observe([alert]).newAlerts).toHaveLength(1);
expect(store.observe([{ ...alert, observedAt: 2 }]).newAlerts).toHaveLength(0);
expect(store.observe([{ ...alert, errorCount: 2, observedAt: 3 }]).newAlerts).toHaveLength(1);
expect(store.observe([]).newAlerts).toHaveLength(0);
expect(store.observe([{ ...alert, observedAt: 4 }]).newAlerts).toHaveLength(1);
expect(JSON.parse(readFileSync(file, "utf8")).version).toBe(1);
rmSync(dir, { recursive: true, force: true });
});
it("tracks dirty revisions and commits the server snapshot", () => {
let state = createWorkflowDraft(workflow());
state = patchWorkflowDraft(state, (current) => ({ ...current, label: "已修改" }), ["label"]);
expect(state.status).toBe("dirty");
expect(state.revision).toBe(1);
expect(state.dirtyPaths).toEqual(["label"]);
state = beginWorkflowSave(state);
expect(state.status).toBe("saving");
state = commitWorkflowSave(state, workflow({ label: "已修改", tasksVersion: 4 }));
expect(state.status).toBe("saved");
expect(state.dirtyPaths).toEqual([]);
expect(state.baseTasksVersion).toBe(4);
});
it("detects optimistic concurrency conflicts and preserves failures", () => {
const state = createWorkflowDraft(workflow());
expect(hasWorkflowVersionConflict(state, workflow({ tasksVersion: 4 }))).toBe(true);
const failed = failWorkflowSave(beginWorkflowSave(patchWorkflowDraft(state, (current) => current)), "网络错误");
expect(failed.status).toBe("failed");
expect(failed.error).toBe("网络错误");
});
it("throws structured AuthenticationError or EkbApiError when Piper unwrap receives null data or non-200 code", async () => {
const unauthorizedClient = {
get: async () =>
new Response(JSON.stringify({ code: 401, message: "登录已过期", data: null }), {
status: 200,
}),
} as any;
await expect(getWorkflowDetail(unauthorizedClient, "wf-1")).rejects.toBeInstanceOf(AuthenticationError);
const nullDataClient = {
get: async () =>
new Response(JSON.stringify({ code: 200, msg: "pipeline not found", data: null }), {
status: 200,
}),
} as any;
await expect(getWorkflowDetail(nullDataClient, "wf-1")).rejects.toBeInstanceOf(EkbApiError);
});
it("calls the 5 Piper Job diagnostic endpoints and parses execution trees, failed nodes, child levels, and logs", async () => {
const client = {
get: async (url: string, options?: any) => {
if (url === "api/easo/jobs/892809886382563347") {
return new Response(
JSON.stringify({
code: 200,
data: {
id: "892809886382563347",
pipelineId: "886351399301758976",
label: "每30分钟创建采购申请单",
state: "COMPLETED",
successTaskCount: 5,
errorTaskCount: 1,
hasError: true,
},
})
);
}
if (url === "api/easo/jobs/892809886382563347/execution") {
return new Response(
JSON.stringify({
code: 200,
data: [
{
id: "892809893789696012",
jobId: "892809886382563347",
name: "every_0",
label: "循环",
type: "every",
state: "COMPLETED",
levelIndex: [0],
},
],
})
);
}
if (url === "api/easo/jobs/892809886382563347/execution/level/failed") {
return new Response(
JSON.stringify({
code: 200,
data: [
{
id: "892809900000000001",
jobId: "892809886382563347",
parentId: "892809893789696012",
name: "ekuaibao_flow_create_task_0",
label: "创建预付申请单",
type: "flow-create-task",
state: "FAILED",
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
outputs: { error: "我方签约主体未填写" },
},
],
})
);
}
if (url === "api/easo/jobs/892809886382563347/execution/level") {
expect(options?.searchParams).toEqual({
parentId: "892809893789696012",
number: "1",
pageSize: "20",
});
return new Response(
JSON.stringify({
code: 200,
data: {
number: 1,
size: 20,
totalPages: 1,
totalItems: 1,
items: [
[
{
id: "892809900000000001",
name: "ekuaibao_flow_create_task_0",
state: "FAILED",
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
outputs: { error: "我方签约主体未填写" },
},
],
],
},
})
);
}
if (url === "api/easo/executions/892809893789696012/logs") {
return new Response(
JSON.stringify({
code: 200,
data: {
total: 1,
items: [{ id: "log-1", message: "MVEL script executed", level: "INFO" }],
},
})
);
}
throw new Error(`Unexpected URL: ${url}`);
},
} as any;
const job = await getJob(client, "892809886382563347");
expect(job.hasError).toBe(true);
expect(job.errorTaskCount).toBe(1);
const tree = await getJobExecutionTree(client, "892809886382563347");
expect(tree).toHaveLength(1);
expect(tree[0]?.name).toBe("every_0");
const failed = await getJobFailedExecutions(client, "892809886382563347");
expect(failed.items).toHaveLength(1);
expect((failed.items[0]?.outputs as any)?.error).toBe("我方签约主体未填写");
const level = await getJobExecutionLevel(client, "892809886382563347", {
parentId: "892809893789696012",
});
expect(level.items).toHaveLength(1);
const logs = await getExecutionLogs(client, "892809893789696012");
expect(logs[0]?.message).toBe("MVEL script executed");
});
describe("execution tree inspection & failure extraction helpers", () => {
const mockTree: any[] = [
{
id: "node_1",
name: "start_node",
type: "start",
status: "COMPLETED",
children: [
{
id: "node_2",
name: "loop_node",
type: "loop",
status: "COMPLETED",
tasks: [
{
id: "node_3",
name: "approve_node",
displayName: "资金调拨自动审批",
type: "flow-approval",
status: "FAILED",
error: { message: "400: 无待办审批事项" },
inputs: { formId: "ZJ-001368", action: "agree" },
},
],
},
],
},
{
id: "node_4",
name: "notice_node",
displayName: "钉钉通知",
type: "dingtalk",
status: "COMPLETED",
},
];
it("flattenExecutionTree flattens nested children and tasks recursively", () => {
const flattened = flattenExecutionTree(mockTree);
expect(flattened).toHaveLength(4);
expect(flattened.map((n) => n.id)).toEqual(["node_1", "node_2", "node_3", "node_4"]);
});
it("isTaskExecutionFailed identifies various failure indicators", () => {
expect(isTaskExecutionFailed({ id: "1", type: "x", status: "FAILED" })).toBe(true);
expect(
isTaskExecutionFailed({
id: "2",
type: "x",
status: "RUNNING",
error: { message: "timeout", stackTrace: [] },
})
).toBe(true);
expect(isTaskExecutionFailed({ id: "3", type: "x", status: "OK", outputs: { error: "reject" } } as any)).toBe(true);
expect(isTaskExecutionFailed({ id: "4", type: "x", status: "COMPLETED" })).toBe(false);
});
it("extractFailureExecutions merges failures from tree and failed items without duplicates", () => {
const failedPageItems: any[] = [
{
id: "node_3",
name: "approve_node",
status: "FAILED",
outputs: { details: "failed downstream" },
},
];
const failures = extractFailureExecutions(mockTree, failedPageItems);
expect(failures).toHaveLength(1);
expect(failures[0].id).toBe("node_3");
expect(failures[0].error?.message).toBe("400: 无待办审批事项");
expect((failures[0] as any).inputs?.formId).toBe("ZJ-001368");
expect((failures[0] as any).outputs?.details).toBe("failed downstream");
});
it("findExecutionNode matches by id, exact name, or partial display name", () => {
const byId = findExecutionNode(mockTree, "node_3");
expect(byId?.id).toBe("node_3");
const byName = findExecutionNode(mockTree, "approve_node");
expect(byName?.id).toBe("node_3");
const byDisplayName = findExecutionNode(mockTree, "资金调拨");
expect(byDisplayName?.id).toBe("node_3");
const notFound = findExecutionNode(mockTree, "non_existent");
expect(notFound).toBeUndefined();
});
});
});