Files
clean-architecture-frontend…/tests/mocks/scenarios/catalog.ts
T
DongHyeonka 112c870fe3 fix(reference): 처리 중 409를 결과 불명으로 보고 같은 키를 유지한다 (0929/03-01)
문제
참조 기능의 생성 분류기가 모든 409를 NOT_APPLIED로 판정한다
(reference-feature-contract-contribution.ts:42-44). 결과 불명 쓰기를 같은
멱등 키로 다시 보냈을 때 첫 요청이 아직 처리 중이면 짝 백엔드 템플릿은
409 IDEMPOTENT_IN_FLIGHT를 준다. 그러면 코디네이터가 intent를 정리하고
conflict를 세우고(application-query.ts:584-589), 폼은 결과 불명 기록을
지운다(use-app-form.ts:227-230). 화면이 "충돌"로 바뀌고 저장 버튼이 다시
열려 다음 저장이 새 키로 나간다. 첫 요청이 끝나면 같은 리소스가 두 번
생긴다(키 [K, K, K']).

고른 방법
분류기가 409를 problem code로 나눈다. fixture가 선언한 충돌 code
(CREATE_NOT_APPLIED_CONFLICT_CODES, 지금은 MSW fixture가 내는 "CONFLICT"
하나)만 NOT_APPLIED다. IDEMPOTENT_IN_FLIGHT, code 없는 409, 모르는 code의
409는 MAYBE_APPLIED다. 결과 불명이 유지되므로 코디네이터가 intent를 들고
있고 다음 전송이 같은 키를 쓴다. 400·422 판정은 바꾸지 않았다.
시나리오 카탈로그에 in-flight-409를 더해 "처리 중 409 -> 결과 불명"과
"충돌 409 -> 적용 안 됨"(기존 conflict-409)을 둘 다 고정했다.

버린 대안
- IDEMPOTENT_IN_FLIGHT 하나만 MAYBE_APPLIED로 빼기: 모르는 409가 계속
  NOT_APPLIED다. 백엔드가 처리 중 code를 바꾸거나 다른 백엔드를 붙이면
  같은 결함이 조용히 돌아온다. "모르는 409는 안전한 쪽" 결정과 어긋난다.
- 플랫폼 방어(같은 intent의 재전송이 NOT_APPLIED를 받아도
  APPLIED_CONFIRMED 전까지 키 결합을 유지, 리뷰 03 5절 A의 (b)): 분류기가
  틀려도 막지만 application-query의 admission 수명 규칙을 바꾸는 구조
  변경이다. 이번 범위를 넘어 뺐다.
- 계약 문서의 409 IDEMPOTENCY_KEY_REUSED(같은 키·다른 지문)를 NOT_APPLIED
  목록에 넣기: 프론트는 canonical 입력이 같을 때만 같은 키를 쓴다. 이
  응답은 서버와 클라이언트의 지문 기준이 어긋났다는 뜻이고 같은 키의 앞선
  요청은 적용됐을 수 있다. NOT_APPLIED로 풀면 다음 저장이 새 키로 중복을
  만든다. 그래서 모르는 409와 같이 MAYBE_APPLIED로 둔다.

위험·한계
- 백엔드 계약(이 repo에서 끝낼 수 없음): backend-api-and-server-state-
  contract.md §6은 같은 키 동시 재전송을 "bounded IN_PROGRESS 결과"라고만
  적고 status·code를 정하지 않는다(:299-300). 409 + IDEMPOTENT_IN_FLIGHT로
  고정하고, 진짜 충돌을 뜻하는 409 code 목록을 계약에 적어야 한다. 짝
  백엔드 템플릿(01a8a2a, 읽기만 함)은 OperationalError.IDEMPOTENT_IN_FLIGHT
  (CONFLICT, 409, retryable=false)를 쓴다. 승인자: 템플릿 소유자, 백엔드
  템플릿 소유자.
- problem 형태: 짝 백엔드 web 어댑터는 실패를 problem+json이 아니라
  Envelope {success:false, error:{code,...}}로 보낸다(ErrorResponseFactory).
  참조 fixture는 최상위 code가 있는 problem 형태다. 그 Envelope가 오면
  referenceProblemSchema 검증이 실패해 MAYBE_APPLIED가 되므로 안전 쪽이지만
  code 분류는 닿지 않는다. 제품 계약 패키지가 code 위치를 정해야 한다.
- 화면 종류는 여전히 mapProblem이 409 전부를 CONFLICT로 만든다
  (reference-http-gateway.ts:38). 폼이 effect를 먼저 보므로 결과 불명이
  이기지만, 효과와 화면 종류가 두 함수에 나뉜 문제(03-04)는 그대로다.
  "처리 중" 전용 문구는 없고 일반 결과 불명 문구를 보인다.
- 다운스트림 tech-log 분류기는 4xx 전체를 NOT_APPLIED로 쓴다(지난 라운드
  확인). 동기화 때 같은 수정이 필요하다.
- 카탈로그 실행 수가 54 -> 57이 된다. 문서 세 곳의 "19개"와
  run-http-scenario-evidence.ts 출력 문구를 맞췄다.
- 초기 JS gzip +37 B(203,507 -> 203,544, 예산 204,800). 같은 build-frontend로
  두 번 빌드해 gzipSync로 쟀다. 예산은 바꾸지 않았다.

검증
- RED(수정 전): reference-production-vertical "keeps the key when the
  resend meets the first attempt still in flight" 실패, 키 [K, K, K'].
  분류 단위 테스트 3건 "expected 'NOT_APPLIED' to be 'MAYBE_APPLIED'"
  (IDEMPOTENT_IN_FLIGHT, 모르는 code, code 없음).
  카탈로그 CREATE_REFERENCE_RESOURCE::in-flight-409 불일치.
- GREEN: 같은 세 파일 23/23 통과.
- 회귀: run-vitest tests/features tests/component tests/contract
  tests/integration tests/unit(pnpm을 띄우는 security-followup-archive
  제외) 233 files / 2817 tests 통과. tests/runtime-schema 56 통과.
  tsc app/test/node rc=0. 바꾼 파일 eslint rc=0. check-adapter-inventory
  PASS. verify-documentation-readiness PASS_SCOPED.
- 미실행: check:architecture(pnpm 필요). depcruise 직접 실행은 TS 7을
  읽지 못해 0 modules라 사실상 미검증. src 변경은 import를 더하지 않는다.
  check:ci 미실행.

Refs: docs/reviews/2026-11-01-maturity-review/03-adapters-http-state.md
2026-11-01 19:09:47 +09:00

452 lines
13 KiB
TypeScript

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";
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];
export const HTTP_SCENARIO_OPERATION_IDS = Object.freeze([
"LIST_REFERENCE_RESOURCES",
"GET_REFERENCE_RESOURCE",
"CREATE_REFERENCE_RESOURCE",
] as const);
export type HttpScenarioOperationId =
(typeof HTTP_SCENARIO_OPERATION_IDS)[number];
export type HttpScenarioExecutionId =
`${HttpScenarioOperationId}::${HttpScenarioId}`;
export type HttpScenarioExpectation = Readonly<{
executionId: HttpScenarioExecutionId;
operationId: HttpScenarioOperationId;
scenarioId: HttpScenarioId;
expected: HttpScenarioAssertionGroups;
testDeadlineOverrideMs: number | null;
}>;
const encoder = new TextEncoder();
const jsonBytes = (value: unknown) => encoder.encode(JSON.stringify(value)).byteLength;
const RESOURCE = Object.freeze({
id: "reference-1",
name: "Reference",
createdAt: "2026-07-26T00:00:00.000Z",
});
const CREATED = Object.freeze({
id: "reference-created",
name: "Created",
createdAt: "2026-07-26T00:00:00.000Z",
});
function operationFacts(operationId: HttpScenarioOperationId) {
const command = operationId === "CREATE_REFERENCE_RESOURCE";
return Object.freeze({
command,
ceiling:
operationId === "LIST_REFERENCE_RESOURCES" ? 262_144 : 32_768,
payload:
operationId === "LIST_REFERENCE_RESOURCES"
? [RESOURCE]
: operationId === "GET_REFERENCE_RESOURCE"
? RESOURCE
: CREATED,
});
}
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: HttpScenarioOperationId,
scenarioId: HttpScenarioId,
): HttpScenarioExpectation {
const { command, ceiling, payload } = operationFacts(operationId);
let statuses: AttemptStatus[] = [200];
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 === "LIST_REFERENCE_RESOURCES") {
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, 200];
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({
LIST_REFERENCE_RESOURCES: HTTP_SCENARIO_IDS,
GET_REFERENCE_RESOURCE: Object.freeze(
HTTP_SCENARIO_IDS.filter((scenario) => scenario !== "empty"),
),
CREATE_REFERENCE_RESOURCE: Object.freeze(
HTTP_SCENARIO_IDS.filter(
(scenario) => scenario !== "empty" && scenario !== "aborted",
),
),
} satisfies Readonly<
Record<HttpScenarioOperationId, 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<HttpScenarioOperationId, readonly HttpScenarioId[]>
>,
);
export function assertOperationScenario(
operationId: HttpScenarioOperationId,
scenario: HttpScenarioId,
) {
if (!OPERATION_SCENARIO_CATALOG[operationId].includes(scenario)) {
throw new Error(`Scenario ${scenario} is not declared for ${operationId}`);
}
return scenario;
}