Files
hose-use/src/domains/platform/workflow/branch/explain.ts
T
gitea 7a19fa8337 feat(workflow): 保存期接口权限预检与 choose 表达式序列化开关
## 一、保存期「接口 → 应用」权限预检

工作流 HTTP 节点调用某些开放接口前,企业必须先开通对应应用,否则运行时
返回 403「未开通功能,无权访问」,而该报文字段里完全看不出缺哪个应用。
真实案例:某客户「单据审批」应用未开通,流程跑到第 9 步才被网关拦下,
排查成本极高。

本次在保存/静态分析阶段按接口路径反推所需应用:

- 新增 `analysis/openapi-app-requirements.ts`:接口路径 → 所需应用的映射表
  (首条 `/api/openapi/v1/backlog/data/` + POST/PUT/PATCH → 「单据审批」
  `TICKET_AUDIT_switch`、productId `o0hMBw000000g0`),配套
  `extractStaticUrlPath`(去域名、截断到第一个 `@{`、去 query/hash)与
  `matchAppRequirement`。
- `analysis/analyzer.ts` 6.3 节重构:以路径反查为主,节点显式声明的
  `powerCode`(`params` / URL query)作为交叉印证;两者指向同一权限时走
  路径规则,以便报文带上接口名、应用名、productId 与判定依据路径。显式
  声明了其它 `powerCode` 时以声明为准,避免两套规则打架。
- 新增保存期钩子 `preflightNodeAppRequirements` / `renderAppRequirementAlerts`
  (`cli/commands/workflow/shared.ts`),接入 `node add` / `node edit`:
  只检查本次写入的 HTTP 节点,未开通则输出 ⛔ 段并在 JSON 模式落到
  `appRequirementAlerts`;读不到企业应用清单时降级为 ⚠️,不阻断写入。
- `domains/store/tools.ts` 抽出 `isClientGoodOpened` 与
  `fetchOpenedPowerCodes`,`workflow analyze` 改为复用,移除内联汇总逻辑
  (`isClientGoodOpened` 仍从 `analyze.ts` 再导出以保持既有契约)。

判定边界(刻意收紧,宁可漏报不误报):只对 HTTP 节点生效;URL 若整体由
上游节点变量拼接则完全不判断;无法静态读出接口路径时不做任何猜测性告警。

## 二、choose 表达式序列化开关

合思前端序列化模板字符串时多写了一个右花括号,产出 `...}')}` 形态;
后端 Jackson 默认未开启 `FAIL_ON_TRAILING_TOKENS`,尾随 `}` 被静默忽略,
因此该形态在引擎侧可正常执行。

- 新增 `models/choose-serialization.ts`:`frontend` / `pure` 双模式序列化,
  以及 `parseChoosePayloadLoose`(逐个剥离尾部多余 `}` 再解析)。
- 全局配置新增 `chooseSerialization`,默认 `frontend`(与设计器字节一致),
  可用 `--choose-serialization` 单次覆盖;读取侧永远双形态兼容。
- 修复 `branch/explain.ts` 的 `parseChooseTag` 在 `}}` 形态下静默返回 null
  的缺陷,该缺陷会导致真实数据上的分支解释与字段引用分析失效。

## 测试

新增 24 个用例,覆盖:
- `choose-serialization.test.ts`:双模式序列化与宽松解析
- `openapi-app-requirements.test.ts`:静态路径提取、路径命中、方法不符跳过、
  纯变量 URL 跳过、非 HTTP 节点不判断、未开通/已开通/无清单三种诊断
- `shared.app-preflight.test.ts`:预检只处理 HTTP 节点、动态 URL 跳过、
  读不到清单降级不阻断、告警分级渲染

`bun test` 1068 pass / 0 fail;`bun run check` 零错误;`check:readme` 通过。

## 实机核对(全部只读,未触碰任何生产流程配置)

- 真实流程的两个 HTTP 节点均命中「单据审批」;同时确认设计器确实会把
  `powerCode` 写入节点 `params`,因此显式声明与路径反推两条规则都需要保留。
- 已开通该应用的企业 → 无诊断;未开通的企业 → 精确打出硬门禁并指向具体
  节点 key 与判定依据路径。
2026-11-04 16:43:34 +08:00

239 lines
11 KiB
TypeScript

import type { WorkflowTaskExecution } from "../types.js";
import { indexExecutionContexts } from "../execution/context.js";
import { parseChoosePayloadLoose } from "../models/choose-serialization.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('...')} 标签中提取上游节点名、属性名与可读标签。
*
* 载荷解析走 `parseChoosePayloadLoose`,同时兼容两种形态:
* - 设计器产出的 `{"k":"v"}}`(多一个右花括号,平台统一形态)
* - 配平形态 `{"k":"v"}`
*
* 早期实现直接用 `JSON.parse`,遇到设计器产出的数据会静默返回 null,
* 导致 `}}` 形态配置的分支解释全部失效。
*/
export function parseChooseTag(tag: string): {
upstreamNode: string;
upstreamProp: string;
label: string;
} | null {
if (typeof tag !== "string") return null;
const match = tag.match(/@\{choose\('([\s\S]*?)'\)\}/);
if (!match) return null;
const normalized = parseChoosePayloadLoose(match[1]);
if (normalized === null) return null;
try {
const parsed = JSON.parse(normalized);
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;
}