문제
HTTP API 하나를 V2 행(check:registries가 보는 선언)과 V3 descriptor(실제로
실행되는 사본)에 두 번 쓴다. 15-01 뒤에도 둘은 feature-runtime.ts의
apiContract와 contractContributions로 나뉘어 그대로 두 벌이다. 둘을 잇는
parity 테스트는 V2 행에서 V3를 찾는 한 방향이고 6필드만 비교한다. 그래서
V3 검증기의 schemaId를 바꾸거나(L1) V3에만 API를 추가해도(L6) 테스트가
통과한다. V3에만 있는 API는 공개 경로·메서드가 FE-REG-API 게이트 밖에서
실행된다. "V2는 게이트용, V3는 실행용"이라는 사실은 테스트 주석에만 있다.
고른 방법 (리뷰 5.1절의 B, 1단계)
- 두 사본의 operation id 집합이 같아야 한다(양방향). V3만 있는 API와
V2만 있는 API가 각각 실패한다.
- 비교 필드에 같은 사실의 사본 넷을 더했다: 쓰기 여부(V2 semantics ↔ V3
commandEffect 유무, 실행기가 쓰기를 메서드가 아니라 effect로 정하므로),
요청 본문(V2 requestSource body ↔ V3 requestBody JSON), 입력 스키마 id
(V2 pathSchema/requestSchema 중 NoRequest가 아닌 것 ↔ V3 inputValidator),
응답 스키마 id(V2 responseSchema ↔ V3 outputValidator).
- V2가 path와 request 스키마를 둘 다 가진 operation은 V3 입력 스키마 하나와
대응 규칙이 아직 없다. 조용히 넘기지 않고 테스트가 실패하며 규칙을
정하라고 알린다. 지금 설치된 operation에는 없다.
- RestOperationV2 위와 starter-experience.md "Adding a feature"에 V2는
게이트용 선언, V3는 실행 사본이고 둘 다 쓴다는 것을 적었다.
버린 대안
- V2 행을 V3에서 생성(5.1절 C)하거나 FE-REG-API 스냅샷을 V3에서 투영하고
V2 행을 없애기(D): 생성기·투영 함수와 기준선 재승인이 필요한 구조
변경이라 이번 범위를 넘는다. 15-01로 V2와 V3가 같은
defineFeatureRuntime 객체에 모였으므로 D로 갈 때 기능 단위 투영 지점은
생겼다.
- "V2 행이 1개 이상" 단언: test:sample-removal이 참조 기능을 지운 사본에서
이 파일을 돌리면 두 집합이 모두 비어 정상인데 실패한다. 양방향 집합
비교가 한쪽만 빈 경우를 잡는다.
- 두 번째 기능 테스트(second-api-feature-registries)에 V3 기여 넣기:
fixture 복사본에서 check:registries를 도는 테스트라 V3 기여를 넣어도 이
parity 검사가 그 사본에서 돌지 않는다. 비용 대비 효과가 작아 뺐다.
위험·한계
- 시간 제한(V2 timeoutMs null ↔ V3 totalDeadlineMs 10000, L3)은 비교하지
않는다. 맞추려면 V2 행 값을 바꿔야 하고 FE-REG-API 기준선이 바뀐다.
주석에 비교하지 않는다고 적었다.
- 응답 스키마 본문, unknownFieldPolicy ↔ zod strip/strict(L7), 손 guard ↔
zod DTO 차이는 여전히 대조하지 않는다.
- 설치된 기능에 대한 테스트다. CI 밖에서 V3만 추가한 다운스트림은 이
파일을 돌려야 걸린다.
검증
- RED: 기존 테스트와 새 테스트를 같은 변이에 돌렸다.
L1(V3 GET_REFERENCE_RESOURCE outputValidator schemaId를
ReferenceResourcePayloadV2로): 기존 통과, 새 테스트 실패
("responseSchema": "ReferenceResourcePayload" vs "...V2").
L6(V3에만 GET_REFERENCE_RESOURCE_V3_ONLY 추가): 기존 통과, 새 테스트
"cover the same operations" 실패(+ "GET_REFERENCE_RESOURCE_V3_ONLY").
- GREEN: 변이 없이 2/2 통과.
- 회귀: tsc test rc=0, 바꾼 파일 eslint rc=0. 전체 회귀는 다음 커밋들과
함께 마지막에 돌렸다(이 커밋의 src 변경은 주석뿐).
Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md
227 lines
7.8 KiB
TypeScript
227 lines
7.8 KiB
TypeScript
export type ApiOperation = Readonly<{
|
|
method: string;
|
|
path: string;
|
|
operationId: string;
|
|
auth: "none" | "external-session";
|
|
timeoutMs: number | null;
|
|
idempotency: "safe" | "keyed" | "none";
|
|
retry: "runtime" | "never";
|
|
requestSource: "search" | "body" | "none";
|
|
requestSchema: string;
|
|
responseSchema: string;
|
|
owner: string;
|
|
contractVersion?: 2;
|
|
protocol?: "REST";
|
|
semantics?: "QUERY" | "COMMAND";
|
|
replayPolicy?: "SAFE" | "IDEMPOTENT" | "KEYED_COMMAND" | "NON_REPLAYABLE";
|
|
idempotencyKeyPolicy?: "NONE" | "REQUIRED";
|
|
mapperId?: string;
|
|
successStatuses?: readonly number[];
|
|
responseMediaTypes?: readonly string[];
|
|
maxResponseBytes?: number;
|
|
providerId?: string;
|
|
authProfileId?: string;
|
|
csrfProfileId?: string;
|
|
pathSchema?: string;
|
|
pathParameterNames?: readonly string[];
|
|
maxEncodedSearchBytes?: number;
|
|
}>;
|
|
|
|
/**
|
|
* 07-02. A V2 row is the declaration `check:registries` (FE-REG-API) governs;
|
|
* it is not what executes. The executed copy of the same HTTP API is the V3
|
|
* descriptor (`InstalledHttpContract`) in the feature's contract contribution.
|
|
* A feature writes both, and `tests/unit/http-operation-v2-v3-parity.test.ts`
|
|
* checks they name the same operations, method, path, statuses, limits, auth
|
|
* profile, replay and write semantics, request body and schema ids. The
|
|
* deadline is not compared: V2 `timeoutMs` is `null` while V3 always has one.
|
|
*/
|
|
export type RestOperationV2 = ApiOperation &
|
|
Readonly<{
|
|
contractVersion: 2;
|
|
protocol: "REST";
|
|
semantics: "QUERY" | "COMMAND";
|
|
replayPolicy:
|
|
| "SAFE"
|
|
| "IDEMPOTENT"
|
|
| "KEYED_COMMAND"
|
|
| "NON_REPLAYABLE";
|
|
idempotencyKeyPolicy: "NONE" | "REQUIRED";
|
|
mapperId: string;
|
|
successStatuses: readonly number[];
|
|
responseMediaTypes: readonly string[];
|
|
maxResponseBytes: number;
|
|
providerId: string;
|
|
authProfileId: string;
|
|
csrfProfileId: string;
|
|
pathSchema: string;
|
|
pathParameterNames: readonly string[];
|
|
maxEncodedSearchBytes: number;
|
|
}>;
|
|
|
|
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
const OPERATION_ID = /^[A-Z][A-Z0-9_]{2,79}$/;
|
|
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
|
|
|
|
export function defineRestOperation(
|
|
operation: RestOperationV2,
|
|
): RestOperationV2 {
|
|
validateRestOperation(operation);
|
|
return Object.freeze({
|
|
...operation,
|
|
successStatuses: Object.freeze([...operation.successStatuses]),
|
|
responseMediaTypes: Object.freeze([...operation.responseMediaTypes]),
|
|
pathParameterNames: Object.freeze([...operation.pathParameterNames]),
|
|
});
|
|
}
|
|
|
|
export function composeApiOperations(
|
|
contributions: readonly Readonly<Record<string, ApiOperation>>[],
|
|
): Readonly<Record<string, ApiOperation>> {
|
|
const result: Record<string, ApiOperation> = Object.create(null);
|
|
for (const contribution of contributions) {
|
|
for (const [registryId, operation] of Object.entries(contribution)) {
|
|
if (registryId !== operation.operationId) {
|
|
throw new TypeError("API operation registry key does not match operationId.");
|
|
}
|
|
if (Object.hasOwn(result, registryId)) {
|
|
throw new TypeError(`Duplicate API operation: ${registryId}`);
|
|
}
|
|
if (operation.contractVersion === 2) {
|
|
validateRestOperation(operation as RestOperationV2);
|
|
}
|
|
result[registryId] = operation;
|
|
}
|
|
}
|
|
return Object.freeze(result);
|
|
}
|
|
|
|
export function validateApiRuntimeBindings(
|
|
operations: Readonly<Record<string, ApiOperation>>,
|
|
schemaMetadata: Readonly<Record<string, Readonly<{ schemaId: string }>>>,
|
|
schemaCodecs: Readonly<Record<string, Readonly<{ schemaId: string }>>>,
|
|
mappers: Readonly<
|
|
Record<
|
|
string,
|
|
Readonly<{ mapperId: string; inputSchemaId: string; maxOutputItems: number }>
|
|
>
|
|
>,
|
|
): true {
|
|
for (const operation of Object.values(operations)) {
|
|
if (operation.contractVersion !== 2) continue;
|
|
for (const schemaId of [
|
|
operation.pathSchema,
|
|
operation.requestSchema,
|
|
operation.responseSchema,
|
|
]) {
|
|
if (
|
|
!schemaId ||
|
|
schemaMetadata[schemaId]?.schemaId !== schemaId ||
|
|
schemaCodecs[schemaId]?.schemaId !== schemaId
|
|
) {
|
|
throw new TypeError(
|
|
`Unresolved API schema binding: ${operation.operationId}`,
|
|
);
|
|
}
|
|
}
|
|
const mapper = mappers[operation.mapperId ?? ""];
|
|
if (
|
|
!mapper ||
|
|
mapper.mapperId !== operation.mapperId ||
|
|
mapper.inputSchemaId !== operation.responseSchema ||
|
|
mapper.maxOutputItems < 1
|
|
) {
|
|
throw new TypeError(
|
|
`Unresolved API mapper binding: ${operation.operationId}`,
|
|
);
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function validateRestOperation(operation: RestOperationV2): void {
|
|
if (
|
|
operation.protocol !== "REST" ||
|
|
!OPERATION_ID.test(operation.operationId) ||
|
|
!operation.owner ||
|
|
!operation.mapperId ||
|
|
!operation.providerId ||
|
|
!operation.authProfileId ||
|
|
!operation.csrfProfileId ||
|
|
!operation.pathSchema ||
|
|
!operation.path.startsWith("/") ||
|
|
operation.path.startsWith("//") ||
|
|
operation.path.includes("?") ||
|
|
operation.path.includes("#") ||
|
|
!Number.isSafeInteger(operation.maxResponseBytes) ||
|
|
operation.maxResponseBytes < 1 ||
|
|
operation.maxResponseBytes > MAX_RESPONSE_BYTES ||
|
|
!Number.isSafeInteger(operation.maxEncodedSearchBytes) ||
|
|
operation.maxEncodedSearchBytes < 0 ||
|
|
operation.maxEncodedSearchBytes > 32_768 ||
|
|
operation.successStatuses.length === 0 ||
|
|
operation.successStatuses.some(
|
|
(status) => !Number.isInteger(status) || status < 200 || status > 299,
|
|
) ||
|
|
new Set(operation.successStatuses).size !== operation.successStatuses.length ||
|
|
operation.responseMediaTypes.length === 0 ||
|
|
operation.responseMediaTypes.some(
|
|
(value) => !MEDIA_TYPE.test(value) || value !== value.toLowerCase(),
|
|
)
|
|
) {
|
|
throw new TypeError(`Invalid REST operation contract: ${operation.operationId}`);
|
|
}
|
|
const placeholders = [
|
|
...operation.path.matchAll(
|
|
/:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g,
|
|
),
|
|
]
|
|
.map((match) => match[1] ?? match[2] ?? "")
|
|
.sort();
|
|
const codecKeys = [...operation.pathParameterNames].sort();
|
|
if (
|
|
new Set(codecKeys).size !== codecKeys.length ||
|
|
placeholders.length !== codecKeys.length ||
|
|
placeholders.some((name, index) => name !== codecKeys[index])
|
|
) {
|
|
throw new TypeError(
|
|
`REST path codec does not match its template: ${operation.operationId}`,
|
|
);
|
|
}
|
|
const isQuery = operation.semantics === "QUERY";
|
|
// R-7.4. CSRF need is decided from the method (rest-profiles), so a COMMAND
|
|
// must use an unsafe method. Same binding as browser-rpc and the V3 runtime.
|
|
if (
|
|
!["QUERY", "COMMAND"].includes(operation.semantics) ||
|
|
!["SAFE", "IDEMPOTENT", "KEYED_COMMAND", "NON_REPLAYABLE"].includes(
|
|
operation.replayPolicy,
|
|
) ||
|
|
(!isQuery && !["POST", "PUT", "PATCH", "DELETE"].includes(operation.method)) ||
|
|
(isQuery && !["GET", "HEAD"].includes(operation.method)) ||
|
|
(isQuery && !["SAFE", "IDEMPOTENT"].includes(operation.replayPolicy)) ||
|
|
(operation.replayPolicy === "KEYED_COMMAND" &&
|
|
(operation.idempotencyKeyPolicy !== "REQUIRED" ||
|
|
operation.idempotency !== "keyed")) ||
|
|
(operation.replayPolicy === "NON_REPLAYABLE" &&
|
|
(operation.retry !== "never" || operation.idempotency !== "none"))
|
|
) {
|
|
throw new TypeError(`Incoherent REST replay contract: ${operation.operationId}`);
|
|
}
|
|
}
|
|
|
|
export const API_OPERATIONS: Readonly<Record<string, ApiOperation>> =
|
|
Object.freeze({});
|
|
|
|
export function getApiOperation(
|
|
operationId: string,
|
|
operations: Readonly<Record<string, ApiOperation>> = API_OPERATIONS,
|
|
): ApiOperation {
|
|
const selected = Object.hasOwn(operations, operationId)
|
|
? operations[operationId]
|
|
: undefined;
|
|
if (!selected) {
|
|
throw new Error(`Unregistered API operation: ${operationId}`);
|
|
}
|
|
return selected;
|
|
}
|