feat: add workflow lifecycle controls and monitoring
This commit is contained in:
1 parent
9f9f3abe22
commit
0cdd62161f
16 files changed
+778
-20
No files matched your search
@@ -6,6 +6,8 @@ import {
|
||||
WorkflowStatsSchema,
|
||||
WorkflowChargeSchema,
|
||||
WorkflowDetailSchema,
|
||||
WorkflowSnapshotPageSchema,
|
||||
WorkflowLogPageSchema,
|
||||
WorkflowJobSchema,
|
||||
WorkflowDslSchema,
|
||||
StaffSchema,
|
||||
@@ -84,6 +86,53 @@ export async function getWorkflowDetail(
|
||||
return unwrap(response, WorkflowDetailSchema);
|
||||
}
|
||||
|
||||
// ── 工作流草稿保存(Piper)───────────────────────────────────────────────────
|
||||
// Web 端“保存更新”会把完整 pipeline 原样 PUT 回服务端;节点不是独立资源。
|
||||
export async function updateWorkflow(
|
||||
client: KyInstance,
|
||||
workflow: import("./types.js").WorkflowDetail
|
||||
): Promise<import("./types.js").WorkflowDetail> {
|
||||
const response = await client.put(`api/easo/pipelines/${workflow.id}`, {
|
||||
json: workflow,
|
||||
});
|
||||
return unwrap(response, WorkflowDetailSchema);
|
||||
}
|
||||
|
||||
export async function listWorkflowSnapshots(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
page: number = 1,
|
||||
pageSize: number = 10
|
||||
): Promise<import("./types.js").WorkflowSnapshotPage> {
|
||||
const response = await client.get(`api/easo/pipelines/${pipelineId}/snapshots`, {
|
||||
searchParams: { number: String(page), pageSize: String(pageSize) },
|
||||
});
|
||||
return unwrap(response, WorkflowSnapshotPageSchema);
|
||||
}
|
||||
|
||||
export async function listWorkflowLogs(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
options: {
|
||||
state?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
} = {},
|
||||
): Promise<import("./types.js").WorkflowLogPage> {
|
||||
const response = await client.get(`api/easo/pipelines/${pipelineId}/log`, {
|
||||
searchParams: {
|
||||
state: options.state ?? "",
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 10),
|
||||
...(options.startTime ? { startTime: options.startTime } : {}),
|
||||
...(options.endTime ? { endTime: options.endTime } : {}),
|
||||
},
|
||||
});
|
||||
return unwrap(response, WorkflowLogPageSchema);
|
||||
}
|
||||
|
||||
// ── 工作流启停(Piper)────────────────────────────────────────────────────────
|
||||
|
||||
export async function toggleWorkflow(
|
||||
|
||||
@@ -283,8 +283,52 @@ export const WorkflowDetailSchema = z.object({
|
||||
tasksVersion: z.number().default(0),
|
||||
tasks: z.array(WorkflowTaskSchema).default([]),
|
||||
alarm: WorkflowAlarmSchema.optional(),
|
||||
inputs: z.array(z.object({ key: z.string(), value: z.any() })).optional(),
|
||||
"$snapshot": z.array(z.object({ key: z.string(), value: z.string() })).optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const WorkflowSnapshotSchema = z.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string(),
|
||||
corporationId: z.string().default(""),
|
||||
platformId: z.string().default(""),
|
||||
triggerKey: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
tasks: z.array(WorkflowTaskSchema).nullable().optional(),
|
||||
inputs: z.union([z.string(), z.array(z.any())]).default("[]"),
|
||||
outputs: z.union([z.string(), z.array(z.any())]).default("[]"),
|
||||
retry: z.number().default(0),
|
||||
state: z.number().default(0),
|
||||
debugState: z.number().default(0),
|
||||
staffId: z.string().nullable().optional(),
|
||||
staffName: z.string().nullable().optional(),
|
||||
createTime: z.string().default(""),
|
||||
updateTime: z.string().default(""),
|
||||
version: z.string().default(""),
|
||||
}).passthrough();
|
||||
|
||||
export const WorkflowSnapshotPageSchema = z.object({
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(10),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
items: z.array(WorkflowSnapshotSchema).default([]),
|
||||
});
|
||||
|
||||
export const WorkflowLogItemSchema = z.record(z.string(), z.any());
|
||||
|
||||
export const WorkflowLogPageSchema = z.object({
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(10),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
items: z.array(WorkflowLogItemSchema).default([]),
|
||||
executeCount: z.number().default(0),
|
||||
successCount: z.number().default(0),
|
||||
errorCount: z.number().default(0),
|
||||
jobList: z.array(WorkflowLogItemSchema).default([]),
|
||||
}).passthrough();
|
||||
|
||||
export const WorkflowChargeSchema = z.object({
|
||||
corporationId: z.string().default(""),
|
||||
status: z.string().default(""),
|
||||
@@ -373,6 +417,10 @@ export type WorkflowPage = z.infer<typeof WorkflowPageSchema>;
|
||||
export type WorkflowStats = z.infer<typeof WorkflowStatsSchema>;
|
||||
export type WorkflowAlarm = z.infer<typeof WorkflowAlarmSchema>;
|
||||
export type WorkflowDetail = z.infer<typeof WorkflowDetailSchema>;
|
||||
export type WorkflowSnapshot = z.infer<typeof WorkflowSnapshotSchema>;
|
||||
export type WorkflowSnapshotPage = z.infer<typeof WorkflowSnapshotPageSchema>;
|
||||
export type WorkflowLogItem = z.infer<typeof WorkflowLogItemSchema>;
|
||||
export type WorkflowLogPage = z.infer<typeof WorkflowLogPageSchema>;
|
||||
export type WorkflowCharge = z.infer<typeof WorkflowChargeSchema>;
|
||||
export type WorkflowJob = z.infer<typeof WorkflowJobSchema>;
|
||||
export type WorkflowDsl = z.infer<typeof WorkflowDslSchema>;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
export interface WorkflowErrorAlert {
|
||||
id: string;
|
||||
pipelineId: string;
|
||||
platformId: string;
|
||||
pipelineName: string;
|
||||
errorCount: number;
|
||||
state: number;
|
||||
observedAt: number;
|
||||
}
|
||||
|
||||
interface PersistedAlerts {
|
||||
version: 1;
|
||||
alerts: Record<string, { errorCount: number; lastSeen: number }>;
|
||||
}
|
||||
|
||||
export interface WorkflowAlertCheckResult {
|
||||
activeAlerts: WorkflowErrorAlert[];
|
||||
newAlerts: WorkflowErrorAlert[];
|
||||
}
|
||||
|
||||
/** 本地持久化工作流错误指纹,避免定时检查时重复提醒同一错误计数。 */
|
||||
export class WorkflowAlertStore {
|
||||
constructor(private readonly filePath: string) {}
|
||||
|
||||
private read(): PersistedAlerts {
|
||||
if (!existsSync(this.filePath)) return { version: 1, alerts: {} };
|
||||
try {
|
||||
const value = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedAlerts>;
|
||||
return { version: 1, alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {} };
|
||||
} catch {
|
||||
return { version: 1, alerts: {} };
|
||||
}
|
||||
}
|
||||
|
||||
observe(alerts: WorkflowErrorAlert[]): WorkflowAlertCheckResult {
|
||||
const data = this.read();
|
||||
const activeIds = new Set(alerts.map((alert) => alert.id));
|
||||
const newAlerts = alerts.filter((alert) => data.alerts[alert.id]?.errorCount !== alert.errorCount);
|
||||
const updated = { ...data.alerts };
|
||||
for (const id of Object.keys(updated)) {
|
||||
if (!activeIds.has(id)) delete updated[id];
|
||||
}
|
||||
for (const alert of alerts) updated[alert.id] = { errorCount: alert.errorCount, lastSeen: alert.observedAt };
|
||||
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`, { mode: 0o600 });
|
||||
return { activeAlerts: alerts, newAlerts };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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 { listWorkflowSnapshots, listWorkflowLogs, toggleWorkflow, updateWorkflow } from "./api.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("网络错误");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
|
||||
export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "failed";
|
||||
|
||||
export interface WorkflowDraftState {
|
||||
workflow: WorkflowDetail;
|
||||
baseVersion: string;
|
||||
baseTasksVersion: number;
|
||||
revision: number;
|
||||
status: WorkflowDraftStatus;
|
||||
dirtyPaths: string[];
|
||||
lastSavedAt?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function pathParts(path: string): string[] {
|
||||
const parts = path
|
||||
.replace(/\[(\d+)\]/g, ".$1")
|
||||
.split(".")
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
if (!parts.length) throw new Error("工作流配置路径不能为空");
|
||||
if (parts.some((part) => !/^[A-Za-z_$][\w$-]*$/.test(part) && !/^\d+$/.test(part))) {
|
||||
throw new Error(`工作流配置路径非法: ${path}`);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在完整 pipeline 草稿上做局部修改。这里只改本地对象,不触发网络请求;
|
||||
* 远端持久化统一交给 workflow save,避免绕过版本保护直接写服务端。
|
||||
*/
|
||||
export function applyWorkflowPathPatch(
|
||||
workflow: WorkflowDetail,
|
||||
path: string,
|
||||
value: unknown,
|
||||
): WorkflowDetail {
|
||||
const parts = pathParts(path);
|
||||
const patched = structuredClone(workflow) as Record<string, any>;
|
||||
let cursor: any = patched;
|
||||
for (const part of parts.slice(0, -1)) {
|
||||
if (cursor === null || typeof cursor !== "object" || !(part in cursor)) {
|
||||
throw new Error(`工作流配置路径不存在: ${path}`);
|
||||
}
|
||||
cursor = cursor[part];
|
||||
}
|
||||
if (cursor === null || typeof cursor !== "object") {
|
||||
throw new Error(`工作流配置路径不可写: ${path}`);
|
||||
}
|
||||
cursor[parts.at(-1)!] = value;
|
||||
return patched as WorkflowDetail;
|
||||
}
|
||||
|
||||
export function createWorkflowDraft(workflow: WorkflowDetail): WorkflowDraftState {
|
||||
return {
|
||||
workflow,
|
||||
baseVersion: workflow.version,
|
||||
baseTasksVersion: workflow.tasksVersion,
|
||||
revision: 0,
|
||||
status: "clean",
|
||||
dirtyPaths: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function patchWorkflowDraft(
|
||||
state: WorkflowDraftState,
|
||||
update: (workflow: WorkflowDetail) => WorkflowDetail,
|
||||
dirtyPaths: string[] = ["*"]
|
||||
): WorkflowDraftState {
|
||||
return {
|
||||
...state,
|
||||
workflow: update(state.workflow),
|
||||
revision: state.revision + 1,
|
||||
status: "dirty",
|
||||
dirtyPaths: [...new Set([...state.dirtyPaths, ...dirtyPaths])],
|
||||
error: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function beginWorkflowSave(state: WorkflowDraftState): WorkflowDraftState {
|
||||
if (state.status !== "dirty" && state.status !== "failed") return state;
|
||||
return { ...state, status: "saving", error: undefined };
|
||||
}
|
||||
|
||||
export function commitWorkflowSave(
|
||||
state: WorkflowDraftState,
|
||||
savedWorkflow: WorkflowDetail
|
||||
): WorkflowDraftState {
|
||||
return {
|
||||
...state,
|
||||
workflow: savedWorkflow,
|
||||
baseVersion: savedWorkflow.version,
|
||||
baseTasksVersion: savedWorkflow.tasksVersion,
|
||||
status: "saved",
|
||||
dirtyPaths: [],
|
||||
lastSavedAt: new Date().toISOString(),
|
||||
error: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function failWorkflowSave(
|
||||
state: WorkflowDraftState,
|
||||
error: unknown
|
||||
): WorkflowDraftState {
|
||||
return {
|
||||
...state,
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
|
||||
export function hasWorkflowVersionConflict(
|
||||
draft: WorkflowDraftState,
|
||||
remote: WorkflowDetail
|
||||
): boolean {
|
||||
return draft.baseTasksVersion !== remote.tasksVersion || draft.baseVersion !== remote.version;
|
||||
}
|
||||
Reference in new issue
Block a user