문제
전송 전 실패가 네 곳에서 원인 없는 위반 FINAL_REQUEST_INVARIANT_FAILED
하나로 바뀐다. 입력 검증 실패, 요청 조립 실패 10종(PATH_PLACEHOLDER_MISSING
등), 최종 불변식 실패 12종, 미설치 계약이다. 바인딩은 이 위반과
MISSING_IDEMPOTENCY_KEY·UNEXPECTED_IDEMPOTENCY_KEY를 모두 VALIDATION_REJECTED로
바꿔 "서버가 입력값을 받아들이지 않았습니다"를 띄운다. 그래서 경로
placeholder 오타나 mutation 정책과 계약의 불일치 같은 개발자 연결 실수가
사용자 입력 문제처럼 보이고, 진단에는 원인이 없다. 미설치 계약은 실행기를
거치지 않아 진단이 0건이다. 또 마감이 시도별 budget 읽기와 최종 불변식
검사 사이에 끝나면 DEADLINE_EXPIRED도 같은 위반이 되어, 시간 초과가 "입력
거절"로 보인다(P-03-05).
고른 방법
- HttpContractViolation에 선택 필드 reason(닫힌 집합
HttpRequestRejectionReason)을 더한다. 실행기의 세 거절 지점이
refusedRequest(reason)로 위반을 만들고, finish()가 그 reason을 관측의
diagnosticReason으로 옮긴다. projector는 03-05에서 만든 경로대로
diagnostics에만 reason을 싣는다. telemetry는 error_kind 그대로다.
- 최종 불변식의 DEADLINE_EXPIRED는 budget 읽기 분기와 똑같이
TRANSPORT_FAILURE/TIMEOUT으로 끝낸다(P-03-05).
- 바인딩은 사용자가 입력을 바꿔 고칠 수 있는 거절(INPUT_INVALID,
PATH_VALUE_INVALID, QUERY_TOO_LARGE, URL_TOO_LARGE, REQUEST_BODY_TOO_LARGE)과
reason 없는 거절만 VALIDATION_REJECTED로 둔다. 나머지 reason과 멱등 키
위반은 UNKNOWN_CLIENT_FAILURE(문의 행동, "요청을 처리할 수 없습니다.")로
낸다. V2 client가 미등록 operation을 같은 종류로 내는 것과 맞췄다.
- 미설치 계약 분기는 같은 projector로 관측 1건(reason
CONTRACT_NOT_INSTALLED)을 직접 남긴다.
버린 대안
- 새 FailureKind 추가: 오류 레지스트리·i18n 카탈로그·화면 분기를 다 바꿔야
한다. 이미 있는 UNKNOWN_CLIENT_FAILURE가 "클라이언트 결함, 문의"라는 같은
뜻이고 V2에서 같은 상황에 쓰고 있다.
- 리뷰 예시대로 MAPPING_CONTRACT_VIOLATION으로 내기: 문구가 "서버 응답을 화면
데이터로 바꾸지 못했습니다"라 응답이 없는 전송 전 실패와 맞지 않는다.
- 사용자 입력 쪽을 reason별 Record로 망라하기: 컴파일 시 분류를 강제하지만
20여 줄이 는다. 새 reason은 기본으로 클라이언트 결함이 되는 쪽이 안전하므로
입력 쪽 5개만 Set으로 적었다.
- terminalReason에 원인을 싣기(리뷰 문구): 03-05와 같은 이유로 버렸다.
위험·한계
- 동작 변경: 멱등 키 위반과 연결 실수가 VALIDATION_REJECTED에서
UNKNOWN_CLIENT_FAILURE로 바뀐다. 폼은 필드 오류 대신 "unavailable" 상태
안내를 띄운다. 기존 계약 테스트의 기대값을 이에 맞게 바꿨다.
- 입력 검증 실패(INPUT_INVALID)는 리뷰 문구("입력 크기 초과만")와 달리
VALIDATION_REJECTED로 남겼다. 입력 validator의 거절은 사용자 입력 문제다.
- reason 없는 FINAL_REQUEST_INVARIANT_FAILED(다른 실행기 구현)는 기존대로
VALIDATION_REJECTED다.
- AppFailure.code는 지금처럼 위반 종류다. 원인 코드는 진단에만 있다.
- 공개 타입은 추가만 했다(위반 선택 필드 1개, 진단 reason 집합 확장).
- validator가 throw하는 경우(VALIDATOR_RUNTIME_FAILURE → SCHEMA_MISMATCH,
"서버 응답 데이터가…" 문구)는 이번 범위가 아니라 그대로다.
- 미설치 계약 거절도 다른 CONTRACT_VIOLATION처럼 api.request.failed
telemetry 1건을 낸다(VD-07 규칙 5).
- 화면: 정상 상태는 그대로이고 위 실패에서만 문구가 바뀐다. 시각 골든은
다시 찍지 않았다.
검증
- RED(수정 전):
- http-execution-v3-observability "names a refused request's assembly
cause in diagnostics only (03-02)": violation.reason 없음.
- 같은 파일 "ends a deadline that expires at the final invariant check as
a timeout (P-03-05)": TRANSPORT_FAILURE 기대, 실제 CONTRACT_VIOLATION.
- feature-http-binding 계약 테스트 5건: PATH_PLACEHOLDER_MISSING,
CONTRACT_NOT_INSTALLED, HEADER_NOT_ALLOWED, MISSING_IDEMPOTENCY_KEY,
UNEXPECTED_IDEMPOTENCY_KEY가 VALIDATION_REJECTED로 나옴.
- runtime-adapters-auth-profile "is refused without a fetch and leaves one
diagnostic naming the cause": reason 없음, 진단 0건.
- GREEN: 세 파일 38/38 통과.
- 회귀: run-vitest tests/unit tests/integration tests/component
tests/features tests/contract tests/runtime-schema(pnpm을 언급하는 파일
13개 제외) 227 files 중 226 통과, 2354/2355. 실패 1건은
provider-guardian-transaction의 ENOSPC(inotify watcher 한도, 이 머신의
다른 실행 때문)로 HTTP와 무관하다. 제외했던 http-scenario-evidence는
pnpm을 띄우지 않아 따로 돌렸고 14/14 통과.
tsc app/test/node rc=0. 바꾼 파일 eslint rc=0.
check-adapter-inventory PASS. verify-documentation-readiness PASS_SCOPED.
- 미실행: check:architecture(pnpm 스크립트 필요), 번들 크기 측정.
Refs: docs/reviews/2026-11-01-maturity-review/03-adapters-http-state.md
312 lines
9.9 KiB
TypeScript
312 lines
9.9 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
createFeatureHttpBinding,
|
|
defineFeatureHttpOperation,
|
|
type HttpExecutionOutcome,
|
|
type InstalledHttpOperationExecutor,
|
|
} from "../../../src/adapters/http/index.ts";
|
|
import {
|
|
mappingFailure,
|
|
mappingSuccess,
|
|
} from "../../../src/contracts/boundary-mapper.ts";
|
|
import type {
|
|
InstalledHttpContract,
|
|
RuntimeValidator,
|
|
} from "../../../src/contracts/external-contract-runtime.ts";
|
|
|
|
type ResourceInput = Readonly<{ resourceId: string }>;
|
|
type ResourceWire = Readonly<{ id: string; title: string }>;
|
|
type ResourceProblem = Readonly<{ code?: string }>;
|
|
|
|
function validator<T>(schemaId: string): RuntimeValidator<T> {
|
|
return Object.freeze({
|
|
schemaId,
|
|
safeParse(value: unknown) {
|
|
return Object.freeze({
|
|
success: true as const,
|
|
data: value as T,
|
|
});
|
|
},
|
|
});
|
|
}
|
|
|
|
const LOAD_RESOURCE_CONTRACT = Object.freeze({
|
|
contract: Object.freeze({
|
|
operationId: "LOAD_RESOURCE",
|
|
method: "GET" as const,
|
|
pathTemplate: "/resources/{resourceId}",
|
|
inputValidator: validator<ResourceInput>("ResourceInput"),
|
|
outputValidator: validator<ResourceWire>("ResourceWire"),
|
|
problemValidator: validator<ResourceProblem>("ResourceProblem"),
|
|
acceptedStatuses: Object.freeze([200]),
|
|
emptyBodyStatuses: Object.freeze([]),
|
|
retrySemantics: "SAFE" as const,
|
|
requestBody: "NONE" as const,
|
|
responseBody: "REQUIRED_JSON" as const,
|
|
commandRecovery: null,
|
|
commandEffect: null,
|
|
projectRequest(input: ResourceInput) {
|
|
return Object.freeze({
|
|
pathValues: Object.freeze({ resourceId: input.resourceId }),
|
|
queryEntries: Object.freeze([]),
|
|
body: null,
|
|
});
|
|
},
|
|
}),
|
|
frontend: Object.freeze({
|
|
policyId: "TEST_LOAD_RESOURCE",
|
|
requestByteLimit: 0,
|
|
responseByteLimit: 8_192,
|
|
totalDeadlineMs: 1_000,
|
|
retryBudget: 0 as const,
|
|
authProfileId: "TEST",
|
|
diagnosticsOperation: "test.load-resource",
|
|
}),
|
|
}) satisfies InstalledHttpContract<ResourceInput, ResourceWire, ResourceProblem>;
|
|
|
|
const OPERATIONS = Object.freeze({
|
|
LOAD_RESOURCE: defineFeatureHttpOperation({
|
|
contract: LOAD_RESOURCE_CONTRACT,
|
|
routeId: "RESOURCE_DETAIL",
|
|
mapSuccess(value) {
|
|
if (value.title.length === 0) {
|
|
return mappingFailure("MAPPING_INVARIANT_REJECTED");
|
|
}
|
|
return mappingSuccess(
|
|
Object.freeze({ id: value.id, title: value.title }),
|
|
);
|
|
},
|
|
mapProblem(problem, metadata) {
|
|
if (metadata.status !== 409) return undefined;
|
|
return Object.freeze({
|
|
kind: "CONFLICT" as const,
|
|
code: problem.code ?? "RESOURCE_CONFLICT",
|
|
});
|
|
},
|
|
}),
|
|
} as const);
|
|
|
|
function scriptedExecutor<WireOutput, Problem>(
|
|
outcome: HttpExecutionOutcome<WireOutput, Problem>,
|
|
) {
|
|
const calls: Array<
|
|
Readonly<{
|
|
contract: unknown;
|
|
input: unknown;
|
|
context: unknown;
|
|
}>
|
|
> = [];
|
|
const implementation = async (
|
|
contract: unknown,
|
|
input: unknown,
|
|
context: unknown,
|
|
) => {
|
|
calls.push(Object.freeze({ contract, input, context }));
|
|
return outcome;
|
|
};
|
|
const execute = vi.fn(implementation) as unknown as
|
|
InstalledHttpOperationExecutor["execute"];
|
|
return {
|
|
executor: Object.freeze({ execute }) satisfies InstalledHttpOperationExecutor,
|
|
calls,
|
|
execute,
|
|
};
|
|
}
|
|
|
|
describe("feature HTTP binding", () => {
|
|
it("keeps contract-derived input while platform owns route/context execution", async () => {
|
|
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(
|
|
Object.freeze({
|
|
kind: "SUCCESS" as const,
|
|
value: Object.freeze({ id: "resource-1", title: "Reference" }),
|
|
metadata: Object.freeze({ status: 200 }),
|
|
effect: "NOT_APPLICABLE" as const,
|
|
}),
|
|
);
|
|
const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS);
|
|
|
|
const result = await binding.execute("LOAD_RESOURCE", {
|
|
resourceId: "resource-1",
|
|
});
|
|
|
|
expect(result).toEqual({
|
|
ok: true,
|
|
value: { id: "resource-1", title: "Reference" },
|
|
});
|
|
expect(scripted.calls).toEqual([
|
|
{
|
|
contract: LOAD_RESOURCE_CONTRACT,
|
|
input: { resourceId: "resource-1" },
|
|
context: { routeId: "RESOURCE_DETAIL" },
|
|
},
|
|
]);
|
|
});
|
|
|
|
it("normalizes transport failure before it crosses the feature gateway", async () => {
|
|
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(
|
|
Object.freeze({
|
|
kind: "TRANSPORT_FAILURE" as const,
|
|
failure: Object.freeze({
|
|
kind: "TIMEOUT" as const,
|
|
retryable: true,
|
|
}),
|
|
effect: "NOT_STARTED" as const,
|
|
}),
|
|
);
|
|
const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS);
|
|
|
|
const result = await binding.execute("LOAD_RESOURCE", {
|
|
resourceId: "resource-1",
|
|
});
|
|
|
|
expect(result.ok).toBe(false);
|
|
if (result.ok) return;
|
|
expect(result.error.kind).toBe("REQUEST_TIMEOUT");
|
|
expect(result.error.operationId).toBe("LOAD_RESOURCE");
|
|
expect(result.error.effect).toBe("NOT_STARTED");
|
|
});
|
|
|
|
it("turns a domain mapper rejection into the shared mapping failure", async () => {
|
|
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(
|
|
Object.freeze({
|
|
kind: "SUCCESS" as const,
|
|
value: Object.freeze({ id: "resource-1", title: "" }),
|
|
metadata: Object.freeze({ status: 200 }),
|
|
effect: "NOT_APPLICABLE" as const,
|
|
}),
|
|
);
|
|
const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS);
|
|
|
|
const result = await binding.execute("LOAD_RESOURCE", {
|
|
resourceId: "resource-1",
|
|
});
|
|
|
|
expect(result.ok).toBe(false);
|
|
if (result.ok) return;
|
|
expect(result.error.kind).toBe("MAPPING_CONTRACT_VIOLATION");
|
|
expect(result.error.code).toBe("MAPPING_INVARIANT_REJECTED");
|
|
});
|
|
|
|
/**
|
|
* 03-02. A request refused before dispatch is never a server answer. Only an
|
|
* input the user can change is "input rejected"; a wiring defect in this
|
|
* client (contract not installed, path template and projection disagree,
|
|
* mutation intent disagrees with the contract) is a client failure.
|
|
*/
|
|
it.each([
|
|
["FINAL_REQUEST_INVARIANT_FAILED", undefined, "VALIDATION_REJECTED"],
|
|
["FINAL_REQUEST_INVARIANT_FAILED", "INPUT_INVALID", "VALIDATION_REJECTED"],
|
|
["FINAL_REQUEST_INVARIANT_FAILED", "PATH_VALUE_INVALID", "VALIDATION_REJECTED"],
|
|
["FINAL_REQUEST_INVARIANT_FAILED", "QUERY_TOO_LARGE", "VALIDATION_REJECTED"],
|
|
["FINAL_REQUEST_INVARIANT_FAILED", "URL_TOO_LARGE", "VALIDATION_REJECTED"],
|
|
["FINAL_REQUEST_INVARIANT_FAILED", "REQUEST_BODY_TOO_LARGE", "VALIDATION_REJECTED"],
|
|
["FINAL_REQUEST_INVARIANT_FAILED", "PATH_PLACEHOLDER_MISSING", "UNKNOWN_CLIENT_FAILURE"],
|
|
["FINAL_REQUEST_INVARIANT_FAILED", "CONTRACT_NOT_INSTALLED", "UNKNOWN_CLIENT_FAILURE"],
|
|
["FINAL_REQUEST_INVARIANT_FAILED", "HEADER_NOT_ALLOWED", "UNKNOWN_CLIENT_FAILURE"],
|
|
["MISSING_IDEMPOTENCY_KEY", undefined, "UNKNOWN_CLIENT_FAILURE"],
|
|
["UNEXPECTED_IDEMPOTENCY_KEY", undefined, "UNKNOWN_CLIENT_FAILURE"],
|
|
] as const)(
|
|
"reports the request-side violation %s (%s) as %s, never as a server answer",
|
|
async (violationKind, reason, expectedKind) => {
|
|
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(
|
|
Object.freeze({
|
|
kind: "CONTRACT_VIOLATION" as const,
|
|
violation: Object.freeze({
|
|
kind: violationKind,
|
|
operation: "REQUEST" as const,
|
|
...(reason === undefined ? {} : { reason }),
|
|
}),
|
|
effect: "NOT_APPLICABLE" as const,
|
|
}),
|
|
);
|
|
const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS);
|
|
|
|
const result = await binding.execute("LOAD_RESOURCE", {
|
|
resourceId: "resource-1",
|
|
});
|
|
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { kind: expectedKind, code: violationKind },
|
|
});
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
[
|
|
"mapSuccess",
|
|
Object.freeze({
|
|
kind: "SUCCESS" as const,
|
|
value: Object.freeze({ id: "resource-1", title: "Reference" }),
|
|
metadata: Object.freeze({ status: 201 }),
|
|
effect: "APPLIED_CONFIRMED" as const,
|
|
}),
|
|
],
|
|
[
|
|
"mapProblem",
|
|
Object.freeze({
|
|
kind: "PROBLEM" as const,
|
|
problem: Object.freeze({ code: "RESOURCE_NAME_EXISTS" }),
|
|
metadata: Object.freeze({ status: 409 }),
|
|
effect: "APPLIED_CONFIRMED" as const,
|
|
}),
|
|
],
|
|
])(
|
|
"returns a mapping failure with the server effect when %s throws",
|
|
async (_mapper, outcome) => {
|
|
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(outcome);
|
|
const binding = createFeatureHttpBinding(scripted.executor, {
|
|
LOAD_RESOURCE: defineFeatureHttpOperation({
|
|
contract: LOAD_RESOURCE_CONTRACT,
|
|
routeId: "RESOURCE_DETAIL",
|
|
mapSuccess(): never {
|
|
throw new TypeError("mapper defect");
|
|
},
|
|
mapProblem(): never {
|
|
throw new TypeError("mapper defect");
|
|
},
|
|
}),
|
|
} as const);
|
|
|
|
const result = await binding.execute("LOAD_RESOURCE", {
|
|
resourceId: "resource-1",
|
|
});
|
|
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
kind: "MAPPING_CONTRACT_VIOLATION",
|
|
code: "MAPPING_CONTRACT_VIOLATION",
|
|
effect: "APPLIED_CONFIRMED",
|
|
},
|
|
});
|
|
},
|
|
);
|
|
|
|
it("lets the feature interpret a typed business problem", async () => {
|
|
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(
|
|
Object.freeze({
|
|
kind: "PROBLEM" as const,
|
|
problem: Object.freeze({ code: "RESOURCE_NAME_EXISTS" }),
|
|
metadata: Object.freeze({ status: 409 }),
|
|
effect: "NOT_APPLIED" as const,
|
|
}),
|
|
);
|
|
const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS);
|
|
|
|
const result = await binding.execute("LOAD_RESOURCE", {
|
|
resourceId: "resource-1",
|
|
});
|
|
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
kind: "CONFLICT",
|
|
code: "RESOURCE_NAME_EXISTS",
|
|
httpStatus: 409,
|
|
},
|
|
});
|
|
});
|
|
});
|