Files
clean-architecture-frontend…/src/contracts/external-contract-runtime.ts
T
DongHyeonka e4caafda30 fix(contracts)!: 읽기 operation은 SAFE·IDEMPOTENT일 때만 조립한다
문제
GET에 `retrySemantics: "KEYED"`(commandRecovery 없음)나 `"NEVER"`를
적어도 계약 조립이 통과하고 FE-REG-API 행에 그 값이 남는다. KEYED 복구
descriptor 검사가 쓰기 분기 안에만 있기 때문이다. 실행기는 이 GET을
쓰기로 보지 않아 재시도 없는 읽기로 돌린다. 매뉴얼은 "읽기(GET)는 늘
SAFE"라 적는다. V2 `defineRestOperation`은 조회에 SAFE·IDEMPOTENT만
허용했는데 V2 삭제 때 이 규칙이 V3로 옮겨지지 않았다(실험 R1).

고른 방법
assertHttpContract의 읽기 분기에서 GET·HEAD의 retrySemantics가 SAFE나
IDEMPOTENT가 아니면 method와 값을 담아 거절한다. realtime snapshot 바인딩이
요구하는 짝(GET + SAFE·IDEMPOTENT)과 같은 어휘다. 매뉴얼 02 3절 "틀리면"에
거절 문구를 더했다.

버린 대안
- 레지스트리 governance의 allowedValues로 막기: method별 허용값을 표현할
  칸이 없고, 조립(부팅 경로)이 아니라 check:registries에서만 걸린다.

위험·한계
- GET·HEAD를 KEYED나 NEVER로 적은 다운스트림 descriptor는 부팅에서 계약
  조립 실패가 된다. 템플릿 안에는 그런 descriptor가 없다(grep).
- 쓰기의 SAFE 금지(03-03)는 이 커밋 범위가 아니다.

검증
- RED: tests/unit/external-contract-runtime.test.ts의 GET·HEAD × KEYED·NEVER
  4건이 실패(조립 통과)했다.
- GREEN: `run-vitest related src/contracts/external-contract-runtime.ts`
  105파일 950건 통과. check:types, eslint, check:registries,
  verify:documentation 통과.

BREAKING CHANGE: GET·HEAD operation의 retrySemantics가 KEYED나 NEVER이면
계약 조립이 CONTRACT_CONTRIBUTION_INVALID로 실패한다. SAFE(재시도 허용)나
IDEMPOTENT로 바꾼다. 재시도를 막으려면 frontend.retryBudget을 0으로 둔다.

Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-01
2026-11-04 20:21:04 +09:00

944 lines
32 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) and
* `problemValidator` sees `error`. Whether a 400, 409, 422 or 503
* `IDEMPOTENCY_UNAVAILABLE` applied comes from the backend's own table
* (`src/adapters/http/backend-envelope.ts`, the frontend contract's 6.1),
* not from `commandEffect.classifyProblem`, which decides every other
* status. 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`);
}
// 1103/07-01 (c). The executor runs a read as a read whatever it is
// declared; KEYED or NEVER here only looks like a decision the executor
// never makes. A realtime snapshot binding reads the same pair.
if (
contract.retrySemantics !== "SAFE" &&
contract.retrySemantics !== "IDEMPOTENT"
) {
fail(
`${label}: ${contract.method} is a read; its retrySemantics is SAFE or IDEMPOTENT, not ${contract.retrySemantics}`,
);
}
} 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);
// A browser attaches an ambient cookie to any site's request, so a
// cookie-authenticated write needs a header only the page can set.
const profile = authProfiles.get(installed.frontend.authProfileId);
if (
!isRead &&
profile?.transport === "SAME_ORIGIN_COOKIE" &&
!profile.requiredCredentialHeaders.some(
(header) => header === "x-csrf-token" || header === "x-xsrf-token",
)
) {
fail(
`${label}: ${contract.method} with cookie profile ${profile.authProfileId} must require x-csrf-token or x-xsrf-token`,
);
}
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),
});
}