문제 commandEffect.refusedBeforeWrite의 조립 검사는 code 문법, 멱등성 접두사, 중복, Envelope 여부만 본다. 계약 문서 6.1절은 BAD_PARAMETER(어느 층이든 IllegalArgumentException), MAPPING_FAILED(멱등성 응답 직렬화는 action 뒤), DB_* 8개, LOCK_ACQUISITION_TIMEOUT, fileserver code를 "쓰기 뒤 가능"으로 적는다. 이 code를 목록에 적어도 조립이 통과하고, 그 code로 온 400·409·422가 NOT_APPLIED가 된다. 쓰기 뒤에 난 실패를 사용자가 다시 저장하면 새 키나 키 없는 새 요청이 나가 같은 항목이 둘 생길 수 있다(리뷰 실험 X2: 네 code가 조립을 통과하고 모두 NOT_APPLIED). 고른 방법 6.1절의 "쓰기 뒤 가능" 플랫폼 code를 src/contracts/external-contract-runtime.ts에 PLATFORM_CODES_POSSIBLY_AFTER_WRITE로 두고, assertRefusedBeforeWrite가 그 code의 선언을 6.1절을 이유로 거절한다. 실행기의 fail-close(조립 없이 부른 경우)도 같은 목록을 무시한다. 목록을 adapters가 아니라 contracts에 둔 것은 조립 검사가 adapters를 import할 수 없기 때문이다(리뷰 문서의 최소 개선은 backend-envelope.ts에 두라고 했다). backend-contract-pin.test.ts가 계약 문서 6.1절 표의 "쓰기 뒤 가능" 행을 읽어 목록과 양방향으로 대조한다. 참조 도메인 code와 web-advanced patch code는 엔드포인트가 단계를 정하므로 테스트의 예외 목록에 적고 선언할 수 있게 둔다. 버린 대안 - 매뉴얼 문장만 둔다(현상 유지): 폼을 막는 code를 넣고 싶어지는 바로 그 자리에 통제가 없다. - 업무 code 접두사 규칙(<FEATURE>_로 시작하는 code만 허용): 다운스트림 code 이름을 강제해 과하다. 위험·한계 - 이미 이 code를 적은 다운스트림 계약은 부팅에서 조립이 실패한다. 의도한 실패다. - 6.1절 표에 플랫폼 code가 더해지면 목록도 같이 고쳐야 한다. 대조 테스트가 알린다. 백엔드가 code를 더한 것은 pin을 올릴 때 6.1절을 다시 읽어야 안다. - 업무 code를 잘못 선언하는 것은 여전히 막지 못한다(기능 작성자의 판단). - 대조 테스트는 계약 문서를 읽으므로, 문서를 복사하지 않는 기능 제거 드릴(FE-GATE-020의 optional-recipe·browser-file-storage·realtime)에서는 돌지 않는다. `scripts/lib/removal-fixture.ts`의 문서 테스트 목록에 `tests/unit/backend-contract-pin.test.ts`를 더했다. 저장소 자신의 test:unit은 그대로 돌린다. 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/external-contract-runtime.test.ts tests/unit/backend-envelope.test.ts tests/unit/backend-contract-pin.test.ts corepack pnpm test:optional-recipe-removal BREAKING CHANGE: refusedBeforeWrite에 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(PLATFORM_CODES_POSSIBLY_AFTER_WRITE)를 적으면 composeContractContributions가 거절한다. 그 code를 목록에서 지운다. 그 code의 실패는 결과 불명으로 남는다. Refs: 1105/03-01
1123 lines
40 KiB
TypeScript
1123 lines
40 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,
|
|
}),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 1101/07-07. How the package says a write whose result is unknown can be
|
|
* settled: resend with the same idempotency key, or read the operation back
|
|
* through `inspectOperationId`. Composition requires one on a KEYED command,
|
|
* and FE-REG-API records it. The HTTP executor does not read it: a write
|
|
* that ends `MAYBE_APPLIED` comes back to the feature, and the feature's
|
|
* gateway decides whether to resend or inspect (closed-deep-design.md
|
|
* §4.4 under docs/architecture).
|
|
*/
|
|
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";
|
|
/**
|
|
* 1103/03-01. `responseEnvelope: "ENVELOPE_V1"` only. The backend codes
|
|
* this endpoint raises only before it writes, such as the paired backend
|
|
* scaffold's `<FEATURE>_INVALID` (its create checks the name before the
|
|
* transaction). A 400, 409 or 422 outside the backend's own table that
|
|
* carries one of these codes is `NOT_APPLIED`, so the next save takes a new
|
|
* key. Every code not listed stays `MAYBE_APPLIED`. Idempotency codes
|
|
* (`IDEMPOTENT_*`, `IDEMPOTENCY_*`) are the backend table's to decide, and
|
|
* composition refuses them here, as it refuses the platform codes contract
|
|
* 6.1 reads as possibly after the write (1105/03-01,
|
|
* `PLATFORM_CODES_POSSIBLY_AFTER_WRITE`). Composition installs a copy of
|
|
* the list.
|
|
*/
|
|
readonly refusedBeforeWrite?: readonly string[];
|
|
}
|
|
|
|
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 one of the
|
|
* backend's own 5xx answers (§2, §4) applied comes from the backend's 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") {
|
|
// 1103/09-07. The reason is in the message too: a gate that prints only
|
|
// the message (check:registries) still names the operation and the cause.
|
|
super(`Installed contract contribution is not composable: ${reason}`);
|
|
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`);
|
|
}
|
|
assertRefusedBeforeWrite(contract, label);
|
|
if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) {
|
|
fail(`${label}: KEYED commands require a recovery descriptor`);
|
|
}
|
|
// 1103/03-03. Runtime design §8.3: SAFE is GET and HEAD, the one kind
|
|
// the executor may send again after dispatch. On a write that resends a
|
|
// request whose answer was lost.
|
|
if (contract.retrySemantics === "SAFE") {
|
|
fail(
|
|
`${label}: SAFE retry semantics is for GET and HEAD only; a ${contract.method} declares IDEMPOTENT, KEYED or NEVER (docs/manual/02-decision-tables.md §3)`,
|
|
);
|
|
}
|
|
}
|
|
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`);
|
|
}
|
|
}
|
|
|
|
/** The paired backend's `error.code` grammar (its docs/web/http-contract.md §1). */
|
|
const BACKEND_ERROR_CODE = /^[A-Z0-9_]{1,64}$/;
|
|
/**
|
|
* 1103/03-01. Codes no operation may declare as refused before the write:
|
|
* the backend's idempotency answers. Its own table decides them, including
|
|
* 409 IDEMPOTENT_IN_FLIGHT, whose earlier request may still apply.
|
|
*/
|
|
const IDEMPOTENCY_CODE = /^IDEMPOTEN(?:T|CY)_/;
|
|
|
|
/**
|
|
* 1105/03-01. The paired backend's platform codes that contract 6.1
|
|
* (docs/architecture/backend-api-and-server-state-contract.md) reads as
|
|
* possibly raised after the write: `IllegalArgumentException` from any layer,
|
|
* the mappers (the idempotency response codec runs after the action), the
|
|
* persistence adapter's SQL and JPA failures, the distributed lock and the
|
|
* fileserver module. Their stage is the template's knowledge, not the
|
|
* feature's, so no operation may declare them as refused before its write.
|
|
* Business codes stay the feature author's to declare.
|
|
* tests/unit/backend-contract-pin.test.ts holds this list to the 6.1 table.
|
|
*/
|
|
export const PLATFORM_CODES_POSSIBLY_AFTER_WRITE: readonly string[] =
|
|
Object.freeze([
|
|
"BAD_PARAMETER",
|
|
"MAPPING_FAILED",
|
|
"DB_SERIALIZATION_FAILURE",
|
|
"DB_DEADLOCK",
|
|
"DB_LOCK_TIMEOUT",
|
|
"DB_NULL_VIOLATION",
|
|
"DB_FK_VIOLATION",
|
|
"DB_UNIQUE_VIOLATION",
|
|
"DB_CHECK_VIOLATION",
|
|
"DB_OPTIMISTIC_CONFLICT",
|
|
"LOCK_ACQUISITION_TIMEOUT",
|
|
"BAD_REQUEST",
|
|
"FILE_ALREADY_EXISTS",
|
|
"FILE_NOT_READY",
|
|
"UPLOAD_OFFSET_MISMATCH",
|
|
"CONCURRENT_MODIFICATION",
|
|
"INTEGRITY_MISMATCH",
|
|
"MALWARE_DETECTED",
|
|
"INVALID_PATH",
|
|
"PATH_OUTSIDE_NAMESPACE",
|
|
]);
|
|
const PLATFORM_CODE_AFTER_WRITE: ReadonlySet<string> = new Set(
|
|
PLATFORM_CODES_POSSIBLY_AFTER_WRITE,
|
|
);
|
|
|
|
function assertRefusedBeforeWrite(
|
|
contract: InstalledHttpContract<unknown, unknown, unknown>["contract"],
|
|
label: string,
|
|
): void {
|
|
const declared = contract.commandEffect?.refusedBeforeWrite;
|
|
if (declared === undefined) return;
|
|
if (!Array.isArray(declared)) {
|
|
fail(`${label}: refusedBeforeWrite must be a list of backend codes`);
|
|
}
|
|
// Without the Envelope the executor never reads a backend code, so the
|
|
// list would promise a verdict nothing applies.
|
|
if (contract.responseEnvelope !== "ENVELOPE_V1") {
|
|
fail(
|
|
`${label}: refusedBeforeWrite needs responseEnvelope ENVELOPE_V1; without it classifyProblem decides`,
|
|
);
|
|
}
|
|
const seen = new Set<string>();
|
|
for (const code of declared as readonly unknown[]) {
|
|
if (typeof code !== "string" || !BACKEND_ERROR_CODE.test(code)) {
|
|
fail(`${label}: refusedBeforeWrite code ${String(code)}`);
|
|
}
|
|
if (IDEMPOTENCY_CODE.test(code)) {
|
|
fail(
|
|
`${label}: refusedBeforeWrite cannot declare ${code}; the backend's idempotency answers are decided by its own table`,
|
|
);
|
|
}
|
|
if (PLATFORM_CODE_AFTER_WRITE.has(code)) {
|
|
fail(
|
|
`${label}: refusedBeforeWrite cannot declare ${code}; contract 6.1 reads this platform code as possibly raised after the write`,
|
|
);
|
|
}
|
|
if (seen.has(code)) fail(`${label}: refusedBeforeWrite repeats ${code}`);
|
|
seen.add(code);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 1103/16-01. `responseEnvelope` is per operation so one app can read two
|
|
* backends, but one contribution is one backend's package: its operations
|
|
* share one frame. A hand-added operation without the line used to pass every
|
|
* gate and the MSW scenarios (they answer whatever the descriptor declares)
|
|
* and read the real backend's Envelope as a DTO. Missing and `"NONE"` are the
|
|
* same frame. Two backends take two contributions.
|
|
*/
|
|
function assertSameWireFrame(
|
|
installed: InstalledHttpContract<unknown, unknown, unknown>,
|
|
first: InstalledHttpContract<unknown, unknown, unknown> | undefined,
|
|
featureId: string,
|
|
): void {
|
|
if (first === undefined) return;
|
|
const frame = installed.contract.responseEnvelope ?? "NONE";
|
|
const firstFrame = first.contract.responseEnvelope ?? "NONE";
|
|
if (frame === firstFrame) return;
|
|
fail(
|
|
`${featureId}/${installed.contract.operationId}: responseEnvelope ${frame}, but ${first.contract.operationId} in the same contribution reads ${firstFrame}; a contribution is one backend's package, so declare the same responseEnvelope on every operation or split the contribution per backend`,
|
|
);
|
|
}
|
|
|
|
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),
|
|
commandEffect: snapshotCommandEffect(source.commandEffect, reject),
|
|
commandRecovery:
|
|
source.commandRecovery === null
|
|
? null
|
|
: exactOwnDataSnapshot<CommandRecoveryDescriptor>(
|
|
source.commandRecovery,
|
|
COMMAND_RECOVERY_KEYS,
|
|
["mode", "operationIdentityField"],
|
|
reject,
|
|
),
|
|
});
|
|
return Object.freeze({ contract, frontend });
|
|
}
|
|
|
|
/**
|
|
* 1103/03-01. The classifiers stay by reference, like validators: behaviour
|
|
* the contribution owns. The refusal list is data that lifts the backend's
|
|
* table, so the installed effect carries its own frozen copy, read once. The
|
|
* copy inherits everything else from the source, so a classifier keeps the
|
|
* `this` it was written for, and a list added to the source later is shadowed.
|
|
*/
|
|
function snapshotCommandEffect(
|
|
effect: CommandEffectDescriptor<unknown> | null,
|
|
reject: (detail: string) => never,
|
|
): CommandEffectDescriptor<unknown> | null {
|
|
// Not an object: assertHttpContract names what is wrong.
|
|
if (effect === null || typeof effect !== "object") return effect;
|
|
let declared: unknown;
|
|
try {
|
|
const descriptor = Object.getOwnPropertyDescriptor(
|
|
effect,
|
|
"refusedBeforeWrite",
|
|
);
|
|
if (descriptor !== undefined && !("value" in descriptor)) {
|
|
return reject("refusedBeforeWrite must be a data property");
|
|
}
|
|
declared = descriptor?.value;
|
|
} catch {
|
|
return reject("refusedBeforeWrite unreadable");
|
|
}
|
|
const codes =
|
|
declared === undefined
|
|
? undefined
|
|
: (snapshotExactArray(declared, 64) ??
|
|
reject("refusedBeforeWrite must be a list of backend codes"));
|
|
return Object.freeze(
|
|
Object.create(effect, {
|
|
refusedBeforeWrite: { value: codes, enumerable: true },
|
|
}) as CommandEffectDescriptor<unknown>,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 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);
|
|
assertSameWireFrame(snapshot, installedHttp[0], featureId);
|
|
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),
|
|
});
|
|
}
|