fix(workflow): 灰度开通网关地址可覆盖,成功判定不再默认成功

网关请求地址此前硬编码在传输层(`https://d9jxeccs5j.sealosgzg.site/hose-workflow-node`),
没有环境变量或参数逃生口;该实例托管在第三方域,同类 Sealos 资产曾被回收,
一旦失效 `workflow nodes grant` 会全线瘫痪。

- 新增 resolveGrayGatewayUrl():显式 gatewayUrl > 环境变量 HOSE_GRAY_GATEWAY_URL >
  内置默认地址,统一拼接 /hose-workflow-node,自动归一化尾部斜杠;
- interpretGatewayOutcome():优先取显式 success,其次 code === 200,
  两者都缺失时判为失败。原先 Boolean(json?.success ?? true) 缺字段即默认成功,
  开通未生效会让下游 analyze 继续报 PERMISSION_MISSING_NODE,谎报比如实报错更难排查;
- 传输失败信息带上实际请求的网关地址;GrantWorkflowNodesOptions 增加 gatewayUrl 透传;
- 澄清 baseUrl 是交给网关定位的目标合思租户地址(body 字段),不是网关地址。

测试与文档:
- 新增 transport/gray-gateway.test.ts 八条用例;用例刻意避免使用 mock.module("ky"),
  该写法会污染同进程其他文件的 ky 引用(write-result.test.ts 曾被连带打断),
  改用可恢复的 spyOn;
- 同步 transport/README.transport.md、README.workflow.md 与 ekuaibao-nodes SKILL.md。
This commit is contained in:
gitea committed 2026-11-01 21:44:51 +08:00
1 parent 6dc96a5eb9
commit 1ee46fd79f
7 files changed
+169 -5

No files matched your search

@@ -27,11 +27,16 @@ description: |
## 执行 ## 执行
```bash ```bash
curl -s -X POST 'https://d9jxeccs5j.sealosgzg.site/hose-workflow-node' \ # 网关地址优先取环境变量 HOSE_GRAY_GATEWAY_URL(尾部斜杠会自动忽略),未配置时用内置默认地址
GATEWAY="${HOSE_GRAY_GATEWAY_URL:-https://d9jxeccs5j.sealosgzg.site}"
curl -s -X POST "${GATEWAY%/}/hose-workflow-node" \
-H 'Content-Type: application/json' \ -H 'Content-Type: application/json' \
-d '{"token":"TOKEN","corpId":"CORPID","nodes":"NODES"}' -d '{"token":"TOKEN","corpId":"CORPID","nodes":"NODES"}'
``` ```
> 网关托管在第三方域,实例可能被回收或迁移。CLI 侧同样支持 `HOSE_GRAY_GATEWAY_URL` 覆盖;
> 网关不可用时不要自行改用其他地址,先确认变量指向的实例仍然有效。
可选参数: 可选参数:
- `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。 - `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。
- `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl` - `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl`
@@ -10,6 +10,8 @@ Platform 域下工作流能力的命令、协议与诊断契约。总体边界
`workflow save --in-place` 遇到这类部分成功仍同步本地版本,返回非零退出码、`status: "partial"`、`remoteSaved: true`、新版本和恢复命令。主保存本身失败则不改本地版本。恢复可用 `workflow refresh-chooses <pipelineId> --platform-id=<id> --yes`,只刷新元数据,不提交快照;该命令也支持 `--dry-run`。 `workflow save --in-place` 遇到这类部分成功仍同步本地版本,返回非零退出码、`status: "partial"`、`remoteSaved: true`、新版本和恢复命令。主保存本身失败则不改本地版本。恢复可用 `workflow refresh-chooses <pipelineId> --platform-id=<id> --yes`,只刷新元数据,不提交快照;该命令也支持 `--dry-run`。
启停(`toggle` / `publish`)属于生产开关:写请求按 EASO 业务码判定成败(HTTP 200 不代表成功),写成功后再回读详情确认 `state` 确实变化。回读状态与期望不一致抛 `BusinessError`(`WORKFLOW_STATE_NOT_APPLIED`);回读失败返回 `verified: false` 并给出非零退出码,不把「请求已提交」说成「已生效」。返回的 `WorkflowToggleResult` 中 `state` 为 `null` 表示未能读到服务端实际状态。
## CLI 常用命令 ## CLI 常用命令
```bash ```bash
@@ -167,7 +169,9 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
快照 Diff 对比节点的全部配置字段(脚本和过滤器沿用专用输出),覆盖 `mapping/inputs/fields` 及自定义配置。节点顺序或父容器变化通过 `configChanges` 中的 `$path` 表达,不依赖服务端是否重算索引。 快照 Diff 对比节点的全部配置字段(脚本和过滤器沿用专用输出),覆盖 `mapping/inputs/fields` 及自定义配置。节点顺序或父容器变化通过 `configChanges` 中的 `$path` 表达,不依赖服务端是否重算索引。
灰度开通网关明确返回失败时,CLI 保留失败详情并返回非零退出码;文本输出不再宣称权限生效,JSON 中的 `success` 与退出码保持一致。 灰度开通网关明确返回失败时,CLI 保留失败详情并返回非零退出码;文本输出不再宣称权限生效,JSON 中的 `success` 与退出码保持一致。网关既没有返回 `success`、也没有返回可识别的 `code` 时,同样判为失败而非成功——谎报开通会让下游继续报 `PERMISSION_MISSING_NODE`,比如实报错更难排查。
网关地址不再硬编码:可用环境变量 `HOSE_GRAY_GATEWAY_URL` 覆盖内置默认地址(原本固定的第三方托管域曾出现实例回收风险),请求路径统一为 `/hose-workflow-node`,详见 [transport/README.transport.md](./transport/README.transport.md)。传入的 `baseUrl` 只是目标租户地址,不是网关地址。
监听结果区分完成、超时、快照和取消:只有到达终态才发送 `job_completed`;超时发送 `timeout` 并设置 `timedOut`,取消设置 `cancelled`。CLI 超时或取消返回非零退出码;`--once` 的运行中快照仍可成功返回,且不冒充完成。持续监听的总超时预算覆盖正在跟踪的 Job。 监听结果区分完成、超时、快照和取消:只有到达终态才发送 `job_completed`;超时发送 `timeout` 并设置 `timedOut`,取消设置 `cancelled`。CLI 超时或取消返回非零退出码;`--once` 的运行中快照仍可成功返回,且不冒充完成。持续监听的总超时预算覆盖正在跟踪的 Job。
@@ -119,6 +119,7 @@ export async function grantWorkflowNodes(
corpId, corpId,
nodes: normalizedNodes, nodes: normalizedNodes,
baseUrl, baseUrl,
gatewayUrl: options.gatewayUrl,
}); });
return result; return result;
@@ -46,6 +46,8 @@ export interface AvailableWorkflowNodes {
export interface GrantWorkflowNodesOptions { export interface GrantWorkflowNodesOptions {
nodes: string[]; nodes: string[];
password?: string; password?: string;
/** 覆盖灰度开通网关地址;缺省使用环境变量 HOSE_GRAY_GATEWAY_URL。 */
gatewayUrl?: string;
} }
export interface GrantWorkflowNodesResult { export interface GrantWorkflowNodesResult {
@@ -7,3 +7,18 @@
- [response.ts](./response.ts):EASO/Piper 响应和写入结果校验。 - [response.ts](./response.ts):EASO/Piper 响应和写入结果校验。
上级 [api.ts](../api.ts) 保留统一传输出口。入口层应使用 `services.ts`,不能直接依赖此目录的 API。 上级 [api.ts](../api.ts) 保留统一传输出口。入口层应使用 `services.ts`,不能直接依赖此目录的 API。
## 写入结果判定
所有写操作(保存、刷新 chooses、删除、启停)统一走 `readEasoWriteResponse`:先按 HTTP 状态,再解析 body 中的业务码 `code`。
**HTTP 200 不等于业务成功**,只看状态码会把未生效的写操作报成成功。
## 灰度开通网关 (grantWorkflowNodesApi)
| 项目 | 说明 |
|---|---|
| 请求地址 | `resolveGrayGatewayUrl()`:显式 `gatewayUrl` 参数 > 环境变量 `HOSE_GRAY_GATEWAY_URL` > 内置默认 `DEFAULT_GRAY_GATEWAY_URL` |
| 环境变量用途 | 网关托管在第三方域,实例可能被回收或迁移;配置环境变量可在不改代码的情况下切换网关 |
| `baseUrl` 参数 | 目标合思租户地址,作为 body 字段交给网关定位企业,与网关自身地址无关 |
| 成功判定 | 优先取显式 `success` 布尔值,其次取 `code === 200`;**两者都缺失时判为失败**,不默认成功 |
| 失败信息 | 传输异常抛 `EkbApiError`(`GATEWAY_ERROR`),消息带上实际请求的网关地址 |
@@ -71,11 +71,45 @@ export async function getWorkflowEnumOptions(
// ── 灰度节点开通网关 ────────────────────────────────────────────────────────── // ── 灰度节点开通网关 ──────────────────────────────────────────────────────────
/** 网关地址环境变量。网关托管在第三方域,实例可能被回收或迁移,必须允许覆盖。 */
export const GRAY_GATEWAY_URL_ENV = "HOSE_GRAY_GATEWAY_URL";
export const DEFAULT_GRAY_GATEWAY_URL = "https://d9jxeccs5j.sealosgzg.site";
export const GRAY_GATEWAY_PATH = "/hose-workflow-node";
/**
* 解析网关请求地址:显式参数 > 环境变量 > 内置默认。
* 网关默认地址指向第三方托管实例(`.sealosgzg.site`),同类实例曾被回收;
* 硬编码且无逃生口会导致 `workflow nodes grant` 全线瘫痪且无从切换。
*/
export function resolveGrayGatewayUrl(explicit?: string): string {
const candidate = (
explicit ??
process.env[GRAY_GATEWAY_URL_ENV] ??
DEFAULT_GRAY_GATEWAY_URL
).trim();
return `${candidate.replace(/\/+$/, "")}${GRAY_GATEWAY_PATH}`;
}
/**
* 判定网关是否真的开通成功。缺字段不默认为成功:开通未生效会让下游
* `analyze` 依旧报 PERMISSION_MISSING_NODE,谎报成功比如实报错更难排查。
*/
export function interpretGatewayOutcome(json: any): boolean {
if (typeof json?.success === "boolean") return json.success;
if (json?.code !== undefined && json?.code !== null) return Number(json.code) === 200;
// 缺少明确成功/失败标记时不默认成功:开通未生效会让下游 analyze 依旧报
// PERMISSION_MISSING_NODE,谎报成功比如实报错更难排查。
return false;
}
export async function grantWorkflowNodesApi(options: { export async function grantWorkflowNodesApi(options: {
token: string; token: string;
corpId: string; corpId: string;
nodes: string[]; nodes: string[];
/** 目标合思租户地址,网关据此定位要开通的企业。 */
baseUrl?: string; baseUrl?: string;
/** 网关自身地址;缺省依次使用环境变量 HOSE_GRAY_GATEWAY_URL 与内置默认地址。 */
gatewayUrl?: string;
}): Promise<import("../../types.js").GrantWorkflowNodesResult> { }): Promise<import("../../types.js").GrantWorkflowNodesResult> {
const payload = { const payload = {
token: options.token, token: options.token,
@@ -83,22 +117,23 @@ export async function grantWorkflowNodesApi(options: {
nodes: options.nodes.join(","), nodes: options.nodes.join(","),
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}), ...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
}; };
const gatewayUrl = resolveGrayGatewayUrl(options.gatewayUrl);
try { try {
const response = await ky.post("https://d9jxeccs5j.sealosgzg.site/hose-workflow-node", { const response = await ky.post(gatewayUrl, {
json: payload, json: payload,
timeout: 30000, timeout: 30000,
}); });
const json = (await response.json()) as any; const json = (await response.json()) as any;
const data = json?.data ?? {}; const data = json?.data ?? {};
return { return {
success: Boolean(json?.success ?? true), success: interpretGatewayOutcome(json),
saved: Array.isArray(data.saved) ? data.saved : [], saved: Array.isArray(data.saved) ? data.saved : [],
skipped: Array.isArray(data.skipped) ? data.skipped : [], skipped: Array.isArray(data.skipped) ? data.skipped : [],
rawMessage: json?.msg || json?.message || "", rawMessage: json?.msg || json?.message || "",
}; };
} catch (err: any) { } catch (err: any) {
const message = err?.message || String(err); const message = err?.message || String(err);
throw new EkbApiError(`灰度节点开通网关调用失败: ${message}`, "GATEWAY_ERROR", 502); throw new EkbApiError(`灰度节点开通网关调用失败 (${gatewayUrl}): ${message}`, "GATEWAY_ERROR", 502);
} }
} }
@@ -0,0 +1,102 @@
import { afterEach, describe, expect, it, spyOn } from "bun:test";
import ky from "ky";
/**
* 灰度开通网关的行为测试。网关地址托管在第三方域,且历史实例曾被回收,
* 必须保证「地址可覆盖」与「成功判定不默认为真」这两件事被固化下来。
*
* 这里刻意只用纯函数断言 + 对 ky.post 的可恢复 spy:
* `mock.module("ky")` 会污染同进程其他用例的 ky 引用。
*/
const {
grantWorkflowNodesApi,
resolveGrayGatewayUrl,
interpretGatewayOutcome,
GRAY_GATEWAY_URL_ENV,
DEFAULT_GRAY_GATEWAY_URL,
GRAY_GATEWAY_PATH,
} = await import("./catalog/api.js");
const ORIGINAL_ENV = process.env[GRAY_GATEWAY_URL_ENV];
function restoreEnv(): void {
if (ORIGINAL_ENV === undefined) delete process.env[GRAY_GATEWAY_URL_ENV];
else process.env[GRAY_GATEWAY_URL_ENV] = ORIGINAL_ENV;
}
afterEach(() => {
restoreEnv();
});
describe("gray gateway address resolution", () => {
it("falls back to the built-in default host", () => {
delete process.env[GRAY_GATEWAY_URL_ENV];
expect(resolveGrayGatewayUrl()).toBe(`${DEFAULT_GRAY_GATEWAY_URL}${GRAY_GATEWAY_PATH}`);
});
it("prefers the environment override and normalizes trailing slashes", () => {
process.env[GRAY_GATEWAY_URL_ENV] = "https://gw.example.com///";
expect(resolveGrayGatewayUrl()).toBe(`https://gw.example.com${GRAY_GATEWAY_PATH}`);
});
it("lets the explicit argument win over the environment", () => {
process.env[GRAY_GATEWAY_URL_ENV] = "https://ignored.example.com";
expect(resolveGrayGatewayUrl("https://explicit.example.com")).toBe(
`https://explicit.example.com${GRAY_GATEWAY_PATH}`
);
});
});
describe("gray gateway outcome interpretation", () => {
it("honours an explicit success flag", () => {
expect(interpretGatewayOutcome({ success: true })).toBe(true);
expect(interpretGatewayOutcome({ success: false })).toBe(false);
});
it("treats a non-200 business code as failure", () => {
expect(interpretGatewayOutcome({ code: 200 })).toBe(true);
expect(interpretGatewayOutcome({ code: 500 })).toBe(false);
});
it("does not assume success when the gateway omits any verdict", () => {
expect(interpretGatewayOutcome({ msg: "ok" })).toBe(false);
expect(interpretGatewayOutcome({})).toBe(false);
expect(interpretGatewayOutcome(null)).toBe(false);
});
});
describe("grantWorkflowNodesApi request contract", () => {
it("posts to the resolved gateway and keeps tenant baseUrl in the payload", async () => {
let requestedUrl = "";
let payload: Record<string, unknown> = {};
spyOn(ky, "post").mockImplementation((async (url: string, options: any) => {
requestedUrl = String(url);
payload = options?.json ?? {};
return { ok: true, status: 200, json: async () => ({ success: true, data: { saved: ["code-js2"], skipped: [] } }) };
}) as never);
const result = await grantWorkflowNodesApi({
token: "tok",
corpId: "corp-1",
nodes: ["code-js2"],
baseUrl: "https://app.ekuaibao.com",
});
expect(result.success).toBe(true);
expect(result.saved).toEqual(["code-js2"]);
expect(requestedUrl).toContain("/hose-workflow-node");
expect(payload.corpId).toBe("corp-1");
expect(payload.baseUrl).toBe("https://app.ekuaibao.com");
});
it("includes the gateway url in transport failures", async () => {
process.env[GRAY_GATEWAY_URL_ENV] = "https://gw.example.com";
spyOn(ky, "post").mockImplementation((async () => {
throw new Error("connect ETIMEDOUT");
}) as never);
await expect(
grantWorkflowNodesApi({ token: "tok", corpId: "corp-1", nodes: ["code-js2"] })
).rejects.toThrow(/https:\/\/gw\.example\.com\/hose-workflow-node/);
});
});