문제
참조 기능의 생성 분류기가 모든 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
420 lines
14 KiB
TypeScript
420 lines
14 KiB
TypeScript
import { mkdir, rm } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
|
|
import { readBoundedBytes } from "../../src/adapters/http/bounded-body-reader.ts";
|
|
import {
|
|
createContractHttpExecutor,
|
|
type HttpExecutionObservation,
|
|
} from "../../src/adapters/http/http-execution-v3.ts";
|
|
import {
|
|
type InstalledHttpContract,
|
|
} from "../../src/contracts/external-contract-runtime.ts";
|
|
import type { CacheScopeSnapshot } from "../../src/contracts/server-state-scope.ts";
|
|
import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts";
|
|
import {
|
|
computeHttpScenarioCatalogDigest,
|
|
httpScenarioReceiptSchema,
|
|
type AttemptStatus,
|
|
type BodyDisposition,
|
|
type HttpScenarioAssertionGroups,
|
|
type RetryReason,
|
|
} from "../../scripts/lib/http-scenario-evidence.ts";
|
|
import { writeValidatedJsonArtifact } from "../../scripts/lib/validated-json-artifact.ts";
|
|
import { createReferenceScenarioHandlers } from "../mocks/handlers/reference-resources.ts";
|
|
import { createStrictMockServer } from "../mocks/server.ts";
|
|
import {
|
|
HTTP_SCENARIO_EXECUTION_IDS,
|
|
HTTP_SCENARIO_EXPECTATIONS,
|
|
HTTP_SCENARIO_RECEIPT_SCHEMA_VERSION,
|
|
OPERATION_SCENARIO_CATALOG,
|
|
type HttpScenarioExpectation,
|
|
type HttpScenarioOperationId,
|
|
} from "../mocks/scenarios/catalog.ts";
|
|
|
|
/** The reference gateway owns these low-cardinality route identities. */
|
|
function routeIdFor(operationId: HttpScenarioOperationId): string {
|
|
return operationId === "GET_REFERENCE_RESOURCE"
|
|
? "REFERENCE_RESOURCE_DETAIL"
|
|
: "REFERENCE_RESOURCE_LIST";
|
|
}
|
|
|
|
const RECEIPT_PATH = path.resolve(
|
|
"artifacts/tests/http-scenario-executions.json",
|
|
);
|
|
const mockApi = createStrictMockServer();
|
|
|
|
beforeAll(mockApi.listen);
|
|
afterAll(mockApi.close);
|
|
|
|
type AttemptTrace = {
|
|
status: AttemptStatus;
|
|
media: string | null;
|
|
pulledBytes: number;
|
|
appliedCeiling: number | null;
|
|
completed: boolean;
|
|
cancelled: boolean;
|
|
};
|
|
|
|
function operationFor(operationId: HttpScenarioOperationId) {
|
|
const operation = REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION.http.find(
|
|
(candidate) => candidate.contract.operationId === operationId,
|
|
);
|
|
if (!operation) throw new Error(`Missing operation fixture: ${operationId}`);
|
|
return operation as InstalledHttpContract<unknown, unknown, unknown>;
|
|
}
|
|
|
|
function inputFor(operationId: HttpScenarioOperationId): unknown {
|
|
if (operationId === "LIST_REFERENCE_RESOURCES") return { limit: 20 };
|
|
if (operationId === "GET_REFERENCE_RESOURCE") {
|
|
return { resourceId: "reference-1" };
|
|
}
|
|
return { name: "Created" };
|
|
}
|
|
|
|
function normalizeMedia(response: Response): string | null {
|
|
const value = response.headers.get("content-type");
|
|
return value?.split(";", 1)[0]?.trim().toLowerCase() || null;
|
|
}
|
|
|
|
function tracingFetcher(attempts: AttemptTrace[]): typeof fetch {
|
|
return async (input, init) => {
|
|
const trace: AttemptTrace = {
|
|
status: "PENDING_ABORT",
|
|
media: null,
|
|
pulledBytes: 0,
|
|
appliedCeiling: null,
|
|
completed: false,
|
|
cancelled: false,
|
|
};
|
|
attempts.push(trace);
|
|
let response: Response;
|
|
try {
|
|
response = await fetch(input, init);
|
|
} catch (error) {
|
|
trace.status = init?.signal?.aborted
|
|
? "PENDING_ABORT"
|
|
: "NETWORK_REJECTION";
|
|
throw error;
|
|
}
|
|
trace.status = response.status;
|
|
trace.media = normalizeMedia(response);
|
|
if (!response.body) return response;
|
|
|
|
const reader = response.body.getReader();
|
|
const proxy = new ReadableStream<Uint8Array>(
|
|
{
|
|
async pull(controller) {
|
|
try {
|
|
const chunk = await reader.read();
|
|
if (chunk.done) {
|
|
trace.completed = true;
|
|
controller.close();
|
|
return;
|
|
}
|
|
trace.pulledBytes += chunk.value.byteLength;
|
|
controller.enqueue(chunk.value);
|
|
} catch (error) {
|
|
controller.error(error);
|
|
}
|
|
},
|
|
cancel(reason) {
|
|
trace.cancelled = true;
|
|
// MSW-transferred oversized bodies leave the original cancel promise
|
|
// permanently pending. Record and request cancellation without making
|
|
// the proxy response less responsive than the real executor contract.
|
|
void reader.cancel(reason).catch(() => {});
|
|
},
|
|
},
|
|
{ highWaterMark: 0 },
|
|
);
|
|
return new Response(proxy, {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
headers: response.headers,
|
|
});
|
|
};
|
|
}
|
|
|
|
function outcomeDetail(outcome: Readonly<Record<string, unknown>>): string | null {
|
|
if (outcome.kind === "CONTRACT_VIOLATION") {
|
|
return String((outcome.violation as Readonly<{ kind: string }>).kind);
|
|
}
|
|
if (outcome.kind === "TRANSPORT_FAILURE") {
|
|
return String((outcome.failure as Readonly<{ kind: string }>).kind);
|
|
}
|
|
if (outcome.kind === "PROBLEM") {
|
|
return String((outcome.metadata as Readonly<{ status: number }>).status);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function retryReason(status: AttemptStatus): RetryReason {
|
|
if (status === "NETWORK_REJECTION") return "NETWORK_FAILURE";
|
|
if (status === 429) return "HTTP_429";
|
|
if (status === 503) return "HTTP_503";
|
|
throw new Error(`Sleep followed a non-retryable attempt: ${String(status)}`);
|
|
}
|
|
|
|
function bodyDisposition(
|
|
trace: AttemptTrace,
|
|
outcome: Readonly<Record<string, unknown>>,
|
|
): BodyDisposition {
|
|
if (trace.status === "NETWORK_REJECTION" || trace.status === "PENDING_ABORT") {
|
|
return "NO_RESPONSE";
|
|
}
|
|
if (
|
|
outcome.kind === "CONTRACT_VIOLATION" &&
|
|
outcomeDetail(outcome) === "RESPONSE_TOO_LARGE" &&
|
|
trace.cancelled
|
|
) {
|
|
return "REJECTED_LIMIT";
|
|
}
|
|
if (trace.completed) return "FULLY_READ_WITHIN_BOUND";
|
|
if (trace.cancelled) return "CANCELLED_WITHOUT_READ";
|
|
throw new Error(`Response body was neither consumed nor cancelled: ${trace.status}`);
|
|
}
|
|
|
|
async function waitForHandler(
|
|
ready: Promise<void>,
|
|
executionId: string,
|
|
): Promise<void> {
|
|
let watchdog: ReturnType<typeof setTimeout> | undefined;
|
|
try {
|
|
await Promise.race([
|
|
ready,
|
|
new Promise<never>((_resolve, reject) => {
|
|
watchdog = setTimeout(
|
|
() => reject(new Error(`Handler readiness timed out: ${executionId}`)),
|
|
2_000,
|
|
);
|
|
}),
|
|
]);
|
|
} finally {
|
|
if (watchdog !== undefined) clearTimeout(watchdog);
|
|
}
|
|
}
|
|
|
|
async function executeScenario(
|
|
entry: HttpScenarioExpectation,
|
|
): Promise<HttpScenarioAssertionGroups> {
|
|
const physicalAttempts: AttemptTrace[] = [];
|
|
const sleeps: RetryReason[] = [];
|
|
const observations: HttpExecutionObservation[] = [];
|
|
const caller = new AbortController();
|
|
const scopeLifetime = new AbortController();
|
|
let scopeCurrent = true;
|
|
let handlerReady!: () => void;
|
|
const ready = new Promise<void>((resolve) => {
|
|
handlerReady = resolve;
|
|
});
|
|
const scope: CacheScopeSnapshot = Object.freeze({
|
|
generation: 1,
|
|
fingerprint: "scenario-scope-1",
|
|
identities: Object.freeze({}) as CacheScopeSnapshot["identities"],
|
|
signal: scopeLifetime.signal,
|
|
isCurrent: () => scopeCurrent,
|
|
});
|
|
const baseOperation = operationFor(entry.operationId);
|
|
const operation =
|
|
entry.testDeadlineOverrideMs === null
|
|
? baseOperation
|
|
: Object.freeze({
|
|
...baseOperation,
|
|
frontend: Object.freeze({
|
|
...baseOperation.frontend,
|
|
totalDeadlineMs: entry.testDeadlineOverrideMs,
|
|
}),
|
|
});
|
|
const fetcher = tracingFetcher(physicalAttempts);
|
|
const executor = createContractHttpExecutor({
|
|
baseUrl: "https://api.test",
|
|
maxRetryAttempts: 2,
|
|
// The reference contribution declares REFERENCE_EXTERNAL_BEARER, so the
|
|
// credential owner must supply the required proof header before dispatch.
|
|
attachCredentials: () => ({
|
|
kind: "READY",
|
|
headers: { authorization: "Bearer scenario-token" },
|
|
}),
|
|
fetcher,
|
|
random: () => 0,
|
|
readBoundedResponseBytes: async (response, maximumBytes) => {
|
|
const trace = physicalAttempts.at(-1);
|
|
if (!trace) throw new Error("Body reader ran before a physical attempt");
|
|
if (trace.appliedCeiling !== null) {
|
|
throw new Error("Body reader ran more than once for one attempt");
|
|
}
|
|
trace.appliedCeiling = maximumBytes;
|
|
return readBoundedBytes(response, maximumBytes);
|
|
},
|
|
sleep: async () => {
|
|
const prior = physicalAttempts.at(-1);
|
|
if (!prior) throw new Error("Retry sleep occurred before an attempt");
|
|
sleeps.push(retryReason(prior.status));
|
|
},
|
|
observe: (observation) => observations.push(observation),
|
|
});
|
|
|
|
mockApi.server.use(
|
|
...createReferenceScenarioHandlers({
|
|
scenarios: { [entry.operationId]: entry.scenarioId },
|
|
onAttempt(attempt) {
|
|
if (
|
|
attempt.operationId === entry.operationId &&
|
|
attempt.scenarioId === entry.scenarioId
|
|
) {
|
|
handlerReady();
|
|
}
|
|
},
|
|
}),
|
|
);
|
|
|
|
try {
|
|
const execution = executor.execute(operation, inputFor(entry.operationId), {
|
|
routeId: routeIdFor(entry.operationId),
|
|
scope,
|
|
signal: caller.signal,
|
|
...(entry.operationId === "CREATE_REFERENCE_RESOURCE"
|
|
? {
|
|
intent: Object.freeze({
|
|
intentId: `intent-${entry.scenarioId}`,
|
|
operationId: entry.operationId,
|
|
canonicalInputIdentity: "scenario-input",
|
|
idempotencyKey: `scenario-${entry.scenarioId}`,
|
|
createdAtMonotonicMs: 1,
|
|
}),
|
|
}
|
|
: {}),
|
|
});
|
|
|
|
if (entry.scenarioId === "timeout" || entry.scenarioId === "aborted") {
|
|
await waitForHandler(ready, entry.executionId);
|
|
if (entry.scenarioId === "aborted") {
|
|
if (entry.operationId === "LIST_REFERENCE_RESOURCES") {
|
|
caller.abort();
|
|
} else {
|
|
scopeCurrent = false;
|
|
scopeLifetime.abort();
|
|
}
|
|
}
|
|
}
|
|
const outcome = (await execution) as unknown as Readonly<Record<string, unknown>>;
|
|
expect(observations, `${entry.executionId} observer count`).toHaveLength(1);
|
|
const observation = observations[0]!;
|
|
const observedSignal = scopeLifetime.signal.aborted ? "ABORTED" : "ACTIVE";
|
|
const cancellationOwner =
|
|
observation.terminalReason === "TIMEOUT"
|
|
? "DEADLINE"
|
|
: caller.signal.aborted
|
|
? "CALLER"
|
|
: scopeLifetime.signal.aborted
|
|
? "SCOPE_FENCE"
|
|
: "NONE";
|
|
const observed: HttpScenarioAssertionGroups = Object.freeze({
|
|
status: Object.freeze({
|
|
attempts: Object.freeze(physicalAttempts.map((attempt) => attempt.status)),
|
|
final: physicalAttempts.at(-1)!.status,
|
|
}),
|
|
outcome: Object.freeze({
|
|
kind: String(outcome.kind),
|
|
detail: outcomeDetail(outcome),
|
|
}),
|
|
effect: Object.freeze({
|
|
outcome: String(outcome.effect),
|
|
observer: observation.terminalReason,
|
|
}),
|
|
retry: Object.freeze({ count: sleeps.length, reasons: Object.freeze(sleeps) }),
|
|
fetch: Object.freeze({
|
|
count: physicalAttempts.length,
|
|
observerAttempts: observation.attemptCount,
|
|
agrees: physicalAttempts.length === observation.attemptCount,
|
|
}),
|
|
media: Object.freeze({
|
|
attempts: Object.freeze(physicalAttempts.map((attempt) => attempt.media)),
|
|
final: physicalAttempts.at(-1)?.media ?? null,
|
|
}),
|
|
body: Object.freeze({
|
|
attempts: Object.freeze(
|
|
physicalAttempts.map((attempt) =>
|
|
Object.freeze({
|
|
disposition: bodyDisposition(attempt, outcome),
|
|
pulledBytes: attempt.pulledBytes,
|
|
ceiling: attempt.appliedCeiling ?? 0,
|
|
}),
|
|
),
|
|
),
|
|
}),
|
|
scope: Object.freeze({
|
|
start: "CURRENT",
|
|
end: scopeCurrent ? "CURRENT" : "STALE",
|
|
signal: observedSignal,
|
|
cancellationOwner,
|
|
}),
|
|
});
|
|
return observed;
|
|
} finally {
|
|
caller.abort();
|
|
scopeLifetime.abort();
|
|
mockApi.reset();
|
|
}
|
|
}
|
|
|
|
describe("HTTP scenario catalog execution evidence", () => {
|
|
it("declares exactly the 57 behaviorally distinct operation scenarios", () => {
|
|
const executionIds = Object.entries(OPERATION_SCENARIO_CATALOG).flatMap(
|
|
([operationId, scenarioIds]) =>
|
|
scenarioIds.map((scenarioId) => `${operationId}::${scenarioId}`),
|
|
);
|
|
|
|
expect(OPERATION_SCENARIO_CATALOG.LIST_REFERENCE_RESOURCES).toHaveLength(20);
|
|
expect(OPERATION_SCENARIO_CATALOG.GET_REFERENCE_RESOURCE).toHaveLength(19);
|
|
expect(OPERATION_SCENARIO_CATALOG.CREATE_REFERENCE_RESOURCE).toHaveLength(18);
|
|
expect(executionIds).toHaveLength(57);
|
|
expect(new Set(executionIds)).toHaveLength(57);
|
|
expect(executionIds).toEqual(HTTP_SCENARIO_EXECUTION_IDS);
|
|
});
|
|
|
|
it("executes every declared scenario and publishes one complete receipt", async () => {
|
|
await rm(RECEIPT_PATH, { force: true });
|
|
const rows: Array<Readonly<{
|
|
executionId: string;
|
|
expected: HttpScenarioAssertionGroups;
|
|
observed: HttpScenarioAssertionGroups;
|
|
testDeadlineOverrideMs: number | null;
|
|
}>> = [];
|
|
|
|
for (const entry of HTTP_SCENARIO_EXPECTATIONS) {
|
|
const observed = await executeScenario(entry);
|
|
expect(observed, entry.executionId).toEqual(entry.expected);
|
|
rows.push(
|
|
Object.freeze({
|
|
executionId: entry.executionId,
|
|
expected: entry.expected,
|
|
observed,
|
|
testDeadlineOverrideMs: entry.testDeadlineOverrideMs,
|
|
}),
|
|
);
|
|
}
|
|
|
|
const sortedRows = [...rows].sort((left, right) =>
|
|
left.executionId.localeCompare(right.executionId),
|
|
);
|
|
await mkdir(path.dirname(RECEIPT_PATH), { recursive: true });
|
|
await writeValidatedJsonArtifact({
|
|
path: RECEIPT_PATH,
|
|
schema: httpScenarioReceiptSchema,
|
|
value: {
|
|
schemaVersion: HTTP_SCENARIO_RECEIPT_SCHEMA_VERSION,
|
|
catalogDigest: computeHttpScenarioCatalogDigest(
|
|
HTTP_SCENARIO_RECEIPT_SCHEMA_VERSION,
|
|
HTTP_SCENARIO_EXPECTATIONS,
|
|
),
|
|
catalogTotal: 57,
|
|
executedIds: sortedRows.map((row) => row.executionId),
|
|
rows: sortedRows,
|
|
},
|
|
});
|
|
}, 30_000);
|
|
});
|