fix(approval-runs): 传输层失败不再被误判为业务结论

`sealApprovalRunFlowGet` 用两次"请求被拒"充当路由信号:记录查询被拒,就
认为入参是单号;运行记录列表被拒,就认为该单据没有 AI 记录。两处都写成
裸 `catch {}`,于是所有失败都被吸收进这两个业务结论。

后果不是偶尔不准,而是以十足的语气给出错误答案:token 过期、连接重置、
网关 5xx 会被渲染成「单据已删除」或「AI 从未审核」,用户没有任何线索去
怀疑刚才那次请求其实失败了;退出码同时失去语义,本该由 classifyCliError
产出 11(认证/上游失败),实际退化成一次"成功的查询"。

现在只有标识符形态的拒绝才计为未命中:HTTP 400/404/422,或响应体确实
到达但不是一条审批记录。认证失败、5xx、限流、以及根本没有响应的传输
错误一律原样上抛。

- errors:导出既有的 `responseStatus` 结构读取器,让调用方能区分"没有
  响应"与"收到了 400/404 响应"。
- approval-runs:新增 `isUpstreamLookupMiss`,替换两处裸 catch。
- test:新增四个回归用例(401/403/503/连接失败),断言原始错误对象抵达
  调用方;另加一条非合思租户的守卫用例。
This commit is contained in:
yunyingk committed 2026-11-10 19:47:48 +08:00
1 parent 8ecadbb124
commit c572cba842
3 files changed
+131 -6

No files matched your search

+7 -1
View File
@@ -97,7 +97,13 @@ function isValidationIssueList(error: unknown): boolean {
);
}
function responseStatus(error: unknown): number | undefined {
/**
* Read the HTTP status off an error thrown by the HTTP layer, structurally:
* ky's `HTTPError` is not a dependency of this module, and test doubles only
* carry `{ response: { status } }`. `undefined` means the request never got a
* response (DNS failure, connection reset, timeout).
*/
export function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
@@ -0,0 +1,95 @@
import { describe, expect, test } from "bun:test";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { findSealCapability } from "../capabilities.js";
/**
* The flow lookup uses a rejected record query as a routing signal ("this was
* not a record ID, treat it as a document number") and a rejected run listing
* as "this document has no AI records". Both are fine for an identifier-shaped
* rejection and catastrophic for anything else: an expired token or a reset
* connection would be reported downstream as 「单据已删除」 or 「AI 从未审核」,
* which is a wrong answer delivered with full confidence.
*
* These cases stop before the Hose client is built, so no tenant is required.
*/
const HOSE_CORP = {
id: "corp-hose",
name: "测试合思企业",
source: { type: "hose" }
} as unknown as CorpConfig;
type Handler = (
client: KyInstance,
params: Record<string, unknown>,
context: { corp: CorpConfig }
) => Promise<unknown>;
function flowHandler(): Handler {
const capability = findSealCapability("sealApprovalRunFlowGet");
expect(capability).toBeDefined();
return capability!.handler as unknown as Handler;
}
function failingClient(error: unknown): KyInstance {
return {
get: () => {
throw error;
}
} as unknown as KyInstance;
}
function httpError(status: number): Error {
return Object.assign(new Error(`Request failed with status code ${status}`), {
response: { status }
});
}
async function captured(promise: Promise<unknown>): Promise<unknown> {
try {
await promise;
return undefined;
} catch (error) {
return error;
}
}
const SURFACED = [
["expired credentials", httpError(401)],
["forbidden credentials", httpError(403)],
["upstream service failure", httpError(503)],
["connection failure without a response", new TypeError("fetch failed")]
] as const;
describe("sealApprovalRunFlowGet failure attribution", () => {
for (const [label, error] of SURFACED) {
test(`surfaces ${label} instead of absorbing it as a document number`, async () => {
const thrown = await captured(
flowHandler()(failingClient(error), { target: "B26001887" }, { corp: HOSE_CORP })
);
// Identity, not message: the original error must reach the CLI layer so
// classifyCliError can still produce exit code 11 for auth failures.
expect(thrown).toBe(error);
});
}
test("keeps rejecting non-Hose enterprises before any request", async () => {
let called = false;
const client = {
get: () => {
called = true;
throw new Error("must not be reached");
}
} as unknown as KyInstance;
const thrown = await captured(
flowHandler()(client, { target: "B26001887" }, {
corp: { id: "corp-seal", name: "Seal 企业", source: { type: "seal" } } as unknown as CorpConfig
})
);
expect(String(thrown)).toContain("非合思");
expect(called).toBe(false);
});
});
+29 -5
View File
@@ -1,4 +1,4 @@
import { usageError, validationError } from "../../../core/errors.js";
import { classifyCliError, responseStatus, usageError, validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
@@ -48,6 +48,28 @@ const {
summarizeRuleVersion
} = helpers;
/**
* Decide whether a failed lookup means "the caller's input was not an ID of
* that kind" or something worse.
*
* Distinguishing them matters because both call sites below use the failure as
* a routing signal: a rejected record lookup means "treat the input as a
* document number", and a rejected run listing means "this document has no AI
* records". Swallowing everything turns a transient failure into a confident
* business verdict — an expired token or a reset connection would surface as
* 「单据已删除」 or 「AI 从未审核」, which is worse than an error.
*/
function isUpstreamLookupMiss(error: unknown): boolean {
const status = responseStatus(error);
if (status !== undefined) {
// Malformed or unknown identifier: the answer we were hoping for.
return status === 400 || status === 404 || status === 422;
}
// No response at all (DNS, reset, timeout) is never a miss. Structural
// validation failures are: the body arrived, it just is not an approval run.
return classifyCliError(error).exitCode === 13;
}
export const approvalRunsCapabilities = [
{
name: "sealApprovalRunsSearch",
@@ -273,8 +295,9 @@ export const approvalRunsCapabilities = [
if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) {
sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!;
}
} catch {
// Continue as SN
} catch (error) {
if (!isUpstreamLookupMiss(error)) throw error;
// Not a record ID: the caller passed a document number. Continue as SN.
}
let runs: ApprovalRun[] = [];
@@ -287,8 +310,9 @@ export const approvalRunsCapabilities = [
runs = (runsData.records || []).filter(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input
);
} catch {
// ignore
} catch (error) {
if (!isUpstreamLookupMiss(error)) throw error;
// No AI records for this document is a legitimate outcome.
}
if (runs.length === 0 && targetRecord) {