refactor(contracts)!: V2 API 행을 지우고 FE-REG-API를 HTTP descriptor에서 뽑는다

문제
기능 하나가 같은 HTTP API를 두 번 적는다. *-api-contract.ts의 V2 행
(defineRestOperation)은 check:registries(FE-REG-API)가 검사하는 선언이고,
contract contribution의 V3 descriptor가 실제로 실행된다. 둘이 어긋나지 않게
http-operation-v2-v3-parity 테스트를 따로 둔다. 048f490으로 V2 클라이언트가
없어져 V2 행을 읽는 실행 코드는 없고, 검사만 남은 두 번째 사본이다. V2 행을
위한 기능별 runtimeSchemas·mappers 레지스트리와 V2 보안 프로필 해석
(resolveRestSecurityProfiles)도 같이 남아 있다. 사용자 지시: 최신 경로 하나만
남기고, 레지스트리 기준선 재승인을 승인했다.

고른 방법
- src/contracts/api-operations.ts를 projectApiOperationRows 하나로 바꿨다.
  조립된 contribution의 descriptor마다 operationId, featureId, method, path,
  authProfileId, retrySemantics, requestBody, responseBody, responseEnvelope,
  request/response/problemSchema(검증기 schemaId) 행을 만든다. FE-REG-API는
  같은 export(API_OPERATIONS)를 읽고, governance 정의를 이 필드로 바꿨다.
  requestSchema·responseSchema는 그대로 FE-REG-SCHEMA를 참조한다.
- FeatureRuntime은 apiContract 대신 schemas(FE-REG-SCHEMA 행)만 받는다.
  installed-feature-runtime-registries는 schemas로 스키마 레지스트리를 만들고
  FE-REG-API 행을 descriptor에서 뽑는다. RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
  REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID를 지웠다.
- realtime snapshot 바인딩은 ApiOperationRow를 받고 method GET과
  retrySemantics SAFE·IDEMPOTENT를 본다(V2의 contractVersion·semantics·
  replayPolicy 대신).
- rest-profiles.ts에서 V2 행용 provider·CSRF 프로필 해석을 지웠다. V3는 조립
  때 auth profile을 검사하고 자격증명 헤더를 프로필로 거른다.
- 참조 기능: reference-api-contract.ts를 reference-schema-metadata.ts로
  바꾸고(스키마 행만), V2 runtime codec·operation mapper·레지스트리 mapper를
  지웠다. V3 descriptor가 쓰지 않는 NoRequest 스키마 행도 지웠다.
- create:feature: <base>-api-contract.ts 대신 <base>-schema-metadata.ts를
  만든다. codec·mapper 레지스트리 행과 그 테스트를 만들지 않는다.
- 레지스트리 기준선을 update:registry-baseline으로 다시 만들고 승인했다
  (digest 16f72742…, 승인자 DongHyeonka, 이유에 사용자 승인을 적음).
- 매뉴얼 01·02·reference, starter-experience, 계약 문서의 V2 설명을 지웠다.

버린 대안
- V2 행을 남기고 V3에서 생성하기: 생성 단계와 생성물이 하나 더 생긴다. 행은
  실행되지 않으므로 메모리에서 뽑아 검사하면 충분하다.
- 스키마 메타데이터(FE-REG-SCHEMA 행)도 검증기에서 뽑기: boundary·
  unknownFieldPolicy·owner는 검증기에 없고, 라우트 스키마도 같은 레지스트리를
  쓴다. 이 행은 V2가 아니라 스키마 레지스트리라 남겼다.

위험·한계
- BREAKING: FeatureRuntime 모양, contracts·rest-profiles·loaded-feature-runtimes
  의 이름이 바뀌거나 없어졌다. memento-frontend의 memento-web이 V2 행을 쓴다.
  옮기는 법은 CHANGELOG에 적는다.
- V2 보안 프로필 일관성 검사(auth "none"과 ANONYMOUS, 쿠키 프로필의 CSRF
  모드)가 사라졌다. V3 descriptor에는 그 칸이 없다.
- BoundedPollOperationContract(realtime polling recipe)는 contractVersion: 2
  필드를 갖지만 자체 계약이라 바꾸지 않았다.

검증
- check:types, lint, check:architecture, check:registries(11 registries PASS,
  compatibility=none), check:ci, check:diagnostics, check:adapter-inventory,
  verify:documentation 통과.
- test:unit 2,566(새 tests/unit/api-operation-rows.test.ts 3건 포함),
  test:integration 114, test:component 245, test:contract 23,
  test:runtime-schema 56, tests/features 99 통과.
- tests/unit/second-api-feature-registries.test.ts: V3 descriptor만 가진 두
  번째 기능을 복사본에 넣으면 기준선을 고치지 않고 check:registries가 통과한다.
- check:bundle 통과. 초기 JS 201,598 → 200,911 B.
- test:feature-scaffold 16개, test:sample-removal 23개 검사 통과.

BREAKING CHANGE: FeatureRuntime이 apiContract 대신 schemas를 받는다.
defineRestOperation, ApiOperation, RestOperationV2, composeApiOperations,
validateApiRuntimeBindings, getApiOperation, contracts의 API_OPERATIONS,
createRestProviderProfile, RestProviderProfile, resolveRestSecurityProfiles,
validateRestProfileBindings, REST_CSRF_PROFILES, RestCsrfProfile,
loaded-feature-runtimes의 RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID가 없어졌다. 기능은
operation을 contract contribution에만 적고, schemas 행을 feature-runtime에
넘긴다.
This commit is contained in:
DongHyeonka
2026-11-03 21:37:48 +09:00
parent 048f490ada
commit 12f3bb7862
44 changed files with 560 additions and 1702 deletions
+34 -112
View File
@@ -277,7 +277,7 @@ export function planFeature(
[`${feature}/contracts/${base}-feature-contract.ts`, renderFeatureContract(shape)],
[`${feature}/contracts/${base}-schemas.ts`, renderSchemas(shape)],
[`${feature}/contracts/${base}-mapper.ts`, renderMapper(shape)],
[`${feature}/contracts/${base}-api-contract.ts`, renderApiContract(shape)],
[`${feature}/contracts/${base}-schema-metadata.ts`, renderSchemaMetadata(shape)],
[
`${feature}/contracts/${base}-contract-contribution.ts`,
renderContractContribution(shape),
@@ -369,9 +369,9 @@ function renderFeatureRuntime({ names }: Shape): string {
const { base, upper } = names;
return `import { defineFeatureRuntime } from "../feature-module.ts";
import { ${upper}_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-${base}-feature-input.ts";
import { ${upper}_API_CONTRACT } from "./contracts/${base}-api-contract.ts";
import { ${upper}_CONTRACT_CONTRIBUTION } from "./contracts/${base}-contract-contribution.ts";
import { ${upper}_FEATURE_ID } from "./contracts/${base}-feature-contract.ts";
import { ${upper}_SCHEMA_METADATA } from "./contracts/${base}-schema-metadata.ts";
/**
* The executable half. \`feature-module.ts\` imports this file dynamically, so
@@ -379,7 +379,7 @@ import { ${upper}_FEATURE_ID } from "./contracts/${base}-feature-contract.ts";
*/
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: ${upper}_FEATURE_ID,
apiContract: ${upper}_API_CONTRACT,
schemas: ${upper}_SCHEMA_METADATA,
adapters: [${upper}_FEATURE_ADAPTER_CONTRIBUTION],
contractContributions: [${upper}_CONTRACT_CONTRIBUTION],
} as const);
@@ -522,8 +522,7 @@ export const ${upper}_FEATURE_CONTRACT = Object.freeze({
function renderSchemas({ names }: Shape): string {
const { camel, pascal, upper } = names;
return `import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
import { z } from "../../../contracts/zod.ts";
return `import { z } from "../../../contracts/zod.ts";
import { zodValidator } from "../../../contracts/zod-validator.ts";
/** The GET takes no input. Schema ids are global, so this one is prefixed too. */
@@ -564,28 +563,16 @@ export const ${upper}_VALIDATORS = Object.freeze({
),
${pascal}Problem: zodValidator("${pascal}Problem", ${camel}ProblemSchema),
});
export const ${upper}_RUNTIME_SCHEMA_CODECS = Object.freeze({
${pascal}NoRequest: runtimeSchemaCodecFromValidator(${upper}_VALIDATORS.${pascal}NoRequest),
${pascal}ItemListPayload: runtimeSchemaCodecFromValidator(
${upper}_VALIDATORS.${pascal}ItemListPayload,
),
});
`;
}
function renderMapper({ names, owner }: Shape): string {
const { base, camel, pascal, upper } = names;
function renderMapper({ names }: Shape): string {
const { base, pascal } = names;
return `import {
mappingFailure,
mappingSuccess,
type BoundaryMappingResult,
type InstalledBoundaryMapper,
} from "../../../contracts/boundary-mapper.ts";
import {
${camel}ItemListPayloadSchema,
type ${pascal}ItemDto,
} from "./${base}-schemas.ts";
import type { ${pascal}ItemDto } from "./${base}-schemas.ts";
/** What the page shows. A wire field never reaches presentation by its wire name. */
export type ${pascal}ItemView = Readonly<{ itemId: string; name: string }>;
@@ -604,93 +591,37 @@ export function map${pascal}ItemList(
),
);
}
/** The registry row (FE-REG-API). The registry is untyped, so it checks the shape. */
export const ${upper}_BOUNDARY_MAPPERS = Object.freeze({
${pascal}ItemListMapper: Object.freeze({
mapperId: "${pascal}ItemListMapper",
mapperVersion: 1,
inputSchemaId: "${pascal}ItemListPayload",
outputContractId: "${pascal}ItemList",
owner: "${owner}",
maxOutputItems: 100,
map(value: unknown) {
const parsed = ${camel}ItemListPayloadSchema.safeParse(value);
return parsed.success
? map${pascal}ItemList(parsed.data)
: mappingFailure("MAPPING_INVARIANT_REJECTED");
},
}),
} satisfies Readonly<Record<string, InstalledBoundaryMapper>>);
`;
}
function renderApiContract({ names, operationId, apiPath, owner }: Shape): string {
const { base, pascal, upper } = names;
return `import { defineRestOperation } from "../../../contracts/api-operations.ts";
import { ${upper}_BOUNDARY_MAPPERS } from "./${base}-mapper.ts";
import { ${upper}_RUNTIME_SCHEMA_CODECS } from "./${base}-schemas.ts";
const OWNER = "${owner}";
function renderSchemaMetadata({ names, owner }: Shape): string {
const { pascal, upper } = names;
return `const OWNER = "${owner}";
/**
* The V2 API contract \`check:registries\` governs (FE-REG-API). The executable
* descriptor of the same operation is in \`${base}-contract-contribution.ts\`;
* tests/unit/http-operation-v2-v3-parity.test.ts fails when they disagree.
* Runtime half only: \`feature-runtime.ts\` loads it.
* FE-REG-SCHEMA rows of the feature's schemas (\`check:registries\`). The HTTP
* operation is written once, in \`${names.base}-contract-contribution.ts\`;
* FE-REG-API rows are projected from it. Runtime half only:
* \`feature-runtime.ts\` loads it.
*/
export const ${upper}_API_CONTRACT = Object.freeze({
runtimeSchemas: ${upper}_RUNTIME_SCHEMA_CODECS,
mappers: ${upper}_BOUNDARY_MAPPERS,
schemas: Object.freeze({
${pascal}NoRequest: Object.freeze({
schemaId: "${pascal}NoRequest",
boundary: "api-request",
owner: OWNER,
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
${pascal}ItemListPayload: Object.freeze({
schemaId: "${pascal}ItemListPayload",
boundary: "api-response",
owner: OWNER,
runtime: "zod",
schemaVersion: 1,
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
export const ${upper}_SCHEMA_METADATA = Object.freeze({
${pascal}NoRequest: Object.freeze({
schemaId: "${pascal}NoRequest",
boundary: "api-request",
owner: OWNER,
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
apiOperations: Object.freeze({
${operationId}: defineRestOperation({
method: "GET",
path: "${apiPath}",
operationId: "${operationId}",
auth: "external-session",
timeoutMs: null,
idempotency: "safe",
retry: "runtime",
requestSource: "none",
requestSchema: "${pascal}NoRequest",
responseSchema: "${pascal}ItemListPayload",
owner: OWNER,
contractVersion: 2,
protocol: "REST",
semantics: "QUERY",
replayPolicy: "SAFE",
idempotencyKeyPolicy: "NONE",
mapperId: "${pascal}ItemListMapper",
successStatuses: [200],
responseMediaTypes: ["application/json"],
maxResponseBytes: 262_144,
providerId: "PRIMARY_API",
authProfileId: "EXTERNAL_BEARER",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "${pascal}NoRequest",
pathParameterNames: [],
maxEncodedSearchBytes: 0,
}),
${pascal}ItemListPayload: Object.freeze({
schemaId: "${pascal}ItemListPayload",
boundary: "api-response",
owner: OWNER,
runtime: "zod",
schemaVersion: 1,
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
} as const);
`;
@@ -713,7 +644,8 @@ import {
} from "./${base}-schemas.ts";
/**
* The executable (V3) descriptor of ${operationId}. It belongs to the contract
* The HTTP descriptor of ${operationId}, the one place the operation is
* written: it executes, and FE-REG-API reads it. It belongs to the contract
* package pinned in \`${base}-feature-contract.ts\`: import \`@org-contracts/*\`
* only in this file (external-contract-package-single-import-path) and take
* the package's descriptor instead of this local one.
@@ -1038,12 +970,11 @@ export default function ${pascal}ListPage() {
}
function renderInputTest({ names, operationId }: Shape): string {
const { base, pascal, upper } = names;
const { base, pascal } = names;
return `import { describe, expect, it, vi } from "vitest";
import { createFailure } from "../../../src/contracts/errors.ts";
import { create${pascal}FeatureInput } from "../../../src/features/${names.id}/application/${base}-feature-api.ts";
import { ${upper}_BOUNDARY_MAPPERS } from "../../../src/features/${names.id}/contracts/${base}-mapper.ts";
import type { TelemetryPort } from "../../../src/platform/telemetry/telemetry-port.ts";
const ITEMS = Object.freeze([Object.freeze({ itemId: "item-1", name: "First item" })]);
@@ -1086,15 +1017,6 @@ describe("${names.id} application input", () => {
await expect(input.listItems()).resolves.toEqual({ ok: false, error: failure });
});
});
describe("${names.id} registry mapper", () => {
it("maps a list payload and rejects any other shape", () => {
const { map } = ${upper}_BOUNDARY_MAPPERS.${pascal}ItemListMapper;
expect(map([{ id: "item-1", name: "First item" }])).toEqual({ ok: true, value: ITEMS });
expect(map({ items: [] })).toEqual({ ok: false, code: "MAPPING_INVARIANT_REJECTED" });
});
});
`;
}
+1 -1
View File
@@ -76,7 +76,7 @@ export const COMPOSITION_WORKLOADS: readonly CompositionWorkload[] = Object.free
loadRuntime: async () =>
Object.freeze({
featureId: id,
apiContract: Object.freeze({}),
schemas: Object.freeze({}),
adapters: Object.freeze([]),
contractContributions: Object.freeze([]),
}),