Files
clean-architecture-frontend…/tests/platform/errors/platform-errors.test.ts
DongHyeonka a934554d28 fix(errors): 플랫폼 JSON 파서의 「JSON 아님」을 response.invalid로 나눈다
parseBoundedJson은 JSON.parse 실패를 JsonBudgetExceededError
("invalid-json")로 감싸 던진다. mapTransportFailure는 violation을 보지
않고 그 이름이면 모두 response.too-large로 돌린다. 그래서 platform의 두
함수를 이어 쓰면 JSON이 아닌 응답이 늘 response.too-large가 되고, 날
SyntaxError(response.invalid)와 갈린다. 시험 표에는 fan-out 초과·
TimeoutError·invalid-json 줄이 없어, fan-out 분기나 TimeoutError 분기를
지워도 시험이 통과했다.

JsonBudgetExceededError일 때 own data violation을 읽어 "invalid-json"이면
response.invalid, 나머지는 response.too-large로 둔다. errorName처럼
accessor는 부르지 않는다(getter violation은 too-large로 남고 getter가
불리지 않는 것을 시험이 단언한다). 시험 표에 RequestFanoutExceededError,
DOMException TimeoutError(deadline 안 지남), invalid-json 세 줄을 더한다.
버린 안: bounded-json이 SyntaxError를 다시 던지게 바꾸기. bounded-json.test가
「날 SyntaxError가 아니라 budget error」를 고정하고, 항목 범위 밖이다.

위험: src 호출처가 없는 다운스트림 확장 지점이다. 두 kind의 category
(contract)·retryability(never)가 같아 kind 이름만 바뀐다.

검증(desktop, 기준 b687a04c 위 작업 트리):
- 고치기 전 src + 새 시험: invalid-json 줄 실패(1 failed | 19 passed).
- 고치기 전 src·시험 + fan-out 분기 삭제 / `|| name === "TimeoutError"`
  삭제: 둘 다 통과(16 passed). 고친 뒤 같은 변이: 각각 더한 줄이 실패.
- 고친 트리: platform-errors 시험 통과.

Refs: REV-FE-0031
2026-11-21 09:58:23 +09:00

146 lines
5.7 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { platformErrorForOutcome } from "../../../src/adapters/http/platform-error-mapping.ts";
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
import {
mapTransportFailure,
PLATFORM_ERRORS,
} from "../../../src/platform/errors/platform-errors.ts";
import { isAppError } from "../../../src/platform/errors/app-error.ts";
import { RequestBudgetExceededError } from "../../../src/platform/traffic/request-budget.ts";
import { ConcurrencyQueueFullError } from "../../../src/platform/traffic/concurrency-budget.ts";
import { RequestFanoutExceededError } from "../../../src/platform/traffic/request-fanout.ts";
import { DeadlineExceededError } from "../../../src/platform/resilience/deadline.ts";
import { JsonBudgetExceededError } from "../../../src/platform/validation/bounded-json.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
import {
networkFailure,
scopeSnapshot,
testExecutionContext,
testExecutor,
type Transport,
} from "../../helpers/traffic-test-kit.ts";
const abortError = () => new DOMException("aborted", "AbortError");
describe("platform error normalization", () => {
it("maps an abort caused by interaction cancellation to request.cancelled", () => {
const error = mapTransportFailure(abortError(), { deadlineExpired: false });
expect(error).toMatchObject({
kind: "request.cancelled",
category: "transport",
retryability: "never",
});
});
it("maps an abort caused by the deadline to request.timeout", () => {
expect(mapTransportFailure(abortError(), { deadlineExpired: true }).kind).toBe(
"request.timeout",
);
expect(
mapTransportFailure(new DeadlineExceededError(10, 11), {
deadlineExpired: false,
}).kind,
).toBe("request.timeout");
});
it.each([
[new TypeError("Failed to fetch"), "network.unavailable"],
[new RequestBudgetExceededError(2), "traffic.budget-exceeded"],
[new ConcurrencyQueueFullError(0), "traffic.budget-exceeded"],
[new RequestFanoutExceededError(2, 1), "traffic.budget-exceeded"],
// `AbortSignal.timeout()` aborts with this reason; it is a timeout even
// when the caller's own deadline has not expired.
[new DOMException("signal timed out", "TimeoutError"), "request.timeout"],
[new JsonBudgetExceededError("too-large", "x"), "response.too-large"],
// `parseBoundedJson` wraps a `JSON.parse` failure in this error.
[new JsonBudgetExceededError("invalid-json", "x"), "response.invalid"],
[new SyntaxError("Unexpected token"), "response.invalid"],
["not even an error", "network.unavailable"],
] as const)("maps %s to %s", (error, kind) => {
expect(mapTransportFailure(error, { deadlineExpired: false }).kind).toBe(kind);
});
it("reads a JSON budget violation only as own data, never through an accessor", () => {
const violation = vi.fn(() => "invalid-json");
const lookalike = Object.defineProperties(new RangeError("x"), {
name: { value: "JsonBudgetExceededError" },
violation: { get: violation },
});
expect(mapTransportFailure(lookalike, { deadlineExpired: false }).kind).toBe(
"response.too-large",
);
expect(violation).not.toHaveBeenCalled();
});
it("keeps every platform error a valid, stable envelope", () => {
for (const error of Object.values(PLATFORM_ERRORS)) {
expect(isAppError(error)).toBe(true);
}
expect(Object.values(PLATFORM_ERRORS).map((error) => error.kind)).toEqual([
"network.unavailable",
"request.timeout",
"request.cancelled",
"response.too-large",
"response.invalid",
"traffic.budget-exceeded",
]);
});
});
describe("V3 outcome normalization at the adapter boundary", () => {
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
unknown,
unknown,
unknown
>;
it("classifies a traffic-budget rejection as traffic.budget-exceeded", async () => {
const transport = vi.fn<Transport>(networkFailure);
const execution = testExecutionContext({ maxPhysicalRequests: 1, maxRetries: 0 });
const executor = testExecutor(transport);
const context = { routeId: "TEST_ROUTE", scope: scopeSnapshot(), execution };
await executor.execute(TEST_QUERY, { limit: 1 }, context);
const rejected = await executor.execute(TEST_QUERY, { limit: 1 }, context);
expect(platformErrorForOutcome(rejected)?.kind).toBe("traffic.budget-exceeded");
});
it.each([
[{ kind: "CANCELLED", effect: "NOT_STARTED" }, "request.cancelled"],
[
{ kind: "TRANSPORT_FAILURE", failure: { kind: "TIMEOUT", retryable: false }, effect: "NOT_STARTED" },
"request.timeout",
],
[
{ kind: "TRANSPORT_FAILURE", failure: { kind: "NETWORK_FAILURE", retryable: false }, effect: "NOT_STARTED" },
"network.unavailable",
],
[
{ kind: "CONTRACT_VIOLATION", violation: { kind: "RESPONSE_TOO_LARGE", operation: "RESPONSE" }, effect: "NOT_APPLICABLE" },
"response.too-large",
],
[
{ kind: "CONTRACT_VIOLATION", violation: { kind: "JSON_INVALID", operation: "RESPONSE" }, effect: "NOT_APPLICABLE" },
"response.invalid",
],
] as const)("maps outcome %# to %s", (outcome, kind) => {
expect(platformErrorForOutcome(outcome)?.kind).toBe(kind);
});
it("leaves owner-interpreted outcomes to their owner", () => {
expect(
platformErrorForOutcome({ kind: "UNAUTHENTICATED", effect: "NOT_APPLICABLE" }),
).toBeNull();
expect(
platformErrorForOutcome({
kind: "CONTRACT_VIOLATION",
violation: { kind: "SCOPE_FENCED", operation: "RESPONSE" },
effect: "NOT_APPLICABLE",
}),
).toBeNull();
});
});