문제: responseEnvelope는 descriptor의 선택 칸이고 없으면 "NONE"이다.
1103/16-01 수정은 계약 조립이 한 기여 안에서 값이 섞이면 거부하고,
refusedBeforeWrite가 있는 쓰기에 Envelope를 요구하게 했다. 그러나 읽기만
있는 기여(기본 생성 판)나 refusedBeforeWrite 없는 쓰기에서 줄을 모두 빼면
조립은 통과하고(모두 같은 NONE), 짝 백엔드의 Envelope를 DTO로 읽어
SCHEMA_MISMATCH로 깨지는 것은 손글씨 gateway 테스트만 잡는다. 지난 완료
기준("줄을 지우면 check:types가 실패한다")을 채우지 못했다.
고른 방법(1103 대안 (b)): InstalledHttpContract의 contract.responseEnvelope를
필수로 바꾼다. 생성 기능·참조 기능·예제의 descriptor는 모두
`satisfies InstalledHttpContract<...>`라 줄을 지우면 tsc가 그 자리에서
실패한다. 줄이 없던 descriptor에 "NONE" as const를 적었다: 참조 기능 셋,
tests/helpers/external-contract-fixture.ts 셋,
tests/contract/reusable-capability/feature-http-binding.test.ts,
scripts/drill-runbook.ts. 값은 전과 같아 FE-REG-API 행과 레지스트리 기준선은
바뀌지 않는다. 조립(external-contract-runtime.ts)은 그대로 빠진 값을 NONE으로
읽는다: TypeScript 밖에서 만든 descriptor를 런타임에 거부하지 않는다.
생성기 주석의 "줄을 지운다" 안내를 "NONE을 적는다"로, 매뉴얼 01(3단계,
짝 백엔드가 아닌 백엔드), errors.md, 계약 문서 4.1절을 같은 뜻으로 고쳤다.
테스트: external-contract-runtime.test.ts에 줄을 뺀 descriptor 선언 위
@ts-expect-error를 두었다. 타입이 다시 선택 칸이 되면 그 지시문이 쓰이지
않아 check:types:test가 실패한다. 같은 테스트가 런타임 조립은 NONE으로
읽는지도 본다.
버린 대안: (c) 기여 단위 기본값 — 규칙이 하나 는다. (d)만으로 두기 — 모두
빠진 경우를 못 막는다. 조립에서 빠진 키를 거부 — JS로 만든 계약 패키지가
런타임에 깨지고, 빠진 값을 일부러 다루는 테스트를 모두 바꿔야 한다.
위험·한계: descriptor를 직접 쓰는 다운스트림 코드는 줄을 더할 때까지
check:types가 실패한다. 모든 operation에 같은 틀린 값을 적는 것(짝 백엔드인데
모두 "NONE")은 여전히 타입도 조립도 통과한다(매뉴얼 "못 잡음"). 이 노트북에서
tsc를 돌리지 못해, 놓친 descriptor가 있으면 desktop check:types가 알려 준다.
검증: desktop batch에서 확인.
corepack pnpm check:types
node scripts/run-vitest.ts run tests/unit/external-contract-runtime.test.ts
tests/features/reference-feature tests/unit/api-operation-rows.test.ts
corepack pnpm check:registries (compatibility 변화 없음 기대)
BREAKING CHANGE: src/contracts/external-contract-runtime.ts의
InstalledHttpContract에서 contract.responseEnvelope가 필수다. 이 줄이 없는
descriptor는 check:types에서 실패한다. 감싸지 않는 백엔드는
responseEnvelope: "NONE" as const, 짝 백엔드(Envelope)는 "ENVELOPE_V1" as const를
operation마다 적는다. 런타임 동작은 같다.
Refs: 1103/16-01
313 lines
10 KiB
TypeScript
313 lines
10 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,
|
|
responseEnvelope: "NONE" 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,
|
|
},
|
|
});
|
|
});
|
|
});
|