Files
clean-architecture-frontend…/src/contracts/external-contract-runtime.ts
T
DongHyeonka 7db32e1343 fix(http): V3 실행기가 짝 백엔드 Envelope를 operation 단위로 읽는다
문제
create:feature가 만든 기능과 참조 기능이 쓰는 V3 실행기
(http-execution-v3.ts, feature-http-binding.ts)는 성공 본문을 DTO로,
실패 본문을 problem details(최상위 code)로 바로 검증한다. 짝 백엔드는
모든 JSON 응답을 Envelope {success, data|error, meta}로 보내고 null 필드는
키째 뺀다(백엔드 docs/web/http-contract.md 1절). 그래서 생성한 기능은 짝
백엔드의 성공을 SCHEMA_MISMATCH로, 실패를 PROBLEM_SCHEMA_INVALID(쓰기는
결과 불명)로 읽는다. 백엔드 맞추기(969979d~64e98ee)는 V2 클라이언트에만
들어갔다.

고른 방법: (가) V3 실행기에 operation 단위 Envelope 읽기
- V3 descriptor에 선택 필드 responseEnvelope("NONE" | "ENVELOPE_V1")를
  둔다. 조립은 이 키를 허용하고 모르는 값을 거부한다. 값이 없으면 지금과
  같다.
- ENVELOPE_V1이면 실행기가 바이트 상한·구조 예산을 Envelope 전체에 건 뒤
  프레임을 확인한다. outputValidator는 data(키가 없으면 null),
  problemValidator는 error를 받는다. 성공 status에 Envelope가 아닌 본문은
  새 위반 ENVELOPE_MISMATCH다. 실패 Envelope의 바이트 상한은
  min(64 KiB, responseByteLimit)이다.
- V2 client.ts의 멱등성 거절 표·필드 검증 판정·gateway status 규칙을
  backend-envelope.ts로 옮기고 V2, V3 실행기, feature binding이 함께
  읽는다. 실행기는 그 표의 판정(422·400 거절, 필드 목록 400은 적용 안 됨,
  409 IDEMPOTENT_IN_FLIGHT·503 IDEMPOTENCY_UNAVAILABLE은 결과 불명)을
  classifyProblem보다 먼저 쓴다. binding은 mapProblem이 답하지 않으면 V2와
  같은 kind·code·validationIssues로 읽는다. V2 출력은 바뀌지 않았다.
- create:feature 뼈대: contribution이 ENVELOPE_V1을 선언하고 problem
  스키마가 Envelope error(code 필수)다. 백엔드 본문을 그대로 적은
  <base>-http-gateway.test.ts를 생성한다.
- MSW createHttpScenarioHandler는 descriptor가 ENVELOPE_V1이면 Envelope로
  답한다.

버린 대안
- provider 단위(실행기 전체): V3 실행기는 baseUrl 하나라 앱 전체가 바뀐다.
  참조 기능·테스트 계약의 problem details fixture가 모두 깨지고 한 앱이 두
  모양의 API를 쓸 수 없다.
- (나) 백엔드 problem+json·DTO 모드: 백엔드 소유자 결정 2(JSON은 모두
  Envelope)와 반대이고 백엔드가 두 모양을 계속 유지해야 한다.
- (다) 기능 스키마가 Envelope를 감쌈: 기능마다 null 생략·success 판별·
  멱등성 판정을 다시 쓰고, V2 행(data 스키마)과 V3 스키마 ID가 갈라진다.

위험·한계
- HttpContractViolationKind에 ENVELOPE_MISMATCH가 더해졌다. default 없는
  exhaustive switch는 분기를 더해야 한다.
- 실행기가 ENVELOPE_V1 operation의 위 판정을 classifyProblem보다 먼저
  정한다. 패키지가 409 IDEMPOTENT_IN_FLIGHT를 적용 안 됨이라 해도 결과
  불명이다.
- V2와 남은 차이: 64 KiB를 넘는 실패 Envelope는 V3만 읽지 않는다. 보낸
  KEYED 요청의 503은 V2만 같은 키로 자동 재시도한다(판정은 같다). 구조
  예산은 V3에만 있다.
- 참조 기능은 그대로 DTO·problem details다. tests/e2e/accessibility.spec.ts는
  모든 API에 []로 답하므로 생성한 기능 라우트는 오류 화면이 검사된다(e2e는
  돌리지 않았다).
- 초기 JS 202,770 → 203,321 B(+551 B, 예산 204,800 B).

검증
- RED: tests/integration/http-execution-v3-envelope.test.ts 19건 중 17건
  실패(성공 → SCHEMA_MISMATCH, 실패 → PROBLEM_SCHEMA_INVALID·MAYBE_APPLIED,
  조립 → unexpected key: responseEnvelope). 크기 2건은 처음부터 통과(동작
  고정).
- GREEN: 같은 파일 25건 통과. 같은 응답을 V2와 V3에 보내 kind·code·
  httpStatus·effect·retryAfterMs·validationIssues가 같음을 7가지 응답으로
  비교한다.
- check:types, lint, check:architecture, check:adapter-inventory,
  check:registries, check:diagnostics, check:i18n, check:ci 통과.
  test:unit 2,604, test:component 244, test:integration 200 통과.
  tests/features·tests/contract 124건 통과.
  test:feature-scaffold 16개 검사 통과(생성한 gateway 테스트 5건,
  Envelope로 답하는 목록 화면 테스트 3건 포함).
  test:sample-removal 23개 검사 통과.
  check:bundle 통과(203,321 / 204,800 B).

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.3, 14.6
2026-11-03 20:10:51 +09:00

917 lines
31 KiB
TypeScript

/**
* External contract package consumer boundary (§4).
*
* This repository does not own OpenAPI/AsyncAPI source, operation semantics,
* Problem Details meaning or event payload schemas. It owns only the normalized
* descriptor interface, the runtime validator protocol, and the bounds it
* applies before a contribution may be composed.
*/
import { isOperationId } from "./operation-id.ts";
import {
INSTALLED_REST_AUTH_PROFILES,
type InstalledRestAuthProfiles,
} from "./rest-profiles.ts";
import {
defineTrafficBudget,
TRAFFIC_BUDGET_KEYS,
type TrafficBudget,
} from "../platform/traffic/traffic-budget.ts";
import {
createReadOnlyRegistry,
type ReadOnlyRegistry,
} from "./read-only-registry.ts";
import { exactOwnDataSnapshot, snapshotExactArray } from "./exact-snapshot.ts";
/** §7.3 hard ceilings. A contribution may lower these, never raise them. */
export const HTTP_EXECUTION_CEILINGS = Object.freeze({
defaultRequestBytes: 262_144,
hardRequestBytes: 1_048_576,
defaultResponseBytes: 1_048_576,
hardResponseBytes: 8_388_608,
problemResponseBytes: 65_536,
pathTemplateBytes: 512,
encodedQueryBytes: 8_192,
examinedHeaderValueBytes: 8_192,
defaultTotalDeadlineMs: 10_000,
hardTotalDeadlineMs: 60_000,
hardRetryCount: 2,
finalUrlBytes: 16_384,
});
/*
* D-15. The validator protocol below is the canonical shape;
* `RuntimeSchemaCodec` (`schema-registry.ts`) adapts over it. `MappingResult`
* below is the contract-package side of a mapping result. Feature mappers and
* the HTTP binding return `BoundaryMappingResult` (`boundary-mapper.ts`)
* instead, whose failure code is a closed set; `toContractMappingResult`
* converts one into this shape (07-01).
*/
export type RuntimeValidationIssue = Readonly<{
path: readonly (string | number)[];
code: string;
}>;
export type RuntimeValidationResult<T> =
| Readonly<{ success: true; data: T }>
| Readonly<{ success: false; issues: readonly RuntimeValidationIssue[] }>;
export interface RuntimeValidator<T> {
readonly schemaId: string;
/**
* 1101/07-03. Absent on a validator that checks its input. `"NONE"` marks
* one made by `unvalidatedPayload` (`unvalidated-payload.ts`), which
* accepts any value as `T`; `listUnvalidatedPayloads` lists it.
* Composition, on the boot path, does not read the marker. A hand-written
* validator that checks nothing and omits the marker is not detected.
*/
readonly validation?: "NONE";
/** Why validation is skipped. `unvalidatedPayload` requires one. */
readonly unvalidatedReason?: string;
safeParse(value: unknown): RuntimeValidationResult<T>;
}
/**
* A validator invocation never escapes as a native throw. `THROWN` is the
* `CONTRACT_RUNTIME_FAILURE` signal; `false` success is the ordinary
* `CONTRACT_VALUE_INVALID` signal.
*/
export type ValidatorInvocation<T> =
| Readonly<{ outcome: "VALID"; value: T }>
| Readonly<{ outcome: "INVALID"; issues: readonly RuntimeValidationIssue[] }>
| Readonly<{ outcome: "THROWN" }>;
export function invokeValidator<T>(
validator: RuntimeValidator<T>,
value: unknown,
): ValidatorInvocation<T> {
// 07-06. Reading the result stays inside the try: a hand-written validator
// may return any shape, including throwing getters.
try {
const result: unknown = validator.safeParse(value);
if (!result || typeof result !== "object") throw new TypeError();
const candidate = result as Readonly<Record<string, unknown>>;
if (candidate.success === true) {
return Object.freeze({
outcome: "VALID" as const,
value: candidate.data as T,
});
}
const issues = candidate.issues;
if (candidate.success !== false || !Array.isArray(issues)) {
throw new TypeError();
}
return Object.freeze({
outcome: "INVALID" as const,
issues: Object.freeze([...(issues as RuntimeValidationIssue[])]),
});
} catch {
return Object.freeze({ outcome: "THROWN" as const });
}
}
export type MappingResult<T> =
| Readonly<{ ok: true; value: T }>
| Readonly<{
ok: false;
error: Readonly<{ kind: "MAPPING_CONTRACT_VIOLATION"; code: string }>;
}>;
export function mappingViolation(code: string): MappingResult<never> {
return Object.freeze({
ok: false as const,
error: Object.freeze({
kind: "MAPPING_CONTRACT_VIOLATION" as const,
code,
}),
});
}
export type CommandRecoveryDescriptor = Readonly<{
mode: "IDEMPOTENCY_REPLAY" | "INSPECT_OPERATION";
operationIdentityField: string;
inspectOperationId?: string;
}>;
export type CommandEffectClassification =
| "NOT_APPLIED"
| "APPLIED_CONFIRMED"
| "MAYBE_APPLIED";
export interface CommandEffectDescriptor<Problem> {
readonly successEffect: "APPLIED_CONFIRMED";
classifyProblem(
input: Readonly<{ status: number; problem: Problem }>,
): CommandEffectClassification;
/**
* D-2. 401, 403 and 429 are admitted by status before any problem body is
* read. Declare `NOT_APPLIED` only when the server contract guarantees the
* command was rejected untouched. Without this, they stay `MAYBE_APPLIED`.
*/
classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED";
}
export type HttpMethod =
| "GET"
| "HEAD"
| "POST"
| "PUT"
| "PATCH"
| "DELETE";
export type RetrySemantics = "SAFE" | "IDEMPOTENT" | "KEYED" | "NEVER";
export type ResponseEnvelope = "NONE" | "ENVELOPE_V1";
export interface HttpExecutionPolicy {
readonly policyId: string;
readonly requestByteLimit: number;
readonly responseByteLimit: number;
readonly totalDeadlineMs: number;
readonly retryBudget: 0 | 1 | 2;
readonly authProfileId: string;
readonly diagnosticsOperation: string;
/**
* scale-architecture.md §11. Optional operation-owned interaction traffic policy. When a
* caller supplies no interaction `ExecutionContext`, the executor creates one
* from this policy (or the bounded platform default), so every logical
* execution carries finite request/retry/concurrency budgets.
*/
readonly traffic?: TrafficBudget;
}
export interface InstalledHttpContract<Input, WireOutput, Problem> {
readonly contract: Readonly<{
operationId: string;
method: HttpMethod;
pathTemplate: string;
inputValidator: RuntimeValidator<Input>;
outputValidator: RuntimeValidator<WireOutput>;
problemValidator: RuntimeValidator<Problem>;
acceptedStatuses: readonly number[];
emptyBodyStatuses: readonly number[];
retrySemantics: RetrySemantics;
requestBody: "NONE" | "JSON";
responseBody: "REQUIRED_JSON" | "OPTIONAL_JSON" | "NONE";
/**
* 1101 README 14.3. How the server frames a JSON body. Absent or `"NONE"`:
* the body is the DTO, and a failure body is the problem. `"ENVELOPE_V1"`:
* the paired backend's `{ success, data | error, meta }`
* (clean-architecture-backend-template docs/web/http-contract.md §1).
* `outputValidator` then sees `data` (`null` when the key is absent),
* `problemValidator` sees `error`, and the backend's operation-independent
* verdicts (§2, §4) come before `commandEffect.classifyProblem`. A body
* that is empty by `emptyBodyStatuses` has no Envelope.
*/
responseEnvelope?: ResponseEnvelope;
commandRecovery: CommandRecoveryDescriptor | null;
commandEffect: CommandEffectDescriptor<Problem> | null;
/**
* Descriptor-owned projection from canonical application input to the wire
* request. The frontend never re-derives method, path or query semantics.
*/
projectRequest(input: Input): HttpRequestProjection;
}>;
readonly frontend: HttpExecutionPolicy;
}
export type HttpRequestProjection = Readonly<{
/** Ordered path placeholder values keyed by descriptor placeholder name. */
pathValues: Readonly<Record<string, string>>;
/** Descriptor-generated query entry order; array encoding is descriptor-owned. */
queryEntries: readonly (readonly [string, string])[];
/** Canonical JSON body value, or `null` when `requestBody` is `NONE`. */
body: unknown;
}>;
export interface InstalledEventContract<Envelope, Payload> {
readonly eventType: string;
readonly envelopeValidator: RuntimeValidator<Envelope>;
readonly payloadValidator: RuntimeValidator<Payload>;
}
export interface InstalledContractPackageIdentity {
readonly packageId: string;
readonly version: string;
readonly digest: `sha256:${string}`;
readonly runtimeProtocolVersion: 1;
readonly sourceRevision: string;
}
export type ContractContributionSource =
| Readonly<{
kind: "EXTERNAL_PACKAGE";
package: InstalledContractPackageIdentity;
}>
| Readonly<{
kind: "TEMPLATE_FIXTURE";
fixtureId: "REFERENCE_FEATURE_V1";
revision: 1;
}>;
export interface InstalledContractContribution {
readonly contributionId: string;
readonly featureId: string;
readonly source: ContractContributionSource;
readonly http: readonly InstalledHttpContract<unknown, unknown, unknown>[];
readonly events: readonly InstalledEventContract<unknown, unknown>[];
}
export type ContractCompositionFailureCode =
| "CONTRACT_CONTRIBUTION_INVALID"
| "CONTRACT_RUNTIME_PROTOCOL_UNSUPPORTED";
export class ContractContributionError extends Error {
readonly code: ContractCompositionFailureCode;
readonly reason: string;
constructor(reason: string, code: ContractCompositionFailureCode = "CONTRACT_CONTRIBUTION_INVALID") {
super("Installed contract contribution is not composable");
this.name = "ContractContributionError";
this.code = code;
this.reason = reason;
}
}
// §4.9 exact validation vocabulary.
const FEATURE_ID = /^[a-z][a-z0-9-]{0,63}$/;
const CONTRIBUTION_ID = /^[a-z][a-z0-9._-]{0,127}$/;
const PACKAGE_ID =
/^@[a-z0-9][a-z0-9._-]{0,62}\/[a-z0-9][a-z0-9._-]{0,62}$/;
const SEM_VER =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
const DIGEST = /^sha256:[0-9a-f]{64}$/;
const SOURCE_REVISION = /^[0-9a-f]{7,64}$/;
/** Whitespace and C0/C1 control characters are rejected in an event type. */
function hasControlOrSpace(value: string): boolean {
for (const character of value) {
const code = character.codePointAt(0) ?? 0;
if (code <= 0x20 || (code >= 0x7f && code <= 0x9f)) return true;
}
return false;
}
const encoder = new TextEncoder();
function utf8Bytes(value: string): number {
return encoder.encode(value).byteLength;
}
function fail(reason: string): never {
throw new ContractContributionError(reason);
}
function assertPackageIdentity(
identity: InstalledContractPackageIdentity,
featureId: string,
): void {
if (!identity || typeof identity !== "object") {
fail(`${featureId}: package identity`);
}
if (identity.runtimeProtocolVersion !== 1) {
throw new ContractContributionError(
`${featureId}: runtime protocol version must be exactly 1`,
"CONTRACT_RUNTIME_PROTOCOL_UNSUPPORTED",
);
}
if (!PACKAGE_ID.test(identity.packageId)) fail(`${featureId}: packageId`);
if (
typeof identity.version !== "string" ||
identity.version !== identity.version.trim() ||
identity.version.startsWith("v") ||
!SEM_VER.test(identity.version)
) {
fail(`${featureId}: package version must be exact SemVer`);
}
if (!DIGEST.test(identity.digest)) fail(`${featureId}: package digest`);
if (!SOURCE_REVISION.test(identity.sourceRevision)) {
fail(`${featureId}: package sourceRevision`);
}
}
function assertValidator(
validator: RuntimeValidator<unknown>,
label: string,
): void {
if (
!validator ||
typeof validator.safeParse !== "function" ||
typeof validator.schemaId !== "string" ||
validator.schemaId.length === 0
) {
fail(`${label}: runtime validator with non-empty schemaId is required`);
}
}
function assertStatuses(
statuses: readonly number[],
label: string,
): void {
if (!Array.isArray(statuses)) fail(`${label}: status array required`);
if (statuses.length < 1 || statuses.length > 32) {
fail(`${label}: 1..32 statuses required`);
}
for (let index = 0; index < statuses.length; index += 1) {
const status = statuses[index] as number;
if (!Number.isInteger(status) || status < 100 || status > 599) {
fail(`${label}: status out of range`);
}
const previous = statuses[index - 1];
if (index > 0 && previous !== undefined && status <= previous) {
fail(`${label}: statuses must be sorted and unique`);
}
}
}
function assertExecutionPolicy(
policy: HttpExecutionPolicy,
label: string,
authProfiles: InstalledRestAuthProfiles,
): void {
const ceilings = HTTP_EXECUTION_CEILINGS;
if (
!policy ||
typeof policy.policyId !== "string" ||
policy.policyId.length === 0 ||
typeof policy.authProfileId !== "string" ||
policy.authProfileId.length === 0 ||
typeof policy.diagnosticsOperation !== "string" ||
policy.diagnosticsOperation.length === 0
) {
fail(`${label}: frontend execution policy identity`);
}
// §7.7 / VD-23. A declared profile that the installed registry does not own
// is a composition failure; the executor must never resolve it at runtime.
if (!authProfiles.has(policy.authProfileId)) {
fail(`${label}: unknown authProfileId ${policy.authProfileId}`);
}
if (
!Number.isSafeInteger(policy.requestByteLimit) ||
policy.requestByteLimit < 0 ||
policy.requestByteLimit > ceilings.hardRequestBytes
) {
fail(`${label}: requestByteLimit exceeds the hard ceiling`);
}
if (
!Number.isSafeInteger(policy.responseByteLimit) ||
policy.responseByteLimit < 1 ||
policy.responseByteLimit > ceilings.hardResponseBytes
) {
fail(`${label}: responseByteLimit exceeds the hard ceiling`);
}
if (
!Number.isSafeInteger(policy.totalDeadlineMs) ||
policy.totalDeadlineMs < 1 ||
policy.totalDeadlineMs > ceilings.hardTotalDeadlineMs
) {
fail(`${label}: totalDeadlineMs exceeds the hard ceiling`);
}
if (
policy.retryBudget !== 0 &&
policy.retryBudget !== 1 &&
policy.retryBudget !== 2
) {
fail(`${label}: retryBudget must be 0, 1 or 2`);
}
if (policy.traffic !== undefined) {
try {
defineTrafficBudget(policy.traffic);
} catch (error) {
fail(
`${label}: traffic policy ${error instanceof Error ? error.message : "invalid"}`,
);
}
}
}
function assertHttpContract(
installed: InstalledHttpContract<unknown, unknown, unknown>,
featureId: string,
authProfiles: InstalledRestAuthProfiles,
): void {
const contract = installed?.contract;
if (!contract || typeof contract !== "object") {
fail(`${featureId}: http contract descriptor missing`);
}
const label = `${featureId}/${String(contract.operationId)}`;
if (!isOperationId(contract.operationId)) {
fail(`${label}: operationId`);
}
if (
contract.method !== "GET" &&
contract.method !== "HEAD" &&
contract.method !== "POST" &&
contract.method !== "PUT" &&
contract.method !== "PATCH" &&
contract.method !== "DELETE"
) {
fail(`${label}: method`);
}
if (
typeof contract.pathTemplate !== "string" ||
!contract.pathTemplate.startsWith("/") ||
utf8Bytes(contract.pathTemplate) > HTTP_EXECUTION_CEILINGS.pathTemplateBytes ||
contract.pathTemplate.includes("?") ||
contract.pathTemplate.includes("#")
) {
fail(`${label}: pathTemplate`);
}
assertValidator(contract.inputValidator, `${label}.input`);
assertValidator(contract.outputValidator, `${label}.output`);
assertValidator(contract.problemValidator, `${label}.problem`);
if (typeof contract.projectRequest !== "function") {
fail(`${label}: descriptor request projection is required`);
}
if (
contract.retrySemantics !== "SAFE" &&
contract.retrySemantics !== "IDEMPOTENT" &&
contract.retrySemantics !== "KEYED" &&
contract.retrySemantics !== "NEVER"
) {
fail(`${label}: retrySemantics`);
}
if (contract.requestBody !== "NONE" && contract.requestBody !== "JSON") {
fail(`${label}: requestBody`);
}
if (
contract.responseBody !== "REQUIRED_JSON" &&
contract.responseBody !== "OPTIONAL_JSON" &&
contract.responseBody !== "NONE"
) {
fail(`${label}: responseBody`);
}
if (
contract.responseEnvelope !== undefined &&
contract.responseEnvelope !== "NONE" &&
contract.responseEnvelope !== "ENVELOPE_V1"
) {
fail(`${label}: responseEnvelope`);
}
assertStatuses(contract.acceptedStatuses, `${label}.acceptedStatuses`);
if (contract.emptyBodyStatuses.length > 0) {
assertStatuses(contract.emptyBodyStatuses, `${label}.emptyBodyStatuses`);
const accepted = new Set(contract.acceptedStatuses);
for (const status of contract.emptyBodyStatuses) {
if (!accepted.has(status)) {
fail(`${label}: empty-body status must be an accepted status`);
}
}
}
const isRead = contract.method === "GET" || contract.method === "HEAD";
if (isRead) {
if (contract.commandEffect !== null || contract.commandRecovery !== null) {
fail(`${label}: read operations carry no command descriptors`);
}
if (contract.requestBody !== "NONE") {
fail(`${label}: read operations carry no request body`);
}
} else {
if (!contract.commandEffect) {
fail(`${label}: command operations require a command effect descriptor`);
}
if (contract.commandEffect.successEffect !== "APPLIED_CONFIRMED") {
fail(`${label}: command success effect`);
}
if (typeof contract.commandEffect.classifyProblem !== "function") {
fail(`${label}: command effect classifier is required`);
}
if (
contract.commandEffect.classifyStatus !== undefined &&
typeof contract.commandEffect.classifyStatus !== "function"
) {
fail(`${label}: command status classifier must be a function`);
}
if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) {
fail(`${label}: KEYED commands require a recovery descriptor`);
}
}
if (contract.commandRecovery) {
const recovery = contract.commandRecovery;
if (
(recovery.mode !== "IDEMPOTENCY_REPLAY" &&
recovery.mode !== "INSPECT_OPERATION") ||
!recovery.operationIdentityField ||
(recovery.mode === "INSPECT_OPERATION" && !recovery.inspectOperationId)
) {
fail(`${label}: command recovery descriptor`);
}
}
assertExecutionPolicy(installed.frontend, label, authProfiles);
if (
installed.frontend.retryBudget > 0 &&
contract.retrySemantics === "NEVER"
) {
fail(`${label}: retry budget contradicts NEVER retry semantics`);
}
}
function assertEventContract(
event: InstalledEventContract<unknown, unknown>,
featureId: string,
): void {
const label = `${featureId}/${String(event?.eventType)}`;
if (
typeof event?.eventType !== "string" ||
event.eventType.length === 0 ||
utf8Bytes(event.eventType) > 160 ||
hasControlOrSpace(event.eventType)
) {
fail(`${label}: eventType`);
}
assertValidator(event.envelopeValidator, `${label}.envelope`);
assertValidator(event.payloadValidator, `${label}.payload`);
}
export type ComposedContractContributions = Readonly<{
contributions: readonly InstalledContractContribution[];
/**
* LIVE-03. Read facades over private stores. The executor resolves an
* operation on every request, so an exported `Map` would let any holder of
* the composed singleton delete or replace a validated row after boot.
*/
httpByOperationId: ReadOnlyRegistry<
string,
InstalledHttpContract<unknown, unknown, unknown>
>;
eventByType: ReadOnlyRegistry<
string,
InstalledEventContract<unknown, unknown>
>;
externalPackages: readonly InstalledContractPackageIdentity[];
}>;
const EXECUTION_POLICY_KEYS = [
"policyId",
"requestByteLimit",
"responseByteLimit",
"totalDeadlineMs",
"retryBudget",
"authProfileId",
"diagnosticsOperation",
] as const;
const EXECUTION_POLICY_ALLOWED_KEYS = [
...EXECUTION_POLICY_KEYS,
"traffic",
] as const;
const HTTP_CONTRACT_KEYS = [
"operationId",
"method",
"pathTemplate",
"inputValidator",
"outputValidator",
"problemValidator",
"acceptedStatuses",
"emptyBodyStatuses",
"retrySemantics",
"requestBody",
"responseBody",
"commandRecovery",
"commandEffect",
"projectRequest",
] as const;
const HTTP_CONTRACT_ALLOWED_KEYS = [
...HTTP_CONTRACT_KEYS,
"responseEnvelope",
] as const;
const COMMAND_RECOVERY_KEYS = [
"mode",
"operationIdentityField",
"inspectOperationId",
] as const;
/**
* LIVE-03. Composition is the last point at which a contribution row is
* trusted, so the registry keeps an exact own-data copy rather than the
* caller's object. A later mutation of the source — including one that swaps a
* deadline or a credential policy — cannot reach what the executor reads.
*
* Validators and the descriptor-owned `projectRequest` stay by reference: they
* are behaviour the contribution owns, not data this repository re-derives.
*/
function snapshotHttpContract(
installed: InstalledHttpContract<unknown, unknown, unknown>,
label: string,
): InstalledHttpContract<unknown, unknown, unknown> {
const reject = (detail: string): never => fail(`${label}: ${detail}`);
// NS-02. The outer row is snapshotted first, so every nested read below comes
// from an owned object rather than from the caller's, which could answer
// differently on a second read.
const row = exactOwnDataSnapshot<
InstalledHttpContract<unknown, unknown, unknown>
>(installed, ["contract", "frontend"], ["contract", "frontend"], reject);
const policy = exactOwnDataSnapshot<HttpExecutionPolicy>(
row.frontend,
EXECUTION_POLICY_ALLOWED_KEYS,
EXECUTION_POLICY_KEYS,
reject,
);
const frontend: HttpExecutionPolicy =
policy.traffic === undefined
? policy
: Object.freeze({
...policy,
traffic: exactOwnDataSnapshot<TrafficBudget>(
policy.traffic,
TRAFFIC_BUDGET_KEYS,
TRAFFIC_BUDGET_KEYS,
(detail) => reject(`traffic policy ${detail}`),
),
});
const source = exactOwnDataSnapshot<
InstalledHttpContract<unknown, unknown, unknown>["contract"]
>(row.contract, HTTP_CONTRACT_ALLOWED_KEYS, HTTP_CONTRACT_KEYS, reject);
const contract = Object.freeze({
...source,
acceptedStatuses: statusArray(source.acceptedStatuses, reject),
emptyBodyStatuses: statusArray(source.emptyBodyStatuses, reject),
commandRecovery:
source.commandRecovery === null
? null
: exactOwnDataSnapshot<CommandRecoveryDescriptor>(
source.commandRecovery,
COMMAND_RECOVERY_KEYS,
["mode", "operationIdentityField"],
reject,
),
});
return Object.freeze({ contract, frontend });
}
/**
* Q-6.7-6. Arrays are copied by index, never through their iterator, so an own
* `Symbol.iterator` cannot hand composition a different list than `length`
* and the indices describe.
*/
function statusArray(
value: readonly number[],
reject: (detail: string) => never,
): readonly number[] {
return (snapshotExactArray(value, 32) as readonly number[] | null) ??
reject("status array");
}
function snapshotEventContract(
event: InstalledEventContract<unknown, unknown>,
label: string,
): InstalledEventContract<unknown, unknown> {
return exactOwnDataSnapshot<InstalledEventContract<unknown, unknown>>(
event,
["eventType", "envelopeValidator", "payloadValidator"],
["eventType", "envelopeValidator", "payloadValidator"],
(detail) => fail(`${label}: ${detail}`),
);
}
/**
* §4.8–§4.9. The only place installed contributions become a runtime registry.
* Every bound is checked before composition; a violation stops the boot rather
* than degrading into an assumed meaning.
*/
export function composeContractContributions(
contributions: readonly InstalledContractContribution[],
/**
* Q-6.7-9. The registry the executor will resolve against. Pass the same
* one the executor receives; the default is the shared installed registry.
*/
authProfiles: InstalledRestAuthProfiles = INSTALLED_REST_AUTH_PROFILES,
): ComposedContractContributions {
const rows =
snapshotExactArray(contributions) ?? fail("contributions: array required");
const httpByOperationId = new Map<
string,
InstalledHttpContract<unknown, unknown, unknown>
>();
const eventByType = new Map<
string,
InstalledEventContract<unknown, unknown>
>();
const packagesById = new Map<string, InstalledContractPackageIdentity>();
const contributionIds = new Set<string>();
const installedContributions: InstalledContractContribution[] = [];
let fixtureInstalled = false;
for (const raw of rows) {
if (!raw || typeof raw !== "object") {
fail("contribution: object required");
}
// NS-02. Snapshot first, then validate the snapshot, then install exactly
// what was validated. Validating the caller's object and reading it again
// to copy it let a stateful answer pass the ceiling check and still install
// a different deadline, retry budget or auth profile.
const contribution = exactOwnDataSnapshot<InstalledContractContribution>(
raw,
["contributionId", "featureId", "source", "http", "events"],
["contributionId", "featureId", "source", "http", "events"],
(detail) => fail(`contribution: ${detail}`),
);
const contributionId = contribution.contributionId;
if (
typeof contributionId !== "string" ||
!CONTRIBUTION_ID.test(contributionId)
) {
fail(`contributionId: ${String(contributionId)}`);
}
if (contributionIds.has(contributionId)) {
fail(`duplicate contributionId: ${contributionId}`);
}
contributionIds.add(contributionId);
const featureId = contribution?.featureId;
if (typeof featureId !== "string" || !FEATURE_ID.test(featureId)) {
fail(`featureId: ${String(featureId)}`);
}
const rawSource = contribution.source;
if (!rawSource || typeof rawSource !== "object" || !("kind" in rawSource)) {
fail(`${featureId}: source`);
}
const httpRows = snapshotExactArray(contribution.http);
const eventRows = snapshotExactArray(contribution.events);
if (!httpRows || !eventRows) fail(`${featureId}: contribution arrays`);
const rejectSource = (detail: string): never =>
fail(`${featureId}: source ${detail}`);
let source: ContractContributionSource;
if (rawSource.kind === "EXTERNAL_PACKAGE") {
const outer = exactOwnDataSnapshot<
Readonly<{ kind: "EXTERNAL_PACKAGE"; package: unknown }>
>(rawSource, ["kind", "package"], ["kind", "package"], rejectSource);
const identity = exactOwnDataSnapshot<InstalledContractPackageIdentity>(
outer.package,
[
"packageId",
"version",
"digest",
"runtimeProtocolVersion",
"sourceRevision",
],
[
"packageId",
"version",
"digest",
"runtimeProtocolVersion",
"sourceRevision",
],
rejectSource,
);
assertPackageIdentity(identity, featureId);
source = Object.freeze({
kind: "EXTERNAL_PACKAGE" as const,
package: identity,
});
const existing = packagesById.get(identity.packageId);
if (
existing &&
(existing.version !== identity.version ||
existing.digest !== identity.digest ||
existing.sourceRevision !== identity.sourceRevision)
) {
fail(
`${featureId}: package ${identity.packageId} has conflicting identities`,
);
}
packagesById.set(identity.packageId, identity);
} else if (rawSource.kind === "TEMPLATE_FIXTURE") {
const fixture = exactOwnDataSnapshot<
Readonly<{
kind: "TEMPLATE_FIXTURE";
fixtureId: "REFERENCE_FEATURE_V1";
revision: 1;
}>
>(
rawSource,
["kind", "fixtureId", "revision"],
["kind", "fixtureId", "revision"],
rejectSource,
);
if (
fixture.kind !== "TEMPLATE_FIXTURE" ||
fixture.fixtureId !== "REFERENCE_FEATURE_V1" ||
fixture.revision !== 1
) {
fail(`${featureId}: template fixture identity`);
}
// §4.8, §24.5 (07-04). The fixture is the sample vertical's test data,
// not a product contract: it never joins the contract set, so a fixture
// copied into a product feature would drop that API from the release
// check without a word. Only the feature the fixture is named after may
// install it; every other feature pins an EXTERNAL_PACKAGE.
// The owner is derived from the fixture id (upper snake case feature id
// plus `_V<revision>`) instead of being written out, because
// test:sample-removal rejects the sample feature's id anywhere in src/
// once the sample is gone.
const fixtureOwner = fixture.fixtureId
.slice(0, -`_V${fixture.revision}`.length)
.toLowerCase()
.replaceAll("_", "-");
if (featureId !== fixtureOwner) {
fail(
`${featureId}: TEMPLATE_FIXTURE ${fixture.fixtureId} belongs to ${fixtureOwner} only; pin an EXTERNAL_PACKAGE`,
);
}
if (fixtureInstalled) {
fail(`${featureId}: only one TEMPLATE_FIXTURE contribution is allowed`);
}
fixtureInstalled = true;
if (eventRows.length !== 0) {
fail(`${featureId}: template fixture must not contribute events`);
}
source = fixture;
} else {
fail(`${featureId}: unknown contribution source kind`);
}
const installedHttp: InstalledHttpContract<unknown, unknown, unknown>[] = [];
for (const installed of httpRows) {
const snapshot = snapshotHttpContract(
installed as InstalledHttpContract<unknown, unknown, unknown>,
featureId,
);
assertHttpContract(snapshot, featureId, authProfiles);
const operationId = snapshot.contract.operationId;
const previous = httpByOperationId.get(operationId);
if (previous) fail(`duplicate operation: ${operationId}`);
httpByOperationId.set(operationId, snapshot);
installedHttp.push(snapshot);
}
const installedEvents: InstalledEventContract<unknown, unknown>[] = [];
for (const event of eventRows) {
const snapshot = snapshotEventContract(
event as InstalledEventContract<unknown, unknown>,
featureId,
);
assertEventContract(snapshot, featureId);
if (eventByType.has(snapshot.eventType)) {
fail(`duplicate event type: ${snapshot.eventType}`);
}
eventByType.set(snapshot.eventType, snapshot);
installedEvents.push(snapshot);
}
// Everything published downstream is the validated snapshot, so no consumer
// can be handed the caller's still-live object.
installedContributions.push(
Object.freeze({
contributionId,
featureId,
source,
http: Object.freeze(installedHttp),
events: Object.freeze(installedEvents),
}),
);
}
const externalPackages = [...packagesById.values()].map((identity) =>
Object.freeze({ ...identity }),
);
return Object.freeze({
contributions: Object.freeze(installedContributions),
httpByOperationId: createReadOnlyRegistry(httpByOperationId),
eventByType: createReadOnlyRegistry(eventByType),
externalPackages: Object.freeze(externalPackages),
});
}