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
@@ -22,7 +22,7 @@ function feature(id: string, paths: Readonly<Record<string, string>>) {
messages: {},
loadRuntime: async () => ({
featureId: id,
apiContract: {},
schemas: {},
adapters: [],
contractContributions: [],
}),
+1 -1
View File
@@ -3,7 +3,7 @@ import { defineFeatureModule } from "../../src/features/feature-module.ts";
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
const feature = defineFeatureModule({ id:"f", contracts:{featureId:"f"}, routes:{}, messages:{}, loadRuntime: async () => ({ featureId: "f", apiContract: {}, adapters: [], contractContributions: [] }) });
const feature = defineFeatureModule({ id:"f", contracts:{featureId:"f"}, routes:{}, messages:{}, loadRuntime: async () => ({ featureId: "f", schemas: {}, adapters: [], contractContributions: [] }) });
describe("module hierarchy", () => {
it("exposes only direct children and freezes copied arrays", () => {
const features = [feature];
@@ -16,7 +16,7 @@ function fakeFeature(id: string) {
messages: {},
loadRuntime: async () => ({
featureId: id,
apiContract: {},
schemas: {},
adapters: [],
contractContributions: [],
}),
+1 -1
View File
@@ -6,7 +6,7 @@ import {
const runtimeOf = async (featureId: string) => ({
featureId,
apiContract: {},
schemas: {},
adapters: [],
contractContributions: [],
});
@@ -14,7 +14,7 @@ describe("REFERENCE_FEATURE_MODULE", () => {
expect(runtime.featureId).toBe("reference-feature");
expect(runtime.adapters.length).toBeGreaterThan(0);
expect(runtime.contractContributions.length).toBeGreaterThan(0);
expect(Object.keys(runtime.apiContract.apiOperations).length).toBeGreaterThan(0);
expect(Object.keys(runtime.schemas).length).toBeGreaterThan(0);
});
it("types a feature message's parameters from its catalog placeholders", () => {
@@ -5,19 +5,20 @@ import {
parseRouteInput,
} from "../../../src/presentation/routes/route-codecs.ts";
import {
mapReferenceOperation,
mapReferenceResourcePayload,
toReferenceView,
} from "../../../src/features/reference-feature/contracts/reference-mapper.ts";
import {
validateReferencePayload,
validateReferenceRequest,
} from "../../../src/features/reference-feature/contracts/reference-schemas.ts";
CREATE_REFERENCE_RESOURCE_CONTRACT,
GET_REFERENCE_RESOURCE_CONTRACT,
LIST_REFERENCE_RESOURCES_CONTRACT,
REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION,
} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts";
import {
REFERENCE_FEATURE_CONTRACT,
REFERENCE_FEATURE_ID,
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
import { REFERENCE_API_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-api-contract.ts";
import { REFERENCE_FEATURE_ROUTE_CODECS } from "../../../src/features/reference-feature/presentation/reference-route-codecs.ts";
import type { ReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts";
import { createTestApplication } from "../../helpers/create-test-application.ts";
@@ -85,31 +86,24 @@ describe("reference feature boundary contracts", () => {
),
).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" });
expect(
validateReferencePayload("ReferenceResourceListPayload", [
LIST_REFERENCE_RESOURCES_CONTRACT.contract.outputValidator.safeParse([
{ id: "unsafe", name: 42 },
]),
).toMatchObject({ success: false });
expect(
mapReferenceOperation("LIST_REFERENCE_RESOURCES", [
{ id: "unsafe", name: 42 },
]),
).toMatchObject({ ok: false });
});
it("normalizes request input and maps only owned domain fields", () => {
expect(
validateReferenceRequest("CreateReferenceResourceCommand", {
CREATE_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.safeParse({
name: " Example ",
}),
).toMatchObject({ success: true, data: { name: "Example" } });
const model = mapReferenceOperation("CREATE_REFERENCE_RESOURCE", {
const model = mapReferenceResourcePayload({
id: "reference-1",
name: "Example",
createdAt: "2026-07-26T00:00:00.000Z",
});
if (!model.ok || !("id" in model.value)) {
throw new Error("expected one model");
}
if (!model.ok) throw new Error("expected one model");
expect(toReferenceView(model.value)).toEqual({
resourceId: "reference-1",
title: "Example",
@@ -124,20 +118,24 @@ describe("reference feature boundary contracts", () => {
"REFERENCE_RESOURCE_FORM",
"REFERENCE_RESOURCE_STATUS",
]);
expect(Object.keys(REFERENCE_API_CONTRACT.apiOperations)).toEqual([
"LIST_REFERENCE_RESOURCES",
"CREATE_REFERENCE_RESOURCE",
"GET_REFERENCE_RESOURCE",
]);
expect(
REFERENCE_API_CONTRACT.apiOperations.GET_REFERENCE_RESOURCE,
).toMatchObject({
pathSchema: "ReferenceResourceParams",
pathParameterNames: ["resourceId"],
providerId: "PRIMARY_API",
authProfileId: "EXTERNAL_BEARER",
csrfProfileId: "NO_CSRF_BEARER",
REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION.http.map(
({ contract }) => contract.operationId,
),
).toEqual([
"LIST_REFERENCE_RESOURCES",
"GET_REFERENCE_RESOURCE",
"CREATE_REFERENCE_RESOURCE",
]);
expect(GET_REFERENCE_RESOURCE_CONTRACT.contract).toMatchObject({
pathTemplate: "/api/reference-resources/{resourceId}",
});
expect(GET_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.schemaId).toBe(
"ReferenceResourceParams",
);
expect(GET_REFERENCE_RESOURCE_CONTRACT.frontend.authProfileId).toBe(
"EXTERNAL_BEARER",
);
});
it("contributes an identity-based invalidation graph and an explicit wire version", () => {
@@ -4,17 +4,10 @@ import {
CREATE_REFERENCE_RESOURCE_CONTRACT,
LIST_REFERENCE_RESOURCES_CONTRACT,
} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts";
import {
REFERENCE_RUNTIME_SCHEMA_CODECS,
validateReferencePayload,
validateReferenceRequest,
} from "../../../src/features/reference-feature/contracts/reference-schemas.ts";
/**
* Q-6.7-8 characterization. The reference feature exposes one schema through
* two protocols: the canonical `RuntimeValidator` (array paths) for the HTTP
* contract and the registry-facing `RuntimeSchemaCodec` (dotted paths). Both
* must keep answering exactly this after they share one zod wrapper.
* Q-6.7-8 characterization. The reference feature's schemas answer through the
* canonical `RuntimeValidator` protocol (array paths) of its HTTP contract.
*/
describe("reference validator protocols", () => {
const badList = [{ id: "unsafe", name: 42 }];
@@ -34,55 +27,4 @@ describe("reference validator protocols", () => {
}),
).toEqual({ success: true, data: { name: "Example" } });
});
it("answers the schema codec with dotted paths", () => {
const codecs = REFERENCE_RUNTIME_SCHEMA_CODECS;
expect(codecs.ReferenceResourceListPayload.parse(badList)).toEqual({
success: false,
issues: [{ path: "0.name", code: "invalid_type" }],
});
expect(
codecs.CreateReferenceResourceCommand.parse({ name: "a", extra: 1 }),
).toEqual({
success: false,
issues: [{ path: "", code: "unrecognized_keys" }],
});
expect(
codecs.ReferenceResourceListQuery.parse({ limit: "5", tags: "open" }),
).toEqual({ success: true, data: { limit: 5, tags: ["open"] } });
expect(Object.keys(codecs)).toEqual([
"ReferenceResourceParams",
"ReferenceResourceListQuery",
"NoRequest",
"CreateReferenceResourceCommand",
"ReferenceResourceListPayload",
"ReferenceResourcePayload",
]);
for (const [schemaId, codec] of Object.entries(codecs)) {
expect(codec.schemaId).toBe(schemaId);
}
});
it("keeps the payload and request lookups apart", () => {
expect(validateReferencePayload("ReferenceResourceListPayload", badList))
.toEqual({
success: false,
issues: [{ path: "0.name", code: "invalid_type" }],
});
expect(validateReferencePayload("NoRequest", {})).toEqual({
success: false,
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }],
});
expect(
validateReferenceRequest("CreateReferenceResourceCommand", {
name: " Example ",
}),
).toEqual({ success: true, data: { name: "Example" } });
expect(
validateReferenceRequest("ReferenceResourcePayload", {}),
).toEqual({
success: false,
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }],
});
});
});
+1 -6
View File
@@ -123,12 +123,7 @@ export const FIXTURE_FEATURE_MODULE = defineFeatureModule({
loadRuntime: async () =>
Object.freeze({
featureId: FIXTURE_FEATURE_ID,
apiContract: Object.freeze({
apiOperations: Object.freeze({}),
schemas: Object.freeze({}),
runtimeSchemas: Object.freeze({}),
mappers: Object.freeze({}),
}),
schemas: Object.freeze({}),
adapters: Object.freeze([]),
contractContributions: Object.freeze([]),
}),
+1 -6
View File
@@ -83,12 +83,7 @@ function layoutFeature(featureId: string, specs: readonly RouteSpec[]) {
loadRuntime: async () =>
Object.freeze({
featureId,
apiContract: Object.freeze({
apiOperations: Object.freeze({}),
schemas: Object.freeze({}),
runtimeSchemas: Object.freeze({}),
mappers: Object.freeze({}),
}),
schemas: Object.freeze({}),
adapters: Object.freeze([]),
contractContributions: Object.freeze([]),
}),
+80
View File
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import { projectApiOperationRows } from "../../src/contracts/api-operations.ts";
import { composeContractContributions } from "../../src/contracts/external-contract-runtime.ts";
import {
API_OPERATIONS,
COMPOSED_CONTRACT_CONTRIBUTIONS,
} from "../../src/features/loaded-feature-runtimes.ts";
import {
TEST_CONTRACT_CONTRIBUTION,
TEST_LIST_HTTP_CONTRACT,
} from "../helpers/external-contract-fixture.ts";
/**
* FE-REG-API rows are projected from the installed HTTP descriptors, so an
* operation is written once and the governed row cannot disagree with what
* executes.
*/
describe("FE-REG-API rows projected from HTTP descriptors", () => {
it("projects each descriptor with its feature, wire and schema identities", () => {
const rows = projectApiOperationRows(
composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).contributions,
);
expect(Object.keys(rows)).toEqual([
"TEST_LIST_ENTITIES",
"TEST_GET_ENTITY",
"TEST_CREATE_ENTITY",
]);
expect(rows.TEST_LIST_ENTITIES).toEqual({
operationId: "TEST_LIST_ENTITIES",
featureId: "test-feature",
method: "GET",
path: "/api/test-entities",
authProfileId: "ANONYMOUS",
retrySemantics: "SAFE",
requestBody: "NONE",
responseBody: "REQUIRED_JSON",
responseEnvelope: "NONE",
requestSchema: "TestEntityListQuery",
responseSchema: "TestEntityListPayload",
problemSchema: "TestProblem",
});
expect(rows.TEST_CREATE_ENTITY).toMatchObject({
method: "POST",
retrySemantics: "KEYED",
requestBody: "JSON",
});
});
it("carries an Envelope declaration", () => {
const rows = projectApiOperationRows(
composeContractContributions([
{
...TEST_CONTRACT_CONTRIBUTION,
http: [
{
...TEST_LIST_HTTP_CONTRACT,
contract: {
...TEST_LIST_HTTP_CONTRACT.contract,
responseEnvelope: "ENVELOPE_V1" as const,
},
},
] as never,
},
]).contributions,
);
expect(rows.TEST_LIST_ENTITIES?.responseEnvelope).toBe("ENVELOPE_V1");
});
it("is what the registry governance reads for the installed features", () => {
expect(API_OPERATIONS).toEqual(
projectApiOperationRows(COMPOSED_CONTRACT_CONTRIBUTIONS.contributions),
);
expect(Object.keys(API_OPERATIONS).sort()).toEqual(
[...COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.keys()].sort(),
);
});
});
-122
View File
@@ -1,122 +0,0 @@
import { describe, expect, it } from "vitest";
import {
composeApiOperations,
defineRestOperation,
type RestOperationV2,
} from "../../src/contracts/api-operations.ts";
import { API_OPERATIONS } from "../../src/features/loaded-feature-runtimes.ts";
function operation(operationId = "GET_RESOURCE") {
return defineRestOperation({
contractVersion: 2,
protocol: "REST",
semantics: "QUERY",
method: "GET",
path: "/resources/{resourceId}",
operationId,
auth: "external-session",
timeoutMs: 5_000,
idempotency: "safe",
retry: "runtime",
replayPolicy: "SAFE",
idempotencyKeyPolicy: "NONE",
requestSource: "none",
requestSchema: "NoRequest",
responseSchema: "ResourcePayload",
mapperId: "ResourceMapper",
successStatuses: [200],
responseMediaTypes: ["application/json"],
maxResponseBytes: 32_768,
providerId: "PRIMARY_API",
authProfileId: "EXTERNAL_BEARER",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "ResourceParams",
pathParameterNames: ["resourceId"],
maxEncodedSearchBytes: 0,
owner: "test",
});
}
describe("REST operation v2 registry", () => {
it("rejects duplicate contributions before an object spread can overwrite them", () => {
const selected = operation();
expect(() =>
composeApiOperations([
{ GET_RESOURCE: selected },
{ GET_RESOURCE: selected },
]),
).toThrow("Duplicate API operation");
});
it("rejects an unsafe query/replay policy combination", () => {
expect(() =>
defineRestOperation({
...operation(),
method: "POST",
}),
).toThrow("Incoherent REST replay contract");
});
// 07-06 (MX5). A KEYED command without a required idempotency key would be
// resent with no key to bind the retry to.
it("rejects a KEYED_COMMAND whose idempotency key is not required", () => {
expect(() =>
defineRestOperation({ ...command(), idempotencyKeyPolicy: "NONE" }),
).toThrow("Incoherent REST replay contract: CREATE_RESOURCE");
expect(defineRestOperation(command()).idempotencyKeyPolicy).toBe("REQUIRED");
});
});
function command(): RestOperationV2 {
return {
...operation(),
semantics: "COMMAND",
method: "POST",
path: "/resources",
operationId: "CREATE_RESOURCE",
idempotency: "keyed",
replayPolicy: "KEYED_COMMAND",
idempotencyKeyPolicy: "REQUIRED",
requestSource: "body",
pathSchema: "NoRequest",
pathParameterNames: [],
};
}
/**
* R-7.4. CSRF protection is chosen from the HTTP method, so a COMMAND sent
* as GET/HEAD would skip it. browser-rpc and the V3 composition already bind
* commands to unsafe methods; REST V2 must too.
*/
describe("REST operation v2 command method and enum rules", () => {
it.each(["POST", "PUT", "PATCH", "DELETE"])("accepts a COMMAND sent as %s", (method) => {
expect(defineRestOperation({ ...command(), method }).method).toBe(method);
});
it.each(["GET", "HEAD", "OPTIONS", "post"])("rejects a COMMAND sent as %s", (method) => {
expect(() => defineRestOperation({ ...command(), method })).toThrow(TypeError);
expect(() =>
composeApiOperations([{ CREATE_RESOURCE: { ...command(), method } }]),
).toThrow(TypeError);
});
it.each<[string, Record<string, unknown>]>([
["semantics", { semantics: "SUBSCRIBE" }],
["replayPolicy", { replayPolicy: "ALWAYS" }],
])("rejects an unknown %s value", (_field, patch) => {
void _field;
const candidate = { ...command(), ...patch } as unknown as RestOperationV2;
expect(() => defineRestOperation(candidate)).toThrow(TypeError);
});
it("keeps every installed REST v2 operation valid", () => {
for (const installed of Object.values(API_OPERATIONS)) {
if (installed.contractVersion !== 2) continue;
expect(
() => defineRestOperation(installed as RestOperationV2),
installed.operationId,
).not.toThrow();
}
});
});
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getApiOperation } from "../../src/contracts/api-operations.ts";
import { mapWithBoundaryRegistry } from "../../src/contracts/boundary-mapper.ts";
import {
isAllowedOfflineTransition,
@@ -17,12 +16,6 @@ import { getStorageDefinition } from "../../src/contracts/storage-keys.ts";
const INHERITED = ["constructor", "__proto__", "toString", "hasOwnProperty"];
describe("registry lookups ignore inherited keys", () => {
it("getApiOperation", () => {
for (const id of INHERITED) {
expect(() => getApiOperation(id), id).toThrow("Unregistered API operation");
}
});
it("getStorageDefinition", () => {
for (const id of INHERITED) {
expect(() => getStorageDefinition(id), id).toThrow(
@@ -1,97 +0,0 @@
import { describe, expect, it } from "vitest";
import type {
ApiOperation,
RestOperationV2,
} from "../../src/contracts/api-operations.ts";
import {
API_OPERATIONS,
INSTALLED_CONTRACT_CONTRIBUTIONS,
} from "../../src/features/loaded-feature-runtimes.ts";
// 07-03 (D-7), 07-02. FE-REG-API governs the V2 rows while the V3 descriptors
// are what executes. Until V2 is generated from V3, both copies must agree.
const RETRY_SEMANTICS_FOR_REPLAY_POLICY = Object.freeze({
SAFE: "SAFE",
IDEMPOTENT: "IDEMPOTENT",
KEYED_COMMAND: "KEYED",
NON_REPLAYABLE: "NEVER",
} as const);
const v3ByOperationId = new Map(
INSTALLED_CONTRACT_CONTRIBUTIONS.flatMap((contribution) =>
contribution.http.map(
(descriptor) => [descriptor.contract.operationId, descriptor] as const,
),
),
);
const v2Rows = (Object.values(API_OPERATIONS) as readonly ApiOperation[]).filter(
(operation): operation is RestOperationV2 => operation.contractVersion === 2,
);
// V3 validates the whole canonical input with one schema; V2 splits it into a
// path schema and a request (search or body) schema. The row says which of
// the two carry input: path parameters, and a request source other than
// "none". The other one names the feature's empty-input schema, whatever the
// feature calls it (schema ids are global, so a second feature cannot reuse
// the sample's `NoRequest`). An operation that needs both has no rule yet and
// fails here until one is written down.
function v2InputSchema(row: RestOperationV2): string {
const declared = [
...(row.pathParameterNames.length > 0 ? [row.pathSchema] : []),
...(row.requestSource !== "none" ? [row.requestSchema] : []),
];
expect(
declared.length,
`${row.operationId}: V2 declares both a path and a request schema; decide which V3 input schema matches them`,
).toBeLessThanOrEqual(1);
return declared[0] ?? row.requestSchema;
}
describe("HTTP operation V2 rows and V3 descriptors", () => {
// 07-02. Both directions: a V3-only operation executes outside the
// FE-REG-API gate, a V2-only one is governed but never executes. With the
// sample feature removed both sets are empty, which is why there is no
// "at least one row" assertion (test:sample-removal runs this file).
it("cover the same operations", () => {
expect([...v3ByOperationId.keys()].sort(), "V3 descriptors").toEqual(
v2Rows.map((row) => row.operationId).sort(),
);
});
it("declare the same method, path, statuses, limit, auth profile, replay policy, write semantics, request body and schema ids", () => {
for (const row of v2Rows) {
const descriptor = v3ByOperationId.get(row.operationId);
expect(descriptor, `${row.operationId} has no V3 descriptor`).toBeDefined();
if (!descriptor) continue;
expect(
{
method: descriptor.contract.method,
path: descriptor.contract.pathTemplate,
successStatuses: [...descriptor.contract.acceptedStatuses],
maxResponseBytes: descriptor.frontend.responseByteLimit,
authProfileId: descriptor.frontend.authProfileId,
retrySemantics: descriptor.contract.retrySemantics,
// The executor treats an operation as a write by its effect
// descriptor, not by its method.
semantics: descriptor.contract.commandEffect === null ? "QUERY" : "COMMAND",
requestBody: descriptor.contract.requestBody,
inputSchema: descriptor.contract.inputValidator.schemaId,
responseSchema: descriptor.contract.outputValidator.schemaId,
},
row.operationId,
).toEqual({
method: row.method,
path: row.path,
successStatuses: [...row.successStatuses],
maxResponseBytes: row.maxResponseBytes,
authProfileId: row.authProfileId,
retrySemantics: RETRY_SEMANTICS_FOR_REPLAY_POLICY[row.replayPolicy],
semantics: row.semantics,
requestBody: row.requestSource === "body" ? "JSON" : "NONE",
inputSchema: v2InputSchema(row),
responseSchema: row.responseSchema,
});
}
});
});
+10 -24
View File
@@ -2,7 +2,7 @@ import {
mappingSuccess,
type InstalledBoundaryMapper,
} from "../../../src/contracts/boundary-mapper.ts";
import type { ApiOperation } from "../../../src/contracts/api-operations.ts";
import type { ApiOperationRow } from "../../../src/contracts/api-operations.ts";
import {
createRealtimePolicyRegistry,
defineEventTypeId,
@@ -102,33 +102,19 @@ export const TEST_MAPPERS = Object.freeze({
ReferenceRealtimeMapper: TEST_MAPPER,
});
const snapshotOperation: ApiOperation = Object.freeze({
const snapshotOperation: ApiOperationRow = Object.freeze({
operationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
featureId: "sample-feature",
method: "GET",
path: "/api/reference-snapshot",
operationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
auth: "external-session",
timeoutMs: 10_000,
idempotency: "safe",
retry: "never",
requestSource: "none",
authProfileId: "EXTERNAL_BEARER",
retrySemantics: "SAFE",
requestBody: "NONE",
responseBody: "REQUIRED_JSON",
responseEnvelope: "NONE",
requestSchema: "NoRequest",
responseSchema: "ReferenceRealtimeCheckpoint",
owner: "sample-owner",
contractVersion: 2,
protocol: "REST",
semantics: "QUERY",
replayPolicy: "SAFE",
idempotencyKeyPolicy: "NONE",
mapperId: "ReferenceRealtimeSnapshotMapper",
successStatuses: [200],
responseMediaTypes: ["application/json"],
maxResponseBytes: 16_384,
providerId: "PRIMARY_API",
authProfileId: "EXTERNAL_SESSION",
csrfProfileId: "NONE",
pathSchema: "NoRequest",
pathParameterNames: [],
maxEncodedSearchBytes: 0,
problemSchema: "ReferenceRealtimeProblem",
});
export const TEST_API_OPERATIONS = Object.freeze({
+10 -155
View File
@@ -3,177 +3,32 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
import { defineRestOperation } from "../../src/contracts/api-operations.ts";
import {
composeContractContributions,
ContractContributionError,
} from "../../src/contracts/external-contract-runtime.ts";
import {
createRestProviderProfile,
INSTALLED_REST_AUTH_PROFILES,
installRestAuthProfileRegistry,
resolveRestSecurityProfiles,
REST_AUTH_PROFILES,
validateRestProfileBindings,
} from "../../src/contracts/rest-profiles.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
/**
* §24.12: the common REST profile contract must stay independently verifiable
* after the sample feature is removed, so this suite owns its own operation
* fixture instead of importing an installed feature contract.
*/
const SAMPLE_COMMAND = defineRestOperation({
method: "POST",
path: "/api/sample-resources",
operationId: "CREATE_SAMPLE_RESOURCE",
auth: "external-session",
timeoutMs: null,
idempotency: "keyed",
retry: "runtime",
requestSource: "body",
requestSchema: "SampleCommand",
responseSchema: "SamplePayload",
owner: "platform-test-fixture",
contractVersion: 2,
protocol: "REST",
semantics: "COMMAND",
replayPolicy: "KEYED_COMMAND",
idempotencyKeyPolicy: "REQUIRED",
mapperId: "SampleMapper",
successStatuses: [200, 201],
responseMediaTypes: ["application/json"],
maxResponseBytes: 32_768,
providerId: "PRIMARY_API",
authProfileId: "EXTERNAL_BEARER",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "NoRequest",
pathParameterNames: [],
maxEncodedSearchBytes: 0,
});
const SAMPLE_OPERATIONS = Object.freeze({
CREATE_SAMPLE_RESOURCE: SAMPLE_COMMAND,
});
describe("REST provider/auth/CSRF profiles", () => {
it("preserves the provider prefix and rejects unsafe endpoint forms", () => {
expect(
createRestProviderProfile(
"PRIMARY_API",
"https://api.test/base/",
["omit"],
),
).toMatchObject({
providerId: "PRIMARY_API",
baseUrl: "https://api.test/base/",
redirect: "error",
referrerPolicy: "no-referrer",
});
expect(() =>
createRestProviderProfile(
"PRIMARY_API",
"https://user:password@api.test/base/",
),
).toThrow("Invalid REST provider profile");
expect(() =>
createRestProviderProfile("PRIMARY_API", "http://api.test/base/"),
).toThrow("Invalid REST provider profile");
});
it("resolves bearer auth to omit credentials and no CSRF", () => {
const resolved = resolveRestSecurityProfiles(
SAMPLE_COMMAND,
createRestProviderProfile("PRIMARY_API", "https://api.test", ["omit"]),
);
expect(resolved).toMatchObject({
auth: {
transport: "BEARER_HEADER",
credentials: "omit",
allowedCredentialHeaders: ["authorization"],
},
csrf: { mode: "NONE" },
});
});
it("validates every installed profile binding as a set", () => {
expect(
validateRestProfileBindings(SAMPLE_OPERATIONS, {
PRIMARY_API: ["omit"],
}),
).toBe(true);
expect(() =>
validateRestProfileBindings(SAMPLE_OPERATIONS, {}),
).toThrow("Unregistered REST provider binding");
});
// 16-03. A copied feature that renamed the sample's profile id stopped every
// gate with one sentence that named neither the operation nor the profile.
it("names the operation, the profile and the broken condition", () => {
const renamed = Object.freeze({
CREATE_SAMPLE_RESOURCE: {
...SAMPLE_COMMAND,
authProfileId: "ORDER_EXTERNAL_BEARER",
},
});
expect(() =>
validateRestProfileBindings(renamed, { PRIMARY_API: ["omit"] }),
).toThrow(
/incoherent.*CREATE_SAMPLE_RESOURCE.*unknown authProfileId ORDER_EXTERNAL_BEARER/,
);
const publicWithBearer = Object.freeze({
CREATE_SAMPLE_RESOURCE: { ...SAMPLE_COMMAND, auth: "none" as const },
});
expect(() =>
validateRestProfileBindings(publicWithBearer, { PRIMARY_API: ["omit"] }),
).toThrow(
/CREATE_SAMPLE_RESOURCE.*auth "none" needs an ANONYMOUS profile.*EXTERNAL_BEARER is BEARER_HEADER/,
);
});
});
/**
* Q-6.7-9. Composition, the V3 executor and the V2 resolve must all answer
* from one validated installed registry. A raw record handed to resolve used
* to skip installation, so a bearer profile with ambient credentials passed.
*/
describe("one installed REST auth profile registry", () => {
const provider = createRestProviderProfile("PRIMARY_API", "https://api.test", [
"omit",
"same-origin",
]);
it("rejects a raw profile record that installation would refuse", () => {
const incoherent = {
EXTERNAL_BEARER: {
...REST_AUTH_PROFILES.EXTERNAL_BEARER,
credentials: "same-origin" as const,
},
};
it("refuses a raw profile record that is incoherent", () => {
expect(() =>
resolveRestSecurityProfiles(SAMPLE_COMMAND, provider, incoherent),
installRestAuthProfileRegistry({
EXTERNAL_BEARER: {
...REST_AUTH_PROFILES.EXTERNAL_BEARER,
credentials: "same-origin" as const,
},
}),
).toThrow(TypeError);
});
it("resolves through the installed registry", () => {
expect(
resolveRestSecurityProfiles(
SAMPLE_COMMAND,
provider,
INSTALLED_REST_AUTH_PROFILES,
).auth,
).toBe(INSTALLED_REST_AUTH_PROFILES.get("EXTERNAL_BEARER"));
});
it("does not resolve an inherited profile id", () => {
expect(() =>
resolveRestSecurityProfiles(
{ ...SAMPLE_COMMAND, authProfileId: "toString" },
provider,
REST_AUTH_PROFILES,
),
).toThrow("incoherent");
it("does not answer for an inherited profile id", () => {
expect(INSTALLED_REST_AUTH_PROFILES.has("toString")).toBe(false);
expect(INSTALLED_REST_AUTH_PROFILES.get("toString")).toBeUndefined();
});
it("composes contributions against the registry it is given", () => {
@@ -23,13 +23,18 @@ const FEATURE_ID = "second-api-feature";
const CONTEXT_ID = "second-api-context";
const TOPIC_ID = "qinv.01kb3m8q2v6t4r9s1n5p7c0w";
const FEATURE_CONTRACT = `import { defineRestOperation } from "../../../contracts/api-operations.ts";
import type { InstalledBoundaryMapper } from "../../../contracts/boundary-mapper.ts";
import { mappingFailure, mappingSuccess } from "../../../contracts/boundary-mapper.ts";
const FEATURE_CONTRACT = `import {
PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,
PLACEHOLDER_CONTRACT_PACKAGE_REVISION,
PLACEHOLDER_CONTRACT_PACKAGE_VERSION,
} from "../../../contracts/deployment-admission.ts";
import type {
InstalledContractContribution,
InstalledHttpContract,
} from "../../../contracts/external-contract-runtime.ts";
import { unvalidatedPayload } from "../../../contracts/unvalidated-payload.ts";
import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts";
import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts";
import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
const OWNER = "feature-frontend-second-api-feature";
const SECOND_ITEM_TOPIC = defineQueryInvalidationTopic("${TOPIC_ID}");
@@ -38,10 +43,16 @@ const SECOND_ITEM_NAMESPACE = defineQueryNamespaceIdentity("second-item", 1);
const schema = (schemaId: string, boundary: string, direction: string) =>
Object.freeze({ schemaId, boundary, owner: OWNER, runtime: "zod", schemaVersion: 1, direction });
const codec = (schemaId: string) =>
runtimeSchemaCodecFromValidator(
unvalidatedPayload(schemaId, "registry fixture: only check-registries reads it"),
);
const unchecked = (schemaId: string) =>
unvalidatedPayload(schemaId, "registry fixture: only check-registries reads it");
const SECOND_CONTRACT_PACKAGE = Object.freeze({
packageId: "@org-contracts/second-api",
version: PLACEHOLDER_CONTRACT_PACKAGE_VERSION,
digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,
runtimeProtocolVersion: 1 as const,
sourceRevision: PLACEHOLDER_CONTRACT_PACKAGE_REVISION,
});
const ROUTES = Object.freeze({
SECOND_ITEM_LIST: Object.freeze({
@@ -81,66 +92,57 @@ export const SECOND_API_CONTRACT = Object.freeze({
topicVersions: Object.freeze([
Object.freeze({ topicId: SECOND_ITEM_TOPIC, topicVersion: 1 }),
]),
contractPackages: Object.freeze([]),
contractPackages: Object.freeze([SECOND_CONTRACT_PACKAGE]),
} as const);
// Runtime half: the V2 API contract, loaded with feature-runtime.ts.
export const SECOND_API_V2_CONTRACT = Object.freeze({
apiOperations: Object.freeze({
GET_SECOND_ITEM: defineRestOperation({
method: "GET",
path: "/api/second-items/{itemId}",
operationId: "GET_SECOND_ITEM",
auth: "none",
timeoutMs: null,
idempotency: "safe",
retry: "runtime",
requestSource: "none",
requestSchema: "SecondItemRequest",
responseSchema: "SecondItemPayload",
owner: OWNER,
contractVersion: 2,
protocol: "REST",
semantics: "QUERY",
replayPolicy: "SAFE",
idempotencyKeyPolicy: "NONE",
mapperId: "SecondItemMapper",
successStatuses: [200],
responseMediaTypes: ["application/json"],
maxResponseBytes: 16_384,
providerId: "PRIMARY_API",
authProfileId: "ANONYMOUS",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "SecondItemParams",
pathParameterNames: ["itemId"],
maxEncodedSearchBytes: 0,
}),
}),
schemas: Object.freeze({
SecondItemListQuery: schema("SecondItemListQuery", "route-search", "REQUEST"),
SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"),
SecondItemRequest: schema("SecondItemRequest", "api-request", "REQUEST"),
SecondItemPayload: schema("SecondItemPayload", "api-response", "RESPONSE"),
}),
runtimeSchemas: Object.freeze({
SecondItemListQuery: codec("SecondItemListQuery"),
SecondItemParams: codec("SecondItemParams"),
SecondItemRequest: codec("SecondItemRequest"),
SecondItemPayload: codec("SecondItemPayload"),
}),
mappers: Object.freeze({
SecondItemMapper: Object.freeze({
mapperId: "SecondItemMapper",
mapperVersion: 1,
inputSchemaId: "SecondItemPayload",
outputContractId: "SecondItem",
owner: OWNER,
maxOutputItems: 1,
map: (value: unknown) =>
value && typeof value === "object" ? mappingSuccess(value) : mappingFailure("MAPPING_INVARIANT_REJECTED"),
} satisfies InstalledBoundaryMapper),
}),
// Runtime half, loaded with feature-runtime.ts.
export const SECOND_API_SCHEMAS = Object.freeze({
SecondItemListQuery: schema("SecondItemListQuery", "route-search", "REQUEST"),
SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"),
SecondItemPayload: schema("SecondItemPayload", "api-response", "RESPONSE"),
} as const);
export const SECOND_API_CONTRIBUTION: InstalledContractContribution = Object.freeze({
contributionId: "second-api-feature-http-v1",
featureId: "${FEATURE_ID}",
source: Object.freeze({ kind: "EXTERNAL_PACKAGE" as const, package: SECOND_CONTRACT_PACKAGE }),
http: Object.freeze([
Object.freeze({
contract: Object.freeze({
operationId: "GET_SECOND_ITEM",
method: "GET" as const,
pathTemplate: "/api/second-items/{itemId}",
inputValidator: unchecked("SecondItemParams"),
outputValidator: unchecked("SecondItemPayload"),
problemValidator: unchecked("SecondItemProblem"),
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: null,
commandEffect: null,
projectRequest: (input: unknown) =>
Object.freeze({
pathValues: Object.freeze({ itemId: String((input as { itemId: string }).itemId) }),
queryEntries: Object.freeze([]),
body: null,
}),
}),
frontend: Object.freeze({
policyId: "SECOND_ITEM_V1",
requestByteLimit: 0,
responseByteLimit: 16_384,
totalDeadlineMs: 10_000,
retryBudget: 0 as const,
authProfileId: "ANONYMOUS",
diagnosticsOperation: "second.item",
}),
}),
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
events: Object.freeze([]),
});
`;
const FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts";
@@ -159,13 +161,16 @@ export const FEATURE_MODULE = defineFeatureModule({
`;
const FEATURE_RUNTIME = `import { defineFeatureRuntime } from "../feature-module.ts";
import { SECOND_API_V2_CONTRACT } from "./contracts/second-api-contract.ts";
import {
SECOND_API_CONTRIBUTION,
SECOND_API_SCHEMAS,
} from "./contracts/second-api-contract.ts";
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: "${FEATURE_ID}",
apiContract: SECOND_API_V2_CONTRACT,
schemas: SECOND_API_SCHEMAS,
adapters: [],
contractContributions: [],
contractContributions: [SECOND_API_CONTRIBUTION],
} as const);
`;
@@ -58,7 +58,7 @@ declare module "../../application/ports/in/application-api.ts" {
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: "second-feature",
apiContract: { apiOperations: {}, schemas: {}, runtimeSchemas: {}, mappers: {} },
schemas: {},
adapters: [
defineFeatureAdapterContribution({
featureId: "second-feature",
@@ -126,7 +126,7 @@ export const FEATURE_MODULE = defineFeatureModule({
messages: { "ko-KR": MESSAGES, "en-US": MESSAGES },
loadRuntime: async () => ({
featureId: FEATURE_MODULE_ID,
apiContract: { apiOperations: {}, schemas: {}, runtimeSchemas: {}, mappers: {} },
schemas: {},
adapters: [],
contractContributions: [],
}),