Files
clean-architecture-frontend…/tests/mocks/scenarios/catalog.ts
T
DongHyeonka 7db32e1343 fix(http): V3 실행기가 짝 백엔드 Envelope를 operation 단위로 읽는다
문제
create:feature가 만든 기능과 참조 기능이 쓰는 V3 실행기
(http-execution-v3.ts, feature-http-binding.ts)는 성공 본문을 DTO로,
실패 본문을 problem details(최상위 code)로 바로 검증한다. 짝 백엔드는
모든 JSON 응답을 Envelope {success, data|error, meta}로 보내고 null 필드는
키째 뺀다(백엔드 docs/web/http-contract.md 1절). 그래서 생성한 기능은 짝
백엔드의 성공을 SCHEMA_MISMATCH로, 실패를 PROBLEM_SCHEMA_INVALID(쓰기는
결과 불명)로 읽는다. 백엔드 맞추기(969979d~64e98ee)는 V2 클라이언트에만
들어갔다.

고른 방법: (가) V3 실행기에 operation 단위 Envelope 읽기
- V3 descriptor에 선택 필드 responseEnvelope("NONE" | "ENVELOPE_V1")를
  둔다. 조립은 이 키를 허용하고 모르는 값을 거부한다. 값이 없으면 지금과
  같다.
- ENVELOPE_V1이면 실행기가 바이트 상한·구조 예산을 Envelope 전체에 건 뒤
  프레임을 확인한다. outputValidator는 data(키가 없으면 null),
  problemValidator는 error를 받는다. 성공 status에 Envelope가 아닌 본문은
  새 위반 ENVELOPE_MISMATCH다. 실패 Envelope의 바이트 상한은
  min(64 KiB, responseByteLimit)이다.
- V2 client.ts의 멱등성 거절 표·필드 검증 판정·gateway status 규칙을
  backend-envelope.ts로 옮기고 V2, V3 실행기, feature binding이 함께
  읽는다. 실행기는 그 표의 판정(422·400 거절, 필드 목록 400은 적용 안 됨,
  409 IDEMPOTENT_IN_FLIGHT·503 IDEMPOTENCY_UNAVAILABLE은 결과 불명)을
  classifyProblem보다 먼저 쓴다. binding은 mapProblem이 답하지 않으면 V2와
  같은 kind·code·validationIssues로 읽는다. V2 출력은 바뀌지 않았다.
- create:feature 뼈대: contribution이 ENVELOPE_V1을 선언하고 problem
  스키마가 Envelope error(code 필수)다. 백엔드 본문을 그대로 적은
  <base>-http-gateway.test.ts를 생성한다.
- MSW createHttpScenarioHandler는 descriptor가 ENVELOPE_V1이면 Envelope로
  답한다.

버린 대안
- provider 단위(실행기 전체): V3 실행기는 baseUrl 하나라 앱 전체가 바뀐다.
  참조 기능·테스트 계약의 problem details fixture가 모두 깨지고 한 앱이 두
  모양의 API를 쓸 수 없다.
- (나) 백엔드 problem+json·DTO 모드: 백엔드 소유자 결정 2(JSON은 모두
  Envelope)와 반대이고 백엔드가 두 모양을 계속 유지해야 한다.
- (다) 기능 스키마가 Envelope를 감쌈: 기능마다 null 생략·success 판별·
  멱등성 판정을 다시 쓰고, V2 행(data 스키마)과 V3 스키마 ID가 갈라진다.

위험·한계
- HttpContractViolationKind에 ENVELOPE_MISMATCH가 더해졌다. default 없는
  exhaustive switch는 분기를 더해야 한다.
- 실행기가 ENVELOPE_V1 operation의 위 판정을 classifyProblem보다 먼저
  정한다. 패키지가 409 IDEMPOTENT_IN_FLIGHT를 적용 안 됨이라 해도 결과
  불명이다.
- V2와 남은 차이: 64 KiB를 넘는 실패 Envelope는 V3만 읽지 않는다. 보낸
  KEYED 요청의 503은 V2만 같은 키로 자동 재시도한다(판정은 같다). 구조
  예산은 V3에만 있다.
- 참조 기능은 그대로 DTO·problem details다. tests/e2e/accessibility.spec.ts는
  모든 API에 []로 답하므로 생성한 기능 라우트는 오류 화면이 검사된다(e2e는
  돌리지 않았다).
- 초기 JS 202,770 → 203,321 B(+551 B, 예산 204,800 B).

검증
- RED: tests/integration/http-execution-v3-envelope.test.ts 19건 중 17건
  실패(성공 → SCHEMA_MISMATCH, 실패 → PROBLEM_SCHEMA_INVALID·MAYBE_APPLIED,
  조립 → unexpected key: responseEnvelope). 크기 2건은 처음부터 통과(동작
  고정).
- GREEN: 같은 파일 25건 통과. 같은 응답을 V2와 V3에 보내 kind·code·
  httpStatus·effect·retryAfterMs·validationIssues가 같음을 7가지 응답으로
  비교한다.
- check:types, lint, check:architecture, check:adapter-inventory,
  check:registries, check:diagnostics, check:i18n, check:ci 통과.
  test:unit 2,604, test:component 244, test:integration 200 통과.
  tests/features·tests/contract 124건 통과.
  test:feature-scaffold 16개 검사 통과(생성한 gateway 테스트 5건,
  Envelope로 답하는 목록 화면 테스트 3건 포함).
  test:sample-removal 23개 검사 통과.
  check:bundle 통과(203,321 / 204,800 B).

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.3, 14.6
2026-11-03 20:10:51 +09:00

516 lines
16 KiB
TypeScript

import type { JsonBodyType } from "msw";
import type {
AttemptStatus,
BodyDisposition,
HttpScenarioAssertionGroups,
RetryReason,
} from "../../../scripts/lib/http-scenario-evidence.ts";
export type {
AttemptStatus,
BodyDisposition,
HttpScenarioAssertionGroups,
RetryReason,
} from "../../../scripts/lib/http-scenario-evidence.ts";
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
import {
TEST_CLASSIFIED_CREATE_HTTP_CONTRACT,
TEST_DETAIL_HTTP_CONTRACT,
TEST_LIST_HTTP_CONTRACT,
} from "../../helpers/external-contract-fixture.ts";
export const HTTP_SCENARIO_RECEIPT_SCHEMA_VERSION = 1 as const;
export const HTTP_SCENARIO_IDS = Object.freeze([
"success",
"empty",
"slow",
"network-error",
"timeout",
"aborted",
"content-type-mismatch",
"malformed-json",
"envelope-mismatch",
"schema-mismatch",
"response-too-large",
"unauthenticated-401",
"forbidden-403",
"not-found-404",
"conflict-409",
"in-flight-409",
"validation-422",
"rate-limited-429",
"server-retry-success",
"server-terminal-503",
] as const);
export type HttpScenarioId = (typeof HTTP_SCENARIO_IDS)[number];
/**
* 0929/10-02. The catalog runs on the test contracts, not the removable sample
* feature, so removing the sample keeps the HTTP scenario evidence
* (FE-GATE-007). The facts an expectation depends on (command or query, body
* ceiling, success status) are read from the contract itself.
*/
export const HTTP_SCENARIO_CONTRACTS = Object.freeze({
TEST_LIST_ENTITIES: TEST_LIST_HTTP_CONTRACT,
TEST_GET_ENTITY: TEST_DETAIL_HTTP_CONTRACT,
TEST_CREATE_ENTITY: TEST_CLASSIFIED_CREATE_HTTP_CONTRACT,
});
/**
* 16-02. Any installed operation, not only the catalog's: a feature test
* answers its own operation with `createHttpScenarioHandler`
* (`tests/mocks/handlers/http-scenarios.ts`) without editing this file.
*/
export type HttpScenarioOperationId = string;
/**
* The part of an installed (V3) descriptor a scenario reads. Every
* `InstalledHttpContract` fits it, whatever its input and output types.
*/
export type HttpScenarioContract = Readonly<{
contract: Readonly<
Pick<
InstalledHttpContract<unknown, unknown, unknown>["contract"],
| "operationId"
| "method"
| "pathTemplate"
| "acceptedStatuses"
| "responseEnvelope"
> & { commandEffect: unknown }
>;
frontend: Readonly<{ responseByteLimit: number }>;
}>;
/** The operations this catalog's evidence (FE-GATE-007) is recorded for. */
type CatalogOperationId = keyof typeof HTTP_SCENARIO_CONTRACTS;
export const HTTP_SCENARIO_OPERATION_IDS = Object.freeze(
Object.keys(HTTP_SCENARIO_CONTRACTS) as CatalogOperationId[],
);
for (const operationId of HTTP_SCENARIO_OPERATION_IDS) {
const declared = HTTP_SCENARIO_CONTRACTS[operationId].contract.operationId;
if (declared !== operationId) {
throw new Error(`Scenario operation ${operationId} names contract ${declared}`);
}
}
export type HttpScenarioExecutionId =
`${CatalogOperationId}::${HttpScenarioId}`;
export type HttpScenarioExpectation = Readonly<{
executionId: HttpScenarioExecutionId;
operationId: CatalogOperationId;
scenarioId: HttpScenarioId;
expected: HttpScenarioAssertionGroups;
testDeadlineOverrideMs: number | null;
}>;
const encoder = new TextEncoder();
const jsonBytes = (value: unknown) => encoder.encode(JSON.stringify(value)).byteLength;
export const HTTP_SCENARIO_ENTITY = Object.freeze({
id: "entity-1",
name: "Entity",
});
export const HTTP_SCENARIO_CREATED_ENTITY = Object.freeze({
id: "entity-created",
name: "Created",
});
/** The success body each catalog operation answers with. */
export const HTTP_SCENARIO_PAYLOADS: Readonly<
Record<CatalogOperationId, JsonBodyType>
> = Object.freeze({
TEST_LIST_ENTITIES: Object.freeze([HTTP_SCENARIO_ENTITY]),
TEST_GET_ENTITY: HTTP_SCENARIO_ENTITY,
TEST_CREATE_ENTITY: HTTP_SCENARIO_CREATED_ENTITY,
});
/** What a scenario's answer depends on, read from the installed descriptor. */
export function httpScenarioOperationFacts(installed: HttpScenarioContract) {
return Object.freeze({
command: installed.contract.commandEffect !== null,
ceiling: installed.frontend.responseByteLimit,
successStatus: installed.contract.acceptedStatuses[0]!,
enveloped: installed.contract.responseEnvelope === "ENVELOPE_V1",
});
}
function problem(status: number, code: string) {
return {
type: `https://api.test/problems/${code.toLowerCase()}`,
title: code,
status,
code,
};
}
function attemptBody(
disposition: BodyDisposition,
pulledBytes: number,
ceiling: number,
) {
return Object.freeze({ disposition, pulledBytes, ceiling });
}
function expectationFor(
operationId: CatalogOperationId,
scenarioId: HttpScenarioId,
): HttpScenarioExpectation {
const { command, ceiling, successStatus } = httpScenarioOperationFacts(
HTTP_SCENARIO_CONTRACTS[operationId],
);
const payload = HTTP_SCENARIO_PAYLOADS[operationId];
let statuses: AttemptStatus[] = [successStatus];
let kind = "SUCCESS";
let detail: string | null = null;
let outcomeEffect = command ? "APPLIED_CONFIRMED" : "NOT_APPLICABLE";
let observer = outcomeEffect;
let retryReasons: RetryReason[] = [];
let media: (string | null)[] = ["application/json"];
let bodies = [attemptBody("FULLY_READ_WITHIN_BOUND", jsonBytes(payload), ceiling)];
let scopeEnd: "CURRENT" | "STALE" = "CURRENT";
let scopeSignal: "ACTIVE" | "ABORTED" = "ACTIVE";
let cancellationOwner: "NONE" | "CALLER" | "SCOPE_FENCE" | "DEADLINE" =
"NONE";
let testDeadlineOverrideMs: number | null = null;
switch (scenarioId) {
case "success":
case "slow":
break;
case "empty":
bodies = [attemptBody("FULLY_READ_WITHIN_BOUND", jsonBytes([]), ceiling)];
break;
case "network-error": {
const attemptCount = command ? 1 : 3;
statuses = Array.from({ length: attemptCount }, () => "NETWORK_REJECTION");
kind = "TRANSPORT_FAILURE";
detail = "NETWORK_FAILURE";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_STARTED";
observer = "NETWORK_FAILURE";
retryReasons = command ? [] : ["NETWORK_FAILURE", "NETWORK_FAILURE"];
media = Array.from({ length: attemptCount }, () => null);
bodies = Array.from({ length: attemptCount }, () =>
attemptBody("NO_RESPONSE", 0, 0),
);
break;
}
case "timeout":
statuses = ["PENDING_ABORT"];
kind = "TRANSPORT_FAILURE";
detail = "TIMEOUT";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_STARTED";
observer = "TIMEOUT";
media = [null];
bodies = [attemptBody("NO_RESPONSE", 0, 0)];
cancellationOwner = "DEADLINE";
testDeadlineOverrideMs = 500;
break;
case "aborted":
statuses = ["PENDING_ABORT"];
media = [null];
bodies = [attemptBody("NO_RESPONSE", 0, 0)];
if (operationId === "TEST_LIST_ENTITIES") {
kind = "CANCELLED";
outcomeEffect = "NOT_STARTED";
observer = "CANCELLED";
cancellationOwner = "CALLER";
} else {
scopeSignal = "ABORTED";
kind = "TRANSPORT_FAILURE";
detail = "ABORTED_BY_SCOPE";
outcomeEffect = "NOT_STARTED";
observer = "SCOPE_FENCED";
scopeEnd = "STALE";
cancellationOwner = "SCOPE_FENCE";
}
break;
case "content-type-mismatch":
kind = "CONTRACT_VIOLATION";
detail = "CONTENT_TYPE_MISMATCH";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
observer = "CONTRACT_VIOLATION";
media = ["text/html"];
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
encoder.encode("<html>not json</html>").byteLength,
ceiling,
),
];
break;
case "malformed-json":
kind = "CONTRACT_VIOLATION";
detail = "JSON_INVALID";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
observer = "CONTRACT_VIOLATION";
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
encoder.encode("{invalid").byteLength,
ceiling,
),
];
break;
case "envelope-mismatch":
kind = "CONTRACT_VIOLATION";
detail = "SUCCESS_SCHEMA_INVALID";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
observer = "CONTRACT_VIOLATION";
bodies = [
attemptBody("FULLY_READ_WITHIN_BOUND", jsonBytes({ data: payload }), ceiling),
];
break;
case "schema-mismatch":
kind = "CONTRACT_VIOLATION";
detail = "SUCCESS_SCHEMA_INVALID";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
observer = "CONTRACT_VIOLATION";
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
jsonBytes({ unexpected: true }),
ceiling,
),
];
break;
case "response-too-large":
kind = "CONTRACT_VIOLATION";
detail = "RESPONSE_TOO_LARGE";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
observer = "RESPONSE_TOO_LARGE";
bodies = [attemptBody("REJECTED_LIMIT", 0, ceiling)];
break;
case "unauthenticated-401":
statuses = [401];
kind = "UNAUTHENTICATED";
outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE";
observer = "UNAUTHENTICATED";
bodies = [attemptBody("CANCELLED_WITHOUT_READ", 0, 0)];
break;
case "forbidden-403":
statuses = [403];
kind = "FORBIDDEN";
outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE";
observer = "FORBIDDEN";
bodies = [attemptBody("CANCELLED_WITHOUT_READ", 0, 0)];
break;
case "not-found-404":
statuses = [404];
kind = "PROBLEM";
detail = "404";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLIED";
observer = command ? "MAYBE_APPLIED" : "NOT_STARTED";
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
jsonBytes(problem(404, "NOT_FOUND")),
65_536,
),
];
break;
case "conflict-409":
statuses = [409];
kind = "PROBLEM";
detail = "409";
outcomeEffect = "NOT_APPLIED";
observer = command ? "NOT_APPLIED" : "NOT_STARTED";
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
jsonBytes(problem(409, "CONFLICT")),
65_536,
),
];
break;
case "in-flight-409":
// 0929/03-01. The same key is still running: the command stays unknown.
statuses = [409];
kind = "PROBLEM";
detail = "409";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLIED";
observer = command ? "MAYBE_APPLIED" : "NOT_STARTED";
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
jsonBytes(problem(409, "IDEMPOTENT_IN_FLIGHT")),
65_536,
),
];
break;
case "validation-422":
statuses = [422];
kind = "PROBLEM";
detail = "422";
outcomeEffect = "NOT_APPLIED";
observer = command ? "NOT_APPLIED" : "NOT_STARTED";
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
jsonBytes(problem(422, "VALIDATION_REJECTED")),
65_536,
),
];
break;
case "rate-limited-429": {
const attemptCount = command ? 1 : 3;
statuses = Array.from({ length: attemptCount }, () => 429);
kind = "RATE_LIMITED";
outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE";
observer = "RATE_LIMITED";
retryReasons = command ? [] : ["HTTP_429", "HTTP_429"];
media = Array.from({ length: attemptCount }, () => "application/json");
bodies = Array.from({ length: attemptCount }, () =>
attemptBody("CANCELLED_WITHOUT_READ", 0, 0),
);
break;
}
case "server-retry-success":
if (command) {
statuses = [503];
kind = "PROBLEM";
detail = "503";
outcomeEffect = "MAYBE_APPLIED";
observer = "MAYBE_APPLIED";
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
jsonBytes(problem(503, "SERVER_FAILURE")),
65_536,
),
];
} else {
statuses = [503, successStatus];
retryReasons = ["HTTP_503"];
media = ["application/json", "application/json"];
bodies = [
attemptBody(
"FULLY_READ_WITHIN_BOUND",
jsonBytes(problem(503, "SERVER_FAILURE")),
65_536,
),
attemptBody("FULLY_READ_WITHIN_BOUND", jsonBytes(payload), ceiling),
];
}
break;
case "server-terminal-503": {
const attemptCount = command ? 1 : 3;
statuses = Array.from({ length: attemptCount }, () => 503);
kind = "PROBLEM";
detail = "503";
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLIED";
observer = command ? "MAYBE_APPLIED" : "NOT_STARTED";
retryReasons = command ? [] : ["HTTP_503", "HTTP_503"];
media = Array.from({ length: attemptCount }, () => "application/json");
bodies = Array.from({ length: attemptCount }, () =>
attemptBody(
"FULLY_READ_WITHIN_BOUND",
jsonBytes(problem(503, "SERVER_FAILURE")),
65_536,
),
);
break;
}
}
const executionId = `${operationId}::${scenarioId}` as const;
return Object.freeze({
executionId,
operationId,
scenarioId,
expected: Object.freeze({
status: Object.freeze({
attempts: Object.freeze(statuses),
final: statuses.at(-1)!,
}),
outcome: Object.freeze({ kind, detail }),
effect: Object.freeze({ outcome: outcomeEffect, observer }),
retry: Object.freeze({
count: retryReasons.length,
reasons: Object.freeze(retryReasons),
}),
fetch: Object.freeze({
count: statuses.length,
observerAttempts: statuses.length,
agrees: true,
}),
media: Object.freeze({
attempts: Object.freeze(media),
final: media.at(-1) ?? null,
}),
body: Object.freeze({ attempts: Object.freeze(bodies) }),
scope: Object.freeze({
start: "CURRENT" as const,
end: scopeEnd,
signal: scopeSignal,
cancellationOwner,
}),
}),
testDeadlineOverrideMs,
});
}
const OPERATION_SCENARIOS = Object.freeze({
TEST_LIST_ENTITIES: HTTP_SCENARIO_IDS,
TEST_GET_ENTITY: Object.freeze(
HTTP_SCENARIO_IDS.filter((scenario) => scenario !== "empty"),
),
TEST_CREATE_ENTITY: Object.freeze(
HTTP_SCENARIO_IDS.filter(
(scenario) => scenario !== "empty" && scenario !== "aborted",
),
),
} satisfies Readonly<
Record<CatalogOperationId, readonly HttpScenarioId[]>
>);
export const HTTP_SCENARIO_EXPECTATIONS = Object.freeze(
HTTP_SCENARIO_OPERATION_IDS.flatMap((operationId) =>
OPERATION_SCENARIOS[operationId].map((scenarioId) =>
expectationFor(operationId, scenarioId),
),
),
);
export const HTTP_SCENARIO_EXECUTION_IDS = Object.freeze(
HTTP_SCENARIO_EXPECTATIONS.map((expectation) => expectation.executionId),
);
export const OPERATION_SCENARIO_CATALOG = Object.freeze(
Object.fromEntries(
HTTP_SCENARIO_OPERATION_IDS.map((operationId) => [
operationId,
Object.freeze(
HTTP_SCENARIO_EXPECTATIONS.filter(
(expectation) => expectation.operationId === operationId,
).map((expectation) => expectation.scenarioId),
),
]),
) as Readonly<
Record<CatalogOperationId, readonly HttpScenarioId[]>
>,
);
export function assertOperationScenario(
operationId: HttpScenarioOperationId,
scenario: HttpScenarioId,
) {
const catalog: Readonly<Partial<Record<string, readonly HttpScenarioId[]>>> =
OPERATION_SCENARIO_CATALOG;
const declared = catalog[operationId];
if (declared === undefined) {
throw new Error(
`${operationId} is not a catalog operation; answer it with createHttpScenarioHandler`,
);
}
if (!declared.includes(scenario)) {
throw new Error(`Scenario ${scenario} is not declared for ${operationId}`);
}
return scenario;
}