Merge pull request #116 from yunyingk/refactor/platform-workflow-submodules
refactor(platform): organize workflow capabilities into structured submodules
This commit is contained in:
36 files changed
+2539
-2472
No files matched your search
@@ -8,11 +8,17 @@ Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能
|
||||
src/domains/platform/
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
├── workflow-nodes.ts # 节点树展平、树形索引定位、声明式增删改与索引重排 SDK
|
||||
├── workflow-watch.ts # 实时任务监听、增量状态跃迁追踪与执行日志流引擎
|
||||
├── workflow-script.ts# 脚本静态语法分析 (JS/MVEL)、AST 括号校验、上游依赖扫描与离线沙箱仿真引擎
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
├── services.ts # 门面聚合与对外服务导出
|
||||
├── workflow/ # 工作流体系子域(高内聚分层架构)
|
||||
│ ├── index.ts # 工作流能力统合导出
|
||||
│ ├── watch/ # 实时任务监听、TaskExecutionTracker 状态机与日志流 (tracker, engine, formatter)
|
||||
│ ├── nodes/ # 声明式节点树编排、树形索引定位、插入追加与重排 (tree, locator, mutations)
|
||||
│ ├── script/ # 脚本 AST 语法校验、上游依赖扫描与隔离沙箱仿真引擎 (lint, scanner, sandbox)
|
||||
│ ├── branch/ # 条件分支与规则解释诊断引擎 (explain, types)
|
||||
│ ├── analysis/ # 工作流静态吞错、禁用状态与联动覆盖巡检 (analyzer, types)
|
||||
│ ├── state/ # 草稿版本状态机与发布乐观锁保护
|
||||
│ └── alert/ # 错误指纹告警与 SQLite 本地持久化
|
||||
└── tools.ts # MCP tool 注册
|
||||
```
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
@@ -1,442 +1 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
export interface WorkflowAstNode {
|
||||
type: string;
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
children: WorkflowAstNode[];
|
||||
}
|
||||
|
||||
export interface WorkflowDependency {
|
||||
path: string;
|
||||
taskType: string;
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
name?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
isLinkageAssignment?: boolean;
|
||||
assignmentRule?: string | null;
|
||||
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
||||
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecLike {
|
||||
id: string;
|
||||
name?: string;
|
||||
components?: WorkflowFormSpecComponentLike[];
|
||||
}
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
}
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
"crontab",
|
||||
"clock",
|
||||
"condition",
|
||||
"every",
|
||||
"stop",
|
||||
"http",
|
||||
"flow-detail",
|
||||
"code",
|
||||
"code-js2",
|
||||
"ekuaibao-datalink-filter",
|
||||
"ekuaibao-datalink-create",
|
||||
"ekuaibao-datalink-edit",
|
||||
"ekuaibao-datalink-delete",
|
||||
"ekuaibao-flowform-trigger",
|
||||
"ekuaibao-ebot-trigger",
|
||||
"ekuaibao-datalink-create-trigger",
|
||||
"ekuaibao-datalink-time-trigger",
|
||||
"ekuaibao-datalink-edit-trigger",
|
||||
"ekuaibao-datalink-delete-trigger",
|
||||
"data-convert",
|
||||
"flow-create-task",
|
||||
]);
|
||||
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [
|
||||
...code.matchAll(
|
||||
/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g
|
||||
),
|
||||
]
|
||||
.map((match) => (match[1] || match[2] || "").trim())
|
||||
.filter(Boolean);
|
||||
return [...new Set(values)];
|
||||
}
|
||||
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] {
|
||||
return tasks.map((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
return {
|
||||
type: task.type,
|
||||
name: task.name,
|
||||
label: task.label || task.displayName || "",
|
||||
path,
|
||||
orderIndex: task.orderIndex,
|
||||
levelIndex: task.levelIndex,
|
||||
children: toAst(task.tasks || [], path),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getTaskSpecificationId(task: WorkflowTask): string | undefined {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (typeof raw.specificationId === "string" && raw.specificationId.trim()) {
|
||||
return raw.specificationId.trim();
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const found = task.inputs.find((item) => item.key === "specificationId");
|
||||
if (found && typeof found.value === "string" && found.value.trim()) {
|
||||
return found.value.trim();
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const specId = (raw.inputs as Record<string, unknown>).specificationId;
|
||||
if (typeof specId === "string" && specId.trim()) {
|
||||
return specId.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getTaskFormEntries(
|
||||
task: WorkflowTask
|
||||
): Array<{ key?: string; label?: string; type?: string; value?: unknown }> {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (Array.isArray(raw.form)) {
|
||||
return raw.form.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (raw.form && typeof raw.form === "object") {
|
||||
return Object.entries(raw.form as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const formInput = task.inputs.find((item) => item.key === "form");
|
||||
if (formInput && Array.isArray(formInput.value)) {
|
||||
return formInput.value.filter(
|
||||
(item: unknown): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formInput && formInput.value && typeof formInput.value === "object") {
|
||||
return Object.entries(formInput.value as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const formVal = (raw.inputs as Record<string, unknown>).form;
|
||||
if (Array.isArray(formVal)) {
|
||||
return formVal.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formVal && typeof formVal === "object") {
|
||||
return Object.entries(formVal as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
||||
const ids = new Set<string>();
|
||||
const walk = (tasks: WorkflowTask[]) => {
|
||||
for (const task of tasks) {
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
if (specId) ids.add(specId);
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
walk(task.tasks);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(detail.tasks || []);
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
||||
if (task.type !== "condition") return false;
|
||||
const raw = task as Record<string, unknown>;
|
||||
const filterSource = raw.combineFilters ?? raw.filters ?? task.inputs ?? raw.conditions ?? {};
|
||||
const serialized = JSON.stringify(filterSource);
|
||||
if (
|
||||
serialized.includes(`${targetTaskName}.$status`) ||
|
||||
serialized.includes(`${targetTaskName}.status`) ||
|
||||
serialized.includes(`${targetTaskName}.result`) ||
|
||||
serialized.includes(`${targetTaskName}.data`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
serialized.includes(targetTaskName) &&
|
||||
(serialized.includes("$status") || serialized.includes("是否运行成功"))
|
||||
);
|
||||
}
|
||||
|
||||
function findUnguardedDatalinkEdits(
|
||||
tasks: WorkflowTask[],
|
||||
basePath: string,
|
||||
createTaskName: string
|
||||
): Array<{ task: WorkflowTask; path: string }> {
|
||||
const found: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
tasks.forEach((task, idx) => {
|
||||
const path = `${basePath}.${idx}`;
|
||||
if (task.type === "ekuaibao-datalink-edit") {
|
||||
found.push({ task, path });
|
||||
return;
|
||||
}
|
||||
if (taskGuardsStatusOf(task, createTaskName)) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
found.push(...findUnguardedDatalinkEdits(task.tasks, path, createTaskName));
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
export function analyzeWorkflow(
|
||||
detail: WorkflowDetail,
|
||||
options: AnalyzeWorkflowOptions = {}
|
||||
): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks);
|
||||
const dependencies: WorkflowDependency[] = [];
|
||||
const diagnostics: WorkflowDiagnostic[] = [];
|
||||
|
||||
if (detail.state === 0) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "WORKFLOW_DISABLED",
|
||||
path: "workflow",
|
||||
message:
|
||||
"工作流当前处于未启用/草稿状态 (state=0),修改或排障后需 publish/toggle --state=1 方可生效",
|
||||
});
|
||||
}
|
||||
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
||||
tasks.forEach((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
const refs = referencesFromTask(task);
|
||||
if (refs.length) {
|
||||
dependencies.push({ path, taskType: task.type, references: refs });
|
||||
}
|
||||
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "EMPTY_CODE",
|
||||
path,
|
||||
message: "代码节点没有可执行脚本",
|
||||
});
|
||||
}
|
||||
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "EMPTY_BRANCH",
|
||||
path,
|
||||
message: `${task.type} 控制节点没有子节点`,
|
||||
});
|
||||
}
|
||||
if (!KNOWN_TYPES.has(task.type)) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNKNOWN_TASK_TYPE",
|
||||
path,
|
||||
message: `未收录的节点类型: ${task.type}`,
|
||||
});
|
||||
}
|
||||
|
||||
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
||||
if (insideEvery && task.type === "flow-create-task") {
|
||||
const onError = (task as Record<string, unknown>).onError as
|
||||
| { defaultAction?: string }
|
||||
| undefined;
|
||||
if (onError?.defaultAction === "SKIP") {
|
||||
const subsequentSiblings = tasks.slice(index + 1);
|
||||
const unguardedEdits: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
subsequentSiblings.forEach((sibling, relIdx) => {
|
||||
const siblingIndex = index + 1 + relIdx;
|
||||
const siblingPath = parentPath ? `${parentPath}.${siblingIndex}` : String(siblingIndex);
|
||||
if (sibling.type === "ekuaibao-datalink-edit") {
|
||||
unguardedEdits.push({ task: sibling, path: siblingPath });
|
||||
} else if (!taskGuardsStatusOf(sibling, task.name) && sibling.tasks?.length) {
|
||||
unguardedEdits.push(
|
||||
...findUnguardedDatalinkEdits(sibling.tasks, siblingPath, task.name)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
for (const edit of unguardedEdits) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
||||
path: edit.path,
|
||||
message: `节点 [${task.label || task.name}] (${task.name}) 配置了报错跳过(SKIP),但后续台账更新节点 [${edit.task.label || edit.task.name}] (${edit.task.name}) 未校验其执行状态(如 ${task.name}.$status),前序建单失败时仍会误改台账状态!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 3: flow-create-task 表单字段联动覆盖告警 (LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN)
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
const spec = specId ? options.specifications?.[specId] : undefined;
|
||||
const formEntries = getTaskFormEntries(task).filter(
|
||||
(entry) =>
|
||||
entry.value !== undefined &&
|
||||
entry.value !== null &&
|
||||
String(entry.value).trim() !== ""
|
||||
);
|
||||
|
||||
const specComponents =
|
||||
spec?.components ??
|
||||
(Array.isArray((spec as unknown as Record<string, unknown> | undefined)?.form)
|
||||
? ((spec as unknown as Record<string, unknown>).form as WorkflowFormSpecComponentLike[])
|
||||
: []);
|
||||
|
||||
if (spec && specComponents.length && formEntries.length > 0) {
|
||||
const matchedComponents = specComponents.filter((comp) => {
|
||||
const compKey = comp.name || comp.field || "";
|
||||
return formEntries.some(
|
||||
(entry) =>
|
||||
(Boolean(compKey) && entry.key === compKey) ||
|
||||
(Boolean(entry.label) && Boolean(comp.label) && entry.label === comp.label)
|
||||
);
|
||||
});
|
||||
|
||||
const linkageSources = matchedComponents.filter(
|
||||
(comp) =>
|
||||
Boolean(comp.assignmentRule) ||
|
||||
(comp.type === "dataLink" && comp.isLinkageAssignment === true)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
const srcKey = src.name || src.field || src.label || "";
|
||||
const overrideTargets = matchedComponents
|
||||
.filter((comp) => (comp.name || comp.field || comp.label || "") !== srcKey)
|
||||
.map((comp) => {
|
||||
const list = comp.priorityList || comp.priority || [];
|
||||
const linkage = list.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = list.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
const linkagePriority = linkage?.priority ?? linkage?.value;
|
||||
const manualPriority = manual?.priority ?? manual?.value;
|
||||
if (
|
||||
linkagePriority !== undefined &&
|
||||
manualPriority !== undefined &&
|
||||
linkagePriority > manualPriority
|
||||
) {
|
||||
return {
|
||||
comp,
|
||||
compKey: comp.name || comp.field || comp.label || "",
|
||||
linkagePriority,
|
||||
manualPriority,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
||||
|
||||
if (overrideTargets.length > 0) {
|
||||
const affectedDesc = overrideTargets
|
||||
.map(
|
||||
(t) =>
|
||||
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
||||
)
|
||||
.join("、");
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "LINKAGE_PRIORITY_OVERRIDE",
|
||||
path,
|
||||
message: `表单模板 [${spec.name || spec.id}] 中字段 [${src.label || srcKey}] (${srcKey}) 存在业务对象联动配置 (isLinkageAssignment=${Boolean(src.isLinkageAssignment)}, assignmentRule=${src.assignmentRule || "-"}),且当前节点同时传入了 [${affectedDesc}],联动赋值优先级高于手动/API 传入,显式传入的值可能被关联对象中的字段值覆盖!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 4: 触发器节点配置了无效的单据审批状态过滤 (DEADLOCK_TRIGGER_STATE_FILTER)
|
||||
if (
|
||||
(task.type === "ekuaibao-flowform-trigger" || task.type === "ekuaibao-ebot-trigger") &&
|
||||
(task as Record<string, unknown>).combineFilters
|
||||
) {
|
||||
const rawFilters = JSON.stringify((task as Record<string, unknown>).combineFilters);
|
||||
if (
|
||||
rawFilters.includes('"key":"state"') &&
|
||||
(rawFilters.includes('"APPROVING"') || rawFilters.includes('"approving"'))
|
||||
) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "DEADLOCK_TRIGGER_STATE_FILTER",
|
||||
path,
|
||||
message: `触发器节点 [${task.label || task.name}] (${task.name}) 配置了 state == APPROVING 状态过滤条件。合思单据审批出站事件属于动作事件(如 backlog.approving),事件载荷中不携带大写 APPROVING 状态字段,该过滤会导致出站事件被 100% 静默丢弃,下游审批流程永久无法触发!建议移除 state 过滤,改用后置条件节点判断审批人。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 5: HTTP 自动审批节点 URL 与中括号校验 (MISSING_BACKLOG_DATA_BRACKETS)
|
||||
if (task.type === "http") {
|
||||
const url = String((task as Record<string, unknown>).url || "");
|
||||
if (url.includes("api/openapi/v1/backlog/data")) {
|
||||
const match = url.match(/api\/openapi\/v1\/backlog\/data\/([^?#]+)/);
|
||||
const segment = match ? match[1] : "";
|
||||
if (segment && (!segment.startsWith("[") || !segment.includes("]"))) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "MISSING_BACKLOG_DATA_BRACKETS",
|
||||
path,
|
||||
message: `HTTP 自动审批节点 [${task.label || task.name}] 的 URL 路径参数缺少合思 OpenAPI 规范的方括号(规范要求: /api/openapi/v1/backlog/data/[{flowId}]),缺少方括号将导致服务端直接返回 404 Not Found。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
});
|
||||
};
|
||||
|
||||
visit(detail.tasks);
|
||||
return {
|
||||
workflow: {
|
||||
id: detail.id,
|
||||
label: detail.label,
|
||||
state: detail.state,
|
||||
version: detail.version,
|
||||
},
|
||||
ast,
|
||||
dependencies,
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
export * from "./workflow/analysis/index.js";
|
||||
@@ -940,6 +940,4 @@ export async function getWorkflowSampleData(
|
||||
return api.getWorkflowSampleData(client, pipelineId, type);
|
||||
}
|
||||
|
||||
export * from "./workflow-nodes.js";
|
||||
export * from "./workflow-watch.js";
|
||||
export * from "./workflow-script.js";
|
||||
export * from "./workflow/index.js";
|
||||
@@ -1,132 +1 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { getDatabase } from "../../core/db/index.js";
|
||||
|
||||
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[];
|
||||
}
|
||||
|
||||
/** 本地持久化工作流错误指纹(统一落盘至 core/db SQLite,兼容显式 JSON 状态文件)。 */
|
||||
export class WorkflowAlertStore {
|
||||
private readonly scopeKey: string;
|
||||
private readonly jsonPath?: string;
|
||||
private readonly customDb?: Database;
|
||||
|
||||
constructor(scopeOrFilePath = "default", db?: Database) {
|
||||
this.scopeKey = scopeOrFilePath;
|
||||
this.customDb = db;
|
||||
if (scopeOrFilePath.endsWith(".json")) {
|
||||
this.jsonPath = scopeOrFilePath;
|
||||
}
|
||||
}
|
||||
|
||||
private get db(): Database {
|
||||
return this.customDb ?? getDatabase();
|
||||
}
|
||||
|
||||
private read(): PersistedAlerts {
|
||||
const dbRows = this.db
|
||||
.query(
|
||||
"SELECT id, error_count, observed_at FROM workflow_error_alerts WHERE scope_key = ?"
|
||||
)
|
||||
.all(this.scopeKey) as Array<{
|
||||
id: string;
|
||||
error_count: number;
|
||||
observed_at: number;
|
||||
}>;
|
||||
|
||||
if (dbRows.length > 0) {
|
||||
const alerts: Record<string, { errorCount: number; lastSeen: number }> = {};
|
||||
for (const row of dbRows) {
|
||||
alerts[row.id] = { errorCount: row.error_count, lastSeen: row.observed_at };
|
||||
}
|
||||
return { version: 1, alerts };
|
||||
}
|
||||
|
||||
if (this.jsonPath && existsSync(this.jsonPath)) {
|
||||
try {
|
||||
const value = JSON.parse(readFileSync(this.jsonPath, "utf8")) as Partial<PersistedAlerts>;
|
||||
return {
|
||||
version: 1,
|
||||
alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {},
|
||||
};
|
||||
} catch {
|
||||
return { version: 1, alerts: {} };
|
||||
}
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
const db = this.db;
|
||||
const upsert = db.prepare(`
|
||||
INSERT INTO workflow_error_alerts (
|
||||
scope_key, id, pipeline_id, platform_id, pipeline_name, error_count, state, observed_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(scope_key, id) DO UPDATE SET
|
||||
pipeline_name = excluded.pipeline_name,
|
||||
error_count = excluded.error_count,
|
||||
state = excluded.state,
|
||||
observed_at = excluded.observed_at
|
||||
`);
|
||||
|
||||
const tx = db.transaction((items: WorkflowErrorAlert[]) => {
|
||||
db.run("DELETE FROM workflow_error_alerts WHERE scope_key = ?", [this.scopeKey]);
|
||||
for (const alert of items) {
|
||||
upsert.run(
|
||||
this.scopeKey,
|
||||
alert.id,
|
||||
alert.pipelineId,
|
||||
alert.platformId,
|
||||
alert.pipelineName,
|
||||
alert.errorCount,
|
||||
alert.state,
|
||||
alert.observedAt
|
||||
);
|
||||
}
|
||||
});
|
||||
tx(alerts);
|
||||
|
||||
if (this.jsonPath) {
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
`${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
}
|
||||
|
||||
return { activeAlerts: alerts, newAlerts };
|
||||
}
|
||||
}
|
||||
export * from "./workflow/alert/index.js";
|
||||
@@ -1,251 +1 @@
|
||||
import type { WorkflowTaskExecution } from "./types.js";
|
||||
import { indexExecutionContexts } from "./execution-context.js";
|
||||
|
||||
export interface ConditionRuleExplanation {
|
||||
leftLabel: string;
|
||||
upstreamNode: string;
|
||||
upstreamProp: string;
|
||||
operator: string;
|
||||
operatorLabel: string;
|
||||
expectedValue: any;
|
||||
actualValue: any;
|
||||
isMissing: boolean;
|
||||
matched: boolean | null;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface ConditionBranchExplanation {
|
||||
conditionNodeId: string;
|
||||
conditionNodeName: string;
|
||||
conditionNodeLabel: string;
|
||||
hasSkippedTasks: boolean;
|
||||
evaluation: boolean | null;
|
||||
skippedTaskNames: string[];
|
||||
rules: ConditionRuleExplanation[];
|
||||
summary: string;
|
||||
}
|
||||
|
||||
const OP_MAP: Record<string, string> = {
|
||||
eq: "等于",
|
||||
neq: "不等于",
|
||||
include: "包含",
|
||||
not_include: "不包含",
|
||||
in: "在列表中",
|
||||
not_in: "不在列表中",
|
||||
gt: "大于",
|
||||
gte: "大于等于",
|
||||
lt: "小于",
|
||||
lte: "小于等于",
|
||||
empty: "为空",
|
||||
not_empty: "不为空",
|
||||
};
|
||||
|
||||
/**
|
||||
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签
|
||||
*/
|
||||
function parseChooseTag(tag: string): {
|
||||
upstreamNode: string;
|
||||
upstreamProp: string;
|
||||
label: string;
|
||||
} | null {
|
||||
if (typeof tag !== "string") return null;
|
||||
const match = tag.match(/@\{choose\('(.*)'\)\}/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]);
|
||||
const upstreamNode = parsed.key || "";
|
||||
const upstreamProp = (parsed.properties ?? []).map((property: { key?: string }) => property.key).filter(Boolean).join(".");
|
||||
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
|
||||
return { upstreamNode, upstreamProp, label };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试从 @{value('...')} 中提取人类可读值
|
||||
*/
|
||||
function parseValueTag(val: any): any {
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((v) => parseValueTag(v));
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const match = val.match(/@\{value\('(.*)'\)\}/);
|
||||
if (match) {
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]);
|
||||
return parsed.label ? `${parsed.label} (${parsed.key})` : parsed.key || parsed.value;
|
||||
} catch {
|
||||
return val;
|
||||
}
|
||||
}
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个值是否匹配
|
||||
*/
|
||||
function cleanRuleValue(value: any): any {
|
||||
if (Array.isArray(value)) return value.map(cleanRuleValue);
|
||||
if (typeof value === "string") {
|
||||
const match = value.match(/@\{value\('(.*)'\)\}/);
|
||||
if (match) {
|
||||
try { const parsed = JSON.parse(match[1]); return parsed.key ?? parsed.value; }
|
||||
catch { return value; }
|
||||
}
|
||||
}
|
||||
if (value && typeof value === "object" && "id" in value) return value.id;
|
||||
return value;
|
||||
}
|
||||
|
||||
function evaluateRule(actual: any, expected: any, compare: string): boolean | null {
|
||||
const empty = actual === undefined || actual === null || actual === "" || (Array.isArray(actual) && actual.length === 0);
|
||||
if (compare === "empty") return empty;
|
||||
if (compare === "not_empty") return !empty;
|
||||
if (!Object.hasOwn(OP_MAP, compare)) return null;
|
||||
if (actual === undefined) return false;
|
||||
actual = cleanRuleValue(actual);
|
||||
expected = cleanRuleValue(expected);
|
||||
if (actual === null) return compare === "eq" ? expected === null : compare === "neq" ? expected !== null : false;
|
||||
if ([actual, expected].some(value => value !== null && typeof value === "object" && !Array.isArray(value))) return null;
|
||||
const equal = (a: any, b: any): boolean => {
|
||||
if (Array.isArray(a) && !Array.isArray(b)) return a.length === 1 && equal(a[0], b);
|
||||
if (!Array.isArray(a) && Array.isArray(b)) return b.length === 1 && equal(a, b[0]);
|
||||
return typeof a === "object" || typeof b === "object" ? JSON.stringify(a) === JSON.stringify(b) : String(a) === String(b);
|
||||
};
|
||||
switch (compare) {
|
||||
case "eq": return equal(actual, expected);
|
||||
case "neq": return !equal(actual, expected);
|
||||
case "in":
|
||||
case "not_in": {
|
||||
if (!Array.isArray(expected) || Array.isArray(actual)) return null;
|
||||
const matches = expected.some(item => equal(actual, item));
|
||||
return compare === "in" ? matches : !matches;
|
||||
}
|
||||
case "include":
|
||||
case "not_include": {
|
||||
if (!Array.isArray(actual) && typeof actual !== "string") return null;
|
||||
const values = Array.isArray(expected) ? expected : [expected];
|
||||
const matches = Array.isArray(actual)
|
||||
? values.every(value => actual.some(item => equal(item, value)))
|
||||
: typeof actual === "string" && values.every(value => actual.includes(String(value)));
|
||||
return compare === "include" ? matches : !matches;
|
||||
}
|
||||
default: {
|
||||
const numeric = (value: unknown) => typeof value === "number" || (typeof value === "string" && value.trim() !== "") ? Number(value) : NaN;
|
||||
const a = numeric(actual), b = numeric(expected);
|
||||
if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
|
||||
return compare === "gt" ? a > b : compare === "gte" ? a >= b : compare === "lt" ? a < b : a <= b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析 Job 执行树中的条件节点,诊断分支是否跳过及跳过的具体字段原因
|
||||
*/
|
||||
export function explainConditionBranches(
|
||||
tree: WorkflowTaskExecution[]
|
||||
): ConditionBranchExplanation[] {
|
||||
const contexts = indexExecutionContexts(tree);
|
||||
const explanations: ConditionBranchExplanation[] = [];
|
||||
|
||||
for (const [position, context] of contexts.entries()) {
|
||||
const node = context.node;
|
||||
const rawNode = node as Record<string, any>;
|
||||
if (rawNode.type !== "condition") continue;
|
||||
const childTasks = Array.isArray(rawNode.tasks) ? rawNode.tasks : [];
|
||||
if (childTasks.length === 0) continue;
|
||||
|
||||
// 检查子任务是否执行过
|
||||
const childNames = childTasks.map((task: any) => task.name || task.id).filter(Boolean);
|
||||
const childContexts = contexts.filter((child, index) => {
|
||||
if (child.loopPath !== context.loopPath || !childNames.includes(child.node.name || child.node.id)) return false;
|
||||
if (child.node.parentId) return child.node.parentId === node.id;
|
||||
const nestedScope = [...context.scope, JSON.stringify([node.name || node.type || "unnamed", context.loopPath])];
|
||||
return JSON.stringify(child.scope) === JSON.stringify(nestedScope) ||
|
||||
(index > position && JSON.stringify(child.scope) === JSON.stringify(context.scope));
|
||||
});
|
||||
const anyExecuted = childContexts.some(child => child.node.status && !["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase()));
|
||||
if (anyExecuted) {
|
||||
// 子分支正常执行,无需诊断跳过
|
||||
continue;
|
||||
}
|
||||
const skippedTaskNames = childTasks.map((task: any) => `${task.name || task.id} (${task.label || task.displayName || task.type})`);
|
||||
const rules: ConditionRuleExplanation[] = [];
|
||||
|
||||
// 解析 combineFilters;保留 AND/OR 和嵌套分组语义。
|
||||
const explainFilter = (filter: any): boolean | null => {
|
||||
if (!filter || typeof filter !== "object") return null;
|
||||
if (Array.isArray(filter.filters)) {
|
||||
const values = filter.filters.map(explainFilter) as Array<boolean | null>;
|
||||
if (!values.length) return null;
|
||||
const condition = String(filter.condition ?? "AND").toUpperCase();
|
||||
if (condition === "AND") return values.includes(false) ? false : values.includes(null) ? null : true;
|
||||
if (condition === "OR") return values.includes(true) ? true : values.includes(null) ? null : false;
|
||||
return null;
|
||||
}
|
||||
const chooseInfo = parseChooseTag(filter.key);
|
||||
const rawExpected = filter.value;
|
||||
const parsedExpected = parseValueTag(rawExpected);
|
||||
const op = filter.compare || "eq";
|
||||
const upstreamNode = chooseInfo?.upstreamNode || "";
|
||||
const upstreamProp = chooseInfo?.upstreamProp || (typeof filter.key === "string" ? filter.key : "");
|
||||
const leftLabel = chooseInfo?.label || String(filter.key);
|
||||
|
||||
// 从上游节点提取真实 outputs;只使用同一次循环或祖先作用域中的执行实例。
|
||||
const candidates = contexts.slice(0, position).filter(candidate =>
|
||||
(candidate.node.name === upstreamNode || candidate.node.id === upstreamNode) &&
|
||||
(!candidate.loopPath || candidate.loopPath === context.loopPath) &&
|
||||
candidate.scope.every((part, i) => context.scope[i] === part)
|
||||
);
|
||||
candidates.sort((a, b) => a.scope.length - b.scope.length);
|
||||
const upstreamExecution = candidates.at(-1)?.node;
|
||||
const upstreamOutputs = upstreamExecution?.output ?? upstreamExecution?.outputs;
|
||||
let actualVal: any = upstreamOutputs;
|
||||
let isMissing = false;
|
||||
for (const part of upstreamProp.split(".")) {
|
||||
if (actualVal && typeof actualVal === "object" && Object.hasOwn(actualVal, part)) actualVal = actualVal[part];
|
||||
else { actualVal = undefined; isMissing = Boolean(upstreamExecution); break; }
|
||||
}
|
||||
// 提取纯净 ID 比对
|
||||
const cleanExpected = cleanRuleValue(rawExpected);
|
||||
const matched = upstreamExecution ? evaluateRule(actualVal, cleanExpected, op) : null;
|
||||
let detail: string;
|
||||
if (isMissing) {
|
||||
const availableKeys = upstreamOutputs && typeof upstreamOutputs === "object" ? Object.keys(upstreamOutputs).join(", ") : "无出参";
|
||||
detail = `上游节点 [${upstreamNode}] 未返回该属性 [${upstreamProp}](字段名可能脱节,上游可用字段: ${availableKeys})➔ 解析值为 null`;
|
||||
} else if (matched === null) {
|
||||
detail = `无法确定:缺少上游执行证据,或操作符/值类型不支持 (${op})`;
|
||||
} else {
|
||||
const actStr = typeof actualVal === "object" ? JSON.stringify(actualVal) : String(actualVal ?? "null");
|
||||
const expStr = typeof parsedExpected === "object" ? JSON.stringify(parsedExpected) : String(parsedExpected);
|
||||
detail = `实际值: ${actStr} 与期望值 [${expStr}] 比对结果为 ${matched ? "True" : "False"}`;
|
||||
}
|
||||
rules.push({ leftLabel, upstreamNode, upstreamProp, operator: op, operatorLabel: OP_MAP[op] || op, expectedValue: parsedExpected, actualValue: actualVal, isMissing, matched, detail });
|
||||
return matched;
|
||||
};
|
||||
const calculated = explainFilter(rawNode.combineFilters);
|
||||
const evaluation = node.status.toUpperCase() === "COMPLETED" ? calculated : null;
|
||||
let summary = evaluation === false
|
||||
? `条件判定未通过 (False),子任务 [${skippedTaskNames.join(", ")}] 被跳过未执行`
|
||||
: evaluation === true
|
||||
? "条件比对为 True,但未见子任务执行记录;请核对执行树是否完整"
|
||||
: "执行证据不足或条件尚未完成,无法确定子任务是否被跳过";
|
||||
const missingRule = rules.find(rule => rule.isMissing);
|
||||
if (evaluation === false && missingRule) {
|
||||
summary = `条件字段脱节: 上游节点 [${missingRule.upstreamNode}] 缺少属性 [${missingRule.upstreamProp}],判定为 False,子任务被跳过`;
|
||||
}
|
||||
explanations.push({
|
||||
conditionNodeId: node.id,
|
||||
conditionNodeName: node.name || "-",
|
||||
conditionNodeLabel: node.label || rawNode.displayName || "条件节点",
|
||||
hasSkippedTasks: evaluation === false || childContexts.some(child => ["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase())),
|
||||
evaluation,
|
||||
skippedTaskNames,
|
||||
rules,
|
||||
summary,
|
||||
});
|
||||
}
|
||||
return explanations;
|
||||
}
|
||||
export * from "./workflow/branch/index.js";
|
||||
@@ -1,451 +1 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
|
||||
export interface FlattenedWorkflowTask {
|
||||
task: WorkflowTask;
|
||||
index: number; // 1-based global sequential index
|
||||
hierarchicalIndex: string; // e.g. "1", "2.1", "2.1.3"
|
||||
depth: number;
|
||||
path: string;
|
||||
parentName?: string;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface LocatedWorkflowTask {
|
||||
task: WorkflowTask;
|
||||
path: string;
|
||||
parentTasks: WorkflowTask[];
|
||||
arrayIndex: number;
|
||||
hierarchicalIndex: string;
|
||||
globalIndex: number;
|
||||
parentName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归计算并生成节点的紧凑配置摘要
|
||||
*/
|
||||
export function summarizeTask(task: WorkflowTask): string {
|
||||
if (task.type === "webhook") {
|
||||
return task.urlPath ? `urlPath: ${task.urlPath}` : "未配置URL";
|
||||
}
|
||||
if (task.type === "clock") {
|
||||
return `cron: ${task.cron || "0 0 * * *"} (${task.timeZone || "Asia/Shanghai"})`;
|
||||
}
|
||||
if (task.type === "code" || task.type === "code-js2") {
|
||||
const rawCode: string = (task as any).code || "";
|
||||
const firstLine = rawCode.trim().split("\n")[0] || "";
|
||||
const len = rawCode.length;
|
||||
return `脚本 (${len} 字符): ${firstLine.slice(0, 40)}${firstLine.length > 40 ? "..." : ""}`;
|
||||
}
|
||||
if (task.type === "http") {
|
||||
return `${(task as any).method || "POST"} ${(task as any).url || ""}`;
|
||||
}
|
||||
if (task.type === "every") {
|
||||
return `循环遍历: ${(task as any).list || "$item"} (含 ${task.tasks?.length || 0} 个子节点)`;
|
||||
}
|
||||
if (task.type === "condition") {
|
||||
const filters = (task as any).combineFilters?.filters || [];
|
||||
return `分支条件: ${filters.length} 组规则 (含 ${task.tasks?.length || 0} 个子节点)`;
|
||||
}
|
||||
if (task.type === "stop") {
|
||||
return "阻断终止流程";
|
||||
}
|
||||
if (task.type === "ekuaibao-datalink-create-trigger") {
|
||||
return "业务对象台账新增触发";
|
||||
}
|
||||
if (task.type === "ekuaibao-flowform-trigger") {
|
||||
return "单据流转事件触发";
|
||||
}
|
||||
return task.desc || task.label || task.type;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将整棵工作流任务树展平为有序列表,便于查看与索引
|
||||
*/
|
||||
export function flattenWorkflowTaskTree(tasks: WorkflowTask[]): FlattenedWorkflowTask[] {
|
||||
const result: FlattenedWorkflowTask[] = [];
|
||||
let globalCounter = 0;
|
||||
|
||||
function traverse(
|
||||
list: WorkflowTask[],
|
||||
prefix: string,
|
||||
depth: number,
|
||||
basePath: string,
|
||||
parentName?: string
|
||||
) {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const task = list[i];
|
||||
globalCounter += 1;
|
||||
const hierarchicalIndex = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
|
||||
const path = basePath ? `${basePath}.${i}` : `tasks.${i}`;
|
||||
|
||||
result.push({
|
||||
task,
|
||||
index: globalCounter,
|
||||
hierarchicalIndex,
|
||||
depth,
|
||||
path,
|
||||
parentName,
|
||||
summary: summarizeTask(task),
|
||||
});
|
||||
|
||||
if (task.tasks && Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
traverse(task.tasks, hierarchicalIndex, depth + 1, `${path}.tasks`, task.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(tasks, "", 0, "tasks");
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在任务树中按节点名称、层级编号 (如 "2.1") 或全局序号定位目标任务
|
||||
*/
|
||||
export function findWorkflowTask(
|
||||
tasksOrWorkflow: WorkflowTask[] | { tasks?: WorkflowTask[] },
|
||||
target: string | number
|
||||
): LocatedWorkflowTask | null {
|
||||
const tasks = Array.isArray(tasksOrWorkflow)
|
||||
? tasksOrWorkflow
|
||||
: tasksOrWorkflow?.tasks || [];
|
||||
const targetStr = String(target).trim();
|
||||
const targetNum = Number(targetStr);
|
||||
const isNumeric = !Number.isNaN(targetNum) && Number.isInteger(targetNum) && targetNum > 0;
|
||||
|
||||
let globalCounter = 0;
|
||||
|
||||
function search(
|
||||
list: WorkflowTask[],
|
||||
prefix: string,
|
||||
basePath: string,
|
||||
parentName?: string
|
||||
): LocatedWorkflowTask | null {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const task = list[i];
|
||||
globalCounter += 1;
|
||||
const hierarchicalIndex = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
|
||||
const path = basePath ? `${basePath}.${i}` : `tasks.${i}`;
|
||||
|
||||
const matched =
|
||||
task.name === targetStr ||
|
||||
hierarchicalIndex === targetStr ||
|
||||
(isNumeric && globalCounter === targetNum);
|
||||
|
||||
if (matched) {
|
||||
return {
|
||||
task,
|
||||
path,
|
||||
parentTasks: list,
|
||||
arrayIndex: i,
|
||||
hierarchicalIndex,
|
||||
globalIndex: globalCounter,
|
||||
parentName,
|
||||
};
|
||||
}
|
||||
|
||||
if (task.tasks && Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
const found = search(task.tasks, hierarchicalIndex, `${path}.tasks`, task.name);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return search(tasks, "", "tasks");
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归重算整棵树的 orderIndex 与 levelIndex
|
||||
*/
|
||||
export function reindexTasks(
|
||||
tasks: WorkflowTask[],
|
||||
parentLevel: number[] = [],
|
||||
startOrder = 0
|
||||
): number {
|
||||
let currentOrder = startOrder;
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
const task = tasks[i];
|
||||
task.orderIndex = currentOrder++;
|
||||
task.levelIndex = [...parentLevel, i];
|
||||
if (task.tasks && Array.isArray(task.tasks)) {
|
||||
currentOrder = reindexTasks(task.tasks, task.levelIndex, currentOrder);
|
||||
}
|
||||
}
|
||||
return currentOrder;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成规范唯一的合思节点 ID
|
||||
*/
|
||||
export function generateNodeName(type: string): string {
|
||||
const rand = Math.random().toString(36).substring(2, 8);
|
||||
if (type === "every" || type === "condition") {
|
||||
return `control_${rand}`;
|
||||
}
|
||||
if (type.includes("trigger") || type === "webhook" || type === "clock") {
|
||||
return `trigger_${rand}`;
|
||||
}
|
||||
return `action_${rand}`;
|
||||
}
|
||||
|
||||
export interface AddTaskOptions {
|
||||
type: string;
|
||||
label?: string;
|
||||
code?: string;
|
||||
desc?: string;
|
||||
parent?: string | number;
|
||||
after?: string | number;
|
||||
extra?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建规范的新节点对象
|
||||
*/
|
||||
export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
|
||||
const normType = type.trim();
|
||||
const name = generateNodeName(normType);
|
||||
|
||||
switch (normType) {
|
||||
case "code-js2":
|
||||
return {
|
||||
name,
|
||||
type: "code-js2",
|
||||
label: options.label || "JS节点(新)",
|
||||
desc: options.desc || "执行一段JavaScript代码",
|
||||
groupName: "action",
|
||||
code: options.code || "// 编写处理逻辑\nreturn items;",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "code":
|
||||
return {
|
||||
name,
|
||||
type: "code",
|
||||
label: options.label || "代码节点",
|
||||
desc: options.desc || "执行一段MVEL代码",
|
||||
groupName: "action",
|
||||
code: options.code || "return true;",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "http":
|
||||
return {
|
||||
name,
|
||||
type: "http",
|
||||
label: options.label || "HTTP请求",
|
||||
groupName: "action",
|
||||
method: options.extra?.method || "POST",
|
||||
url: options.extra?.url || "",
|
||||
header: options.extra?.header || [],
|
||||
params: options.extra?.params || [],
|
||||
successCode: options.extra?.successCode || ["200"],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "stop":
|
||||
return {
|
||||
name,
|
||||
type: "stop",
|
||||
label: options.label || "终止流程",
|
||||
desc: options.desc || "如果满足条件终止流程",
|
||||
groupName: "control",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "every":
|
||||
return {
|
||||
name,
|
||||
type: "every",
|
||||
label: options.label || "依次执行",
|
||||
desc: options.desc || "依次遍历每个对象",
|
||||
groupName: "control",
|
||||
mode: "sequence",
|
||||
batch: false,
|
||||
list: options.extra?.list || "@{choose('...$item')}",
|
||||
filters: [],
|
||||
tasksMaxLevel: 1,
|
||||
tasks: [],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "condition":
|
||||
return {
|
||||
name,
|
||||
type: "condition",
|
||||
label: options.label || "条件分支",
|
||||
desc: options.desc || "如果满足条件则执行以下动作",
|
||||
groupName: "control",
|
||||
combineFilters: options.extra?.combineFilters || { condition: "or", filters: [] },
|
||||
tasksMaxLevel: 1,
|
||||
tasks: [],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "webhook":
|
||||
return {
|
||||
name,
|
||||
type: "webhook",
|
||||
label: options.label || "Webhook触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
urlPath: crypto.randomUUID(),
|
||||
params: [],
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "clock":
|
||||
return {
|
||||
name,
|
||||
type: "clock",
|
||||
label: options.label || "定时触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
cron: options.extra?.cron || "0 0 * * *",
|
||||
timeZone: options.extra?.timeZone || "Asia/Shanghai",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
name,
|
||||
type: normType,
|
||||
label: options.label || `${normType}节点`,
|
||||
desc: options.desc || "",
|
||||
groupName: normType.startsWith("control") ? "control" : "action",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向工作流声明式追加或插入任务节点
|
||||
*/
|
||||
export function addWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
options: AddTaskOptions
|
||||
): { workflow: WorkflowDetail; newTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks) cloned.tasks = [];
|
||||
|
||||
const newTask = buildWorkflowTask(options.type, options);
|
||||
|
||||
if (options.after !== undefined && options.after !== "") {
|
||||
const target = findWorkflowTask(cloned.tasks, options.after);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到插入基准节点 (--after): ${options.after}`);
|
||||
}
|
||||
// 插入在该节点的下一个位置
|
||||
target.parentTasks.splice(target.arrayIndex + 1, 0, newTask);
|
||||
} else if (options.parent !== undefined && options.parent !== "") {
|
||||
const parentTarget = findWorkflowTask(cloned.tasks, options.parent);
|
||||
if (!parentTarget) {
|
||||
throw new NotFoundError(`未找到父级容器节点 (--parent): ${options.parent}`);
|
||||
}
|
||||
if (!parentTarget.task.tasks) parentTarget.task.tasks = [];
|
||||
parentTarget.task.tasks.push(newTask);
|
||||
} else {
|
||||
// 默认追加到顶级 tasks 末尾
|
||||
cloned.tasks.push(newTask);
|
||||
}
|
||||
|
||||
// 重排索引
|
||||
reindexTasks(cloned.tasks);
|
||||
return { workflow: cloned, newTask };
|
||||
}
|
||||
|
||||
export interface EditTaskOptions {
|
||||
label?: string;
|
||||
code?: string;
|
||||
desc?: string;
|
||||
set?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定向修改工作流任务节点配置
|
||||
*/
|
||||
export function editWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
targetKey: string | number,
|
||||
updates: EditTaskOptions
|
||||
): { workflow: WorkflowDetail; editedTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks) cloned.tasks = [];
|
||||
|
||||
const target = findWorkflowTask(cloned.tasks, targetKey);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到目标工作流任务节点: ${targetKey}`);
|
||||
}
|
||||
|
||||
const { task } = target;
|
||||
if (updates.label !== undefined) task.label = updates.label;
|
||||
if (updates.desc !== undefined) task.desc = updates.desc;
|
||||
if (updates.code !== undefined) (task as any).code = updates.code;
|
||||
|
||||
if (updates.set && typeof updates.set === "object") {
|
||||
for (const [k, v] of Object.entries(updates.set)) {
|
||||
(task as any)[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
return { workflow: cloned, editedTask: task };
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全剔除工作流任务节点
|
||||
*/
|
||||
export function removeWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
targetKey: string | number
|
||||
): { workflow: WorkflowDetail; removedTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks || cloned.tasks.length === 0) {
|
||||
throw new ValidationError("工作流中无任何任务节点,无法删除");
|
||||
}
|
||||
|
||||
const target = findWorkflowTask(cloned.tasks, targetKey);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到待删除的工作流任务节点: ${targetKey}`);
|
||||
}
|
||||
|
||||
// 触发器保护:如果工作流只有首节点且是触发器,或者删除首节点触发器
|
||||
if (
|
||||
target.parentTasks === cloned.tasks &&
|
||||
target.arrayIndex === 0 &&
|
||||
cloned.tasks.length > 1 &&
|
||||
(target.task.groupName === "trigger" || target.task.type.includes("trigger") || target.task.type === "webhook" || target.task.type === "clock")
|
||||
) {
|
||||
throw new ValidationError(
|
||||
`节点 [${target.task.name}] (${target.task.label || target.task.type}) 是工作流的触发源节点。直接移除会导致工作流缺少触发器,请使用 workflow save 或在设计器中调整触发器。`
|
||||
);
|
||||
}
|
||||
|
||||
const [removedTask] = target.parentTasks.splice(target.arrayIndex, 1);
|
||||
reindexTasks(cloned.tasks);
|
||||
return { workflow: cloned, removedTask };
|
||||
}
|
||||
export * from "./workflow/nodes/index.js";
|
||||
@@ -1,425 +1 @@
|
||||
import vm from "node:vm";
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
import { flattenExecutionTree } from "./services.js";
|
||||
|
||||
export interface ScriptIssue {
|
||||
level: "error" | "warning";
|
||||
line?: number;
|
||||
column?: number;
|
||||
message: string;
|
||||
rule: string;
|
||||
}
|
||||
|
||||
export interface NodeScriptLintReport {
|
||||
nodeName: string;
|
||||
displayName?: string;
|
||||
label?: string;
|
||||
type: "code-js2" | "code";
|
||||
codeLength: number;
|
||||
lineCount: number;
|
||||
hasReturn: boolean;
|
||||
boundVariables: Array<{ key: string; upstreamTarget?: string }>;
|
||||
referencedNodes: Array<{ name: string; exists: boolean }>;
|
||||
issues: ScriptIssue[];
|
||||
valid: boolean;
|
||||
}
|
||||
|
||||
export interface WorkflowScriptLintReport {
|
||||
pipelineId?: string;
|
||||
label?: string;
|
||||
totalCodeNodes: number;
|
||||
validCount: number;
|
||||
invalidCount: number;
|
||||
reports: NodeScriptLintReport[];
|
||||
allValid: boolean;
|
||||
}
|
||||
|
||||
export interface ScriptEvalLog {
|
||||
level: "log" | "warn" | "error";
|
||||
message: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface ScriptEvalResult {
|
||||
success: boolean;
|
||||
durationMs: number;
|
||||
returnValue: unknown;
|
||||
logs: ScriptEvalLog[];
|
||||
error?: {
|
||||
name: string;
|
||||
message: string;
|
||||
stack?: string;
|
||||
line?: number;
|
||||
column?: number;
|
||||
};
|
||||
inputs: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查代码中是否存在 return 关键字(排除纯注释中的 return)
|
||||
*/
|
||||
export function hasReturnStatement(code: string): boolean {
|
||||
const lines = code.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
||||
continue;
|
||||
}
|
||||
if (/\breturn\b/.test(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态检查 JavaScript (code-js2) 语法与规范
|
||||
*/
|
||||
export function lintJavaScriptCode(
|
||||
code: string,
|
||||
boundVariables: string[] = []
|
||||
): { issues: ScriptIssue[]; hasReturn: boolean } {
|
||||
const issues: ScriptIssue[] = [];
|
||||
const trimmed = code.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: "代码节点脚本内容为空,合思调度时将报错",
|
||||
rule: "empty-script",
|
||||
});
|
||||
return { issues, hasReturn: false };
|
||||
}
|
||||
|
||||
const hasRet = hasReturnStatement(code);
|
||||
if (!hasRet) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "脚本中缺少显式 return 语句,可能导致下游节点接收到 null 或 undefined",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
// 语法验证:通过 Function 构造器做 AST 编译期语法解析
|
||||
try {
|
||||
// 注入声明的参数名以验证语法合法性
|
||||
new Function(...boundVariables, code);
|
||||
} catch (err: any) {
|
||||
let line: number | undefined;
|
||||
let column: number | undefined;
|
||||
|
||||
const msg = err?.message || String(err);
|
||||
// 尝试从堆栈或错误描述提取行号
|
||||
const match = err?.stack?.match(/<anonymous>:(\d+):(\d+)/) || msg.match(/line (\d+)/i);
|
||||
if (match) {
|
||||
line = Number(match[1]);
|
||||
if (match[2]) column = Number(match[2]);
|
||||
}
|
||||
|
||||
issues.push({
|
||||
level: "error",
|
||||
line,
|
||||
column,
|
||||
message: `JavaScript 语法错误: ${msg}`,
|
||||
rule: "syntax-error",
|
||||
});
|
||||
}
|
||||
|
||||
return { issues, hasReturn: hasRet };
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态检查 MVEL (code) 括号闭合与上游节点引用有效性
|
||||
*/
|
||||
export function lintMvelCode(
|
||||
code: string,
|
||||
existingNodeNames?: Set<string>
|
||||
): {
|
||||
issues: ScriptIssue[];
|
||||
referencedNodes: Array<{ name: string; exists: boolean }>;
|
||||
hasReturn: boolean;
|
||||
} {
|
||||
const issues: ScriptIssue[] = [];
|
||||
const referencedNodes: Array<{ name: string; exists: boolean }> = [];
|
||||
const trimmed = code.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: "MVEL 代码内容为空,合思调度时将报错",
|
||||
rule: "empty-script",
|
||||
});
|
||||
return { issues, referencedNodes, hasReturn: false };
|
||||
}
|
||||
|
||||
const hasRet = hasReturnStatement(code);
|
||||
if (!hasRet) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "MVEL 代码中未发现 return 语句,合思代码节点通常需要 return 包装后的 Map 或结果对象",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
// 1. 括号与引号对称性平衡检查
|
||||
const stack: Array<{ char: string; line: number }> = [];
|
||||
const lines = code.split(/\r?\n/);
|
||||
|
||||
for (let l = 0; l < lines.length; l++) {
|
||||
const lineText = lines[l];
|
||||
// 忽略单行注释
|
||||
const cleanLine = lineText.replace(/\/\/.*$/, "");
|
||||
|
||||
for (let c = 0; c < cleanLine.length; c++) {
|
||||
const ch = cleanLine[c];
|
||||
if (ch === "{" || ch === "(" || ch === "[") {
|
||||
stack.push({ char: ch, line: l + 1 });
|
||||
} else if (ch === "}" || ch === ")" || ch === "]") {
|
||||
const top = stack.pop();
|
||||
const expected = ch === "}" ? "{" : ch === ")" ? "(" : "[";
|
||||
if (!top || top.char !== expected) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
line: l + 1,
|
||||
column: c + 1,
|
||||
message: `括号不匹配: 遇到闭合 '${ch}',但预期匹配 '${expected}'`,
|
||||
rule: "unmatched-brackets",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (stack.length > 0) {
|
||||
const unclosed = stack.pop()!;
|
||||
issues.push({
|
||||
level: "error",
|
||||
line: unclosed.line,
|
||||
message: `未闭合的括号: '${unclosed.char}' 缺少对应的闭合括号`,
|
||||
rule: "unclosed-bracket",
|
||||
});
|
||||
}
|
||||
|
||||
// 2. 提取引用的上游节点标识并比对有效性
|
||||
// 合思节点命名规范形如 action_xxx, control_xxx, trigger_xxx
|
||||
const nodeRefRegex = /\b(action_[a-zA-Z0-9_]+|control_[a-zA-Z0-9_]+|trigger_[a-zA-Z0-9_]+)\b/g;
|
||||
const foundRefs = new Set<string>();
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = nodeRefRegex.exec(code)) !== null) {
|
||||
foundRefs.add(match[1]);
|
||||
}
|
||||
|
||||
for (const ref of foundRefs) {
|
||||
const exists = existingNodeNames ? existingNodeNames.has(ref) : true;
|
||||
referencedNodes.push({ name: ref, exists });
|
||||
if (!exists) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: `引用的上游节点 [${ref}] 在工作流中不存在(可能已被重命名或移除)`,
|
||||
rule: "dangling-node-reference",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { issues, referencedNodes, hasReturn: hasRet };
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归收集工作流任务树中所有节点标识
|
||||
*/
|
||||
export function collectAllWorkflowNodeNames(tasks: WorkflowTask[]): Set<string> {
|
||||
const names = new Set<string>();
|
||||
|
||||
function walk(list: WorkflowTask[]) {
|
||||
for (const t of list) {
|
||||
if (!t) continue;
|
||||
if (t.name) names.add(t.name);
|
||||
if (Array.isArray(t.tasks) && t.tasks.length > 0) {
|
||||
walk(t.tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(tasks);
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描并全面静态校验工作流中的全部代码节点(JS 与 MVEL)
|
||||
*/
|
||||
export function lintWorkflowScripts(
|
||||
workflow: WorkflowDetail,
|
||||
targetNodeQuery?: string
|
||||
): WorkflowScriptLintReport {
|
||||
const tasks = workflow.tasks || [];
|
||||
const allNodeNames = collectAllWorkflowNodeNames(tasks);
|
||||
const reports: NodeScriptLintReport[] = [];
|
||||
|
||||
function traverse(list: WorkflowTask[]) {
|
||||
for (const task of list) {
|
||||
if (!task) continue;
|
||||
|
||||
if (task.type === "code" || task.type === "code-js2") {
|
||||
if (!targetNodeQuery || task.name === targetNodeQuery || task.label === targetNodeQuery || task.displayName === targetNodeQuery) {
|
||||
const rawCode = (task as any).code || "";
|
||||
const lineCount = rawCode ? rawCode.split(/\r?\n/).length : 0;
|
||||
const mappings = Array.isArray((task as any).mapping) ? (task as any).mapping : [];
|
||||
const boundVariables: Array<{ key: string; upstreamTarget?: string }> = mappings.map((m: any) => ({
|
||||
key: m.key,
|
||||
upstreamTarget: m.value,
|
||||
}));
|
||||
|
||||
let issues: ScriptIssue[] = [];
|
||||
let hasReturn = false;
|
||||
let referencedNodes: Array<{ name: string; exists: boolean }> = [];
|
||||
|
||||
if (task.type === "code-js2") {
|
||||
const paramNames = boundVariables.map((b) => b.key);
|
||||
const res = lintJavaScriptCode(rawCode, paramNames);
|
||||
issues = res.issues;
|
||||
hasReturn = res.hasReturn;
|
||||
} else {
|
||||
const res = lintMvelCode(rawCode, allNodeNames);
|
||||
issues = res.issues;
|
||||
hasReturn = res.hasReturn;
|
||||
referencedNodes = res.referencedNodes;
|
||||
}
|
||||
|
||||
const hasErrors = issues.some((i) => i.level === "error");
|
||||
|
||||
reports.push({
|
||||
nodeName: task.name,
|
||||
displayName: task.displayName || undefined,
|
||||
label: task.label || undefined,
|
||||
type: task.type,
|
||||
codeLength: rawCode.length,
|
||||
lineCount,
|
||||
hasReturn,
|
||||
boundVariables,
|
||||
referencedNodes,
|
||||
issues,
|
||||
valid: !hasErrors,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
traverse(task.tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(tasks);
|
||||
|
||||
const validCount = reports.filter((r) => r.valid).length;
|
||||
const invalidCount = reports.length - validCount;
|
||||
|
||||
return {
|
||||
pipelineId: workflow.id,
|
||||
label: workflow.label,
|
||||
totalCodeNodes: reports.length,
|
||||
validCount,
|
||||
invalidCount,
|
||||
reports,
|
||||
allValid: invalidCount === 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 在隔离沙箱中执行 JavaScript 代码节点,仿真合思云端运行时并捕获输出与异常
|
||||
*/
|
||||
export async function executeJavaScriptSandbox(
|
||||
code: string,
|
||||
inputs: Record<string, unknown> = {},
|
||||
options: { timeoutMs?: number } = {}
|
||||
): Promise<ScriptEvalResult> {
|
||||
const timeoutMs = options.timeoutMs ?? 3000;
|
||||
const logs: ScriptEvalLog[] = [];
|
||||
const start = performance.now();
|
||||
|
||||
const recordLog = (level: "log" | "warn" | "error", ...args: unknown[]) => {
|
||||
const message = args
|
||||
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
|
||||
.join(" ");
|
||||
logs.push({ level, message, timestamp: Date.now() });
|
||||
};
|
||||
|
||||
const sandboxConsole = {
|
||||
log: (...args: unknown[]) => recordLog("log", ...args),
|
||||
info: (...args: unknown[]) => recordLog("log", ...args),
|
||||
warn: (...args: unknown[]) => recordLog("warn", ...args),
|
||||
error: (...args: unknown[]) => recordLog("error", ...args),
|
||||
};
|
||||
|
||||
// 创建安全的执行沙箱上下文
|
||||
const sandboxContext = vm.createContext({
|
||||
...inputs,
|
||||
console: sandboxConsole,
|
||||
Date,
|
||||
Math,
|
||||
JSON,
|
||||
RegExp,
|
||||
Array,
|
||||
Object,
|
||||
Number,
|
||||
String,
|
||||
Boolean,
|
||||
parseInt,
|
||||
parseFloat,
|
||||
isNaN,
|
||||
isFinite,
|
||||
encodeURI,
|
||||
decodeURI,
|
||||
encodeURIComponent,
|
||||
decodeURIComponent,
|
||||
});
|
||||
|
||||
// 包裹立即执行函数体 (IIFE),既允许顶层 return 语句,又能直接受 vm timeout 保护
|
||||
const wrappedCode = `(function() {\n${code}\n})()`;
|
||||
|
||||
try {
|
||||
const returnValue = vm.runInContext(wrappedCode, sandboxContext, {
|
||||
timeout: timeoutMs,
|
||||
displayErrors: true,
|
||||
});
|
||||
const durationMs = Number((performance.now() - start).toFixed(2));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
durationMs,
|
||||
returnValue,
|
||||
logs,
|
||||
inputs,
|
||||
};
|
||||
} catch (err: any) {
|
||||
const durationMs = Number((performance.now() - start).toFixed(2));
|
||||
const msg = err?.message || String(err);
|
||||
let line: number | undefined;
|
||||
let column: number | undefined;
|
||||
|
||||
const stack = err?.stack || "";
|
||||
// 匹配包裹函数内的行号(第 1 行是包裹头,因此需要 -1)
|
||||
const match = stack.match(/evalmachine\.<anonymous>:(\d+):(\d+)/);
|
||||
if (match) {
|
||||
const rawLine = Number(match[1]);
|
||||
line = Math.max(1, rawLine - 1);
|
||||
column = Number(match[2]);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
durationMs,
|
||||
returnValue: undefined,
|
||||
logs,
|
||||
error: {
|
||||
name: err?.name || "ExecutionError",
|
||||
message: msg,
|
||||
stack,
|
||||
line,
|
||||
column,
|
||||
},
|
||||
inputs,
|
||||
};
|
||||
}
|
||||
}
|
||||
export * from "./workflow/script/index.js";
|
||||
@@ -1,118 +1 @@
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
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 ValidationError("工作流配置路径不能为空");
|
||||
if (parts.some((part) => !/^[A-Za-z_$][\w$-]*$/.test(part) && !/^\d+$/.test(part))) {
|
||||
throw new ValidationError(`工作流配置路径非法: ${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 NotFoundError(`工作流配置路径不存在: ${path}`);
|
||||
}
|
||||
cursor = cursor[part];
|
||||
}
|
||||
if (cursor === null || typeof cursor !== "object") {
|
||||
throw new ValidationError(`工作流配置路径不可写: ${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;
|
||||
}
|
||||
export * from "./workflow/state/index.js";
|
||||
@@ -1,645 +1 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "./types.js";
|
||||
import * as api from "./api.js";
|
||||
import { flattenExecutionTree, isTaskExecutionFailed } from "./services.js";
|
||||
|
||||
export type WorkflowWatchEventType =
|
||||
| "pipeline_watch_start"
|
||||
| "job_detected"
|
||||
| "task_started"
|
||||
| "task_completed"
|
||||
| "task_failed"
|
||||
| "task_skipped"
|
||||
| "job_completed"
|
||||
| "idle"
|
||||
| "timeout";
|
||||
|
||||
export interface WorkflowWatchEvent {
|
||||
type: WorkflowWatchEventType;
|
||||
pipelineId?: string;
|
||||
pipelineLabel?: string;
|
||||
jobId?: string;
|
||||
runType?: string;
|
||||
executionId?: string;
|
||||
name?: string;
|
||||
displayName?: string;
|
||||
label?: string;
|
||||
taskType?: string;
|
||||
status?: string;
|
||||
durationMs?: number;
|
||||
startTime?: string;
|
||||
loopPath?: string;
|
||||
error?: string;
|
||||
jobSummary?: {
|
||||
status: string;
|
||||
durationMs?: number;
|
||||
successCount: number;
|
||||
errorCount: number;
|
||||
hasError: boolean;
|
||||
};
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface WatchWorkflowOptions {
|
||||
jobId?: string;
|
||||
intervalMs?: number;
|
||||
timeoutMs?: number;
|
||||
maxJobs?: number;
|
||||
once?: boolean;
|
||||
follow?: boolean;
|
||||
failedOnly?: boolean;
|
||||
onEvent?: (event: WorkflowWatchEvent) => Promise<void> | void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface WatchedJobResult {
|
||||
jobId: string;
|
||||
pipelineId: string;
|
||||
status: string;
|
||||
runType?: string;
|
||||
durationMs?: number;
|
||||
successCount: number;
|
||||
errorCount: number;
|
||||
hasError: boolean;
|
||||
events: WorkflowWatchEvent[];
|
||||
}
|
||||
|
||||
export interface WorkflowWatchReport {
|
||||
pipelineId: string;
|
||||
totalJobsWatched: number;
|
||||
jobs: WatchedJobResult[];
|
||||
timedOut: boolean;
|
||||
hasFailures: boolean;
|
||||
}
|
||||
|
||||
const TERMINAL_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 any).status;
|
||||
const rawState = (job as any).state;
|
||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
||||
return rawStatus.trim().toUpperCase();
|
||||
}
|
||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
export function isJobTerminal(status: string): boolean {
|
||||
return TERMINAL_STATES.has(status.toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取节点执行失败或跳过时的具体错误原因
|
||||
*/
|
||||
export function extractTaskErrorMessage(node: WorkflowTaskExecution): string | undefined {
|
||||
if (!node) return undefined;
|
||||
const anyNode = node as any;
|
||||
if (node.error?.message && String(node.error.message).trim()) {
|
||||
return String(node.error.message).trim();
|
||||
}
|
||||
if (anyNode.errorMessage && String(anyNode.errorMessage).trim()) {
|
||||
return String(anyNode.errorMessage).trim();
|
||||
}
|
||||
const outputs = anyNode.outputs ?? anyNode.output;
|
||||
if (outputs && typeof outputs === "object") {
|
||||
if (outputs.error) {
|
||||
return typeof outputs.error === "string" ? outputs.error.trim() : JSON.stringify(outputs.error);
|
||||
}
|
||||
if (outputs.message && typeof outputs.message === "string") {
|
||||
return outputs.message.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点状态追踪器:比对并生成增量任务状态变更事件,避免轮询时重复日志刷屏
|
||||
*/
|
||||
export class TaskExecutionTracker {
|
||||
private seenStatuses = new Map<string, string>();
|
||||
|
||||
constructor(public readonly jobId: string) {}
|
||||
|
||||
public processExecutions(executions: WorkflowTaskExecution[]): WorkflowWatchEvent[] {
|
||||
const flattened = flattenExecutionTree(executions);
|
||||
const events: WorkflowWatchEvent[] = [];
|
||||
const now = Date.now();
|
||||
|
||||
for (const node of flattened) {
|
||||
if (!node?.id) continue;
|
||||
const executionId = node.id;
|
||||
const rawStatus = (node.status || "UNKNOWN").toUpperCase();
|
||||
const previousStatus = this.seenStatuses.get(executionId);
|
||||
|
||||
const name = node.name || executionId;
|
||||
const label = node.label || node.displayName || undefined;
|
||||
const displayName = node.displayName || undefined;
|
||||
const taskType = node.type || "unknown";
|
||||
const durationMs = typeof node.executionTime === "number" ? node.executionTime : undefined;
|
||||
const loopPath = node.currentLoopPath || undefined;
|
||||
const error = extractTaskErrorMessage(node);
|
||||
const isFailed = isTaskExecutionFailed(node) || rawStatus === "FAILED";
|
||||
const isSkipped = rawStatus === "SKIPPED" || rawStatus === "SKIP";
|
||||
|
||||
if (previousStatus === undefined) {
|
||||
// 第一次发现该节点
|
||||
this.seenStatuses.set(executionId, rawStatus);
|
||||
|
||||
if (isSkipped) {
|
||||
events.push({
|
||||
type: "task_skipped",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error,
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (isFailed) {
|
||||
events.push({
|
||||
type: "task_failed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error: error || "执行异常或未通过规则校验",
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (rawStatus === "COMPLETED" || rawStatus === "SUCCESS") {
|
||||
events.push({
|
||||
type: "task_completed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
} else {
|
||||
events.push({
|
||||
type: "task_started",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
}
|
||||
} else if (previousStatus !== rawStatus) {
|
||||
// 状态发生跃迁(例如从 RUNNING -> COMPLETED 或 FAILED)
|
||||
this.seenStatuses.set(executionId, rawStatus);
|
||||
|
||||
if (isSkipped) {
|
||||
events.push({
|
||||
type: "task_skipped",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error,
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (isFailed) {
|
||||
events.push({
|
||||
type: "task_failed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error: error || "执行异常或未通过规则校验",
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (rawStatus === "COMPLETED" || rawStatus === "SUCCESS") {
|
||||
events.push({
|
||||
type: "task_completed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将事件格式化为带时间戳的清晰控制台文本行
|
||||
*/
|
||||
export function formatWatchEvent(event: WorkflowWatchEvent): string {
|
||||
const timeStr = new Date(event.timestamp).toTimeString().slice(0, 8);
|
||||
const tag = `[${timeStr}]`;
|
||||
|
||||
switch (event.type) {
|
||||
case "pipeline_watch_start":
|
||||
return `${tag} 🔍 开始监听工作流 [${event.pipelineLabel || event.pipelineId}] 运行动态 (按 Ctrl+C 退出)...`;
|
||||
|
||||
case "job_detected":
|
||||
return `${tag} 🚀 捕获新运行任务 Job [${event.jobId}] (${event.runType || "RUN"}, 状态: ${event.status || "RUNNING"})`;
|
||||
|
||||
case "task_started":
|
||||
return ` ⏳ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} 开始运行...${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}`;
|
||||
|
||||
case "task_completed":
|
||||
return ` ✓ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} COMPLETED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}`;
|
||||
|
||||
case "task_skipped": {
|
||||
const errHint = event.error ? `\n ↳ ⚠️ 异常跳过原因: ${event.error}` : "";
|
||||
return ` ⚠️ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} SKIPPED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}${errHint}`;
|
||||
}
|
||||
|
||||
case "task_failed":
|
||||
return ` ❌ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} FAILED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}\n ↳ 错误详情: ${event.error || "未捕获明确错误信息"}`;
|
||||
|
||||
case "job_completed": {
|
||||
const summary = event.jobSummary;
|
||||
const isOk = summary?.status === "COMPLETED" && !summary.hasError && summary.errorCount === 0;
|
||||
const icon = isOk ? "🏁" : "❌";
|
||||
const statusText = summary?.status || "COMPLETED";
|
||||
return `${tag} ${icon} Job [${event.jobId}] 执行结束: 状态 [${statusText}] | 耗时: ${summary?.durationMs ?? "-"}ms | 成功: ${summary?.successCount ?? 0} | 失败: ${summary?.errorCount ?? 0} | 存在错误: ${summary?.hasError ? "是" : "否"}`;
|
||||
}
|
||||
|
||||
case "timeout":
|
||||
return `${tag} ⏱️ 监听超时,未在指定时间内捕获到新的任务状态变更。`;
|
||||
|
||||
case "idle":
|
||||
return `${tag} 💤 暂无新运行实例,继续等待中...`;
|
||||
|
||||
default:
|
||||
return `${tag} [${event.type}]`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听指定单个 Job 的实时执行,直至其达到终态或超时
|
||||
*/
|
||||
export async function watchSingleJob(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: WatchWorkflowOptions = {}
|
||||
): Promise<WatchedJobResult> {
|
||||
const intervalMs = Math.max(options.intervalMs ?? 1500, 500);
|
||||
const timeoutMs = options.timeoutMs ?? 60000;
|
||||
const startTime = Date.now();
|
||||
const tracker = new TaskExecutionTracker(jobId);
|
||||
const events: WorkflowWatchEvent[] = [];
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
events.push(event);
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
}
|
||||
};
|
||||
|
||||
let latestJob: WorkflowJobDetail | undefined;
|
||||
let isTerminal = false;
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (options.signal?.aborted) break;
|
||||
|
||||
try {
|
||||
latestJob = await api.getJob(client, jobId);
|
||||
} catch {
|
||||
// 任务初创可能存在 404/延迟,忽略单次瞬态
|
||||
}
|
||||
|
||||
const currentStatus = normalizeJobStatus(latestJob);
|
||||
|
||||
// 获取当前执行树并比对增量事件
|
||||
try {
|
||||
const tree = await api.getJobExecutionTree(client, jobId);
|
||||
const deltaEvents = tracker.processExecutions(tree);
|
||||
for (const ev of deltaEvents) {
|
||||
await emit(ev);
|
||||
}
|
||||
} catch {
|
||||
// 忽略执行树瞬态读取异常
|
||||
}
|
||||
|
||||
if (isJobTerminal(currentStatus)) {
|
||||
isTerminal = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (options.once) {
|
||||
break;
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const remaining = timeoutMs - elapsed;
|
||||
if (remaining <= 0) break;
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
|
||||
}
|
||||
|
||||
// 终态最后同步一次失败节点信息
|
||||
let failureItems: WorkflowTaskExecution[] = [];
|
||||
try {
|
||||
const failedPage = await api.getJobFailedExecutions(client, jobId);
|
||||
failureItems = failedPage.items || [];
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
const finalStatus = normalizeJobStatus(latestJob);
|
||||
const anyJob = latestJob as any;
|
||||
const successCount = Number(anyJob?.successTaskCount ?? 0);
|
||||
const errorCount = Math.max(Number(anyJob?.errorTaskCount ?? 0), failureItems.length);
|
||||
const hasError = anyJob?.hasError === true || anyJob?.hasError === "存在" || errorCount > 0 || finalStatus === "FAILED";
|
||||
const durationMs = typeof anyJob?.durationTime === "number" ? anyJob.durationTime : undefined;
|
||||
|
||||
const completionEvent: WorkflowWatchEvent = {
|
||||
type: "job_completed",
|
||||
jobId,
|
||||
status: finalStatus,
|
||||
timestamp: Date.now(),
|
||||
jobSummary: {
|
||||
status: finalStatus,
|
||||
durationMs,
|
||||
successCount,
|
||||
errorCount,
|
||||
hasError,
|
||||
},
|
||||
};
|
||||
await emit(completionEvent);
|
||||
|
||||
return {
|
||||
jobId,
|
||||
pipelineId: latestJob?.pipelineId || "",
|
||||
status: finalStatus,
|
||||
runType: latestJob?.runType,
|
||||
durationMs,
|
||||
successCount,
|
||||
errorCount,
|
||||
hasError,
|
||||
events,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听工作流流水线:持续捕获新派发的 Job,并实时输出其节点执行动态
|
||||
*/
|
||||
export async function watchWorkflowPipeline(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
options: WatchWorkflowOptions = {}
|
||||
): Promise<WorkflowWatchReport> {
|
||||
const intervalMs = Math.max(options.intervalMs ?? 2000, 500);
|
||||
const timeoutMs = options.timeoutMs ?? (options.once || options.jobId ? 60000 : Infinity);
|
||||
const maxJobs = options.jobId ? 1 : (options.maxJobs ?? (options.follow ? Infinity : 1));
|
||||
const startTime = Date.now();
|
||||
const watchedJobs: WatchedJobResult[] = [];
|
||||
const seenJobIds = new Set<string>();
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
}
|
||||
};
|
||||
|
||||
// 1. 如果用户显式指定了 --job=<jobId>
|
||||
if (options.jobId) {
|
||||
const jobResult = await watchSingleJob(client, options.jobId, {
|
||||
...options,
|
||||
onEvent: emit,
|
||||
});
|
||||
watchedJobs.push(jobResult);
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 1,
|
||||
jobs: watchedJobs,
|
||||
timedOut: false,
|
||||
hasFailures: jobResult.hasError || jobResult.status === "FAILED",
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 发出监听开始事件
|
||||
let pipelineLabel = "";
|
||||
try {
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
pipelineLabel = detail.label || "";
|
||||
} catch {
|
||||
// 忽略标签读取失败
|
||||
}
|
||||
|
||||
await emit({
|
||||
type: "pipeline_watch_start",
|
||||
pipelineId,
|
||||
pipelineLabel,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 如果是一次性快照检视 (--once)
|
||||
if (options.once) {
|
||||
let targetJobId: string | undefined;
|
||||
|
||||
// 先查是否有正在运行的任务
|
||||
try {
|
||||
const running = await api.listRunningJobs(client, pipelineId, "DEBUG");
|
||||
if (running.length > 0) targetJobId = running[0].id;
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
if (!targetJobId) {
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 1 });
|
||||
if (logs.jobList && logs.jobList.length > 0) {
|
||||
const first = logs.jobList[0];
|
||||
targetJobId = first.jobId || first.id;
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetJobId) {
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 0,
|
||||
jobs: [],
|
||||
timedOut: false,
|
||||
hasFailures: false,
|
||||
};
|
||||
}
|
||||
|
||||
const singleRes = await watchSingleJob(client, targetJobId, {
|
||||
...options,
|
||||
once: true,
|
||||
onEvent: emit,
|
||||
});
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 1,
|
||||
jobs: [singleRes],
|
||||
timedOut: false,
|
||||
hasFailures: singleRes.hasError || singleRes.status === "FAILED",
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 持续监听循环
|
||||
let timedOut = false;
|
||||
|
||||
// 记录初次启动时的最新已知 JobId,避免将老历史任务当作新触发任务(除非有处于 RUNNING 状态的任务)
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 5 });
|
||||
for (const j of logs.jobList || []) {
|
||||
const jid = j.jobId || j.id;
|
||||
const status = normalizeJobStatus(j);
|
||||
// 如果不是运行中,标为已知历史
|
||||
if (jid && !isJobTerminal(status)) {
|
||||
// 运行中的保留待观察
|
||||
} else if (jid) {
|
||||
seenJobIds.add(jid);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (options.signal?.aborted) break;
|
||||
|
||||
let candidateJob: { id: string; status: string; runType?: string } | undefined;
|
||||
|
||||
// 优先检查 running 接口
|
||||
try {
|
||||
const runningJobs = await api.listRunningJobs(client, pipelineId, "DEBUG");
|
||||
const found = runningJobs.find((j) => !seenJobIds.has(j.id));
|
||||
if (found) {
|
||||
candidateJob = { id: found.id, status: found.status || "RUNNING", runType: "DEBUG" };
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
// 其次检查流水线最新 log
|
||||
if (!candidateJob) {
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 3 });
|
||||
for (const j of logs.jobList || []) {
|
||||
const jid = j.jobId || j.id;
|
||||
if (jid && !seenJobIds.has(jid)) {
|
||||
candidateJob = { id: jid, status: normalizeJobStatus(j), runType: j.runType };
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
if (candidateJob) {
|
||||
seenJobIds.add(candidateJob.id);
|
||||
|
||||
await emit({
|
||||
type: "job_detected",
|
||||
pipelineId,
|
||||
jobId: candidateJob.id,
|
||||
status: candidateJob.status,
|
||||
runType: candidateJob.runType,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 实时跟踪该 Job 执行
|
||||
const jobResult = await watchSingleJob(client, candidateJob.id, {
|
||||
...options,
|
||||
onEvent: emit,
|
||||
});
|
||||
|
||||
watchedJobs.push(jobResult);
|
||||
|
||||
if (watchedJobs.length >= maxJobs) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const remaining = timeoutMs - elapsed;
|
||||
if (remaining <= 0) {
|
||||
timedOut = true;
|
||||
break;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
|
||||
}
|
||||
|
||||
if (Date.now() - startTime >= timeoutMs && watchedJobs.length === 0) {
|
||||
timedOut = true;
|
||||
await emit({
|
||||
type: "timeout",
|
||||
pipelineId,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const hasFailures = watchedJobs.some((j) => j.hasError || j.status === "FAILED");
|
||||
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: watchedJobs.length,
|
||||
jobs: watchedJobs,
|
||||
timedOut,
|
||||
hasFailures,
|
||||
};
|
||||
}
|
||||
export * from "./workflow/watch/index.js";
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { getDatabase } from "../../../../core/db/index.js";
|
||||
|
||||
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[];
|
||||
}
|
||||
|
||||
/** 本地持久化工作流错误指纹(统一落盘至 core/db SQLite,兼容显式 JSON 状态文件)。 */
|
||||
export class WorkflowAlertStore {
|
||||
private readonly scopeKey: string;
|
||||
private readonly jsonPath?: string;
|
||||
private readonly customDb?: Database;
|
||||
|
||||
constructor(scopeOrFilePath = "default", db?: Database) {
|
||||
this.scopeKey = scopeOrFilePath;
|
||||
this.customDb = db;
|
||||
if (scopeOrFilePath.endsWith(".json")) {
|
||||
this.jsonPath = scopeOrFilePath;
|
||||
}
|
||||
}
|
||||
|
||||
private get db(): Database {
|
||||
return this.customDb ?? getDatabase();
|
||||
}
|
||||
|
||||
private read(): PersistedAlerts {
|
||||
const dbRows = this.db
|
||||
.query(
|
||||
"SELECT id, error_count, observed_at FROM workflow_error_alerts WHERE scope_key = ?"
|
||||
)
|
||||
.all(this.scopeKey) as Array<{
|
||||
id: string;
|
||||
error_count: number;
|
||||
observed_at: number;
|
||||
}>;
|
||||
|
||||
if (dbRows.length > 0) {
|
||||
const alerts: Record<string, { errorCount: number; lastSeen: number }> = {};
|
||||
for (const row of dbRows) {
|
||||
alerts[row.id] = { errorCount: row.error_count, lastSeen: row.observed_at };
|
||||
}
|
||||
return { version: 1, alerts };
|
||||
}
|
||||
|
||||
if (this.jsonPath && existsSync(this.jsonPath)) {
|
||||
try {
|
||||
const value = JSON.parse(readFileSync(this.jsonPath, "utf8")) as Partial<PersistedAlerts>;
|
||||
return {
|
||||
version: 1,
|
||||
alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {},
|
||||
};
|
||||
} catch {
|
||||
return { version: 1, alerts: {} };
|
||||
}
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
const db = this.db;
|
||||
const upsert = db.prepare(`
|
||||
INSERT INTO workflow_error_alerts (
|
||||
scope_key, id, pipeline_id, platform_id, pipeline_name, error_count, state, observed_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(scope_key, id) DO UPDATE SET
|
||||
pipeline_name = excluded.pipeline_name,
|
||||
error_count = excluded.error_count,
|
||||
state = excluded.state,
|
||||
observed_at = excluded.observed_at
|
||||
`);
|
||||
|
||||
const tx = db.transaction((items: WorkflowErrorAlert[]) => {
|
||||
db.run("DELETE FROM workflow_error_alerts WHERE scope_key = ?", [this.scopeKey]);
|
||||
for (const alert of items) {
|
||||
upsert.run(
|
||||
this.scopeKey,
|
||||
alert.id,
|
||||
alert.pipelineId,
|
||||
alert.platformId,
|
||||
alert.pipelineName,
|
||||
alert.errorCount,
|
||||
alert.state,
|
||||
alert.observedAt
|
||||
);
|
||||
}
|
||||
});
|
||||
tx(alerts);
|
||||
|
||||
if (this.jsonPath) {
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
`${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
}
|
||||
|
||||
return { activeAlerts: alerts, newAlerts };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type {
|
||||
WorkflowAnalysis,
|
||||
WorkflowAstNode,
|
||||
WorkflowDependency,
|
||||
WorkflowDiagnostic,
|
||||
WorkflowFormSpecComponentLike,
|
||||
AnalyzeWorkflowOptions,
|
||||
} from "./types.js";
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
"crontab",
|
||||
"clock",
|
||||
"condition",
|
||||
"every",
|
||||
"stop",
|
||||
"http",
|
||||
"flow-detail",
|
||||
"code",
|
||||
"code-js2",
|
||||
"ekuaibao-datalink-filter",
|
||||
"ekuaibao-datalink-create",
|
||||
"ekuaibao-datalink-edit",
|
||||
"ekuaibao-datalink-delete",
|
||||
"ekuaibao-flowform-trigger",
|
||||
"ekuaibao-ebot-trigger",
|
||||
"ekuaibao-datalink-create-trigger",
|
||||
"ekuaibao-datalink-time-trigger",
|
||||
"ekuaibao-datalink-edit-trigger",
|
||||
"ekuaibao-datalink-delete-trigger",
|
||||
"data-convert",
|
||||
"flow-create-task",
|
||||
]);
|
||||
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [
|
||||
...code.matchAll(
|
||||
/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g
|
||||
),
|
||||
]
|
||||
.map((match) => (match[1] || match[2] || "").trim())
|
||||
.filter(Boolean);
|
||||
return [...new Set(values)];
|
||||
}
|
||||
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] {
|
||||
return tasks.map((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
return {
|
||||
type: task.type,
|
||||
name: task.name,
|
||||
label: task.label || task.displayName || "",
|
||||
path,
|
||||
orderIndex: task.orderIndex,
|
||||
levelIndex: task.levelIndex,
|
||||
children: toAst(task.tasks || [], path),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getTaskSpecificationId(task: WorkflowTask): string | undefined {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (typeof raw.specificationId === "string" && raw.specificationId.trim()) {
|
||||
return raw.specificationId.trim();
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const found = task.inputs.find((item) => item.key === "specificationId");
|
||||
if (found && typeof found.value === "string" && found.value.trim()) {
|
||||
return found.value.trim();
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const specId = (raw.inputs as Record<string, unknown>).specificationId;
|
||||
if (typeof specId === "string" && specId.trim()) {
|
||||
return specId.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getTaskFormEntries(
|
||||
task: WorkflowTask
|
||||
): Array<{ key?: string; label?: string; type?: string; value?: unknown }> {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (Array.isArray(raw.form)) {
|
||||
return raw.form.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (raw.form && typeof raw.form === "object") {
|
||||
return Object.entries(raw.form as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const formInput = task.inputs.find((item) => item.key === "form");
|
||||
if (formInput && Array.isArray(formInput.value)) {
|
||||
return formInput.value.filter(
|
||||
(item: unknown): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formInput && formInput.value && typeof formInput.value === "object") {
|
||||
return Object.entries(formInput.value as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const formVal = (raw.inputs as Record<string, unknown>).form;
|
||||
if (Array.isArray(formVal)) {
|
||||
return formVal.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formVal && typeof formVal === "object") {
|
||||
return Object.entries(formVal as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
||||
const ids = new Set<string>();
|
||||
const walk = (tasks: WorkflowTask[]) => {
|
||||
for (const task of tasks) {
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
if (specId) ids.add(specId);
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
walk(task.tasks);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(detail.tasks || []);
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
||||
if (task.type !== "condition") return false;
|
||||
const raw = task as Record<string, unknown>;
|
||||
const filterSource = raw.combineFilters ?? raw.filters ?? task.inputs ?? raw.conditions ?? {};
|
||||
const serialized = JSON.stringify(filterSource);
|
||||
if (
|
||||
serialized.includes(`${targetTaskName}.$status`) ||
|
||||
serialized.includes(`${targetTaskName}.status`) ||
|
||||
serialized.includes(`${targetTaskName}.result`) ||
|
||||
serialized.includes(`${targetTaskName}.data`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
serialized.includes(targetTaskName) &&
|
||||
(serialized.includes("$status") || serialized.includes("是否运行成功"))
|
||||
);
|
||||
}
|
||||
|
||||
function findUnguardedDatalinkEdits(
|
||||
tasks: WorkflowTask[],
|
||||
basePath: string,
|
||||
createTaskName: string
|
||||
): Array<{ task: WorkflowTask; path: string }> {
|
||||
const found: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
tasks.forEach((task, idx) => {
|
||||
const path = `${basePath}.${idx}`;
|
||||
if (task.type === "ekuaibao-datalink-edit") {
|
||||
found.push({ task, path });
|
||||
return;
|
||||
}
|
||||
if (taskGuardsStatusOf(task, createTaskName)) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
found.push(...findUnguardedDatalinkEdits(task.tasks, path, createTaskName));
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
export function analyzeWorkflow(
|
||||
detail: WorkflowDetail,
|
||||
options: AnalyzeWorkflowOptions = {}
|
||||
): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks);
|
||||
const dependencies: WorkflowDependency[] = [];
|
||||
const diagnostics: WorkflowDiagnostic[] = [];
|
||||
|
||||
if (detail.state === 0) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "WORKFLOW_DISABLED",
|
||||
path: "workflow",
|
||||
message:
|
||||
"工作流当前处于未启用/草稿状态 (state=0),修改或排障后需 publish/toggle --state=1 方可生效",
|
||||
});
|
||||
}
|
||||
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
||||
tasks.forEach((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
const refs = referencesFromTask(task);
|
||||
if (refs.length) {
|
||||
dependencies.push({ path, taskType: task.type, references: refs });
|
||||
}
|
||||
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "EMPTY_CODE",
|
||||
path,
|
||||
message: "代码节点没有可执行脚本",
|
||||
});
|
||||
}
|
||||
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "EMPTY_BRANCH",
|
||||
path,
|
||||
message: `${task.type} 控制节点没有子节点`,
|
||||
});
|
||||
}
|
||||
if (!KNOWN_TYPES.has(task.type)) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNKNOWN_TASK_TYPE",
|
||||
path,
|
||||
message: `未收录的节点类型: ${task.type}`,
|
||||
});
|
||||
}
|
||||
|
||||
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
||||
if (insideEvery && task.type === "flow-create-task") {
|
||||
const onError = (task as Record<string, unknown>).onError as
|
||||
| { defaultAction?: string }
|
||||
| undefined;
|
||||
if (onError?.defaultAction === "SKIP") {
|
||||
const subsequentSiblings = tasks.slice(index + 1);
|
||||
const unguardedEdits: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
subsequentSiblings.forEach((sibling, relIdx) => {
|
||||
const siblingIndex = index + 1 + relIdx;
|
||||
const siblingPath = parentPath ? `${parentPath}.${siblingIndex}` : String(siblingIndex);
|
||||
if (sibling.type === "ekuaibao-datalink-edit") {
|
||||
unguardedEdits.push({ task: sibling, path: siblingPath });
|
||||
} else if (!taskGuardsStatusOf(sibling, task.name) && sibling.tasks?.length) {
|
||||
unguardedEdits.push(
|
||||
...findUnguardedDatalinkEdits(sibling.tasks, siblingPath, task.name)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
for (const edit of unguardedEdits) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
||||
path: edit.path,
|
||||
message: `节点 [${task.label || task.name}] (${task.name}) 配置了报错跳过(SKIP),但后续台账更新节点 [${edit.task.label || edit.task.name}] (${edit.task.name}) 未校验其执行状态(如 ${task.name}.$status),前序建单失败时仍会误改台账状态!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 3: flow-create-task 表单字段联动覆盖告警 (LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN)
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
const spec = specId ? options.specifications?.[specId] : undefined;
|
||||
const formEntries = getTaskFormEntries(task).filter(
|
||||
(entry) =>
|
||||
entry.value !== undefined &&
|
||||
entry.value !== null &&
|
||||
String(entry.value).trim() !== ""
|
||||
);
|
||||
|
||||
const specComponents =
|
||||
spec?.components ??
|
||||
(Array.isArray((spec as unknown as Record<string, unknown> | undefined)?.form)
|
||||
? ((spec as unknown as Record<string, unknown>).form as WorkflowFormSpecComponentLike[])
|
||||
: []);
|
||||
|
||||
if (spec && specComponents.length && formEntries.length > 0) {
|
||||
const matchedComponents = specComponents.filter((comp) => {
|
||||
const compKey = comp.name || comp.field || "";
|
||||
return formEntries.some(
|
||||
(entry) =>
|
||||
(Boolean(compKey) && entry.key === compKey) ||
|
||||
(Boolean(entry.label) && Boolean(comp.label) && entry.label === comp.label)
|
||||
);
|
||||
});
|
||||
|
||||
const linkageSources = matchedComponents.filter(
|
||||
(comp) =>
|
||||
Boolean(comp.assignmentRule) ||
|
||||
(comp.type === "dataLink" && comp.isLinkageAssignment === true)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
const srcKey = src.name || src.field || src.label || "";
|
||||
const overrideTargets = matchedComponents
|
||||
.filter((comp) => (comp.name || comp.field || comp.label || "") !== srcKey)
|
||||
.map((comp) => {
|
||||
const list = comp.priorityList || comp.priority || [];
|
||||
const linkage = list.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = list.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
const linkagePriority = linkage?.priority ?? linkage?.value;
|
||||
const manualPriority = manual?.priority ?? manual?.value;
|
||||
if (
|
||||
linkagePriority !== undefined &&
|
||||
manualPriority !== undefined &&
|
||||
linkagePriority > manualPriority
|
||||
) {
|
||||
return {
|
||||
comp,
|
||||
compKey: comp.name || comp.field || comp.label || "",
|
||||
linkagePriority,
|
||||
manualPriority,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
||||
|
||||
if (overrideTargets.length > 0) {
|
||||
const affectedDesc = overrideTargets
|
||||
.map(
|
||||
(t) =>
|
||||
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
||||
)
|
||||
.join("、");
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "LINKAGE_PRIORITY_OVERRIDE",
|
||||
path,
|
||||
message: `表单模板 [${spec.name || spec.id}] 中字段 [${src.label || srcKey}] (${srcKey}) 存在业务对象联动配置 (isLinkageAssignment=${Boolean(src.isLinkageAssignment)}, assignmentRule=${src.assignmentRule || "-"}),且当前节点同时传入了 [${affectedDesc}],联动赋值优先级高于手动/API 传入,显式传入的值可能被关联对象中的字段值覆盖!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 4: 触发器节点配置了无效的单据审批状态过滤 (DEADLOCK_TRIGGER_STATE_FILTER)
|
||||
if (
|
||||
(task.type === "ekuaibao-flowform-trigger" || task.type === "ekuaibao-ebot-trigger") &&
|
||||
(task as Record<string, unknown>).combineFilters
|
||||
) {
|
||||
const rawFilters = JSON.stringify((task as Record<string, unknown>).combineFilters);
|
||||
if (
|
||||
rawFilters.includes('"key":"state"') &&
|
||||
(rawFilters.includes('"APPROVING"') || rawFilters.includes('"approving"'))
|
||||
) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "DEADLOCK_TRIGGER_STATE_FILTER",
|
||||
path,
|
||||
message: `触发器节点 [${task.label || task.name}] (${task.name}) 配置了 state == APPROVING 状态过滤条件。合思单据审批出站事件属于动作事件(如 backlog.approving),事件载荷中不携带大写 APPROVING 状态字段,该过滤会导致出站事件被 100% 静默丢弃,下游审批流程永久无法触发!建议移除 state 过滤,改用后置条件节点判断审批人。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 5: HTTP 自动审批节点 URL 与中括号校验 (MISSING_BACKLOG_DATA_BRACKETS)
|
||||
if (task.type === "http") {
|
||||
const url = String((task as Record<string, unknown>).url || "");
|
||||
if (url.includes("api/openapi/v1/backlog/data")) {
|
||||
const match = url.match(/api\/openapi\/v1\/backlog\/data\/([^?#]+)/);
|
||||
const segment = match ? match[1] : "";
|
||||
if (segment && (!segment.startsWith("[") || !segment.includes("]"))) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "MISSING_BACKLOG_DATA_BRACKETS",
|
||||
path,
|
||||
message: `HTTP 自动审批节点 [${task.label || task.name}] 的 URL 路径参数缺少合思 OpenAPI 规范的方括号(规范要求: /api/openapi/v1/backlog/data/[{flowId}]),缺少方括号将导致服务端直接返回 404 Not Found。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
});
|
||||
};
|
||||
|
||||
visit(detail.tasks);
|
||||
return {
|
||||
workflow: {
|
||||
id: detail.id,
|
||||
label: detail.label,
|
||||
state: detail.state,
|
||||
version: detail.version,
|
||||
},
|
||||
ast,
|
||||
dependencies,
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./types.js";
|
||||
export * from "./analyzer.js";
|
||||
@@ -0,0 +1,50 @@
|
||||
export interface WorkflowAstNode {
|
||||
type: string;
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
children: WorkflowAstNode[];
|
||||
}
|
||||
|
||||
export interface WorkflowDependency {
|
||||
path: string;
|
||||
taskType: string;
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
name?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
isLinkageAssignment?: boolean;
|
||||
assignmentRule?: string | null;
|
||||
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
||||
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecLike {
|
||||
id: string;
|
||||
name?: string;
|
||||
components?: WorkflowFormSpecComponentLike[];
|
||||
}
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
import { indexExecutionContexts } from "../../execution-context.js";
|
||||
import type { ConditionBranchExplanation, ConditionRuleExplanation } from "./types.js";
|
||||
|
||||
export const OP_MAP: Record<string, string> = {
|
||||
eq: "等于",
|
||||
neq: "不等于",
|
||||
include: "包含",
|
||||
not_include: "不包含",
|
||||
in: "在列表中",
|
||||
not_in: "不在列表中",
|
||||
gt: "大于",
|
||||
gte: "大于等于",
|
||||
lt: "小于",
|
||||
lte: "小于等于",
|
||||
empty: "为空",
|
||||
not_empty: "不为空",
|
||||
};
|
||||
|
||||
/**
|
||||
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签
|
||||
*/
|
||||
export function parseChooseTag(tag: string): {
|
||||
upstreamNode: string;
|
||||
upstreamProp: string;
|
||||
label: string;
|
||||
} | null {
|
||||
if (typeof tag !== "string") return null;
|
||||
const match = tag.match(/@\{choose\('(.*)'\)\}/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]);
|
||||
const upstreamNode = parsed.key || "";
|
||||
const upstreamProp = (parsed.properties ?? []).map((property: { key?: string }) => property.key).filter(Boolean).join(".");
|
||||
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
|
||||
return { upstreamNode, upstreamProp, label };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试从 @{value('...')} 中提取人类可读值
|
||||
*/
|
||||
export function parseValueTag(val: any): any {
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((v) => parseValueTag(v));
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const match = val.match(/@\{value\('(.*)'\)\}/);
|
||||
if (match) {
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]);
|
||||
return parsed.label ? `${parsed.label} (${parsed.key})` : parsed.key || parsed.value;
|
||||
} catch {
|
||||
return val;
|
||||
}
|
||||
}
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个值是否匹配
|
||||
*/
|
||||
export function cleanRuleValue(value: any): any {
|
||||
if (Array.isArray(value)) return value.map(cleanRuleValue);
|
||||
if (typeof value === "string") {
|
||||
const match = value.match(/@\{value\('(.*)'\)\}/);
|
||||
if (match) {
|
||||
try { const parsed = JSON.parse(match[1]); return parsed.key ?? parsed.value; }
|
||||
catch { return value; }
|
||||
}
|
||||
}
|
||||
if (value && typeof value === "object" && "id" in value) return value.id;
|
||||
return value;
|
||||
}
|
||||
|
||||
export function evaluateRule(actual: any, expected: any, compare: string): boolean | null {
|
||||
const empty = actual === undefined || actual === null || actual === "" || (Array.isArray(actual) && actual.length === 0);
|
||||
if (compare === "empty") return empty;
|
||||
if (compare === "not_empty") return !empty;
|
||||
if (!Object.hasOwn(OP_MAP, compare)) return null;
|
||||
if (actual === undefined) return false;
|
||||
actual = cleanRuleValue(actual);
|
||||
expected = cleanRuleValue(expected);
|
||||
if (actual === null) return compare === "eq" ? expected === null : compare === "neq" ? expected !== null : false;
|
||||
if ([actual, expected].some(value => value !== null && typeof value === "object" && !Array.isArray(value))) return null;
|
||||
const equal = (a: any, b: any): boolean => {
|
||||
if (Array.isArray(a) && !Array.isArray(b)) return a.length === 1 && equal(a[0], b);
|
||||
if (!Array.isArray(a) && Array.isArray(b)) return b.length === 1 && equal(a, b[0]);
|
||||
return typeof a === "object" || typeof b === "object" ? JSON.stringify(a) === JSON.stringify(b) : String(a) === String(b);
|
||||
};
|
||||
switch (compare) {
|
||||
case "eq": return equal(actual, expected);
|
||||
case "neq": return !equal(actual, expected);
|
||||
case "in":
|
||||
case "not_in": {
|
||||
if (!Array.isArray(expected) || Array.isArray(actual)) return null;
|
||||
const matches = expected.some(item => equal(actual, item));
|
||||
return compare === "in" ? matches : !matches;
|
||||
}
|
||||
case "include":
|
||||
case "not_include": {
|
||||
if (!Array.isArray(actual) && typeof actual !== "string") return null;
|
||||
const values = Array.isArray(expected) ? expected : [expected];
|
||||
const matches = Array.isArray(actual)
|
||||
? values.every(value => actual.some(item => equal(item, value)))
|
||||
: typeof actual === "string" && values.every(value => actual.includes(String(value)));
|
||||
return compare === "include" ? matches : !matches;
|
||||
}
|
||||
default: {
|
||||
const numeric = (value: unknown) => typeof value === "number" || (typeof value === "string" && value.trim() !== "") ? Number(value) : NaN;
|
||||
const a = numeric(actual), b = numeric(expected);
|
||||
if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
|
||||
return compare === "gt" ? a > b : compare === "gte" ? a >= b : compare === "lt" ? a < b : a <= b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析 Job 执行树中的条件节点,诊断分支是否跳过及跳过的具体字段原因
|
||||
*/
|
||||
export function explainConditionBranches(
|
||||
tree: WorkflowTaskExecution[]
|
||||
): ConditionBranchExplanation[] {
|
||||
const contexts = indexExecutionContexts(tree);
|
||||
const explanations: ConditionBranchExplanation[] = [];
|
||||
|
||||
for (const [position, context] of contexts.entries()) {
|
||||
const node = context.node;
|
||||
const rawNode = node as Record<string, any>;
|
||||
if (rawNode.type !== "condition") continue;
|
||||
const childTasks = Array.isArray(rawNode.tasks) ? rawNode.tasks : [];
|
||||
if (childTasks.length === 0) continue;
|
||||
|
||||
// 检查子任务是否执行过
|
||||
const childNames = childTasks.map((task: any) => task.name || task.id).filter(Boolean);
|
||||
const childContexts = contexts.filter((child, index) => {
|
||||
if (child.loopPath !== context.loopPath || !childNames.includes(child.node.name || child.node.id)) return false;
|
||||
if (child.node.parentId) return child.node.parentId === node.id;
|
||||
const nestedScope = [...context.scope, JSON.stringify([node.name || node.type || "unnamed", context.loopPath])];
|
||||
return JSON.stringify(child.scope) === JSON.stringify(nestedScope) ||
|
||||
(index > position && JSON.stringify(child.scope) === JSON.stringify(context.scope));
|
||||
});
|
||||
const anyExecuted = childContexts.some(child => child.node.status && !["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase()));
|
||||
if (anyExecuted) {
|
||||
// 子分支正常执行,无需诊断跳过
|
||||
continue;
|
||||
}
|
||||
const skippedTaskNames = childTasks.map((task: any) => `${task.name || task.id} (${task.label || task.displayName || task.type})`);
|
||||
const rules: ConditionRuleExplanation[] = [];
|
||||
|
||||
// 解析 combineFilters;保留 AND/OR 和嵌套分组语义。
|
||||
const explainFilter = (filter: any): boolean | null => {
|
||||
if (!filter || typeof filter !== "object") return null;
|
||||
if (Array.isArray(filter.filters)) {
|
||||
const values = filter.filters.map(explainFilter) as Array<boolean | null>;
|
||||
if (!values.length) return null;
|
||||
const condition = String(filter.condition ?? "AND").toUpperCase();
|
||||
if (condition === "AND") return values.includes(false) ? false : values.includes(null) ? null : true;
|
||||
if (condition === "OR") return values.includes(true) ? true : values.includes(null) ? null : false;
|
||||
return null;
|
||||
}
|
||||
const chooseInfo = parseChooseTag(filter.key);
|
||||
const rawExpected = filter.value;
|
||||
const parsedExpected = parseValueTag(rawExpected);
|
||||
const op = filter.compare || "eq";
|
||||
const upstreamNode = chooseInfo?.upstreamNode || "";
|
||||
const upstreamProp = chooseInfo?.upstreamProp || (typeof filter.key === "string" ? filter.key : "");
|
||||
const leftLabel = chooseInfo?.label || String(filter.key);
|
||||
|
||||
// 从上游节点提取真实 outputs;只使用同一次循环或祖先作用域中的执行实例。
|
||||
const candidates = contexts.slice(0, position).filter(candidate =>
|
||||
(candidate.node.name === upstreamNode || candidate.node.id === upstreamNode) &&
|
||||
(!candidate.loopPath || candidate.loopPath === context.loopPath) &&
|
||||
candidate.scope.every((part, i) => context.scope[i] === part)
|
||||
);
|
||||
candidates.sort((a, b) => a.scope.length - b.scope.length);
|
||||
const upstreamExecution = candidates.at(-1)?.node;
|
||||
const upstreamOutputs = upstreamExecution?.output ?? upstreamExecution?.outputs;
|
||||
let actualVal: any = upstreamOutputs;
|
||||
let isMissing = false;
|
||||
for (const part of upstreamProp.split(".")) {
|
||||
if (actualVal && typeof actualVal === "object" && Object.hasOwn(actualVal, part)) actualVal = actualVal[part];
|
||||
else { actualVal = undefined; isMissing = Boolean(upstreamExecution); break; }
|
||||
}
|
||||
// 提取纯净 ID 比对
|
||||
const cleanExpected = cleanRuleValue(rawExpected);
|
||||
const matched = upstreamExecution ? evaluateRule(actualVal, cleanExpected, op) : null;
|
||||
let detail: string;
|
||||
if (isMissing) {
|
||||
const availableKeys = upstreamOutputs && typeof upstreamOutputs === "object" ? Object.keys(upstreamOutputs).join(", ") : "无出参";
|
||||
detail = `上游节点 [${upstreamNode}] 未返回该属性 [${upstreamProp}](字段名可能脱节,上游可用字段: ${availableKeys})➔ 解析值为 null`;
|
||||
} else if (matched === null) {
|
||||
detail = `无法确定:缺少上游执行证据,或操作符/值类型不支持 (${op})`;
|
||||
} else {
|
||||
const actStr = typeof actualVal === "object" ? JSON.stringify(actualVal) : String(actualVal ?? "null");
|
||||
const expStr = typeof parsedExpected === "object" ? JSON.stringify(parsedExpected) : String(parsedExpected);
|
||||
detail = `实际值: ${actStr} 与期望值 [${expStr}] 比对结果为 ${matched ? "True" : "False"}`;
|
||||
}
|
||||
rules.push({ leftLabel, upstreamNode, upstreamProp, operator: op, operatorLabel: OP_MAP[op] || op, expectedValue: parsedExpected, actualValue: actualVal, isMissing, matched, detail });
|
||||
return matched;
|
||||
};
|
||||
const calculated = explainFilter(rawNode.combineFilters);
|
||||
const evaluation = node.status.toUpperCase() === "COMPLETED" ? calculated : null;
|
||||
let summary = evaluation === false
|
||||
? `条件判定未通过 (False),子任务 [${skippedTaskNames.join(", ")}] 被跳过未执行`
|
||||
: evaluation === true
|
||||
? "条件比对为 True,但未见子任务执行记录;请核对执行树是否完整"
|
||||
: "执行证据不足或条件尚未完成,无法确定子任务是否被跳过";
|
||||
const missingRule = rules.find(rule => rule.isMissing);
|
||||
if (evaluation === false && missingRule) {
|
||||
summary = `条件字段脱节: 上游节点 [${missingRule.upstreamNode}] 缺少属性 [${missingRule.upstreamProp}],判定为 False,子任务被跳过`;
|
||||
}
|
||||
explanations.push({
|
||||
conditionNodeId: node.id,
|
||||
conditionNodeName: node.name || "-",
|
||||
conditionNodeLabel: node.label || rawNode.displayName || "条件节点",
|
||||
hasSkippedTasks: evaluation === false || childContexts.some(child => ["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase())),
|
||||
evaluation,
|
||||
skippedTaskNames,
|
||||
rules,
|
||||
summary,
|
||||
});
|
||||
}
|
||||
return explanations;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./types.js";
|
||||
export * from "./explain.js";
|
||||
@@ -0,0 +1,23 @@
|
||||
export interface ConditionRuleExplanation {
|
||||
leftLabel: string;
|
||||
upstreamNode: string;
|
||||
upstreamProp: string;
|
||||
operator: string;
|
||||
operatorLabel: string;
|
||||
expectedValue: any;
|
||||
actualValue: any;
|
||||
isMissing: boolean;
|
||||
matched: boolean | null;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface ConditionBranchExplanation {
|
||||
conditionNodeId: string;
|
||||
conditionNodeName: string;
|
||||
conditionNodeLabel: string;
|
||||
hasSkippedTasks: boolean;
|
||||
evaluation: boolean | null;
|
||||
skippedTaskNames: string[];
|
||||
rules: ConditionRuleExplanation[];
|
||||
summary: string;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export * from "./watch/index.js";
|
||||
export * from "./nodes/index.js";
|
||||
export * from "./script/index.js";
|
||||
export * from "./branch/index.js";
|
||||
export * from "./analysis/index.js";
|
||||
export * from "./state/index.js";
|
||||
export * from "./alert/index.js";
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./types.js";
|
||||
export * from "./tree.js";
|
||||
export * from "./locator.js";
|
||||
export * from "./mutations.js";
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { LocatedWorkflowTask } from "./types.js";
|
||||
|
||||
/**
|
||||
* 在任务树中按节点名称、层级编号 (如 "2.1") 或全局序号定位目标任务
|
||||
*/
|
||||
export function findWorkflowTask(
|
||||
tasksOrWorkflow: WorkflowTask[] | { tasks?: WorkflowTask[] },
|
||||
target: string | number
|
||||
): LocatedWorkflowTask | null {
|
||||
const tasks = Array.isArray(tasksOrWorkflow)
|
||||
? tasksOrWorkflow
|
||||
: tasksOrWorkflow?.tasks || [];
|
||||
const targetStr = String(target).trim();
|
||||
const targetNum = Number(targetStr);
|
||||
const isNumeric = !Number.isNaN(targetNum) && Number.isInteger(targetNum) && targetNum > 0;
|
||||
|
||||
let globalCounter = 0;
|
||||
|
||||
function search(
|
||||
list: WorkflowTask[],
|
||||
prefix: string,
|
||||
basePath: string,
|
||||
parentName?: string
|
||||
): LocatedWorkflowTask | null {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const task = list[i];
|
||||
globalCounter += 1;
|
||||
const hierarchicalIndex = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
|
||||
const path = basePath ? `${basePath}.${i}` : `tasks.${i}`;
|
||||
|
||||
const matched =
|
||||
task.name === targetStr ||
|
||||
hierarchicalIndex === targetStr ||
|
||||
(isNumeric && globalCounter === targetNum);
|
||||
|
||||
if (matched) {
|
||||
return {
|
||||
task,
|
||||
path,
|
||||
parentTasks: list,
|
||||
arrayIndex: i,
|
||||
hierarchicalIndex,
|
||||
globalIndex: globalCounter,
|
||||
parentName,
|
||||
};
|
||||
}
|
||||
|
||||
if (task.tasks && Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
const found = search(task.tasks, hierarchicalIndex, `${path}.tasks`, task.name);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return search(tasks, "", "tasks");
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import { NotFoundError, ValidationError } from "../../../../core/errors.js";
|
||||
import { findWorkflowTask } from "./locator.js";
|
||||
|
||||
/**
|
||||
* 递归重算整棵树的 orderIndex 与 levelIndex
|
||||
*/
|
||||
export function reindexTasks(
|
||||
tasks: WorkflowTask[],
|
||||
parentLevel: number[] = [],
|
||||
startOrder = 0
|
||||
): number {
|
||||
let currentOrder = startOrder;
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
const task = tasks[i];
|
||||
task.orderIndex = currentOrder++;
|
||||
task.levelIndex = [...parentLevel, i];
|
||||
if (task.tasks && Array.isArray(task.tasks)) {
|
||||
currentOrder = reindexTasks(task.tasks, task.levelIndex, currentOrder);
|
||||
}
|
||||
}
|
||||
return currentOrder;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成规范唯一的合思节点 ID
|
||||
*/
|
||||
export function generateNodeName(type: string): string {
|
||||
const rand = Math.random().toString(36).substring(2, 8);
|
||||
if (type === "every" || type === "condition") {
|
||||
return `control_${rand}`;
|
||||
}
|
||||
if (type.includes("trigger") || type === "webhook" || type === "clock") {
|
||||
return `trigger_${rand}`;
|
||||
}
|
||||
return `action_${rand}`;
|
||||
}
|
||||
|
||||
export interface AddTaskOptions {
|
||||
type: string;
|
||||
label?: string;
|
||||
code?: string;
|
||||
desc?: string;
|
||||
parent?: string | number;
|
||||
after?: string | number;
|
||||
extra?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建规范的新节点对象
|
||||
*/
|
||||
export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
|
||||
const normType = type.trim();
|
||||
const name = generateNodeName(normType);
|
||||
|
||||
switch (normType) {
|
||||
case "code-js2":
|
||||
return {
|
||||
name,
|
||||
type: "code-js2",
|
||||
label: options.label || "JS节点(新)",
|
||||
desc: options.desc || "执行一段JavaScript代码",
|
||||
groupName: "action",
|
||||
code: options.code || "// 编写处理逻辑\nreturn items;",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "code":
|
||||
return {
|
||||
name,
|
||||
type: "code",
|
||||
label: options.label || "代码节点",
|
||||
desc: options.desc || "执行一段MVEL代码",
|
||||
groupName: "action",
|
||||
code: options.code || "return true;",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "http":
|
||||
return {
|
||||
name,
|
||||
type: "http",
|
||||
label: options.label || "HTTP请求",
|
||||
groupName: "action",
|
||||
method: options.extra?.method || "POST",
|
||||
url: options.extra?.url || "",
|
||||
header: options.extra?.header || [],
|
||||
params: options.extra?.params || [],
|
||||
successCode: options.extra?.successCode || ["200"],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "stop":
|
||||
return {
|
||||
name,
|
||||
type: "stop",
|
||||
label: options.label || "终止流程",
|
||||
desc: options.desc || "如果满足条件终止流程",
|
||||
groupName: "control",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "every":
|
||||
return {
|
||||
name,
|
||||
type: "every",
|
||||
label: options.label || "依次执行",
|
||||
desc: options.desc || "依次遍历每个对象",
|
||||
groupName: "control",
|
||||
mode: "sequence",
|
||||
batch: false,
|
||||
list: options.extra?.list || "@{choose('...$item')}",
|
||||
filters: [],
|
||||
tasksMaxLevel: 1,
|
||||
tasks: [],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "condition":
|
||||
return {
|
||||
name,
|
||||
type: "condition",
|
||||
label: options.label || "条件分支",
|
||||
desc: options.desc || "如果满足条件则执行以下动作",
|
||||
groupName: "control",
|
||||
combineFilters: options.extra?.combineFilters || { condition: "or", filters: [] },
|
||||
tasksMaxLevel: 1,
|
||||
tasks: [],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "webhook":
|
||||
return {
|
||||
name,
|
||||
type: "webhook",
|
||||
label: options.label || "Webhook触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
urlPath: crypto.randomUUID(),
|
||||
params: [],
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "clock":
|
||||
return {
|
||||
name,
|
||||
type: "clock",
|
||||
label: options.label || "定时触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
cron: options.extra?.cron || "0 0 * * *",
|
||||
timeZone: options.extra?.timeZone || "Asia/Shanghai",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
name,
|
||||
type: normType,
|
||||
label: options.label || `${normType}节点`,
|
||||
desc: options.desc || "",
|
||||
groupName: normType.startsWith("control") ? "control" : "action",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向工作流声明式追加或插入任务节点
|
||||
*/
|
||||
export function addWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
options: AddTaskOptions
|
||||
): { workflow: WorkflowDetail; newTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks) cloned.tasks = [];
|
||||
|
||||
const newTask = buildWorkflowTask(options.type, options);
|
||||
|
||||
if (options.after !== undefined && options.after !== "") {
|
||||
const target = findWorkflowTask(cloned.tasks, options.after);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到插入基准节点 (--after): ${options.after}`);
|
||||
}
|
||||
// 插入在该节点的下一个位置
|
||||
target.parentTasks.splice(target.arrayIndex + 1, 0, newTask);
|
||||
} else if (options.parent !== undefined && options.parent !== "") {
|
||||
const parentTarget = findWorkflowTask(cloned.tasks, options.parent);
|
||||
if (!parentTarget) {
|
||||
throw new NotFoundError(`未找到父级容器节点 (--parent): ${options.parent}`);
|
||||
}
|
||||
if (!parentTarget.task.tasks) parentTarget.task.tasks = [];
|
||||
parentTarget.task.tasks.push(newTask);
|
||||
} else {
|
||||
// 默认追加到顶级 tasks 末尾
|
||||
cloned.tasks.push(newTask);
|
||||
}
|
||||
|
||||
// 重排索引
|
||||
reindexTasks(cloned.tasks);
|
||||
return { workflow: cloned, newTask };
|
||||
}
|
||||
|
||||
export interface EditTaskOptions {
|
||||
label?: string;
|
||||
code?: string;
|
||||
desc?: string;
|
||||
set?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定向修改工作流任务节点配置
|
||||
*/
|
||||
export function editWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
targetKey: string | number,
|
||||
updates: EditTaskOptions
|
||||
): { workflow: WorkflowDetail; editedTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks) cloned.tasks = [];
|
||||
|
||||
const target = findWorkflowTask(cloned.tasks, targetKey);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到目标工作流任务节点: ${targetKey}`);
|
||||
}
|
||||
|
||||
const { task } = target;
|
||||
if (updates.label !== undefined) task.label = updates.label;
|
||||
if (updates.desc !== undefined) task.desc = updates.desc;
|
||||
if (updates.code !== undefined) (task as any).code = updates.code;
|
||||
|
||||
if (updates.set && typeof updates.set === "object") {
|
||||
for (const [k, v] of Object.entries(updates.set)) {
|
||||
(task as any)[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
return { workflow: cloned, editedTask: task };
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全剔除工作流任务节点
|
||||
*/
|
||||
export function removeWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
targetKey: string | number
|
||||
): { workflow: WorkflowDetail; removedTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks || cloned.tasks.length === 0) {
|
||||
throw new ValidationError("工作流中无任何任务节点,无法删除");
|
||||
}
|
||||
|
||||
const target = findWorkflowTask(cloned.tasks, targetKey);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到待删除的工作流任务节点: ${targetKey}`);
|
||||
}
|
||||
|
||||
// 触发器保护:如果工作流只有首节点且是触发器,或者删除首节点触发器
|
||||
if (
|
||||
target.parentTasks === cloned.tasks &&
|
||||
target.arrayIndex === 0 &&
|
||||
cloned.tasks.length > 1 &&
|
||||
(target.task.groupName === "trigger" || target.task.type.includes("trigger") || target.task.type === "webhook" || target.task.type === "clock")
|
||||
) {
|
||||
throw new ValidationError(
|
||||
`节点 [${target.task.name}] (${target.task.label || target.task.type}) 是工作流的触发源节点。直接移除会导致工作流缺少触发器,请使用 workflow save 或在设计器中调整触发器。`
|
||||
);
|
||||
}
|
||||
|
||||
const [removedTask] = target.parentTasks.splice(target.arrayIndex, 1);
|
||||
reindexTasks(cloned.tasks);
|
||||
return { workflow: cloned, removedTask };
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { FlattenedWorkflowTask } from "./types.js";
|
||||
|
||||
/**
|
||||
* 递归计算并生成节点的紧凑配置摘要
|
||||
*/
|
||||
export function summarizeTask(task: WorkflowTask): string {
|
||||
if (task.type === "webhook") {
|
||||
return task.urlPath ? `urlPath: ${task.urlPath}` : "未配置URL";
|
||||
}
|
||||
if (task.type === "clock") {
|
||||
return `cron: ${task.cron || "0 0 * * *"} (${task.timeZone || "Asia/Shanghai"})`;
|
||||
}
|
||||
if (task.type === "code" || task.type === "code-js2") {
|
||||
const rawCode: string = (task as any).code || "";
|
||||
const firstLine = rawCode.trim().split("\n")[0] || "";
|
||||
const len = rawCode.length;
|
||||
return `脚本 (${len} 字符): ${firstLine.slice(0, 40)}${firstLine.length > 40 ? "..." : ""}`;
|
||||
}
|
||||
if (task.type === "http") {
|
||||
return `${(task as any).method || "POST"} ${(task as any).url || ""}`;
|
||||
}
|
||||
if (task.type === "every") {
|
||||
return `循环遍历: ${(task as any).list || "$item"} (含 ${task.tasks?.length || 0} 个子节点)`;
|
||||
}
|
||||
if (task.type === "condition") {
|
||||
const filters = (task as any).combineFilters?.filters || [];
|
||||
return `分支条件: ${filters.length} 组规则 (含 ${task.tasks?.length || 0} 个子节点)`;
|
||||
}
|
||||
if (task.type === "stop") {
|
||||
return "阻断终止流程";
|
||||
}
|
||||
if (task.type === "ekuaibao-datalink-create-trigger") {
|
||||
return "业务对象台账新增触发";
|
||||
}
|
||||
if (task.type === "ekuaibao-flowform-trigger") {
|
||||
return "单据流转事件触发";
|
||||
}
|
||||
return task.desc || task.label || task.type;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将整棵工作流任务树展平为有序列表,便于查看与索引
|
||||
*/
|
||||
export function flattenWorkflowTaskTree(tasks: WorkflowTask[]): FlattenedWorkflowTask[] {
|
||||
const result: FlattenedWorkflowTask[] = [];
|
||||
let globalCounter = 0;
|
||||
|
||||
function traverse(
|
||||
list: WorkflowTask[],
|
||||
prefix: string,
|
||||
depth: number,
|
||||
basePath: string,
|
||||
parentName?: string
|
||||
) {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const task = list[i];
|
||||
globalCounter += 1;
|
||||
const hierarchicalIndex = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
|
||||
const path = basePath ? `${basePath}.${i}` : `tasks.${i}`;
|
||||
|
||||
result.push({
|
||||
task,
|
||||
index: globalCounter,
|
||||
hierarchicalIndex,
|
||||
depth,
|
||||
path,
|
||||
parentName,
|
||||
summary: summarizeTask(task),
|
||||
});
|
||||
|
||||
if (task.tasks && Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
traverse(task.tasks, hierarchicalIndex, depth + 1, `${path}.tasks`, task.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(tasks, "", 0, "tasks");
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
|
||||
export interface FlattenedWorkflowTask {
|
||||
task: WorkflowTask;
|
||||
index: number; // 1-based global sequential index
|
||||
hierarchicalIndex: string; // e.g. "1", "2.1", "2.1.3"
|
||||
depth: number;
|
||||
path: string;
|
||||
parentName?: string;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface LocatedWorkflowTask {
|
||||
task: WorkflowTask;
|
||||
path: string;
|
||||
parentTasks: WorkflowTask[];
|
||||
arrayIndex: number;
|
||||
hierarchicalIndex: string;
|
||||
globalIndex: number;
|
||||
parentName?: string;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from "./types.js";
|
||||
export * from "./lint-js.js";
|
||||
export * from "./lint-mvel.js";
|
||||
export * from "./scanner.js";
|
||||
export * from "./sandbox.js";
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
|
||||
/**
|
||||
* 检查代码中是否存在 return 关键字(排除纯注释中的 return)
|
||||
*/
|
||||
export function hasReturnStatement(code: string): boolean {
|
||||
const lines = code.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
||||
continue;
|
||||
}
|
||||
if (/\breturn\b/.test(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态检查 JavaScript (code-js2) 语法与规范
|
||||
*/
|
||||
export function lintJavaScriptCode(
|
||||
code: string,
|
||||
boundVariables: string[] = []
|
||||
): { issues: ScriptIssue[]; hasReturn: boolean } {
|
||||
const issues: ScriptIssue[] = [];
|
||||
const trimmed = code.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: "代码节点脚本内容为空,合思调度时将报错",
|
||||
rule: "empty-script",
|
||||
});
|
||||
return { issues, hasReturn: false };
|
||||
}
|
||||
|
||||
const hasRet = hasReturnStatement(code);
|
||||
if (!hasRet) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "脚本中缺少显式 return 语句,可能导致下游节点接收到 null 或 undefined",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
// 语法验证:通过 Function 构造器做 AST 编译期语法解析
|
||||
try {
|
||||
// 注入声明的参数名以验证语法合法性
|
||||
new Function(...boundVariables, code);
|
||||
} catch (err: any) {
|
||||
let line: number | undefined;
|
||||
let column: number | undefined;
|
||||
|
||||
const msg = err?.message || String(err);
|
||||
// 尝试从堆栈或错误描述提取行号
|
||||
const match = err?.stack?.match(/<anonymous>:(\d+):(\d+)/) || msg.match(/line (\d+)/i);
|
||||
if (match) {
|
||||
line = Number(match[1]);
|
||||
if (match[2]) column = Number(match[2]);
|
||||
}
|
||||
|
||||
issues.push({
|
||||
level: "error",
|
||||
line,
|
||||
column,
|
||||
message: `JavaScript 语法错误: ${msg}`,
|
||||
rule: "syntax-error",
|
||||
});
|
||||
}
|
||||
|
||||
return { issues, hasReturn: hasRet };
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
import { hasReturnStatement } from "./lint-js.js";
|
||||
|
||||
/**
|
||||
* 静态检查 MVEL (code) 括号闭合与上游节点引用有效性
|
||||
*/
|
||||
export function lintMvelCode(
|
||||
code: string,
|
||||
existingNodeNames?: Set<string>
|
||||
): {
|
||||
issues: ScriptIssue[];
|
||||
referencedNodes: Array<{ name: string; exists: boolean }>;
|
||||
hasReturn: boolean;
|
||||
} {
|
||||
const issues: ScriptIssue[] = [];
|
||||
const referencedNodes: Array<{ name: string; exists: boolean }> = [];
|
||||
const trimmed = code.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: "MVEL 代码内容为空,合思调度时将报错",
|
||||
rule: "empty-script",
|
||||
});
|
||||
return { issues, referencedNodes, hasReturn: false };
|
||||
}
|
||||
|
||||
const hasRet = hasReturnStatement(code);
|
||||
if (!hasRet) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "MVEL 代码中未发现 return 语句,合思代码节点通常需要 return 包装后的 Map 或结果对象",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
// 1. 括号与引号对称性平衡检查
|
||||
const stack: Array<{ char: string; line: number }> = [];
|
||||
const lines = code.split(/\r?\n/);
|
||||
|
||||
for (let l = 0; l < lines.length; l++) {
|
||||
const lineText = lines[l];
|
||||
// 忽略单行注释
|
||||
const cleanLine = lineText.replace(/\/\/.*$/, "");
|
||||
|
||||
for (let c = 0; c < cleanLine.length; c++) {
|
||||
const ch = cleanLine[c];
|
||||
if (ch === "{" || ch === "(" || ch === "[") {
|
||||
stack.push({ char: ch, line: l + 1 });
|
||||
} else if (ch === "}" || ch === ")" || ch === "]") {
|
||||
const top = stack.pop();
|
||||
const expected = ch === "}" ? "{" : ch === ")" ? "(" : "[";
|
||||
if (!top || top.char !== expected) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
line: l + 1,
|
||||
column: c + 1,
|
||||
message: `括号不匹配: 遇到闭合 '${ch}',但预期匹配 '${expected}'`,
|
||||
rule: "unmatched-brackets",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (stack.length > 0) {
|
||||
const unclosed = stack.pop()!;
|
||||
issues.push({
|
||||
level: "error",
|
||||
line: unclosed.line,
|
||||
message: `未闭合的括号: '${unclosed.char}' 缺少对应的闭合括号`,
|
||||
rule: "unclosed-bracket",
|
||||
});
|
||||
}
|
||||
|
||||
// 2. 提取引用的上游节点标识并比对有效性
|
||||
// 合思节点命名规范形如 action_xxx, control_xxx, trigger_xxx
|
||||
const nodeRefRegex = /\b(action_[a-zA-Z0-9_]+|control_[a-zA-Z0-9_]+|trigger_[a-zA-Z0-9_]+)\b/g;
|
||||
const foundRefs = new Set<string>();
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = nodeRefRegex.exec(code)) !== null) {
|
||||
foundRefs.add(match[1]);
|
||||
}
|
||||
|
||||
for (const ref of foundRefs) {
|
||||
const exists = existingNodeNames ? existingNodeNames.has(ref) : true;
|
||||
referencedNodes.push({ name: ref, exists });
|
||||
if (!exists) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: `引用的上游节点 [${ref}] 在工作流中不存在(可能已被重命名或移除)`,
|
||||
rule: "dangling-node-reference",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { issues, referencedNodes, hasReturn: hasRet };
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归收集工作流任务树中所有节点标识
|
||||
*/
|
||||
export function collectAllWorkflowNodeNames(tasks: WorkflowTask[]): Set<string> {
|
||||
const names = new Set<string>();
|
||||
|
||||
function walk(list: WorkflowTask[]) {
|
||||
for (const t of list) {
|
||||
if (!t) continue;
|
||||
if (t.name) names.add(t.name);
|
||||
if (Array.isArray(t.tasks) && t.tasks.length > 0) {
|
||||
walk(t.tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(tasks);
|
||||
return names;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import vm from "node:vm";
|
||||
import type { ScriptEvalResult, ScriptEvalLog } from "./types.js";
|
||||
|
||||
/**
|
||||
* 在隔离沙箱中执行 JavaScript 代码节点,仿真合思云端运行时并捕获输出与异常
|
||||
*/
|
||||
export async function executeJavaScriptSandbox(
|
||||
code: string,
|
||||
inputs: Record<string, unknown> = {},
|
||||
options: { timeoutMs?: number } = {}
|
||||
): Promise<ScriptEvalResult> {
|
||||
const timeoutMs = options.timeoutMs ?? 3000;
|
||||
const logs: ScriptEvalLog[] = [];
|
||||
const start = performance.now();
|
||||
|
||||
const recordLog = (level: "log" | "warn" | "error", ...args: unknown[]) => {
|
||||
const message = args
|
||||
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
|
||||
.join(" ");
|
||||
logs.push({ level, message, timestamp: Date.now() });
|
||||
};
|
||||
|
||||
const sandboxConsole = {
|
||||
log: (...args: unknown[]) => recordLog("log", ...args),
|
||||
info: (...args: unknown[]) => recordLog("log", ...args),
|
||||
warn: (...args: unknown[]) => recordLog("warn", ...args),
|
||||
error: (...args: unknown[]) => recordLog("error", ...args),
|
||||
};
|
||||
|
||||
// 创建安全的执行沙箱上下文
|
||||
const sandboxContext = vm.createContext({
|
||||
...inputs,
|
||||
console: sandboxConsole,
|
||||
Date,
|
||||
Math,
|
||||
JSON,
|
||||
RegExp,
|
||||
Array,
|
||||
Object,
|
||||
Number,
|
||||
String,
|
||||
Boolean,
|
||||
parseInt,
|
||||
parseFloat,
|
||||
isNaN,
|
||||
isFinite,
|
||||
encodeURI,
|
||||
decodeURI,
|
||||
encodeURIComponent,
|
||||
decodeURIComponent,
|
||||
});
|
||||
|
||||
// 包裹立即执行函数体 (IIFE),既允许顶层 return 语句,又能直接受 vm timeout 保护
|
||||
const wrappedCode = `(function() {\n${code}\n})()`;
|
||||
|
||||
try {
|
||||
const returnValue = vm.runInContext(wrappedCode, sandboxContext, {
|
||||
timeout: timeoutMs,
|
||||
displayErrors: true,
|
||||
});
|
||||
const durationMs = Number((performance.now() - start).toFixed(2));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
durationMs,
|
||||
returnValue,
|
||||
logs,
|
||||
inputs,
|
||||
};
|
||||
} catch (err: any) {
|
||||
const durationMs = Number((performance.now() - start).toFixed(2));
|
||||
const msg = err?.message || String(err);
|
||||
let line: number | undefined;
|
||||
let column: number | undefined;
|
||||
|
||||
const stack = err?.stack || "";
|
||||
// 匹配包裹函数内的行号(第 1 行是包裹头,因此需要 -1)
|
||||
const match = stack.match(/evalmachine\.<anonymous>:(\d+):(\d+)/);
|
||||
if (match) {
|
||||
const rawLine = Number(match[1]);
|
||||
line = Math.max(1, rawLine - 1);
|
||||
column = Number(match[2]);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
durationMs,
|
||||
returnValue: undefined,
|
||||
logs,
|
||||
error: {
|
||||
name: err?.name || "ExecutionError",
|
||||
message: msg,
|
||||
stack,
|
||||
line,
|
||||
column,
|
||||
},
|
||||
inputs,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type { NodeScriptLintReport, WorkflowScriptLintReport, ScriptIssue } from "./types.js";
|
||||
import { lintJavaScriptCode } from "./lint-js.js";
|
||||
import { lintMvelCode, collectAllWorkflowNodeNames } from "./lint-mvel.js";
|
||||
|
||||
/**
|
||||
* 扫描并全面静态校验工作流中的全部代码节点(JS 与 MVEL)
|
||||
*/
|
||||
export function lintWorkflowScripts(
|
||||
workflow: WorkflowDetail,
|
||||
targetNodeQuery?: string
|
||||
): WorkflowScriptLintReport {
|
||||
const tasks = workflow.tasks || [];
|
||||
const allNodeNames = collectAllWorkflowNodeNames(tasks);
|
||||
const reports: NodeScriptLintReport[] = [];
|
||||
|
||||
function traverse(list: WorkflowTask[]) {
|
||||
for (const task of list) {
|
||||
if (!task) continue;
|
||||
|
||||
if (task.type === "code" || task.type === "code-js2") {
|
||||
if (!targetNodeQuery || task.name === targetNodeQuery || task.label === targetNodeQuery || task.displayName === targetNodeQuery) {
|
||||
const rawCode = (task as any).code || "";
|
||||
const lineCount = rawCode ? rawCode.split(/\r?\n/).length : 0;
|
||||
const mappings = Array.isArray((task as any).mapping) ? (task as any).mapping : [];
|
||||
const boundVariables: Array<{ key: string; upstreamTarget?: string }> = mappings.map((m: any) => ({
|
||||
key: m.key,
|
||||
upstreamTarget: m.value,
|
||||
}));
|
||||
|
||||
let issues: ScriptIssue[] = [];
|
||||
let hasReturn = false;
|
||||
let referencedNodes: Array<{ name: string; exists: boolean }> = [];
|
||||
|
||||
if (task.type === "code-js2") {
|
||||
const paramNames = boundVariables.map((b) => b.key);
|
||||
const res = lintJavaScriptCode(rawCode, paramNames);
|
||||
issues = res.issues;
|
||||
hasReturn = res.hasReturn;
|
||||
} else {
|
||||
const res = lintMvelCode(rawCode, allNodeNames);
|
||||
issues = res.issues;
|
||||
hasReturn = res.hasReturn;
|
||||
referencedNodes = res.referencedNodes;
|
||||
}
|
||||
|
||||
const hasErrors = issues.some((i) => i.level === "error");
|
||||
|
||||
reports.push({
|
||||
nodeName: task.name,
|
||||
displayName: task.displayName || undefined,
|
||||
label: task.label || undefined,
|
||||
type: task.type,
|
||||
codeLength: rawCode.length,
|
||||
lineCount,
|
||||
hasReturn,
|
||||
boundVariables,
|
||||
referencedNodes,
|
||||
issues,
|
||||
valid: !hasErrors,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
traverse(task.tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(tasks);
|
||||
|
||||
const validCount = reports.filter((r) => r.valid).length;
|
||||
const invalidCount = reports.length - validCount;
|
||||
|
||||
return {
|
||||
pipelineId: workflow.id,
|
||||
label: workflow.label,
|
||||
totalCodeNodes: reports.length,
|
||||
validCount,
|
||||
invalidCount,
|
||||
reports,
|
||||
allValid: invalidCount === 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export interface ScriptIssue {
|
||||
level: "error" | "warning";
|
||||
line?: number;
|
||||
column?: number;
|
||||
message: string;
|
||||
rule: string;
|
||||
}
|
||||
|
||||
export interface NodeScriptLintReport {
|
||||
nodeName: string;
|
||||
displayName?: string;
|
||||
label?: string;
|
||||
type: "code-js2" | "code";
|
||||
codeLength: number;
|
||||
lineCount: number;
|
||||
hasReturn: boolean;
|
||||
boundVariables: Array<{ key: string; upstreamTarget?: string }>;
|
||||
referencedNodes: Array<{ name: string; exists: boolean }>;
|
||||
issues: ScriptIssue[];
|
||||
valid: boolean;
|
||||
}
|
||||
|
||||
export interface WorkflowScriptLintReport {
|
||||
pipelineId?: string;
|
||||
label?: string;
|
||||
totalCodeNodes: number;
|
||||
validCount: number;
|
||||
invalidCount: number;
|
||||
reports: NodeScriptLintReport[];
|
||||
allValid: boolean;
|
||||
}
|
||||
|
||||
export interface ScriptEvalLog {
|
||||
level: "log" | "warn" | "error";
|
||||
message: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface ScriptEvalResult {
|
||||
success: boolean;
|
||||
durationMs: number;
|
||||
returnValue: unknown;
|
||||
logs: ScriptEvalLog[];
|
||||
error?: {
|
||||
name: string;
|
||||
message: string;
|
||||
stack?: string;
|
||||
line?: number;
|
||||
column?: number;
|
||||
};
|
||||
inputs: Record<string, unknown>;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { NotFoundError, ValidationError } from "../../../../core/errors.js";
|
||||
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 ValidationError("工作流配置路径不能为空");
|
||||
if (parts.some((part) => !/^[A-Za-z_$][\w$-]*$/.test(part) && !/^\d+$/.test(part))) {
|
||||
throw new ValidationError(`工作流配置路径非法: ${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 NotFoundError(`工作流配置路径不存在: ${path}`);
|
||||
}
|
||||
cursor = cursor[part];
|
||||
}
|
||||
if (cursor === null || typeof cursor !== "object") {
|
||||
throw new ValidationError(`工作流配置路径不可写: ${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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { WorkflowWatchEvent } from "./types.js";
|
||||
|
||||
/**
|
||||
* 将事件格式化为带时间戳的清晰控制台文本行
|
||||
*/
|
||||
export function formatWatchEvent(event: WorkflowWatchEvent): string {
|
||||
const timeStr = new Date(event.timestamp).toTimeString().slice(0, 8);
|
||||
const tag = `[${timeStr}]`;
|
||||
|
||||
switch (event.type) {
|
||||
case "pipeline_watch_start":
|
||||
return `${tag} 🔍 开始监听工作流 [${event.pipelineLabel || event.pipelineId}] 运行动态 (按 Ctrl+C 退出)...`;
|
||||
|
||||
case "job_detected":
|
||||
return `${tag} 🚀 捕获新运行任务 Job [${event.jobId}] (${event.runType || "RUN"}, 状态: ${event.status || "RUNNING"})`;
|
||||
|
||||
case "task_started":
|
||||
return ` ⏳ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} 开始运行...${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}`;
|
||||
|
||||
case "task_completed":
|
||||
return ` ✓ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} COMPLETED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}`;
|
||||
|
||||
case "task_skipped": {
|
||||
const errHint = event.error ? `\n ↳ ⚠️ 异常跳过原因: ${event.error}` : "";
|
||||
return ` ⚠️ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} SKIPPED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}${errHint}`;
|
||||
}
|
||||
|
||||
case "task_failed":
|
||||
return ` ❌ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} FAILED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}\n ↳ 错误详情: ${event.error || "未捕获明确错误信息"}`;
|
||||
|
||||
case "job_completed": {
|
||||
const summary = event.jobSummary;
|
||||
const isOk = summary?.status === "COMPLETED" && !summary.hasError && summary.errorCount === 0;
|
||||
const icon = isOk ? "🏁" : "❌";
|
||||
const statusText = summary?.status || "COMPLETED";
|
||||
return `${tag} ${icon} Job [${event.jobId}] 执行结束: 状态 [${statusText}] | 耗时: ${summary?.durationMs ?? "-"}ms | 成功: ${summary?.successCount ?? 0} | 失败: ${summary?.errorCount ?? 0} | 存在错误: ${summary?.hasError ? "是" : "否"}`;
|
||||
}
|
||||
|
||||
case "timeout":
|
||||
return `${tag} ⏱️ 监听超时,未在指定时间内捕获到新的任务状态变更。`;
|
||||
|
||||
case "idle":
|
||||
return `${tag} 💤 暂无新运行实例,继续等待中...`;
|
||||
|
||||
default:
|
||||
return `${tag} [${event.type}]`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../../types.js";
|
||||
|
||||
export const TERMINAL_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 any).status;
|
||||
const rawState = (job as any).state;
|
||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
||||
return rawStatus.trim().toUpperCase();
|
||||
}
|
||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
export function isJobTerminal(status: string): boolean {
|
||||
return TERMINAL_STATES.has(status.toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取节点执行失败或跳过时的具体错误原因
|
||||
*/
|
||||
export function extractTaskErrorMessage(node: WorkflowTaskExecution): string | undefined {
|
||||
if (!node) return undefined;
|
||||
const anyNode = node as any;
|
||||
if (node.error?.message && String(node.error.message).trim()) {
|
||||
return String(node.error.message).trim();
|
||||
}
|
||||
if (anyNode.errorMessage && String(anyNode.errorMessage).trim()) {
|
||||
return String(anyNode.errorMessage).trim();
|
||||
}
|
||||
const outputs = anyNode.outputs ?? anyNode.output;
|
||||
if (outputs && typeof outputs === "object") {
|
||||
if (outputs.error) {
|
||||
return typeof outputs.error === "string" ? outputs.error.trim() : JSON.stringify(outputs.error);
|
||||
}
|
||||
if (outputs.message && typeof outputs.message === "string") {
|
||||
return outputs.message.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from "./types.js";
|
||||
export * from "./helpers.js";
|
||||
export * from "./tracker.js";
|
||||
export * from "./formatter.js";
|
||||
export * from "./single-job.js";
|
||||
export * from "./pipeline-watcher.js";
|
||||
@@ -0,0 +1,223 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
import { watchSingleJob } from "./single-job.js";
|
||||
|
||||
/**
|
||||
* 监听工作流流水线:持续捕获新派发的 Job,并实时输出其节点执行动态
|
||||
*/
|
||||
export async function watchWorkflowPipeline(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
options: WatchWorkflowOptions = {}
|
||||
): Promise<WorkflowWatchReport> {
|
||||
const intervalMs = Math.max(options.intervalMs ?? 2000, 500);
|
||||
const timeoutMs = options.timeoutMs ?? (options.once || options.jobId ? 60000 : Infinity);
|
||||
const maxJobs = options.jobId ? 1 : (options.maxJobs ?? (options.follow ? Infinity : 1));
|
||||
const startTime = Date.now();
|
||||
const watchedJobs: WatchedJobResult[] = [];
|
||||
const seenJobIds = new Set<string>();
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
}
|
||||
};
|
||||
|
||||
// 1. 如果用户显式指定了 --job=<jobId>
|
||||
if (options.jobId) {
|
||||
const jobResult = await watchSingleJob(client, options.jobId, {
|
||||
...options,
|
||||
onEvent: emit,
|
||||
});
|
||||
watchedJobs.push(jobResult);
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 1,
|
||||
jobs: watchedJobs,
|
||||
timedOut: false,
|
||||
hasFailures: jobResult.hasError || jobResult.status === "FAILED",
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 发出监听开始事件
|
||||
let pipelineLabel = "";
|
||||
try {
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
pipelineLabel = detail.label || "";
|
||||
} catch {
|
||||
// 忽略标签读取失败
|
||||
}
|
||||
|
||||
await emit({
|
||||
type: "pipeline_watch_start",
|
||||
pipelineId,
|
||||
pipelineLabel,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 如果是一次性快照检视 (--once)
|
||||
if (options.once) {
|
||||
let targetJobId: string | undefined;
|
||||
|
||||
// 先查是否有正在运行的任务
|
||||
try {
|
||||
const running = await api.listRunningJobs(client, pipelineId, "DEBUG");
|
||||
if (running.length > 0) targetJobId = running[0].id;
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
if (!targetJobId) {
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 1 });
|
||||
if (logs.jobList && logs.jobList.length > 0) {
|
||||
const first = logs.jobList[0];
|
||||
targetJobId = first.jobId || first.id;
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetJobId) {
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 0,
|
||||
jobs: [],
|
||||
timedOut: false,
|
||||
hasFailures: false,
|
||||
};
|
||||
}
|
||||
|
||||
const singleRes = await watchSingleJob(client, targetJobId, {
|
||||
...options,
|
||||
once: true,
|
||||
onEvent: emit,
|
||||
});
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: 1,
|
||||
jobs: [singleRes],
|
||||
timedOut: false,
|
||||
hasFailures: singleRes.hasError || singleRes.status === "FAILED",
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 持续监听循环
|
||||
let timedOut = false;
|
||||
|
||||
// 记录初次启动时的最新已知 JobId,避免将老历史任务当作新触发任务(除非有处于 RUNNING 状态的任务)
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 5 });
|
||||
for (const j of logs.jobList || []) {
|
||||
const jid = j.jobId || j.id;
|
||||
const status = normalizeJobStatus(j);
|
||||
// 如果不是运行中,标为已知历史
|
||||
if (jid && !isJobTerminal(status)) {
|
||||
// 运行中的保留待观察
|
||||
} else if (jid) {
|
||||
seenJobIds.add(jid);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (options.signal?.aborted) break;
|
||||
|
||||
let candidateJob: { id: string; status: string; runType?: string } | undefined;
|
||||
|
||||
// 优先检查 running 接口
|
||||
try {
|
||||
const runningJobs = await api.listRunningJobs(client, pipelineId, "DEBUG");
|
||||
const found = runningJobs.find((j) => !seenJobIds.has(j.id));
|
||||
if (found) {
|
||||
candidateJob = { id: found.id, status: found.status || "RUNNING", runType: "DEBUG" };
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
// 其次检查流水线最新 log
|
||||
if (!candidateJob) {
|
||||
try {
|
||||
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 3 });
|
||||
for (const j of logs.jobList || []) {
|
||||
const jid = j.jobId || j.id;
|
||||
if (jid && !seenJobIds.has(jid)) {
|
||||
candidateJob = { id: jid, status: normalizeJobStatus(j), runType: j.runType };
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
if (candidateJob) {
|
||||
seenJobIds.add(candidateJob.id);
|
||||
|
||||
await emit({
|
||||
type: "job_detected",
|
||||
pipelineId,
|
||||
jobId: candidateJob.id,
|
||||
status: candidateJob.status,
|
||||
runType: candidateJob.runType,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 实时跟踪该 Job 执行
|
||||
const jobResult = await watchSingleJob(client, candidateJob.id, {
|
||||
...options,
|
||||
onEvent: emit,
|
||||
});
|
||||
|
||||
watchedJobs.push(jobResult);
|
||||
|
||||
if (watchedJobs.length >= maxJobs) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const remaining = timeoutMs - elapsed;
|
||||
if (remaining <= 0) {
|
||||
timedOut = true;
|
||||
break;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
|
||||
}
|
||||
|
||||
if (Date.now() - startTime >= timeoutMs && watchedJobs.length === 0) {
|
||||
timedOut = true;
|
||||
await emit({
|
||||
type: "timeout",
|
||||
pipelineId,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const hasFailures = watchedJobs.some((j) => j.hasError || j.status === "FAILED");
|
||||
|
||||
return {
|
||||
pipelineId,
|
||||
totalJobsWatched: watchedJobs.length,
|
||||
jobs: watchedJobs,
|
||||
timedOut,
|
||||
hasFailures,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../../types.js";
|
||||
import * as api from "../../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
import { TaskExecutionTracker } from "./tracker.js";
|
||||
|
||||
/**
|
||||
* 监听指定单个 Job 的实时执行,直至其达到终态或超时
|
||||
*/
|
||||
export async function watchSingleJob(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: WatchWorkflowOptions = {}
|
||||
): Promise<WatchedJobResult> {
|
||||
const intervalMs = Math.max(options.intervalMs ?? 1500, 500);
|
||||
const timeoutMs = options.timeoutMs ?? 60000;
|
||||
const startTime = Date.now();
|
||||
const tracker = new TaskExecutionTracker(jobId);
|
||||
const events: WorkflowWatchEvent[] = [];
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
events.push(event);
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
}
|
||||
};
|
||||
|
||||
let latestJob: WorkflowJobDetail | undefined;
|
||||
let isTerminal = false;
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (options.signal?.aborted) break;
|
||||
|
||||
try {
|
||||
latestJob = await api.getJob(client, jobId);
|
||||
} catch {
|
||||
// 任务初创可能存在 404/延迟,忽略单次瞬态
|
||||
}
|
||||
|
||||
const currentStatus = normalizeJobStatus(latestJob);
|
||||
|
||||
// 获取当前执行树并比对增量事件
|
||||
try {
|
||||
const tree = await api.getJobExecutionTree(client, jobId);
|
||||
const deltaEvents = tracker.processExecutions(tree);
|
||||
for (const ev of deltaEvents) {
|
||||
await emit(ev);
|
||||
}
|
||||
} catch {
|
||||
// 忽略执行树瞬态读取异常
|
||||
}
|
||||
|
||||
if (isJobTerminal(currentStatus)) {
|
||||
isTerminal = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (options.once) {
|
||||
break;
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const remaining = timeoutMs - elapsed;
|
||||
if (remaining <= 0) break;
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
|
||||
}
|
||||
|
||||
// 终态最后同步一次失败节点信息
|
||||
let failureItems: WorkflowTaskExecution[] = [];
|
||||
try {
|
||||
const failedPage = await api.getJobFailedExecutions(client, jobId);
|
||||
failureItems = failedPage.items || [];
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
const finalStatus = normalizeJobStatus(latestJob);
|
||||
const anyJob = latestJob as any;
|
||||
const successCount = Number(anyJob?.successTaskCount ?? 0);
|
||||
const errorCount = Math.max(Number(anyJob?.errorTaskCount ?? 0), failureItems.length);
|
||||
const hasError = anyJob?.hasError === true || anyJob?.hasError === "存在" || errorCount > 0 || finalStatus === "FAILED";
|
||||
const durationMs = typeof anyJob?.durationTime === "number" ? anyJob.durationTime : undefined;
|
||||
|
||||
const completionEvent: WorkflowWatchEvent = {
|
||||
type: "job_completed",
|
||||
jobId,
|
||||
status: finalStatus,
|
||||
timestamp: Date.now(),
|
||||
jobSummary: {
|
||||
status: finalStatus,
|
||||
durationMs,
|
||||
successCount,
|
||||
errorCount,
|
||||
hasError,
|
||||
},
|
||||
};
|
||||
await emit(completionEvent);
|
||||
|
||||
return {
|
||||
jobId,
|
||||
pipelineId: latestJob?.pipelineId || "",
|
||||
status: finalStatus,
|
||||
runType: latestJob?.runType,
|
||||
durationMs,
|
||||
successCount,
|
||||
errorCount,
|
||||
hasError,
|
||||
events,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
import { flattenExecutionTree, isTaskExecutionFailed } from "../../services.js";
|
||||
import type { WorkflowWatchEvent } from "./types.js";
|
||||
import { extractTaskErrorMessage } from "./helpers.js";
|
||||
|
||||
/**
|
||||
* 节点状态追踪器:比对并生成增量任务状态变更事件,避免轮询时重复日志刷屏
|
||||
*/
|
||||
export class TaskExecutionTracker {
|
||||
private seenStatuses = new Map<string, string>();
|
||||
|
||||
constructor(public readonly jobId: string) {}
|
||||
|
||||
public processExecutions(executions: WorkflowTaskExecution[]): WorkflowWatchEvent[] {
|
||||
const flattened = flattenExecutionTree(executions);
|
||||
const events: WorkflowWatchEvent[] = [];
|
||||
const now = Date.now();
|
||||
|
||||
for (const node of flattened) {
|
||||
if (!node?.id) continue;
|
||||
const executionId = node.id;
|
||||
const rawStatus = (node.status || "UNKNOWN").toUpperCase();
|
||||
const previousStatus = this.seenStatuses.get(executionId);
|
||||
|
||||
const name = node.name || executionId;
|
||||
const label = node.label || node.displayName || undefined;
|
||||
const displayName = node.displayName || undefined;
|
||||
const taskType = node.type || "unknown";
|
||||
const durationMs = typeof node.executionTime === "number" ? node.executionTime : undefined;
|
||||
const loopPath = node.currentLoopPath || undefined;
|
||||
const error = extractTaskErrorMessage(node);
|
||||
const isFailed = isTaskExecutionFailed(node) || rawStatus === "FAILED";
|
||||
const isSkipped = rawStatus === "SKIPPED" || rawStatus === "SKIP";
|
||||
|
||||
if (previousStatus === undefined) {
|
||||
// 第一次发现该节点
|
||||
this.seenStatuses.set(executionId, rawStatus);
|
||||
|
||||
if (isSkipped) {
|
||||
events.push({
|
||||
type: "task_skipped",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error,
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (isFailed) {
|
||||
events.push({
|
||||
type: "task_failed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error: error || "执行异常或未通过规则校验",
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (rawStatus === "COMPLETED" || rawStatus === "SUCCESS") {
|
||||
events.push({
|
||||
type: "task_completed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
} else {
|
||||
events.push({
|
||||
type: "task_started",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
}
|
||||
} else if (previousStatus !== rawStatus) {
|
||||
// 状态发生跃迁(例如从 RUNNING -> COMPLETED 或 FAILED)
|
||||
this.seenStatuses.set(executionId, rawStatus);
|
||||
|
||||
if (isSkipped) {
|
||||
events.push({
|
||||
type: "task_skipped",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error,
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (isFailed) {
|
||||
events.push({
|
||||
type: "task_failed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
error: error || "执行异常或未通过规则校验",
|
||||
timestamp: now,
|
||||
});
|
||||
} else if (rawStatus === "COMPLETED" || rawStatus === "SUCCESS") {
|
||||
events.push({
|
||||
type: "task_completed",
|
||||
jobId: this.jobId,
|
||||
executionId,
|
||||
name,
|
||||
label,
|
||||
displayName,
|
||||
taskType,
|
||||
status: rawStatus,
|
||||
durationMs,
|
||||
loopPath,
|
||||
timestamp: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { WorkflowJobDetail } from "../../types.js";
|
||||
|
||||
export type WorkflowWatchEventType =
|
||||
| "pipeline_watch_start"
|
||||
| "job_detected"
|
||||
| "task_started"
|
||||
| "task_completed"
|
||||
| "task_failed"
|
||||
| "task_skipped"
|
||||
| "job_completed"
|
||||
| "idle"
|
||||
| "timeout";
|
||||
|
||||
export interface WorkflowWatchEvent {
|
||||
type: WorkflowWatchEventType;
|
||||
pipelineId?: string;
|
||||
pipelineLabel?: string;
|
||||
jobId?: string;
|
||||
runType?: string;
|
||||
executionId?: string;
|
||||
name?: string;
|
||||
displayName?: string;
|
||||
label?: string;
|
||||
taskType?: string;
|
||||
status?: string;
|
||||
durationMs?: number;
|
||||
startTime?: string;
|
||||
loopPath?: string;
|
||||
error?: string;
|
||||
jobSummary?: {
|
||||
status: string;
|
||||
durationMs?: number;
|
||||
successCount: number;
|
||||
errorCount: number;
|
||||
hasError: boolean;
|
||||
};
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface WatchWorkflowOptions {
|
||||
jobId?: string;
|
||||
intervalMs?: number;
|
||||
timeoutMs?: number;
|
||||
maxJobs?: number;
|
||||
once?: boolean;
|
||||
follow?: boolean;
|
||||
failedOnly?: boolean;
|
||||
onEvent?: (event: WorkflowWatchEvent) => Promise<void> | void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface WatchedJobResult {
|
||||
jobId: string;
|
||||
pipelineId: string;
|
||||
status: string;
|
||||
runType?: string;
|
||||
durationMs?: number;
|
||||
successCount: number;
|
||||
errorCount: number;
|
||||
hasError: boolean;
|
||||
events: WorkflowWatchEvent[];
|
||||
}
|
||||
|
||||
export interface WorkflowWatchReport {
|
||||
pipelineId: string;
|
||||
totalJobsWatched: number;
|
||||
jobs: WatchedJobResult[];
|
||||
timedOut: boolean;
|
||||
hasFailures: boolean;
|
||||
}
|
||||
Reference in new issue
Block a user