fix(workflow): 启停结果改为回读确认,不再依赖 HTTP 状态码

生产启停此前用 ok() 判定结果,该函数只读 response.status 是否等于 200:
- 漏掉 HTTP 200 携带 code != 200 的业务失败,与 README「HTTP 200 不等于业务成功」冲突;
- 反向也会错,服务端 204 成功会被判成失败。

本次调整:
- 删除 transport/response.ts 的 ok(),消除这一判定来源;
- toggleWorkflowState 改用 readEasoWriteResponse 校验 EASO 业务码;
- management toggleWorkflow 写操作后回读详情确认状态,未变化抛 BusinessError
  (WORKFLOW_STATE_NOT_APPLIED),回读失败返回 verified: false,不谎称已生效;
- lifecycle handleToggle 此前完全不看返回值,无条件输出 [SUCCESS] 且 exitCode 0,
  现按 verified 给出 stderr 与退出码;handlePublish 同步调整;
- 新增 WorkflowToggleResult 模型并从 services 导出;
- 测试覆盖四种情形:回读确认成功、状态未生效、业务失败、回读失败。
This commit is contained in:
gitea committed 2026-11-01 21:35:22 +08:00
1 parent eb9b979943
commit 6dc96a5eb9
7 files changed
+125 -21

No files matched your search

+22 -5
View File
@@ -29,13 +29,27 @@ export async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime):
} }
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await toggleWorkflow(client, pipelineId, state); const result = await toggleWorkflow(client, pipelineId, state);
const label = state === 1 ? "🟢 启用" : "⚪ 停用";
if (runtime.jsonMode) { if (runtime.jsonMode) {
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return {
stdout: printJson(result, runtime.outputOptions),
stderr: "",
exitCode: result.verified ? 0 : 1,
};
}
// 启停未回读确认时必须如实告知:不得把「请求已提交」呈现为「已生效」。
if (!result.verified) {
return {
stdout: "",
stderr: `[WARNING] 工作流 ${pipelineId} 启停请求已提交,但${result.message}\n`,
exitCode: 1,
};
} }
return { return {
stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${state === 1 ? "🟢 启用" : "⚪ 停用"}\n`, stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${label}(已回读确认)\n`,
stderr: "", stderr: "",
exitCode: 0, exitCode: 0,
}; };
@@ -55,7 +69,10 @@ export async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime):
} }
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await toggleWorkflow(client, pipelineId, 1); const result = await toggleWorkflow(client, pipelineId, 1);
const output = { success: result.success, pipelineId, published: result.success, state: 1 }; const output = { success: result.verified, pipelineId, published: result.verified, state: 1, verified: result.verified, message: result.message };
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.success ? 0 : 1 }; if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.verified ? 0 : 1 };
return { stdout: result.success ? `✅ 工作流 [${pipelineId}] 已发布并启用。\n` : `❌ 工作流 [${pipelineId}] 发布失败。\n`, stderr: "", exitCode: result.success ? 0 : 1 }; if (!result.verified) {
return { stdout: "", stderr: `❌ 工作流 [${pipelineId}] 发布状态未能确认:${result.message}\n`, exitCode: 1 };
}
return { stdout: `✅ 工作流 [${pipelineId}] 已发布并启用(已回读确认)。\n`, stderr: "", exitCode: 0 };
} }
@@ -1,3 +1,4 @@
import { BusinessError } from "../../../../core/errors.js";
import { KyInstance } from "ky"; import { KyInstance } from "ky";
import { WorkflowSavePartialError } from "./save-error.js"; import { WorkflowSavePartialError } from "./save-error.js";
import * as api from "../api.js"; import * as api from "../api.js";
@@ -136,6 +137,48 @@ export function deleteWorkflow(...args: Parameters<typeof api.deleteWorkflow>) {
} }
export function toggleWorkflow(...args: Parameters<typeof api.toggleWorkflow>) { /**
return api.toggleWorkflow(...args); * 启停是生产开关:写请求按 EASO 业务码判定成败,写成功之后再回读详情确认状态确实变化。
* 回读失败(网络、鉴权、详情不可用)时不得宣称已生效,返回 `verified: false` 交由调用方如实呈现。
* `verify: false` 仅用于无法回读的场景(如只需要触发写写的内部场景),默认为确认模式。
*/
export async function toggleWorkflow(
client: import("ky").KyInstance,
pipelineId: string,
state: import("../types.js").WorkflowState,
options: { verify?: boolean } = {}
): Promise<import("../types.js").WorkflowToggleResult> {
await api.toggleWorkflowState(client, pipelineId, state);
const notVerified = (reason: string): import("../types.js").WorkflowToggleResult => ({
pipelineId,
requestedState: state,
state: null,
success: true,
verified: false,
message: `已提交启停请求,但${reason},服务端实际状态未能确认。请稍后用 workflow get 核对。`,
});
if (options.verify === false) return notVerified("未请求回读");
try {
const remote = await api.getWorkflowDetail(client, pipelineId);
const actual: import("../types.js").WorkflowState = remote.state === 1 ? 1 : 0;
if (actual !== state) {
throw new BusinessError(
`工作流 [${pipelineId}] 启停未生效:期望 state=${state},服务端回读 state=${actual}。请勿据此认为已发布或已停用。`,
"WORKFLOW_STATE_NOT_APPLIED"
);
}
return {
pipelineId,
requestedState: state,
state: actual,
success: true,
verified: true,
message: state === 1 ? "已确认启用" : "已确认停用",
};
} catch (error) {
if (error instanceof BusinessError) throw error;
return notVerified(`回读详情失败(${error instanceof Error ? error.message : String(error)})`);
}
} }
@@ -174,3 +174,19 @@ export type WorkflowSummary = z.infer<typeof WorkflowSummarySchema>;
export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>; export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>;
export type TaskMatch = z.infer<typeof TaskMatchSchema>; export type TaskMatch = z.infer<typeof TaskMatchSchema>;
export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>; export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>;
// ── 启停结果 ──────────────────────────────────────────────────────────────────
/**
* 工作流启停结果。启停是生产开关,必须在写操作之后回读确认:
* `verified` 区分「已确认生效」与「已提交但未能确认」,两者都不能谎称成功。
* `state` 为 null 表示未能读到服务端实际状态。
*/
export interface WorkflowToggleResult {
pipelineId: string;
requestedState: WorkflowState;
state: WorkflowState | null;
success: boolean;
verified: boolean;
message: string;
}
+2 -3
View File
@@ -34,10 +34,9 @@ export {
createWorkflow, createWorkflow,
deleteWorkflow, deleteWorkflow,
toggleWorkflow, toggleWorkflow,
type CreateWorkflowOptions,
} from "./management/configuration.js"; } from "./management/configuration.js";
export type { export type { WorkflowToggleResult } from "./models/workflow.js";
CreateWorkflowOptions,
} from "./management/configuration.js";
export { export {
listDsl, listDsl,
listStaffs, listStaffs,
@@ -19,8 +19,8 @@ import {
getWorkflowDetail, getWorkflowDetail,
listWorkflowSnapshots, listWorkflowSnapshots,
listWorkflowLogs, listWorkflowLogs,
toggleWorkflow,
} from "../api.js"; } from "../api.js";
import { toggleWorkflow } from "../management/configuration.js";
import { import {
extractFailureExecutions, extractFailureExecutions,
findExecutionNode, findExecutionNode,
@@ -144,20 +144,49 @@ describe("workflow draft state machine", () => {
expect(result.items[0]?.message).toBe("测试错误"); expect(result.items[0]?.message).toBe("测试错误");
}); });
it("uses the state endpoint for publishing a workflow", async () => { it("uses the state endpoint for publishing a workflow and confirms the new state", async () => {
let request: { url: string; options: any } | undefined; let request: { url: string; options: any } | undefined;
const client = { const client = {
put: async (url: string, options: any) => { put: async (url: string, options: any) => {
request = { url, options }; request = { url, options };
return new Response(JSON.stringify({ code: 200, msg: "更新成功", data: null }), { status: 200 }); return new Response(JSON.stringify({ code: 200, msg: "更新成功", data: null }), { status: 200 });
}, },
get: async () => new Response(JSON.stringify({ code: 200, data: { id: "wf-1", state: 1, version: "v1", tasksVersion: 1, tasks: [] } }), { status: 200 }),
} as any; } as any;
const result = await toggleWorkflow(client, "wf-1", 1); const result = await toggleWorkflow(client, "wf-1", 1);
expect(result.success).toBe(true); expect(result.success).toBe(true);
expect(result.verified).toBe(true);
expect(result.state).toBe(1);
expect(request?.url).toBe("api/easo/pipelines/state/wf-1"); expect(request?.url).toBe("api/easo/pipelines/state/wf-1");
expect(request?.options.searchParams).toEqual({ state: "1" }); expect(request?.options.searchParams).toEqual({ state: "1" });
}); });
it("refuses to claim success when the server keeps the old state", async () => {
const client = {
put: async () => new Response(JSON.stringify({ code: 200, data: null }), { status: 200 }),
get: async () => new Response(JSON.stringify({ code: 200, data: { id: "wf-1", state: 0, version: "v1", tasksVersion: 1, tasks: [] } }), { status: 200 }),
} as any;
await expect(toggleWorkflow(client, "wf-1", 1)).rejects.toThrow("启停未生效");
});
it("reports business failures carried by HTTP 200 responses", async () => {
const client = {
put: async () => new Response(JSON.stringify({ code: 500, msg: "流程存在非法节点" }), { status: 200 }),
} as any;
await expect(toggleWorkflow(client, "wf-1", 1)).rejects.toThrow("流程存在非法节点");
});
it("does not claim success when the confirmation read fails", async () => {
const client = {
put: async () => new Response(JSON.stringify({ code: 200, data: null }), { status: 200 }),
get: async () => new Response(JSON.stringify({ code: 401, msg: "凭证过期" }), { status: 200 }),
} as any;
const result = await toggleWorkflow(client, "wf-1", 0);
expect(result.success).toBe(true);
expect(result.verified).toBe(false);
expect(result.state).toBeNull();
});
it("persists workflow alert fingerprints and only reports new counts", () => { it("persists workflow alert fingerprints and only reports new counts", () => {
const dir = mkdtempSync("hose-workflow-alert-"); const dir = mkdtempSync("hose-workflow-alert-");
const file = join(dir, "alerts.json"); const file = join(dir, "alerts.json");
@@ -1,7 +1,7 @@
import type { KyInstance } from "ky"; import type { KyInstance } from "ky";
import { WorkflowPageSchema, WorkflowStatsSchema, WorkflowChargeSchema, WorkflowDetailSchema, WorkflowSnapshotSchema, WorkflowSnapshotPageSchema, WorkflowLogPageSchema } from "../../types.js"; import { WorkflowPageSchema, WorkflowStatsSchema, WorkflowChargeSchema, WorkflowDetailSchema, WorkflowSnapshotSchema, WorkflowSnapshotPageSchema, WorkflowLogPageSchema } from "../../types.js";
import type { WorkflowState } from "../../types.js"; import type { WorkflowState } from "../../types.js";
import { unwrap, readEasoWriteResponse, ok } from "../response.js"; import { unwrap, readEasoWriteResponse } from "../response.js";
// ── 工作流(EASO)───────────────────────────────────────────────────────────── // ── 工作流(EASO)─────────────────────────────────────────────────────────────
// 注意:EASO 客户端已自动注入 corpId,无需再传 // 注意:EASO 客户端已自动注入 corpId,无需再传
@@ -166,13 +166,18 @@ export async function listWorkflowLogs(
// ── 工作流启停(Piper)──────────────────────────────────────────────────────── // ── 工作流启停(Piper)────────────────────────────────────────────────────────
export async function toggleWorkflow( /**
* 工作流启停写操作。响应必须走 `readEasoWriteResponse` 校验业务码:
* HTTP 200 也可能携带 code != 200 的业务失败,只看状态码会把未生效的启停报成成功。
* 是否真的生效由上层回读详情确认,本层不做推断。
*/
export async function toggleWorkflowState(
client: KyInstance, client: KyInstance,
pipelineId: string, pipelineId: string,
state: WorkflowState state: WorkflowState
): Promise<{ success: boolean }> { ): Promise<void> {
const response = await client.put(`api/easo/pipelines/state/${pipelineId}`, { const response = await client.put(`api/easo/pipelines/state/${pipelineId}`, {
searchParams: { state: String(state) }, searchParams: { state: String(state) },
}); });
return ok(response); await readEasoWriteResponse(response);
} }
@@ -54,8 +54,3 @@ export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promi
return schema.parse(payload); return schema.parse(payload);
} }
// Helper for simple success responses
export async function ok(response: Response): Promise<{ success: boolean }> {
return { success: response.status === 200 };
}