fix: 表达工作流部分保存结果并校验认证重放

Piper 的 chooses 刷新与删除检查业务码,保留空成功响应。主保存成功后刷新失败抛出携带已保存版本的 WorkflowSavePartialError;统一 JSON 错误保留可选 EkbError.details。
workflow save 在部分成功时返回非零与恢复信息,--in-place 仍同步已保存版本;新增带写确认的 refresh-chooses,仅重试元数据刷新,不重发完整快照。主保存失败不改本地版本。
认证重放保留最终鉴权响应检查(含 HTTP 200 的错误头),最多重放一次,其他 HTTP 错误维持 Ky 语义。补充 SDK、CLI、恢复与重放回归,并更新文档。

验证:bun test 922 通过、0 失败;bun run check、git diff --check 通过。所有业务请求均为离线假接口。
This commit is contained in:
gitea committed 2026-10-29 18:21:30 +08:00
1 parent 51fb54dfe8
commit 55d31e27e6
19 files changed
+298 -23

No files matched your search

+2
View File
@@ -1,5 +1,7 @@
# 应用管理、自建应用与工作流指南 (App, Platform & Workflow Guide)
保存返回 `remoteSaved: true` / `status: "partial"`,或错误 `details.remoteSaved: true` 时,主保存已经完成。保留返回的新版本,仅用 `workflow refresh-chooses <pipelineId> --platform-id=<id> --yes` 恢复元数据刷新;不要重复提交完整快照。`save --in-place` 会在部分成功时同步本地版本,退出码仍非零。
本参考专卷详细说明合思桌面端【应用管理】、企业后台【自建应用】(DataLink 数据建模与底层记录)以及任务节点工作流(Workflow)的查询与使用。
> **核心概念辨析(严禁混淆)**:
+1
View File
@@ -11,6 +11,7 @@
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
完整 JSON 按值类型脱敏,保留 `keepItSecret` 等布尔业务标记和 null,凭据字符串及数值仍被遮蔽;紧凑 NDJSON 保持单行。普通诊断文本沿用 URL、Bearer 和键值脱敏。
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
带结构化元数据的 `EkbError.details` 会保留在 JSON 错误中,例如工作流主保存已完成但元数据刷新失败时的 `remoteSaved` 和服务端版本;普通错误输出不变。
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
+1
View File
@@ -214,6 +214,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"save": "保存草稿到远端",
"toggle": "切换启停状态",
"publish": "发布并启用工作流",
"refresh-chooses": "只刷新工作流选择器元数据,用于主保存后的失败恢复",
"history": "查看版本历史",
"logs": "查看运行日志",
"check": "检查错误管道",
+1 -1
View File
@@ -1523,7 +1523,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
},
put: (url: string, opts: any) => {
if (url.endsWith("/chooses")) {
return { json: async () => ({ code: 200, data: [] }) };
return Response.json({ code: 200, data: [] });
}
if (url.includes("api/easo/pipelines/pipe_node_test")) {
savedWorkflowPayload = opts.json;
+33 -4
View File
@@ -1,5 +1,7 @@
import { readFileSync, writeFileSync } from "node:fs";
import { getWorkflowDetail, listAllWorkflows, updateWorkflow } from "../../../domains/platform/services.js";
import { EkbError } from "../../../core/errors.js";
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/services.js";
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/save-error.js";
import { WorkflowDetailSchema } from "../../../domains/platform/types.js";
import {
applyWorkflowPathPatch,
@@ -137,8 +139,14 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
const payload = state.workflow.inputs?.length
? state.workflow
: { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] };
const saved = await updateWorkflow(piperClient, payload);
let partialError: WorkflowSavePartialError | undefined;
const saved = await updateWorkflow(piperClient, payload).catch((error: unknown) => {
if (!(error instanceof WorkflowSavePartialError)) throw error;
partialError = error;
return error.savedWorkflow;
});
state = commitWorkflowSave(state, saved);
if (partialError) state = { ...state, status: "partial", error: partialError.message };
let fileSynced = false;
let fileSyncWarning = "";
if (syncFile) {
@@ -155,8 +163,11 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
fileSyncWarning = `本地文件同步失败: ${error instanceof Error ? error.message : String(error)}`;
}
}
const quoteArg = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
const nextAction = `hose-use workflow refresh-chooses ${quoteArg(pipelineId)} --platform-id=${quoteArg(platformId)} --corp=${quoteArg(runtime.selectedCorp!.id)} --yes`;
const result = {
success: true,
success: !partialError,
...(partialError ? { remoteSaved: true, failedStep: "chooses", nextAction, message: partialError.message } : {}),
pipelineId,
status: state.status,
version: saved.version,
@@ -165,7 +176,12 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
fileSynced,
...(fileSyncWarning ? { fileSyncWarning } : {}),
};
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: 0 };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: partialError ? 1 : 0 };
if (partialError) return {
stdout: `⚠️ ${partialError.message}\n${fileSynced ? "已同步本地文件版本。\n" : ""}恢复命令: ${nextAction}\n`,
stderr: fileSyncWarning,
exitCode: 1,
};
return {
stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功:${formatWorkflowVersion(saved)}。${fileSynced ? "\n📝 已同步更新本地文件。" : ""}${fileSyncWarning ? `\n⚠️ ${fileSyncWarning}` : ""}\n`,
stderr: fileSyncWarning,
@@ -173,10 +189,23 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
};
} catch (error) {
state = failWorkflowSave(state, error);
if (error instanceof EkbError) throw error;
throw new Error(`工作流保存失败(${state.status}): ${state.error}`);
}
}
export async function handleRefreshChooses(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) throw new Error("请提供工作流 ID: hose-use workflow refresh-chooses <pipelineId> --yes");
requireMutationConfirmation(parsed, runtime, "刷新工作流元数据", `hose-use workflow refresh-chooses ${pipelineId} --yes`);
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "刷新工作流元数据", pipelineId, { retryStep: "chooses", saveWorkflow: false });
const clients = await createClientsForCorp(runtime.selectedCorp!);
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
const client = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
await refreshWorkflowChooses(client, pipelineId);
return { stdout: runtime.jsonMode ? printJson({ success: true, pipelineId, metadataRefreshed: true }, runtime.outputOptions) : `工作流 [${pipelineId}] 元数据刷新成功,未重新提交快照。\n`, stderr: "", exitCode: 0 };
}
async function resolveWorkflowPlatformId(
parsed: CliParsedArgs,
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
+4 -2
View File
@@ -1,7 +1,7 @@
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { handleList, handleGet, handleFind } from "./list.js";
import { handleToggle, handlePublish } from "./lifecycle.js";
import { handlePatch, handleSave } from "./draft.js";
import { handlePatch, handleSave, handleRefreshChooses } from "./draft.js";
import { handleHistory, handleLogs } from "./history.js";
import { handleJob } from "./job.js";
import { handleCheck } from "./check.js";
@@ -52,6 +52,8 @@ export async function handleWorkflowCommand(
case "save":
case "update":
return handleSave(parsed, runtime);
case "refresh-chooses":
return handleRefreshChooses(parsed, runtime);
case "patch":
return handlePatch(parsed, runtime);
case "history":
@@ -122,7 +124,7 @@ export async function handleWorkflowCommand(
default:
return {
stdout: "",
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
exitCode: 1,
};
}
@@ -0,0 +1,77 @@
import { afterEach, expect, spyOn, test } from "bun:test";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import ky from "ky";
import * as helpers from "../../helpers.js";
import { parseArgs } from "../../parser.js";
import { cliErrorResult } from "../../runner.js";
import { normalizeCliArgs, tokenizeCommand } from "../../../server.js";
import { handleWorkflowCommand } from "./index.js";
import { WorkflowDetailSchema } from "../../../domains/platform/types.js";
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/save-error.js";
import type { CliRuntime } from "../../types.js";
const spies: Array<{ mockRestore(): void }> = [];
const directories: string[] = [];
afterEach(() => {
for (const spy of spies.splice(0)) spy.mockRestore();
for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true });
});
function fixture(mainFails = false) {
const dir = mkdtempSync(join(tmpdir(), "hose-save-partial-"));
directories.push(dir);
const file = join(dir, "workflow.json");
const workflow = WorkflowDetailSchema.parse({ id: "p", label: "本地名称", version: "v1", tasksVersion: 1, localNote: "keep" });
writeFileSync(file, JSON.stringify(workflow));
const requests: Array<{ method: string; path: string }> = [];
let failRefresh = true;
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async (input, init) => {
const req = input instanceof Request ? input : new Request(input.toString(), init);
const path = new URL(req.url).pathname;
requests.push({ method: req.method, path });
if (req.method === "GET") return Response.json({ code: 200, data: workflow });
if (path.endsWith("/chooses")) return Response.json(failRefresh ? { code: 500, msg: "刷新失败" } : { code: 200, data: [] });
return Response.json(mainFails ? { code: 500, msg: "保存失败" } : { code: 200, data: { ...workflow, label: "远端名称", version: "v2", tasksVersion: 2 } });
} });
const corp = { id: "corp", name: "测试企业", baseUrl: "https://tenant.invalid", source: "manual", credentials: { corpId: "corp", staffId: "staff", accessToken: "fake" } } as const;
const runtime = { selectedCorp: corp, corpContext: {}, jsonMode: true } as CliRuntime;
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ corp, sessionClient: client, ekbClient: client, unityClient: client, easoClient: client }));
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(client));
return { file, workflow, runtime, requests, restoreRefresh: () => { failRefresh = false; } };
}
test("部分保存返回非零与新版本,同步本地版本后可只重试 chooses", async () => {
const f = fixture();
const result = await handleWorkflowCommand(parseArgs(["workflow", "save", "p", "--file", f.file, "--platform-id", "app", "--in-place", "--yes", "--json"]), f.runtime);
expect(result.exitCode).toBe(1);
const partial = JSON.parse(result.stdout);
expect(partial).toMatchObject({ success: false, remoteSaved: true, failedStep: "chooses", status: "partial", version: "v2", tasksVersion: 2, fileSynced: true });
expect(JSON.parse(readFileSync(f.file, "utf8"))).toMatchObject({ label: "本地名称", localNote: "keep", version: "v2", tasksVersion: 2 });
f.restoreRefresh();
const retry = await handleWorkflowCommand(parseArgs(normalizeCliArgs(tokenizeCommand(partial.nextAction))), f.runtime);
expect(retry.exitCode).toBe(0);
expect(f.requests.filter(r => r.method === "PUT").map(r => r.path)).toEqual(["/api/easo/pipelines/p", "/api/easo/pipelines/p/chooses", "/api/easo/pipelines/p/chooses"]);
});
test("主保存失败不更新本地版本,也不发送 chooses", async () => {
const f = fixture(true);
await expect(handleWorkflowCommand(parseArgs(["workflow", "save", "p", "--file", f.file, "--platform-id", "app", "--in-place", "--yes"]), f.runtime)).rejects.toThrow("保存失败");
expect(JSON.parse(readFileSync(f.file, "utf8")).tasksVersion).toBe(1);
expect(f.requests.some(r => r.path.endsWith("/chooses"))).toBe(false);
});
test("定向刷新支持无网络预演,且仍要求写确认", async () => {
const f = fixture();
const preview = await handleWorkflowCommand(parseArgs(["workflow", "refresh-chooses", "p", "--dry-run", "--json"]), f.runtime);
expect(JSON.parse(preview.stdout)).toMatchObject({ dryRun: true, changes: { saveWorkflow: false } });
await expect(handleWorkflowCommand(parseArgs(["workflow", "refresh-chooses", "p"]), f.runtime)).rejects.toThrow("--yes");
expect(f.requests).toEqual([]);
});
test("其他保存入口的部分成功异常通过统一 JSON 错误边界保留元数据", () => {
const result = cliErrorResult(new WorkflowSavePartialError(WorkflowDetailSchema.parse({ id: "p", tasksVersion: 2 }), new Error("refresh failed")), true);
expect(result.exitCode).not.toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({ error: true, details: { remoteSaved: true, failedStep: "chooses", saved: { pipelineId: "p", tasksVersion: 2 } } });
});
+2 -1
View File
@@ -6,6 +6,7 @@ import { classifyCliError } from "./errors.js";
import { initCorpRuntime } from "./helpers.js";
import { findCommandByArea, isStandingCommand } from "./registry.js";
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
import { EkbError } from "../core/errors.js";
let runQueue = Promise.resolve<any>(undefined);
@@ -109,7 +110,7 @@ export function cliErrorResult(error: unknown, jsonMode: boolean): CliResult {
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
return {
stdout: jsonMode ? JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}) }, null, 2) : "",
stdout: jsonMode ? redactSensitiveText(JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}), ...(error instanceof EkbError && error.details ? { details: error.details } : {}) }, null, 2)) : "",
stderr: jsonMode ? "" : `[ERROR] ${message}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
exitCode: classification.exitCode,
};
+2
View File
@@ -60,3 +60,5 @@ src/core/
- 校验签发身份与目标一致,并在保存成功后更新内存配置;失败时不留下半更新的内存身份。
子域客户端在 401 后使缓存失效、重新换票,并从新缓存读取请求头重放原请求一次;同一客户端无需重建。持续鉴权失败停止重试,POST 请求体在重放时保持一致。
重放响应仍检查 HTTP 401 与 `error-type` 鉴权错误头(包括 HTTP 200 携带错误头的情况);再次失败抛出 `AuthenticationError`,不再第三次请求。非鉴权 HTTP 错误保持 Ky 的错误语义。
+2 -1
View File
@@ -2,7 +2,8 @@ export class EkbError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly status?: number
public readonly status?: number,
public readonly details?: Record<string, unknown>
) {
super(message);
this.name = "EkbError";
+18 -6
View File
@@ -1,4 +1,10 @@
import ky, { KyInstance, type BeforeRequestState } from "ky";
import { AuthenticationError } from "../errors.js";
function isAuthenticationFailure(response: Response): boolean {
const errorType = response.headers.get("error-type");
return response.status === 401 || errorType === "UnauthenticatedException" || errorType === "UnauthorizedException";
}
export interface CreateClientOptions {
prefixUrl: string;
@@ -45,11 +51,7 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
afterResponse: [
async ({ request, response }) => {
if (!response) return response;
const errorType = response.headers.get("error-type");
const isAuthError =
response.status === 401 ||
errorType === "UnauthenticatedException" ||
errorType === "UnauthorizedException";
const isAuthError = isAuthenticationFailure(response);
if (isAuthError && options.onUnauthorized && options.retryUnauthorized !== false) {
const replay = replays.get(request);
@@ -66,7 +68,17 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
}
}
// Ky's Request.clone type omits Bun's extra Headers methods; the runtime object is unchanged.
return ky(replay as unknown as Request, { retry: 0, timeout: options.timeout ?? 30000 });
return ky(replay as unknown as Request, {
retry: 0,
timeout: options.timeout ?? 30000,
// 只执行最终鉴权检查,不再续期;非鉴权 HTTP 错误仍由 Ky 处理。
hooks: { afterResponse: [({ response: replayResponse }) => {
if (isAuthenticationFailure(replayResponse)) {
throw options.onAuthFailure?.(replayResponse) ?? new AuthenticationError("认证续期后仍失败,请重新登录");
}
return replayResponse;
}] },
});
}
if (isAuthError && options.onAuthFailure) {
throw options.onAuthFailure(response);
+45
View File
@@ -0,0 +1,45 @@
import { afterEach, expect, test } from "bun:test";
import { HTTPError } from "ky";
import { createAuthClient } from "./factory.js";
import { AuthenticationError } from "../errors.js";
const originalFetch = globalThis.fetch;
afterEach(() => { globalThis.fetch = originalFetch; });
for (const finalStatus of [200, 401]) {
test(`续期后 HTTP ${finalStatus} 的鉴权错误仍拒绝,且不第三次请求`, async () => {
const bodies: string[] = [];
let refreshes = 0;
globalThis.fetch = (async (input: Request) => {
bodies.push(await input.text());
return bodies.length === 1 ? new Response("expired", { status: 401 })
: Response.json({ error: true }, { status: finalStatus, headers: { "error-type": "UnauthenticatedException" } });
}) as unknown as typeof fetch;
const client = createAuthClient({ prefixUrl: "https://tenant.invalid", getHeaders: () => ({ token: "fake" }), onUnauthorized: () => { refreshes++; } });
await expect(client.post("action", { json: { amount: 42 } }).json()).rejects.toBeInstanceOf(AuthenticationError);
expect(refreshes).toBe(1);
expect(bodies).toEqual(['{"amount":42}', '{"amount":42}']);
});
}
test("重放保留正常成功和非鉴权 HTTP 错误的 Ky 语义", async () => {
for (const status of [200, 503]) {
let requests = 0;
globalThis.fetch = (async () => ++requests === 1 ? new Response("", { status: 401 }) : Response.json({ ok: true }, { status })) as unknown as typeof fetch;
const client = createAuthClient({ prefixUrl: "https://tenant.invalid", getHeaders: () => ({}), onUnauthorized: () => {} });
const result = client.get("action").json();
if (status === 200) expect(await result).toEqual({ ok: true });
else await expect(result).rejects.toBeInstanceOf(HTTPError);
expect(requests).toBe(2);
}
});
test("最终鉴权失败仍调用调用方提供的错误构造器", async () => {
let requests = 0;
let failures = 0;
globalThis.fetch = (async () => { requests++; return new Response("", { status: 401 }); }) as unknown as typeof fetch;
const client = createAuthClient({ prefixUrl: "https://tenant.invalid", getHeaders: () => ({}), onUnauthorized: () => {}, onAuthFailure: () => { failures++; return new AuthenticationError("重新登录"); } });
await expect(client.get("action")).rejects.toThrow("重新登录");
expect(requests).toBe(2);
expect(failures).toBe(1);
});
+19 -4
View File
@@ -44,8 +44,7 @@ function throwEasoResponseError(response: Response, record?: Record<string, unkn
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
}
async function readEasoResponse(response: Response) {
const raw = await response.json();
function checkEasoResponse(response: Response, raw: unknown) {
const record =
raw !== null && typeof raw === "object" && !Array.isArray(raw)
? (raw as Record<string, unknown>)
@@ -57,6 +56,21 @@ async function readEasoResponse(response: Response) {
return { raw, record };
}
async function readEasoResponse(response: Response) {
return checkEasoResponse(response, await response.json());
}
/** 无返回值的写接口也要检查业务码;兼容 204 与空成功响应。 */
async function readEasoWriteResponse(response: Response): Promise<void> {
const text = await response.text();
if (response.ok === false) throwEasoResponseError(response);
if (!text.trim()) return;
let raw: unknown;
try { raw = JSON.parse(text); }
catch { throw new EkbApiError("EASO/Piper 写接口返回无效 JSON", "EASO_RESPONSE_INVALID", 502); }
checkEasoResponse(response, raw);
}
// Helper to unwrap { data: T } / { value: T } response with null/error defense
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
const { raw, record } = await readEasoResponse(response);
@@ -152,7 +166,8 @@ export async function updateWorkflowChooses(
client: KyInstance,
pipelineId: string
): Promise<void> {
await client.put(`api/easo/pipelines/${pipelineId}/chooses`);
const response = await client.put(`api/easo/pipelines/${pipelineId}/chooses`);
await readEasoWriteResponse(response);
}
export async function copyWorkflow(
@@ -181,7 +196,7 @@ export async function deleteWorkflow(
pipelineId: string
): Promise<boolean> {
const response = await client.delete(`api/easo/pipelines/${pipelineId}`);
await response.text().catch(() => "");
await readEasoWriteResponse(response);
return true;
}
+11 -1
View File
@@ -1,5 +1,6 @@
import { KyInstance } from "ky";
import { CorpConfig } from "../../core/config/types.js";
import { WorkflowSavePartialError } from "./workflow/save-error.js";
import * as api from "./api.js";
import { PermissionError, ValidationError } from "../../core/errors.js";
import { explainConditionBranches } from "./workflow/branch/index.js";
@@ -76,10 +77,19 @@ export async function updateWorkflow(
const sanitized = sanitizeWorkflowSnapshot(payload);
const updated = await api.updateWorkflow(client, sanitized);
// 复刻前端“保存更新”:主线 PUT 之后刷新 chooses。
await api.updateWorkflowChooses(client, updated.id || workflow.id);
try {
await api.updateWorkflowChooses(client, updated.id || workflow.id);
} catch (error) {
throw new WorkflowSavePartialError(updated, error);
}
return updated;
}
/** 只重试元数据刷新,不重新提交完整工作流快照。 */
export function refreshWorkflowChooses(client: KyInstance, pipelineId: string): Promise<void> {
return api.updateWorkflowChooses(client, pipelineId);
}
export async function copyWorkflow(
client: import("ky").KyInstance,
pipelineId: string,
@@ -2,6 +2,12 @@
Platform 域下工作流能力的命令、协议与诊断契约。总体边界见 [Platform 概览](../README.platform.md)。
## 保存结果与恢复
主保存 PUT 后仍需刷新 chooses。刷新返回的业务错误会被检查;HTTP 200 不等于业务成功,空成功响应仍兼容。主保存成功、刷新失败时,SDK 抛出 `WorkflowSavePartialError`,携带 `savedWorkflow` 及结构化 `details`,不得自动重发整个保存。
`workflow save --in-place` 遇到这类部分成功仍同步本地版本,返回非零退出码、`status: "partial"`、`remoteSaved: true`、新版本和恢复命令。主保存本身失败则不改本地版本。恢复可用 `workflow refresh-chooses <pipelineId> --platform-id=<id> --yes`,只刷新元数据,不提交快照;该命令也支持 `--dry-run`。
## CLI 常用命令
```bash
@@ -0,0 +1,17 @@
import { EkbError } from "../../../core/errors.js";
import type { WorkflowDetail } from "../types.js";
/** 主保存已经提交,后续元数据刷新失败。调用方必须保留已保存版本。 */
export class WorkflowSavePartialError extends EkbError {
readonly remoteSaved = true;
constructor(readonly savedWorkflow: WorkflowDetail, readonly cause: unknown) {
super(
`工作流 [${savedWorkflow.id}] 主保存已完成(tasksVersion=${savedWorkflow.tasksVersion}),元数据刷新失败;请仅重试元数据刷新,不要重复主保存。原因: ${cause instanceof Error ? cause.message : String(cause)}`,
"WORKFLOW_SAVE_PARTIAL",
502,
{ remoteSaved: true, failedStep: "chooses", saved: { pipelineId: savedWorkflow.id, version: savedWorkflow.version, tasksVersion: savedWorkflow.tasksVersion, updateTime: savedWorkflow.updateTime } }
);
this.name = "WorkflowSavePartialError";
}
}
@@ -67,7 +67,7 @@ describe("workflow draft state machine", () => {
let request: { url: string; json: WorkflowDetail } | undefined;
const client = {
put: async (url: string, options: { json: WorkflowDetail }) => {
if (url.endsWith("/chooses")) return { json: async () => ({ data: [] }) };
if (url.endsWith("/chooses")) return Response.json({ data: [] });
request = { url, json: options.json };
return { json: async () => ({ data: options.json }) };
},
@@ -83,7 +83,7 @@ describe("workflow draft state machine", () => {
let sentWorkflow: WorkflowDetail | undefined;
const client = {
put: async (url: string, options: { json: WorkflowDetail }) => {
if (url.endsWith("/chooses")) return { json: async () => ({ data: [] }) };
if (url.endsWith("/chooses")) return Response.json({ data: [] });
sentWorkflow = options.json;
return { json: async () => ({ data: options.json }) };
},
+1 -1
View File
@@ -1,7 +1,7 @@
import { NotFoundError, ValidationError } from "../../../../core/errors.js";
import type { WorkflowDetail } from "../../types.js";
export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "failed";
export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "partial" | "failed";
export interface WorkflowDraftState {
workflow: WorkflowDetail;
+54
View File
@@ -0,0 +1,54 @@
import { expect, test } from "bun:test";
import ky from "ky";
import { deleteWorkflow, updateWorkflowChooses } from "./api.js";
import { refreshWorkflowChooses, updateWorkflow } from "./services.js";
import { WorkflowDetailSchema } from "./types.js";
import { WorkflowSavePartialError } from "./workflow/save-error.js";
import { AuthenticationError } from "../../core/errors.js";
test("Piper 无返回值写操作兼容空成功,拒绝业务失败与无效 JSON", async () => {
for (const action of [deleteWorkflow, updateWorkflowChooses]) {
for (const body of ["", JSON.stringify({ code: 200, data: [] })]) {
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => new Response(body) });
await action(client, "p");
}
for (const body of [JSON.stringify({ code: 500, msg: "拒绝写入" }), "{broken"]) {
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => new Response(body) });
await expect(action(client, "p")).rejects.toThrow();
}
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => Response.json({ code: 401, msg: "凭证失效" }) });
await expect(action(client, "p")).rejects.toBeInstanceOf(AuthenticationError);
}
});
test("两阶段保存保留已提交版本,恢复只刷新 chooses", async () => {
const workflow = WorkflowDetailSchema.parse({ id: "p", version: "v1", tasksVersion: 1 });
const calls: string[] = [];
let failRefresh = true;
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async input => {
const path = new URL(input instanceof Request ? input.url : input.toString()).pathname;
calls.push(path);
return path.endsWith("/chooses")
? Response.json(failRefresh ? { code: 500, msg: "刷新拒绝" } : { code: 200, data: [] })
: Response.json({ code: 200, data: { ...workflow, tasksVersion: 2 } });
} });
let partial: WorkflowSavePartialError | undefined;
try { await updateWorkflow(client, workflow); }
catch (error) { expect(error).toBeInstanceOf(WorkflowSavePartialError); partial = error as WorkflowSavePartialError; }
expect(partial?.savedWorkflow.tasksVersion).toBe(2);
expect(partial?.details).toMatchObject({ remoteSaved: true, failedStep: "chooses", saved: { tasksVersion: 2 } });
failRefresh = false;
await refreshWorkflowChooses(client, "p");
expect(calls).toEqual(["/api/easo/pipelines/p", "/api/easo/pipelines/p/chooses", "/api/easo/pipelines/p/chooses"]);
});
test("主保存失败不会刷新 chooses,也不报告部分成功", async () => {
const calls: string[] = [];
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async input => {
calls.push(input instanceof Request ? input.url : input.toString());
return Response.json({ code: 500, msg: "主保存拒绝" });
} });
const error = await updateWorkflow(client, WorkflowDetailSchema.parse({ id: "p" })).catch(error => error);
expect(error).not.toBeInstanceOf(WorkflowSavePartialError);
expect(calls).toHaveLength(1);
});