문제
HTTP 실행 경로가 둘이다. V3 실행기(createContractHttpExecutor)가 모든 기능을
실행하고, V2 클라이언트(createHttpClient)는 bootstrap의
createRuntimeHttpClient에서만 만들어지는데 그 함수를 앱 안에서 부르는 곳이
없다(테스트만 부른다). tech-log·memento도 같다. 그런데도 V2는 초기 청크에
들어가고, 짝 백엔드 해석(7db32e1~3261208)과 테스트를 두 벌로 유지하게 했다.
사용자 지시: 레거시를 두지 말고 최신 경로 하나만 남긴다.
고른 방법
- src/adapters/http/의 client.ts, bounded-json.ts, request-builder.ts,
resource-mapper.ts, retry-policy.ts, schema-registry.ts를 지웠다. Envelope
스키마는 backend-envelope.ts로 옮겼다. V3가 retry-policy.ts에서 쓰던
parseRetryAfter는 그것이 감싸던 platform/retry-after.ts의
parseRetryAfterDelay를 직접 부른다.
- 배럴의 V2 export와 bootstrap의 createRuntimeHttpClient·RuntimeHttpContract를
지웠다.
- V2 전용 테스트(http-client, http-diagnostics, auth-recovery,
legacy-http-credential-authority, bounded-json-compatibility,
request-builder, retry-policy)와 tests/helpers/http-contract-fixture.ts를
지웠다. 섞인 파일(http-execution-contract, runtime-adapters,
boundary-mapper)은 V2 블록만 지웠다.
- V2로 돌던 폼 테스트(form-foundation)는 Envelope을 읽는 V3 keyed create
계약으로 옮겼다. 400 VALIDATION_FAILED 필드 오류, {cause} 뒤 다시 저장,
422 뒤 저장 꺼짐을 그대로 검사한다. http-execution-v3-envelope 테스트는 V2와
비교하던 행을 기대 판정을 직접 적는 행으로 바꿨다.
- drill:runbook FE-RB-003은 V2 shouldRetry 대신 V3 실행기를 실제로 돌려
보낸 요청 수를 센다(NEVER 503: 1회, SAFE 503: 재시도, SAFE 스키마 불일치:
1회).
- check:diagnostics의 http 이벤트 생산자, registry-governance의 오류 표 소비자,
risk-coverage 고위험 경로, 아키텍처 금지 fixture, adapter INVENTORY, 문서의
경로를 V3 파일로 바꿨다.
버린 대안
- V2를 @deprecated로 한 릴리스 남기기: 템플릿과 두 다운스트림 모두 부르는
곳이 없어 옮겨 갈 사용자가 없다. 남기면 초기 JS와 두 벌 유지 비용만 남는다.
위험·한계
- BREAKING: 배럴과 bootstrap의 V2 이름을 쓰던 제품 코드는 컴파일이 깨진다.
CHANGELOG에 옮기는 방법을 적었다.
- V2에만 있던 동작이 사라졌다: 401 뒤 세션 복구 후 한 번 재전송, KEYED 503
자동 재시도. V3는 401을 UNAUTHENTICATED로 넘기고 KEYED 요청은 보낸 뒤
재시도하지 않는다.
- 기능마다 적는 V2 API 행(*-api-contract.ts, check:registries가 읽음)은 이
커밋에서 지우지 않았다. 다음 커밋이 지운다.
검증
- check:types, lint, check:architecture(금지 fixture 9건 거절),
check:adapter-inventory(140 files), check:diagnostics, check:registries,
check:ci, verify:documentation 통과.
- test:unit 2,585, test:integration 114, test:component 245, test:contract 23,
test:runtime-schema 56, tests/features 101 통과.
- drill:runbook FE-RB-003: no local check failed.
- check:bundle 통과. 초기 JS 203,354 → 201,598 B(−1,756 B).
BREAKING CHANGE: src/adapters/http/index.ts가 createHttpClient, HttpClient,
HttpClientDependencies, HttpFailure, HttpResult, LegacyHttpInput, Scheduler,
OperationRequestInput를, src/bootstrap/runtime-adapters.ts가
createRuntimeHttpClient, RuntimeHttpContract를 내보내지 않는다. 그 operation의
V3 descriptor를 만들어 createFeatureHttpBinding으로 실행한다.
1881 lines
61 KiB
TypeScript
1881 lines
61 KiB
TypeScript
import {
|
|
HTTP_EXECUTION_CEILINGS,
|
|
invokeValidator,
|
|
type InstalledHttpContract,
|
|
type ValidatorInvocation,
|
|
} from "../../contracts/external-contract-runtime.ts";
|
|
import type { CacheScopeSnapshot } from "../../contracts/server-state-scope.ts";
|
|
import {
|
|
defineMutationIntent,
|
|
// OPT-NET-02. One shared key authority, so the intent factory and this
|
|
// admission site cannot drift apart.
|
|
isValidIdempotencyKey,
|
|
type MutationIntent,
|
|
} from "../../contracts/mutation-intent.ts";
|
|
import {
|
|
decodeJsonBytes,
|
|
isEffectivelyEmpty,
|
|
isJsonMediaType,
|
|
probeForbiddenBody,
|
|
readBoundedBytes,
|
|
} from "./bounded-body-reader.ts";
|
|
import {
|
|
admitCredentialHeaders,
|
|
checkFinalInvariants,
|
|
projectRequest,
|
|
type CredentialAdmissionFailure,
|
|
type CredentialPatchOutcome,
|
|
type FinalInvariantFailure,
|
|
type RequestProjectionFailure,
|
|
} from "./http-contract-bridge.ts";
|
|
import {
|
|
INSTALLED_REST_AUTH_PROFILES,
|
|
type InstalledRestAuthProfiles,
|
|
} from "../../contracts/rest-profiles.ts";
|
|
import {
|
|
snapshotExactObject,
|
|
snapshotOwnDataRecord,
|
|
} from "../../contracts/exact-snapshot.ts";
|
|
import {
|
|
certaintyForAbandonedAttempt,
|
|
classifyProblemEffect,
|
|
classifyStatusEffect,
|
|
joinMutationEffectCertainty,
|
|
type MutationEffectCertainty,
|
|
type PhysicalAttemptState,
|
|
} from "./http-effect-certainty.ts";
|
|
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
|
import {
|
|
envelopeFailureEffect,
|
|
idempotencyRefusalReason,
|
|
readFailureEnvelope,
|
|
readSuccessEnvelope,
|
|
type IdempotencyRefusalReason,
|
|
} from "./backend-envelope.ts";
|
|
import {
|
|
createExecutionContext,
|
|
MAX_INTERACTION_DEADLINE_MS,
|
|
type ExecutionContext,
|
|
} from "../../platform/execution/execution-context.ts";
|
|
import {
|
|
ConcurrencyQueueFullError,
|
|
type ConcurrencyLease,
|
|
} from "../../platform/traffic/concurrency-budget.ts";
|
|
import type { TrafficBudget } from "../../platform/traffic/traffic-budget.ts";
|
|
import { checkJsonStructure } from "../../platform/validation/bounded-json.ts";
|
|
import {
|
|
buildTraceHeaders,
|
|
CORRELATION_ID_HEADER,
|
|
} from "../../platform/telemetry/trace-context.ts";
|
|
import { responseValidationBudget } from "../../platform/validation/validation-budget.ts";
|
|
import {
|
|
canRetryTransport,
|
|
isRetryableHttpStatus,
|
|
isRetryableSemantics,
|
|
jitteredDelay,
|
|
retryDelayFor,
|
|
} from "./http-retry-lifecycle.ts";
|
|
|
|
/**
|
|
* §7–§8. Descriptor-driven HTTP execution.
|
|
*
|
|
* This is not a general purpose HTTP client. A caller passes an installed
|
|
* contract and typed input; the runtime owns bounds, the total deadline, the
|
|
* single retry authority and the effect-certainty verdict.
|
|
*/
|
|
|
|
export type SafeResponseMetadata = Readonly<{
|
|
status: number;
|
|
correlationReference?: string;
|
|
retryAfterMs?: number;
|
|
validatorToken?: string;
|
|
}>;
|
|
|
|
export type HttpContractViolationKind =
|
|
| "MISSING_IDEMPOTENCY_KEY"
|
|
| "UNEXPECTED_IDEMPOTENCY_KEY"
|
|
| "UNEXPECTED_STATUS"
|
|
| "UNEXPECTED_EMPTY_BODY"
|
|
| "UNEXPECTED_BODY"
|
|
| "CONTENT_TYPE_MISMATCH"
|
|
| "RESPONSE_TOO_LARGE"
|
|
| "UTF8_INVALID"
|
|
| "JSON_INVALID"
|
|
/** 1101 README 14.3. A success status whose body is not a success Envelope. */
|
|
| "ENVELOPE_MISMATCH"
|
|
| "SUCCESS_SCHEMA_INVALID"
|
|
| "PROBLEM_SCHEMA_INVALID"
|
|
| "VALIDATOR_RUNTIME_FAILURE"
|
|
| "MAPPING_CONTRACT_VIOLATION"
|
|
| "FINAL_REQUEST_INVARIANT_FAILED"
|
|
| "SCOPE_FENCED";
|
|
|
|
export type HttpContractViolation = Readonly<{
|
|
kind: HttpContractViolationKind;
|
|
operation: "REQUEST" | "RESPONSE" | "VALIDATION" | "MAPPING";
|
|
/**
|
|
* 03-02. Why a `FINAL_REQUEST_INVARIANT_FAILED` request was refused before
|
|
* dispatch. Absent on every other violation.
|
|
*/
|
|
reason?: HttpRequestRejectionReason;
|
|
}>;
|
|
|
|
/**
|
|
* 03-02. Closed set of pre-dispatch refusal causes: the input validator said
|
|
* no (`INPUT_INVALID`), the request could not be assembled, a final invariant
|
|
* failed, or the composition root holds no contract for the operation
|
|
* (`CONTRACT_NOT_INSTALLED`). A deadline or scope fence at the final check is
|
|
* not a refusal; it ends as a timeout or a fence.
|
|
*/
|
|
export type HttpRequestRejectionReason =
|
|
| "INPUT_INVALID"
|
|
| "CONTRACT_NOT_INSTALLED"
|
|
| RequestProjectionFailure
|
|
| Exclude<FinalInvariantFailure, "DEADLINE_EXPIRED" | "SCOPE_FENCED">;
|
|
|
|
export type HttpEffectCertainty =
|
|
| "NOT_APPLICABLE"
|
|
| "NOT_STARTED"
|
|
| "NOT_APPLIED"
|
|
| "APPLIED_CONFIRMED"
|
|
| "MAYBE_APPLIED";
|
|
|
|
export type HttpTransportFailure = Readonly<{
|
|
kind:
|
|
| "DNS_OR_CONNECT_FAILURE"
|
|
| "TLS_OR_NETWORK_FAILURE"
|
|
| "NETWORK_FAILURE"
|
|
| "TIMEOUT"
|
|
| "RESPONSE_STREAM_FAILURE"
|
|
| "ABORTED_BY_SCOPE"
|
|
| "ABORTED_BY_CALLER"
|
|
| "OVERLOADED_BEFORE_SEND";
|
|
retryable: boolean;
|
|
}>;
|
|
|
|
export type HttpExecutionOutcome<Value, Problem> = (
|
|
| Readonly<{
|
|
kind: "SUCCESS";
|
|
value: Value;
|
|
metadata: SafeResponseMetadata;
|
|
effect: "NOT_APPLICABLE" | "APPLIED_CONFIRMED";
|
|
}>
|
|
| Readonly<{
|
|
kind: "PROBLEM";
|
|
problem: Problem;
|
|
metadata: SafeResponseMetadata;
|
|
effect: "NOT_APPLIED" | "APPLIED_CONFIRMED" | "MAYBE_APPLIED";
|
|
}>
|
|
| Readonly<{
|
|
kind: "UNAUTHENTICATED";
|
|
/**
|
|
* Present only when the server answered 401. Absent means no credential
|
|
* existed and nothing was sent; that is not a session verdict.
|
|
*/
|
|
metadata?: SafeResponseMetadata;
|
|
effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED";
|
|
}>
|
|
| Readonly<{
|
|
kind: "FORBIDDEN";
|
|
metadata?: SafeResponseMetadata;
|
|
effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED";
|
|
}>
|
|
| Readonly<{
|
|
kind: "RATE_LIMITED";
|
|
retryAfterMs?: number;
|
|
metadata?: SafeResponseMetadata;
|
|
effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED";
|
|
}>
|
|
| Readonly<{
|
|
kind: "CONTRACT_VIOLATION";
|
|
violation: HttpContractViolation;
|
|
/**
|
|
* Present when an error status arrived without a usable problem body.
|
|
* A 5xx/408/425 here is a server outage, not a contract breach (R-3.3).
|
|
*/
|
|
metadata?: SafeResponseMetadata;
|
|
effect: HttpEffectCertainty;
|
|
}>
|
|
| Readonly<{
|
|
kind: "TRANSPORT_FAILURE";
|
|
failure: HttpTransportFailure;
|
|
effect: "NOT_STARTED" | "MAYBE_APPLIED";
|
|
}>
|
|
| Readonly<{
|
|
kind: "CANCELLED";
|
|
effect: "NOT_STARTED" | "MAYBE_APPLIED";
|
|
}>
|
|
| Readonly<{
|
|
kind: "AUTH_INTEGRATION_FAILURE";
|
|
reason: AuthIntegrationFailureReason;
|
|
effect: "NOT_APPLICABLE" | "NOT_STARTED";
|
|
}>
|
|
) &
|
|
Readonly<{
|
|
/**
|
|
* 0929/03-04. The `x-correlation-id` this execution put on its request,
|
|
* on every variant: a timeout or lost connection has no response to echo
|
|
* one. Absent when the request was never assembled or no id could be made.
|
|
* Diagnostics and support references only; never telemetry.
|
|
*/
|
|
sentRequestId?: string;
|
|
}>;
|
|
|
|
/**
|
|
* §7.7 / VD-23. A configuration or collaborator contract breach, never a user
|
|
* session state. `UNAUTHENTICATED` stays reserved for the latter.
|
|
*/
|
|
export type AuthIntegrationFailureReason =
|
|
| "UNKNOWN_AUTH_PROFILE"
|
|
/**
|
|
* LIVE-01. The collaborator answered that the auth system itself cannot serve
|
|
* this request. That is an outage of the integration, not a statement about
|
|
* the user's session, so it must never reach the composition root's logout
|
|
* path.
|
|
*/
|
|
| "CREDENTIAL_OWNER_UNAVAILABLE"
|
|
/** LIVE-01. The collaborator threw, rejected, or answered off-contract. */
|
|
| "CREDENTIAL_OWNER_FAILED"
|
|
| CredentialAdmissionFailure;
|
|
|
|
/**
|
|
* §8.5. Credential collaborators receive the operation lifetime so a
|
|
* cooperative owner can abandon its own work; a non-cooperative one is still
|
|
* bounded by the executor's race against the same signal.
|
|
*/
|
|
export type AuthOperationContext = Readonly<{
|
|
signal: AbortSignal;
|
|
deadlineAtMonotonicMs: number;
|
|
}>;
|
|
|
|
export type CancellationOwner =
|
|
| "CALLER"
|
|
| "ROUTE_TRANSITION"
|
|
| "SCOPE_FENCE"
|
|
| "APPLICATION_SHUTDOWN"
|
|
| "DEADLINE";
|
|
|
|
export interface HttpExecutionContext {
|
|
/**
|
|
* §7.4. The low-cardinality route identity that owns this logical execution.
|
|
* It is required at the installed operation-executor boundary so a terminal
|
|
* outcome can always be attributed without reconstructing it from a URL.
|
|
*/
|
|
readonly routeId: string;
|
|
readonly signal?: AbortSignal;
|
|
readonly scope: CacheScopeSnapshot;
|
|
readonly intent?: MutationIntent;
|
|
/**
|
|
* scale-architecture.md §10–§15. The interaction this execution belongs to. Every physical
|
|
* attempt consumes the interaction's shared request budget, retry budget and
|
|
* concurrency lease, and the interaction's absolute deadline caps the
|
|
* operation deadline. Absent, the executor creates a single-operation
|
|
* interaction from the operation's own traffic policy, so no execution is
|
|
* ever unbudgeted.
|
|
*/
|
|
readonly execution?: ExecutionContext;
|
|
}
|
|
|
|
/**
|
|
* scale-architecture.md §11. The bounded traffic policy of an operation that declares none:
|
|
* one initial attempt plus the hard retry ceiling, strictly sequential.
|
|
*/
|
|
export const DEFAULT_OPERATION_TRAFFIC_BUDGET: TrafficBudget = Object.freeze({
|
|
maxPhysicalRequests: 1 + HTTP_EXECUTION_CEILINGS.hardRetryCount,
|
|
maxRetries: HTTP_EXECUTION_CEILINGS.hardRetryCount,
|
|
maxConcurrentRequests: 1,
|
|
maxQueuedRequests: 0,
|
|
});
|
|
|
|
export interface ContractHttpExecutor {
|
|
execute<Input, WireOutput, Problem>(
|
|
operation: InstalledHttpContract<Input, WireOutput, Problem>,
|
|
input: Input,
|
|
context: HttpExecutionContext,
|
|
): Promise<HttpExecutionOutcome<WireOutput, Problem>>;
|
|
}
|
|
|
|
/**
|
|
* §7.4 / VD-07. One typed internal record per logical execution. It is not an
|
|
* arbitrary context map: the composition root owns the projection into the
|
|
* closed diagnostics and telemetry buckets, and raw attempt count, duration and
|
|
* status never leave that projection.
|
|
*/
|
|
export type HttpExecutionObservation = Readonly<{
|
|
routeId: string;
|
|
operationId: string;
|
|
diagnosticsOperation: string;
|
|
outcome: HttpExecutionOutcome<unknown, unknown>["kind"];
|
|
errorKind: string;
|
|
status?: number;
|
|
attemptCount: number;
|
|
durationMs: number;
|
|
effect: HttpEffectCertainty;
|
|
cancellationOwner?: CancellationOwner;
|
|
/**
|
|
* 03-03. The server's echoed `x-correlation-id`, else the request id this
|
|
* execution sent. Diagnostics only; never telemetry.
|
|
*/
|
|
correlationId?: string;
|
|
/**
|
|
* The internal terminal-reason label recorded by the execution site. It is
|
|
* evidence for the HTTP scenario catalog only; the composition-root
|
|
* projection never forwards it to diagnostics or telemetry.
|
|
*/
|
|
terminalReason: string;
|
|
/**
|
|
* 03-05. A client-side defect the outcome alone cannot show, from a closed
|
|
* set. Diagnostics carry it as `reason`; telemetry never does (VD-07).
|
|
*/
|
|
diagnosticReason?: HttpDiagnosticReason;
|
|
}>;
|
|
|
|
/**
|
|
* Closed set behind `HttpExecutionObservation.diagnosticReason`.
|
|
*
|
|
* - `CLASSIFIER_FAILED`: the package `classifyProblem` threw or answered
|
|
* outside the closed classification set, so the effect fell back to
|
|
* `MAYBE_APPLIED` (03-05).
|
|
* - an `HttpRequestRejectionReason`: copied from the refused request's
|
|
* violation (03-02).
|
|
* - an `IdempotencyRefusalReason`: an Envelope operation's backend refused
|
|
* the idempotency key (1101 README 14.4). No other backend code reaches
|
|
* diagnostics; the failure's code carries it.
|
|
*/
|
|
export type HttpDiagnosticReason =
|
|
| "CLASSIFIER_FAILED"
|
|
| HttpRequestRejectionReason
|
|
| IdempotencyRefusalReason;
|
|
|
|
/**
|
|
* The outcome is the single authority for the observed error kind. The terminal
|
|
* reason only distinguishes an internal runtime failure from a transport
|
|
* failure, because both surface as the same public outcome.
|
|
*/
|
|
function observationErrorKind(
|
|
outcome: HttpExecutionOutcome<unknown, unknown>,
|
|
terminalReason: string,
|
|
): string {
|
|
switch (outcome.kind) {
|
|
case "SUCCESS":
|
|
return "NONE";
|
|
case "PROBLEM":
|
|
return "PROBLEM";
|
|
case "UNAUTHENTICATED":
|
|
return "UNAUTHENTICATED";
|
|
case "FORBIDDEN":
|
|
return "FORBIDDEN";
|
|
case "RATE_LIMITED":
|
|
return "RATE_LIMITED";
|
|
case "CONTRACT_VIOLATION":
|
|
return outcome.violation.kind;
|
|
case "TRANSPORT_FAILURE":
|
|
return terminalReason === "RUNTIME_FAILURE"
|
|
? "RUNTIME_FAILURE"
|
|
: outcome.failure.kind;
|
|
case "CANCELLED":
|
|
return "REQUEST_ABORTED";
|
|
case "AUTH_INTEGRATION_FAILURE":
|
|
return outcome.reason;
|
|
}
|
|
}
|
|
|
|
function observationStatus(
|
|
outcome: HttpExecutionOutcome<unknown, unknown>,
|
|
): number | undefined {
|
|
return "metadata" in outcome ? outcome.metadata?.status : undefined;
|
|
}
|
|
|
|
function responseCorrelation(
|
|
outcome: HttpExecutionOutcome<unknown, unknown>,
|
|
): string | undefined {
|
|
return "metadata" in outcome
|
|
? outcome.metadata?.correlationReference
|
|
: undefined;
|
|
}
|
|
|
|
export type ContractHttpExecutorDependencies = Readonly<{
|
|
baseUrl: string;
|
|
/** §8.2. `MAX_RETRY_ATTEMPTS` from Runtime Config; the ceiling is still 2. */
|
|
maxRetryAttempts: number;
|
|
/**
|
|
* §6.1 / §8.5. `REQUEST_TIMEOUT_MS` from Runtime Config, as a ceiling only.
|
|
*
|
|
* The contract owns each operation's deadline, because the deadline is part
|
|
* of what the operation promises. A deployment still has to be able to hold
|
|
* the whole app to something stricter than the sum of its contracts, so this
|
|
* value may only shorten a deadline, never extend one — the same direction
|
|
* `CAPABILITY_OVERRIDES` is allowed to move in. Absent, contracts stand
|
|
* exactly as written.
|
|
*/
|
|
requestDeadlineCeilingMs?: number;
|
|
/** The installed profile registry; the executor never invents a profile. */
|
|
authProfiles?: InstalledRestAuthProfiles;
|
|
attachCredentials(
|
|
operation: Readonly<{
|
|
operationId: string;
|
|
authProfileId: string;
|
|
method: string;
|
|
}>,
|
|
context: AuthOperationContext,
|
|
): Promise<CredentialPatchOutcome> | CredentialPatchOutcome;
|
|
fetcher?: typeof fetch;
|
|
/** Adapter seam for the common bounded response reader. */
|
|
readBoundedResponseBytes?: typeof readBoundedBytes;
|
|
monotonicNow?: () => number;
|
|
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
random?: () => number;
|
|
/** 03-03. One id per logical execution, sent as `x-correlation-id`. */
|
|
createRequestId?: () => string;
|
|
observe?: (observation: HttpExecutionObservation) => void;
|
|
}>;
|
|
|
|
type MutationIntentValidation =
|
|
| Readonly<{ ok: true; intent?: MutationIntent }>
|
|
| Readonly<{
|
|
ok: false;
|
|
violation: "MISSING_IDEMPOTENCY_KEY" | "UNEXPECTED_IDEMPOTENCY_KEY";
|
|
}>;
|
|
|
|
function validateMutationIntent(
|
|
contract: Readonly<{
|
|
operationId: string;
|
|
retrySemantics: "SAFE" | "IDEMPOTENT" | "KEYED" | "NEVER";
|
|
commandEffect: unknown | null;
|
|
}>,
|
|
intent: MutationIntent | undefined,
|
|
): MutationIntentValidation {
|
|
const isCommand = contract.commandEffect !== null;
|
|
const requiresKey = contract.retrySemantics === "KEYED";
|
|
if (!isCommand) {
|
|
return intent === undefined
|
|
? Object.freeze({ ok: true })
|
|
: Object.freeze({
|
|
ok: false,
|
|
violation: "UNEXPECTED_IDEMPOTENCY_KEY",
|
|
});
|
|
}
|
|
if (intent === undefined) {
|
|
return requiresKey
|
|
? Object.freeze({ ok: false, violation: "MISSING_IDEMPOTENCY_KEY" })
|
|
: Object.freeze({ ok: true });
|
|
}
|
|
|
|
let validated: MutationIntent;
|
|
try {
|
|
validated = defineMutationIntent(intent);
|
|
} catch {
|
|
return Object.freeze({
|
|
ok: false,
|
|
violation: requiresKey
|
|
? "MISSING_IDEMPOTENCY_KEY"
|
|
: "UNEXPECTED_IDEMPOTENCY_KEY",
|
|
});
|
|
}
|
|
if (validated.operationId !== contract.operationId) {
|
|
return Object.freeze({
|
|
ok: false,
|
|
violation: requiresKey
|
|
? "MISSING_IDEMPOTENCY_KEY"
|
|
: "UNEXPECTED_IDEMPOTENCY_KEY",
|
|
});
|
|
}
|
|
|
|
const key = validated.idempotencyKey;
|
|
if (requiresKey && !isValidIdempotencyKey(key)) {
|
|
return Object.freeze({
|
|
ok: false,
|
|
violation: "MISSING_IDEMPOTENCY_KEY",
|
|
});
|
|
}
|
|
if (!requiresKey && key !== undefined) {
|
|
return Object.freeze({
|
|
ok: false,
|
|
violation: "UNEXPECTED_IDEMPOTENCY_KEY",
|
|
});
|
|
}
|
|
return Object.freeze({ ok: true, intent: validated });
|
|
}
|
|
|
|
export function createContractHttpExecutor(
|
|
dependencies: ContractHttpExecutorDependencies,
|
|
): ContractHttpExecutor {
|
|
const fetcher = dependencies.fetcher ?? fetch;
|
|
const authProfiles =
|
|
dependencies.authProfiles ?? INSTALLED_REST_AUTH_PROFILES;
|
|
const readResponseBytes =
|
|
dependencies.readBoundedResponseBytes ?? readBoundedBytes;
|
|
const now = dependencies.monotonicNow ?? (() => performance.now());
|
|
const random = dependencies.random ?? Math.random;
|
|
const createRequestId =
|
|
dependencies.createRequestId ?? (() => globalThis.crypto.randomUUID());
|
|
const deadlineCeilingMs = dependencies.requestDeadlineCeilingMs;
|
|
const effectiveDeadlineMs = (contractDeadlineMs: number): number =>
|
|
typeof deadlineCeilingMs === "number" &&
|
|
Number.isFinite(deadlineCeilingMs) &&
|
|
deadlineCeilingMs > 0
|
|
? Math.min(contractDeadlineMs, deadlineCeilingMs)
|
|
: contractDeadlineMs;
|
|
const sleep =
|
|
dependencies.sleep ??
|
|
((ms: number, signal: AbortSignal) =>
|
|
new Promise<void>((resolve) => {
|
|
const timer = setTimeout(resolve, ms);
|
|
signal.addEventListener(
|
|
"abort",
|
|
() => {
|
|
clearTimeout(timer);
|
|
resolve();
|
|
},
|
|
{ once: true },
|
|
);
|
|
}));
|
|
|
|
async function execute<Input, WireOutput, Problem>(
|
|
operation: InstalledHttpContract<Input, WireOutput, Problem>,
|
|
input: Input,
|
|
context: HttpExecutionContext,
|
|
): Promise<HttpExecutionOutcome<WireOutput, Problem>> {
|
|
const contract = operation.contract;
|
|
const policy = operation.frontend;
|
|
const isCommand = contract.commandEffect !== null;
|
|
|
|
// §8.5. One monotonic deadline covers credential resolution, encoding,
|
|
// backoff, every physical attempt, body read and validation.
|
|
const startedAt = now();
|
|
const execution =
|
|
context.execution ??
|
|
createExecutionContext({
|
|
interactionId: "implicit-operation",
|
|
deadlineMs: Math.max(
|
|
1,
|
|
Math.min(
|
|
MAX_INTERACTION_DEADLINE_MS,
|
|
Math.ceil(effectiveDeadlineMs(policy.totalDeadlineMs)),
|
|
),
|
|
),
|
|
traffic: policy.traffic ?? DEFAULT_OPERATION_TRAFFIC_BUDGET,
|
|
clock: now,
|
|
startedAt,
|
|
});
|
|
// scale-architecture.md §15. A late operation only receives what is left of the
|
|
// interaction's absolute deadline; it never restarts its own full timeout.
|
|
const totalDeadlineMs = Math.max(
|
|
0,
|
|
Math.min(effectiveDeadlineMs(policy.totalDeadlineMs), execution.remainingMs()),
|
|
);
|
|
const deadlineAt = startedAt + totalDeadlineMs;
|
|
const remaining = () =>
|
|
Math.min(deadlineAt - now(), execution.remainingMs());
|
|
|
|
let attemptState: PhysicalAttemptState = "PREPARING";
|
|
let attempts = 0;
|
|
/**
|
|
* §8.7 / D-01. Per-attempt state stays local to the attempt; this monotonic
|
|
* accumulator is the logical execution history. A retry that has not been
|
|
* dispatched can never lower what an earlier attempt already established.
|
|
*/
|
|
let logicalCertainty: MutationEffectCertainty = "NOT_STARTED";
|
|
const observeCertainty = (observed: MutationEffectCertainty) => {
|
|
logicalCertainty = joinMutationEffectCertainty(logicalCertainty, observed);
|
|
return logicalCertainty;
|
|
};
|
|
/** Pre-dispatch failures read the accumulator, never a fresh attempt. */
|
|
const logicalPreDispatchEffect = (): HttpEffectCertainty =>
|
|
isCommand ? logicalCertainty : "NOT_APPLICABLE";
|
|
const abandonedCertainty = (): MutationEffectCertainty =>
|
|
observeCertainty(certaintyForAbandonedAttempt(attemptState, isCommand));
|
|
const abandonedTransportFailure = (
|
|
kind: HttpTransportFailure["kind"],
|
|
): HttpExecutionOutcome<WireOutput, Problem> =>
|
|
transportFailure(kind, false, abandonedCertainty());
|
|
/**
|
|
* Q-6.3-7. What the attempts that were retried settled on. The logical
|
|
* accumulator above is raised at dispatch, before the attempt's own answer
|
|
* is known, so it cannot tell a rejected attempt from a lost one.
|
|
*/
|
|
let retriedCertainty: MutationEffectCertainty = "NOT_STARTED";
|
|
const rememberRetried = (settled: MutationEffectCertainty) => {
|
|
if (isCommand) {
|
|
retriedCertainty = joinMutationEffectCertainty(retriedCertainty, settled);
|
|
}
|
|
};
|
|
let terminalCancellation: CancellationOwner | null = null;
|
|
const lifetimeController = new AbortController();
|
|
const forwardCallerToLifetime = () => {
|
|
terminalCancellation ??= "CALLER";
|
|
lifetimeController.abort();
|
|
};
|
|
const forwardScopeToLifetime = () => {
|
|
terminalCancellation ??= "SCOPE_FENCE";
|
|
lifetimeController.abort();
|
|
};
|
|
const callerSignal =
|
|
context.signal === context.scope.signal ? undefined : context.signal;
|
|
if (callerSignal?.aborted) forwardCallerToLifetime();
|
|
else {
|
|
callerSignal?.addEventListener("abort", forwardCallerToLifetime, {
|
|
once: true,
|
|
});
|
|
}
|
|
// scale-architecture.md §10. Cancelling the interaction cancels every child execution the
|
|
// same way the caller's own signal does.
|
|
const interactionSignal = context.execution?.cancellation.signal;
|
|
if (interactionSignal?.aborted) forwardCallerToLifetime();
|
|
else {
|
|
interactionSignal?.addEventListener("abort", forwardCallerToLifetime, {
|
|
once: true,
|
|
});
|
|
}
|
|
if (context.scope.signal.aborted) forwardScopeToLifetime();
|
|
else {
|
|
context.scope.signal.addEventListener("abort", forwardScopeToLifetime, {
|
|
once: true,
|
|
});
|
|
}
|
|
const lifetimeDeadlineTimer = setTimeout(() => {
|
|
terminalCancellation ??= "DEADLINE";
|
|
lifetimeController.abort();
|
|
}, totalDeadlineMs);
|
|
let lifetimeDisposed = false;
|
|
const disposeLifetime = () => {
|
|
if (lifetimeDisposed) return;
|
|
lifetimeDisposed = true;
|
|
clearTimeout(lifetimeDeadlineTimer);
|
|
callerSignal?.removeEventListener("abort", forwardCallerToLifetime);
|
|
interactionSignal?.removeEventListener("abort", forwardCallerToLifetime);
|
|
context.scope.signal.removeEventListener("abort", forwardScopeToLifetime);
|
|
lifetimeController.abort();
|
|
};
|
|
|
|
let sentRequestId: string | undefined;
|
|
const finish = (
|
|
outcome: HttpExecutionOutcome<WireOutput, Problem>,
|
|
terminalReason: string,
|
|
diagnosticReason?: HttpDiagnosticReason,
|
|
): HttpExecutionOutcome<WireOutput, Problem> => {
|
|
disposeLifetime();
|
|
// 03-02. A refused request carries its cause on the violation itself.
|
|
const recordedReason =
|
|
diagnosticReason ??
|
|
(outcome.kind === "CONTRACT_VIOLATION"
|
|
? outcome.violation.reason
|
|
: undefined);
|
|
try {
|
|
const status = observationStatus(outcome);
|
|
const correlationId = responseCorrelation(outcome) ?? sentRequestId;
|
|
dependencies.observe?.(
|
|
Object.freeze({
|
|
routeId: context.routeId,
|
|
operationId: contract.operationId,
|
|
diagnosticsOperation: policy.diagnosticsOperation,
|
|
outcome: outcome.kind,
|
|
errorKind: observationErrorKind(outcome, terminalReason),
|
|
...(status === undefined ? {} : { status }),
|
|
attemptCount: attempts,
|
|
durationMs: Math.max(0, now() - startedAt),
|
|
effect: outcome.effect,
|
|
terminalReason,
|
|
...(recordedReason === undefined
|
|
? {}
|
|
: { diagnosticReason: recordedReason }),
|
|
...(terminalCancellation === null
|
|
? {}
|
|
: { cancellationOwner: terminalCancellation }),
|
|
...(correlationId === undefined ? {} : { correlationId }),
|
|
}),
|
|
);
|
|
} catch {
|
|
// Observation is outside the execution authority.
|
|
}
|
|
return sentRequestId === undefined
|
|
? outcome
|
|
: Object.freeze({ ...outcome, sentRequestId });
|
|
};
|
|
|
|
/**
|
|
* Q-6.3-6. The one classifier for a wait that a terminal owner ended. The
|
|
* caller cancels and the deadline times out. A scope fence during a `WAIT`
|
|
* (credentials, lease, dispatch, backoff) aborts the transport; during
|
|
* `ADMISSION` the response headers prove the request reached the server,
|
|
* so a stale generation stays the `SCOPE_FENCED` contract violation.
|
|
*/
|
|
const terminalOutcomeFor = (
|
|
phase: "WAIT" | "ADMISSION",
|
|
): HttpExecutionOutcome<WireOutput, Problem> => {
|
|
switch (terminalCancellation) {
|
|
case "CALLER":
|
|
return finish(cancelled(abandonedCertainty()), "CANCELLED");
|
|
case "SCOPE_FENCE":
|
|
return phase === "ADMISSION"
|
|
? finish(scopeFenced(abandonedCertainty()), "SCOPE_FENCED")
|
|
: finish(
|
|
abandonedTransportFailure("ABORTED_BY_SCOPE"),
|
|
"SCOPE_FENCED",
|
|
);
|
|
default:
|
|
return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT");
|
|
}
|
|
};
|
|
|
|
try {
|
|
|
|
// §7.7. The installed registry is the only source of a profile. Composition
|
|
// already rejects unknown identities; this is the runtime fail-close.
|
|
const authProfile = authProfiles.get(policy.authProfileId);
|
|
if (!authProfile) {
|
|
return finish(
|
|
authIntegrationFailure("UNKNOWN_AUTH_PROFILE", isCommand),
|
|
"AUTH_INTEGRATION_FAILURE",
|
|
);
|
|
}
|
|
|
|
// §7.4 step 1-2: capture the scope and verify it is still current.
|
|
if (!context.scope.isCurrent()) {
|
|
return finish(scopeFenced(preDispatchEffect(isCommand)), "NOT_STARTED");
|
|
}
|
|
|
|
const intentValidation = validateMutationIntent(contract, context.intent);
|
|
if (!intentValidation.ok) {
|
|
return finish(
|
|
violation(intentValidation.violation, "REQUEST", "NOT_STARTED"),
|
|
"NOT_STARTED",
|
|
);
|
|
}
|
|
|
|
const validated = invokeValidator(contract.inputValidator, input);
|
|
if (validated.outcome === "THROWN") {
|
|
return finish(
|
|
violation(
|
|
"VALIDATOR_RUNTIME_FAILURE",
|
|
"VALIDATION",
|
|
preDispatchEffect(isCommand),
|
|
),
|
|
"NOT_STARTED",
|
|
);
|
|
}
|
|
if (validated.outcome === "INVALID") {
|
|
return finish(
|
|
refusedRequest("INPUT_INVALID", preDispatchEffect(isCommand)),
|
|
"NOT_STARTED",
|
|
);
|
|
}
|
|
|
|
const projected = projectRequest(
|
|
operation,
|
|
validated.value,
|
|
dependencies.baseUrl,
|
|
);
|
|
if (!projected.ok) {
|
|
return finish(
|
|
refusedRequest(projected.failure, preDispatchEffect(isCommand)),
|
|
"NOT_STARTED",
|
|
);
|
|
}
|
|
|
|
// §7.7 / §8.4. Credentials are resolved before send. A response 401 is
|
|
// terminal; there is no hidden refresh-and-replay.
|
|
//
|
|
// LIVE-01. A synchronous throw and an asynchronous rejection are the same
|
|
// event seen from two call sites, so one classifier owns both. Neither is
|
|
// evidence about the user's session.
|
|
let patchOperation: Promise<CredentialPatchOutcome>;
|
|
try {
|
|
patchOperation = Promise.resolve(
|
|
dependencies.attachCredentials(
|
|
{
|
|
operationId: contract.operationId,
|
|
authProfileId: policy.authProfileId,
|
|
method: contract.method,
|
|
},
|
|
Object.freeze({
|
|
signal: lifetimeController.signal,
|
|
deadlineAtMonotonicMs: deadlineAt,
|
|
}),
|
|
),
|
|
);
|
|
} catch {
|
|
return finish(
|
|
authIntegrationFailure("CREDENTIAL_OWNER_FAILED", isCommand),
|
|
"AUTH_INTEGRATION_FAILURE",
|
|
);
|
|
}
|
|
let patchResult: CredentialPatchOutcome | typeof ABORTED;
|
|
try {
|
|
patchResult = await awaitWithAbort(
|
|
patchOperation,
|
|
lifetimeController.signal,
|
|
);
|
|
} catch {
|
|
return finish(
|
|
authIntegrationFailure("CREDENTIAL_OWNER_FAILED", isCommand),
|
|
"AUTH_INTEGRATION_FAILURE",
|
|
);
|
|
}
|
|
if (patchResult === ABORTED) return terminalOutcomeFor("WAIT");
|
|
// NS-01. The whole answer is decoded once, inside the auth boundary, before
|
|
// any field is used. Reading `kind` and `headers` off the raw object left
|
|
// the decode outside that boundary: a throwing getter escaped into the
|
|
// transport catch and an auth outage was classified as a network failure.
|
|
const patch = decodeCredentialPatch(patchResult);
|
|
if (patch === null) {
|
|
// An off-contract answer is a collaborator breach, never a session
|
|
// verdict the caller may act on.
|
|
return finish(
|
|
authIntegrationFailure("CREDENTIAL_OWNER_FAILED", isCommand),
|
|
"AUTH_INTEGRATION_FAILURE",
|
|
);
|
|
}
|
|
if (patch.kind === "SCOPE_FENCED") {
|
|
return finish(scopeFenced(preDispatchEffect(isCommand)), "NOT_STARTED");
|
|
}
|
|
if (patch.kind === "UNAUTHENTICATED") {
|
|
// A missing credential never downgrades into an anonymous request.
|
|
return finish(unauthenticated("NOT_STARTED", isCommand), "NOT_STARTED");
|
|
}
|
|
if (patch.kind === "UNAVAILABLE") {
|
|
return finish(
|
|
authIntegrationFailure("CREDENTIAL_OWNER_UNAVAILABLE", isCommand),
|
|
"AUTH_INTEGRATION_FAILURE",
|
|
);
|
|
}
|
|
|
|
// The idempotency key is contract-owned, so a credential owner supplying it
|
|
// stays the more specific request-contract violation.
|
|
if (
|
|
Object.keys(patch.headers).some(
|
|
(name) => name.toLowerCase() === "idempotency-key",
|
|
)
|
|
) {
|
|
return finish(
|
|
violation("UNEXPECTED_IDEMPOTENCY_KEY", "REQUEST", "NOT_STARTED"),
|
|
"NOT_STARTED",
|
|
);
|
|
}
|
|
|
|
// §7.7. The profile, not the patch, decides what may travel. Rejection here
|
|
// means zero fetch calls.
|
|
const admission = admitCredentialHeaders(patch.headers, authProfile);
|
|
if (!admission.ok) {
|
|
return finish(
|
|
authIntegrationFailure(admission.failure, isCommand),
|
|
"AUTH_INTEGRATION_FAILURE",
|
|
);
|
|
}
|
|
|
|
// Transport-owned headers are written last so no credential entry can
|
|
// shadow Accept or Content-Type through key ordering.
|
|
const headers: Record<string, string> = {
|
|
...admission.headers,
|
|
Accept: "application/json",
|
|
};
|
|
if (contract.requestBody === "JSON") {
|
|
headers["Content-Type"] = "application/json";
|
|
}
|
|
if (intentValidation.intent?.idempotencyKey !== undefined) {
|
|
headers["Idempotency-Key"] = intentValidation.intent.idempotencyKey;
|
|
}
|
|
// scale-architecture.md §29. Only an interaction that opted into tracing propagates its
|
|
// identity; every child request carries the same trace and correlation.
|
|
if (context.execution?.trace !== undefined) {
|
|
Object.assign(headers, buildTraceHeaders(context.execution));
|
|
}
|
|
// 03-03. Every other logical execution still sends its own request id,
|
|
// shared by its retries, so a failure can be found in the server log.
|
|
if (headers[CORRELATION_ID_HEADER] === undefined) {
|
|
try {
|
|
headers[CORRELATION_ID_HEADER] = createRequestId();
|
|
} catch {
|
|
// A diagnostic id never blocks the request (e.g. no secure context).
|
|
}
|
|
}
|
|
sentRequestId = headers[CORRELATION_ID_HEADER];
|
|
|
|
const retryCeiling = Math.min(
|
|
policy.retryBudget,
|
|
dependencies.maxRetryAttempts,
|
|
HTTP_EXECUTION_CEILINGS.hardRetryCount,
|
|
);
|
|
|
|
// scale-architecture.md §13. A retry is admitted only when the interaction still has both a
|
|
// shared retry and a physical request left; the retry budget is consumed
|
|
// only for a retry that will actually be dispatched.
|
|
const admitRetry = (): boolean =>
|
|
execution.traffic.requests.remaining > 0 &&
|
|
execution.traffic.retries.tryConsume(contract.operationId);
|
|
|
|
for (let retryIndex = 0; ; retryIndex += 1) {
|
|
if (callerSignal?.aborted || interactionSignal?.aborted) {
|
|
terminalCancellation ??= "CALLER";
|
|
return finish(
|
|
cancelled(abandonedCertainty()),
|
|
"CANCELLED",
|
|
);
|
|
}
|
|
if (!context.scope.isCurrent()) {
|
|
terminalCancellation ??= "SCOPE_FENCE";
|
|
return finish(
|
|
scopeFenced(abandonedCertainty()),
|
|
"SCOPE_FENCED",
|
|
);
|
|
}
|
|
|
|
if (remaining() <= 0) {
|
|
return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT");
|
|
}
|
|
// scale-architecture.md §11 / §14. Physical request budget first, then a cancellable
|
|
// concurrency lease whose wait is bounded by the operation lifetime.
|
|
if (!execution.traffic.requests.tryConsume()) {
|
|
return finish(
|
|
abandonedTransportFailure("OVERLOADED_BEFORE_SEND"),
|
|
"TRAFFIC_BUDGET_EXCEEDED",
|
|
);
|
|
}
|
|
let lease: ConcurrencyLease;
|
|
try {
|
|
lease = await execution.traffic.concurrency.acquire(
|
|
lifetimeController.signal,
|
|
);
|
|
} catch (error) {
|
|
if (error instanceof ConcurrencyQueueFullError) {
|
|
return finish(
|
|
abandonedTransportFailure("OVERLOADED_BEFORE_SEND"),
|
|
"TRAFFIC_BUDGET_EXCEEDED",
|
|
);
|
|
}
|
|
return terminalOutcomeFor("WAIT");
|
|
}
|
|
try {
|
|
const controller = new AbortController();
|
|
const budget = remaining();
|
|
if (budget <= 0) {
|
|
return finish(
|
|
abandonedTransportFailure("TIMEOUT"),
|
|
"TIMEOUT",
|
|
);
|
|
}
|
|
const deadlineTimer = setTimeout(() => {
|
|
terminalCancellation ??= "DEADLINE";
|
|
controller.abort();
|
|
}, budget);
|
|
const forwardLifetime = () => {
|
|
controller.abort();
|
|
};
|
|
if (lifetimeController.signal.aborted) forwardLifetime();
|
|
else {
|
|
lifetimeController.signal.addEventListener("abort", forwardLifetime, {
|
|
once: true,
|
|
});
|
|
}
|
|
|
|
const init: RequestInit = {
|
|
method: contract.method,
|
|
headers,
|
|
redirect: "error",
|
|
referrerPolicy: "no-referrer",
|
|
credentials: authProfile.credentials,
|
|
cache: "no-store",
|
|
signal: controller.signal,
|
|
...(projected.request.bodyBytes
|
|
? { body: projected.request.bodyBytes.slice() }
|
|
: {}),
|
|
};
|
|
|
|
const invariantFailure = checkFinalInvariants({
|
|
request: projected.request,
|
|
expectedMethod: contract.method,
|
|
baseUrl: dependencies.baseUrl,
|
|
init,
|
|
headers,
|
|
requestByteLimit: policy.requestByteLimit,
|
|
deadlineRemainingMs: remaining(),
|
|
scopeIsCurrent: context.scope.isCurrent(),
|
|
authProfile,
|
|
});
|
|
if (invariantFailure) {
|
|
clearTimeout(deadlineTimer);
|
|
lifetimeController.signal.removeEventListener("abort", forwardLifetime);
|
|
// P-03-05. The deadline can run out between the budget read above and
|
|
// this check. Nothing was sent and the request is not wrong: end it
|
|
// exactly as the budget read does.
|
|
if (invariantFailure === "DEADLINE_EXPIRED") {
|
|
return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT");
|
|
}
|
|
return finish(
|
|
invariantFailure === "SCOPE_FENCED"
|
|
? scopeFenced(logicalPreDispatchEffect())
|
|
: refusedRequest(invariantFailure, logicalPreDispatchEffect()),
|
|
"NOT_STARTED",
|
|
);
|
|
}
|
|
|
|
let response: Response;
|
|
attemptState = "READY_TO_SEND";
|
|
// LIVE-04. The dispatch wait is raced against the attempt signal, which
|
|
// already carries the caller, the scope fence and the total deadline. A
|
|
// `fetch` that ignores its own `signal` therefore still cannot outlive
|
|
// the operation, and a response that lands late is drained, not admitted.
|
|
let dispatch: BoundedRace<Response>;
|
|
try {
|
|
attempts += 1;
|
|
const pending = fetcher(projected.request.url, init);
|
|
attemptState = "DISPATCHED";
|
|
// D-01. Dispatch is the point of no return for the logical execution.
|
|
// No later retry may claim the command never started.
|
|
observeCertainty(certaintyForAbandonedAttempt("DISPATCHED", isCommand));
|
|
dispatch = await raceTerminal(
|
|
pending,
|
|
controller.signal,
|
|
cancelResponseBody,
|
|
);
|
|
} catch {
|
|
dispatch = REJECTED_RACE;
|
|
}
|
|
if (dispatch.kind === "VALUE") {
|
|
response = dispatch.value;
|
|
attemptState = "RESPONSE_HEADERS";
|
|
} else {
|
|
clearTimeout(deadlineTimer);
|
|
lifetimeController.signal.removeEventListener("abort", forwardLifetime);
|
|
if (terminalCancellation !== null) {
|
|
return terminalOutcomeFor("WAIT");
|
|
}
|
|
if (
|
|
canRetryTransport(contract.retrySemantics, attemptState) &&
|
|
retryIndex < retryCeiling &&
|
|
remaining() > 0
|
|
) {
|
|
const delay = jitteredDelay(retryIndex, random);
|
|
if (delay < remaining() && admitRetry()) {
|
|
lease.release();
|
|
const slept = await awaitWithAbort(
|
|
sleep(delay, lifetimeController.signal),
|
|
lifetimeController.signal,
|
|
);
|
|
if (slept === ABORTED) return terminalOutcomeFor("WAIT");
|
|
rememberRetried(certaintyForAbandonedAttempt(attemptState, isCommand));
|
|
continue;
|
|
}
|
|
}
|
|
return finish(
|
|
abandonedTransportFailure("NETWORK_FAILURE"),
|
|
"NETWORK_FAILURE",
|
|
);
|
|
}
|
|
|
|
try {
|
|
// LIVE-04. Response admission reads a body, so it is a physical wait
|
|
// too. It is bounded by the same signal, the reader is handed that
|
|
// signal so a cooperative stream stops early, and an admission that
|
|
// completes after the terminal owner fired is discarded.
|
|
const admission = await raceTerminal(
|
|
admitResponse(
|
|
operation,
|
|
response,
|
|
context,
|
|
attemptState,
|
|
readResponseBytes,
|
|
controller.signal,
|
|
),
|
|
controller.signal,
|
|
() => cancelResponseBody(response),
|
|
);
|
|
// LIVE-04. A terminal owner that lands during admission wins over the
|
|
// admitted answer.
|
|
if (admission.kind !== "VALUE") {
|
|
cancelResponseBody(response);
|
|
return terminalCancellation === null
|
|
? finish(
|
|
abandonedTransportFailure("NETWORK_FAILURE"),
|
|
"NETWORK_FAILURE",
|
|
)
|
|
: terminalOutcomeFor("ADMISSION");
|
|
}
|
|
const outcome = admission.value;
|
|
attemptState = "SETTLED";
|
|
if (terminalCancellation !== null) {
|
|
return terminalOutcomeFor("ADMISSION");
|
|
}
|
|
if (
|
|
outcome.retryHint &&
|
|
// Q-6.3-7. An answer that says the command may already be applied
|
|
// is not replayed; reconciliation owns it from here.
|
|
outcome.certainty !== "MAYBE_APPLIED" &&
|
|
outcome.certainty !== "APPLIED_CONFIRMED" &&
|
|
retryIndex < retryCeiling &&
|
|
isRetryableSemantics(contract.retrySemantics)
|
|
) {
|
|
const delay = retryDelayFor(outcome.retryAfterMs, retryIndex, random);
|
|
if (delay !== null && delay < remaining() && admitRetry()) {
|
|
lease.release();
|
|
clearTimeout(deadlineTimer);
|
|
lifetimeController.signal.removeEventListener(
|
|
"abort",
|
|
forwardLifetime,
|
|
);
|
|
const slept = await awaitWithAbort(
|
|
sleep(delay, lifetimeController.signal),
|
|
lifetimeController.signal,
|
|
);
|
|
if (slept === ABORTED) return terminalOutcomeFor("WAIT");
|
|
rememberRetried(outcome.result.effect as MutationEffectCertainty);
|
|
continue;
|
|
}
|
|
}
|
|
// Q-6.3-7. A retry never reports less than an earlier attempt of the
|
|
// same command already established.
|
|
const effect = isCommand
|
|
? joinMutationEffectCertainty(
|
|
retriedCertainty,
|
|
outcome.result.effect as MutationEffectCertainty,
|
|
)
|
|
: outcome.result.effect;
|
|
return finish(
|
|
effect === outcome.result.effect
|
|
? outcome.result
|
|
: (Object.freeze({
|
|
...outcome.result,
|
|
effect,
|
|
}) as HttpExecutionOutcome<WireOutput, Problem>),
|
|
outcome.certainty,
|
|
outcome.diagnosticReason,
|
|
);
|
|
} finally {
|
|
clearTimeout(deadlineTimer);
|
|
lifetimeController.signal.removeEventListener("abort", forwardLifetime);
|
|
}
|
|
} finally {
|
|
lease.release();
|
|
}
|
|
}
|
|
} catch {
|
|
return finish(
|
|
abandonedTransportFailure("NETWORK_FAILURE"),
|
|
"RUNTIME_FAILURE",
|
|
);
|
|
} finally {
|
|
disposeLifetime();
|
|
}
|
|
}
|
|
|
|
return Object.freeze({ execute });
|
|
}
|
|
|
|
const CREDENTIAL_HEADER_VALUE_CEILING = 8_192;
|
|
|
|
/**
|
|
* NS-01. Decodes a credential owner's answer into an owned, frozen value. Every
|
|
* field is read exactly once through its own data descriptor, so an accessor, a
|
|
* Proxy that answers differently on a second read, an inherited or smuggled
|
|
* field, or a trap that throws all resolve to `null` — a collaborator breach —
|
|
* rather than escaping as an exception or being installed unvalidated.
|
|
*/
|
|
function decodeCredentialPatch(
|
|
source: unknown,
|
|
): CredentialPatchOutcome | null {
|
|
const outer = snapshotExactObject(source, {
|
|
allowed: ["kind", "headers"],
|
|
required: ["kind"],
|
|
});
|
|
if (outer === null) return null;
|
|
const kind = outer["kind"];
|
|
if (
|
|
kind === "UNAUTHENTICATED" ||
|
|
kind === "UNAVAILABLE" ||
|
|
kind === "SCOPE_FENCED"
|
|
) {
|
|
return Object.hasOwn(outer, "headers")
|
|
? null
|
|
: Object.freeze({ kind } as const);
|
|
}
|
|
if (kind !== "READY") return null;
|
|
|
|
// The key set stays open here so the profile's own admission — and the more
|
|
// specific reserved-header violation — can still report the precise reason.
|
|
const headers = snapshotOwnDataRecord(outer["headers"]);
|
|
if (headers === null) return null;
|
|
for (const value of Object.values(headers)) {
|
|
if (
|
|
typeof value !== "string" ||
|
|
value.length > CREDENTIAL_HEADER_VALUE_CEILING
|
|
) {
|
|
return null;
|
|
}
|
|
}
|
|
return Object.freeze({
|
|
kind: "READY" as const,
|
|
headers,
|
|
}) as CredentialPatchOutcome;
|
|
}
|
|
|
|
type AdmissionOutcome<Value, Problem> = Readonly<{
|
|
result: HttpExecutionOutcome<Value, Problem>;
|
|
certainty: string;
|
|
retryHint: boolean;
|
|
retryAfterMs: number | null;
|
|
diagnosticReason?: HttpDiagnosticReason;
|
|
}>;
|
|
|
|
/**
|
|
* §7.9. Admission order is fixed: redirect, status allowlist, media type,
|
|
* declared length, bounded stream, body policy, decode, validate, scope fence.
|
|
* `response.ok` is never used on its own.
|
|
*/
|
|
async function admitResponse<Input, WireOutput, Problem>(
|
|
operation: InstalledHttpContract<Input, WireOutput, Problem>,
|
|
response: Response,
|
|
context: HttpExecutionContext,
|
|
attemptState: PhysicalAttemptState,
|
|
readResponseBytes: typeof readBoundedBytes,
|
|
signal: AbortSignal,
|
|
): Promise<AdmissionOutcome<WireOutput, Problem>> {
|
|
const contract = operation.contract;
|
|
const policy = operation.frontend;
|
|
const isCommand = contract.commandEffect !== null;
|
|
const status = response.status;
|
|
const retryAfterMs = parseRetryAfterDelay(
|
|
response.headers.get("retry-after"),
|
|
Date.now(),
|
|
);
|
|
|
|
if (response.redirected || response.type === "opaqueredirect") {
|
|
await response.body?.cancel().catch(() => {});
|
|
return settled(
|
|
violation(
|
|
"UNEXPECTED_STATUS",
|
|
"RESPONSE",
|
|
postDispatchEffect(isCommand),
|
|
),
|
|
"CONTRACT_VIOLATION",
|
|
);
|
|
}
|
|
|
|
const metadata = safeMetadata(response, retryAfterMs);
|
|
const statusEffect = (classified: 401 | 403 | 429) =>
|
|
classifyStatusEffect(
|
|
contract.commandEffect,
|
|
classified,
|
|
certaintyForAbandonedAttempt(attemptState, isCommand),
|
|
);
|
|
|
|
if (!contract.acceptedStatuses.includes(status)) {
|
|
if (status === 401) {
|
|
await response.body?.cancel().catch(() => {});
|
|
return settled(
|
|
unauthenticated(statusEffect(401), isCommand, metadata),
|
|
"UNAUTHENTICATED",
|
|
);
|
|
}
|
|
if (status === 403) {
|
|
await response.body?.cancel().catch(() => {});
|
|
return settled(
|
|
forbidden(statusEffect(403), isCommand, metadata),
|
|
"FORBIDDEN",
|
|
);
|
|
}
|
|
if (status === 429) {
|
|
await response.body?.cancel().catch(() => {});
|
|
return Object.freeze({
|
|
result: Object.freeze({
|
|
kind: "RATE_LIMITED" as const,
|
|
...(retryAfterMs === null ? {} : { retryAfterMs }),
|
|
metadata,
|
|
effect: normalizeOptionalEffect(statusEffect(429), isCommand),
|
|
}),
|
|
certainty: "RATE_LIMITED",
|
|
retryHint: true,
|
|
retryAfterMs,
|
|
});
|
|
}
|
|
return admitProblem(
|
|
operation,
|
|
response,
|
|
status,
|
|
metadata,
|
|
attemptState,
|
|
readResponseBytes,
|
|
signal,
|
|
);
|
|
}
|
|
|
|
// Success status: body policy first.
|
|
if (contract.responseBody === "NONE") {
|
|
const probe = await probeForbiddenBody(response, signal);
|
|
if (!probe.ok) {
|
|
return settled(
|
|
transportFailure(
|
|
"RESPONSE_STREAM_FAILURE",
|
|
false,
|
|
certaintyForAbandonedAttempt(attemptState, isCommand),
|
|
),
|
|
probe.code,
|
|
);
|
|
}
|
|
if (probe.present) {
|
|
return settled(
|
|
violation("UNEXPECTED_BODY", "RESPONSE", postDispatchEffect(isCommand)),
|
|
"CONTRACT_VIOLATION",
|
|
);
|
|
}
|
|
if (!context.scope.isCurrent()) {
|
|
return settled(
|
|
scopeFenced(postDispatchEffect(isCommand)),
|
|
"SCOPE_FENCED",
|
|
);
|
|
}
|
|
return settled(
|
|
Object.freeze({
|
|
kind: "SUCCESS" as const,
|
|
value: undefined as WireOutput,
|
|
metadata,
|
|
effect: (isCommand
|
|
? "APPLIED_CONFIRMED"
|
|
: "NOT_APPLICABLE") as "NOT_APPLICABLE" | "APPLIED_CONFIRMED",
|
|
}),
|
|
isCommand ? "APPLIED_CONFIRMED" : "NOT_APPLICABLE",
|
|
);
|
|
}
|
|
|
|
const emptyAllowed = contract.emptyBodyStatuses.includes(status);
|
|
const mediaOk = isJsonMediaType(response.headers.get("content-type"));
|
|
const bytes = await readResponseBytes(
|
|
response,
|
|
policy.responseByteLimit,
|
|
signal,
|
|
);
|
|
if (!bytes.ok) {
|
|
return settled(
|
|
bytes.code === "RESPONSE_TOO_LARGE"
|
|
? violation(
|
|
"RESPONSE_TOO_LARGE",
|
|
"RESPONSE",
|
|
postDispatchEffect(isCommand),
|
|
)
|
|
: transportFailure(
|
|
"RESPONSE_STREAM_FAILURE",
|
|
false,
|
|
certaintyForAbandonedAttempt(attemptState, isCommand),
|
|
),
|
|
bytes.code,
|
|
);
|
|
}
|
|
|
|
const empty = isEffectivelyEmpty(bytes.bytes);
|
|
if (empty) {
|
|
if (contract.responseBody === "REQUIRED_JSON" || !emptyAllowed) {
|
|
return settled(
|
|
violation(
|
|
"UNEXPECTED_EMPTY_BODY",
|
|
"RESPONSE",
|
|
postDispatchEffect(isCommand),
|
|
),
|
|
"CONTRACT_VIOLATION",
|
|
);
|
|
}
|
|
if (!context.scope.isCurrent()) {
|
|
return settled(
|
|
scopeFenced(postDispatchEffect(isCommand)),
|
|
"SCOPE_FENCED",
|
|
);
|
|
}
|
|
return settled(
|
|
Object.freeze({
|
|
kind: "SUCCESS" as const,
|
|
value: undefined as WireOutput,
|
|
metadata,
|
|
effect: (isCommand
|
|
? "APPLIED_CONFIRMED"
|
|
: "NOT_APPLICABLE") as "NOT_APPLICABLE" | "APPLIED_CONFIRMED",
|
|
}),
|
|
isCommand ? "APPLIED_CONFIRMED" : "NOT_APPLICABLE",
|
|
);
|
|
}
|
|
|
|
if (!mediaOk) {
|
|
return settled(
|
|
violation(
|
|
"CONTENT_TYPE_MISMATCH",
|
|
"RESPONSE",
|
|
postDispatchEffect(isCommand),
|
|
),
|
|
"CONTRACT_VIOLATION",
|
|
);
|
|
}
|
|
|
|
const decoded = decodeJsonBytes(bytes.bytes);
|
|
if (!decoded.ok) {
|
|
return settled(
|
|
violation(decoded.code, "RESPONSE", postDispatchEffect(isCommand)),
|
|
"CONTRACT_VIOLATION",
|
|
);
|
|
}
|
|
// scale-architecture.md §21–§22. Structure before validation/mapping: the byte ceiling
|
|
// already bounded the parse; the structural budget bounds what the schema
|
|
// validator and mapper are asked to walk.
|
|
if (
|
|
!checkJsonStructure(
|
|
decoded.value,
|
|
responseValidationBudget(policy.responseByteLimit),
|
|
).ok
|
|
) {
|
|
return settled(
|
|
violation("RESPONSE_TOO_LARGE", "RESPONSE", postDispatchEffect(isCommand)),
|
|
"RESPONSE_STRUCTURE_LIMIT",
|
|
);
|
|
}
|
|
|
|
// 1101 README 14.3. The frame is checked after the byte and structure
|
|
// bounds, which count the whole Envelope.
|
|
let wireValue = decoded.value;
|
|
if (contract.responseEnvelope === "ENVELOPE_V1") {
|
|
const framed = readSuccessEnvelope(decoded.value);
|
|
if (!framed.ok) {
|
|
return settled(
|
|
violation(
|
|
"ENVELOPE_MISMATCH",
|
|
"RESPONSE",
|
|
postDispatchEffect(isCommand),
|
|
),
|
|
"CONTRACT_VIOLATION",
|
|
);
|
|
}
|
|
wireValue = framed.value;
|
|
}
|
|
|
|
const validated = invokeValidator(contract.outputValidator, wireValue);
|
|
if (validated.outcome === "THROWN") {
|
|
return settled(
|
|
violation(
|
|
"VALIDATOR_RUNTIME_FAILURE",
|
|
"VALIDATION",
|
|
postDispatchEffect(isCommand),
|
|
),
|
|
"CONTRACT_VIOLATION",
|
|
);
|
|
}
|
|
if (validated.outcome === "INVALID") {
|
|
return settled(
|
|
violation(
|
|
"SUCCESS_SCHEMA_INVALID",
|
|
"VALIDATION",
|
|
postDispatchEffect(isCommand),
|
|
),
|
|
"CONTRACT_VIOLATION",
|
|
);
|
|
}
|
|
|
|
// §10.8. A successful response for a stale scope is discarded, not committed.
|
|
if (!context.scope.isCurrent()) {
|
|
return settled(
|
|
scopeFenced(postDispatchEffect(isCommand)),
|
|
"SCOPE_FENCED",
|
|
);
|
|
}
|
|
|
|
return settled(
|
|
Object.freeze({
|
|
kind: "SUCCESS" as const,
|
|
value: validated.value,
|
|
metadata,
|
|
effect: (isCommand
|
|
? "APPLIED_CONFIRMED"
|
|
: "NOT_APPLICABLE") as "NOT_APPLICABLE" | "APPLIED_CONFIRMED",
|
|
}),
|
|
isCommand ? "APPLIED_CONFIRMED" : "NOT_APPLICABLE",
|
|
);
|
|
}
|
|
|
|
/**
|
|
* LIVE-04. The outcome of a physical wait that the operation's terminal signal
|
|
* bounds.
|
|
*
|
|
* `REJECTED` is kept distinct from `TERMINAL` on purpose: a collaborator's own
|
|
* rejection is evidence about the request, and forging it into a cancellation
|
|
* state would erase the reason the attempt actually failed.
|
|
*/
|
|
type BoundedRace<Value> =
|
|
| Readonly<{ kind: "VALUE"; value: Value }>
|
|
| Readonly<{ kind: "REJECTED" }>
|
|
| Readonly<{ kind: "TERMINAL" }>;
|
|
|
|
const TERMINAL_RACE: BoundedRace<never> = Object.freeze({
|
|
kind: "TERMINAL" as const,
|
|
});
|
|
const REJECTED_RACE: BoundedRace<never> = Object.freeze({
|
|
kind: "REJECTED" as const,
|
|
});
|
|
|
|
/**
|
|
* LIVE-04. Races a physical operation against the terminal signal so a
|
|
* non-cooperative `fetch` or reader cannot hold the port result open past the
|
|
* total deadline.
|
|
*
|
|
* Two properties matter beyond the race itself. A value that arrives while the
|
|
* terminal owner has already fired is *late*, so it is compensated rather than
|
|
* admitted. And the abandoned operation is still observed exactly once, so a
|
|
* late native rejection never surfaces as an unhandled rejection.
|
|
*/
|
|
async function raceTerminal<Value>(
|
|
operation: Promise<Value>,
|
|
signal: AbortSignal,
|
|
compensate: (value: Value) => void,
|
|
): Promise<BoundedRace<Value>> {
|
|
let landed: BoundedRace<Value> | null = null;
|
|
const settled: Promise<BoundedRace<Value>> = operation.then(
|
|
(value) => (landed = Object.freeze({ kind: "VALUE" as const, value })),
|
|
() => (landed = REJECTED_RACE),
|
|
);
|
|
const observeLate = () => {
|
|
void settled.then((outcome) => {
|
|
if (outcome.kind !== "VALUE") return;
|
|
try {
|
|
compensate(outcome.value);
|
|
} catch {
|
|
// Compensation is outside the execution authority.
|
|
}
|
|
});
|
|
};
|
|
let onAbort: (() => void) | undefined;
|
|
const terminal = new Promise<BoundedRace<Value>>((resolve) => {
|
|
if (signal.aborted) {
|
|
resolve(TERMINAL_RACE);
|
|
return;
|
|
}
|
|
onAbort = () => resolve(TERMINAL_RACE);
|
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
});
|
|
try {
|
|
const winner = await Promise.race([settled, terminal]);
|
|
if (winner !== TERMINAL_RACE) return winner;
|
|
// The terminal owner reached the await first. Drain the microtask queue
|
|
// once so an operation that had *already* settled can still hand over its
|
|
// value: a microtask turn cannot be extended by a collaborator that has
|
|
// not settled, so a non-cooperative operation is still abandoned here.
|
|
for (let turn = 0; turn < 4 && landed === null; turn += 1) {
|
|
await Promise.resolve();
|
|
}
|
|
if (landed !== null) return landed;
|
|
observeLate();
|
|
return TERMINAL_RACE;
|
|
} finally {
|
|
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
}
|
|
}
|
|
|
|
function cancelResponseBody(response: Response): void {
|
|
void response.body?.cancel().catch(() => {});
|
|
}
|
|
|
|
const ABORTED = Symbol("http-operation-aborted");
|
|
|
|
async function awaitWithAbort<Value>(
|
|
operation: Promise<Value>,
|
|
signal: AbortSignal,
|
|
): Promise<Value | typeof ABORTED> {
|
|
if (signal.aborted) return ABORTED;
|
|
let onAbort: (() => void) | undefined;
|
|
const aborted = new Promise<typeof ABORTED>((resolve) => {
|
|
onAbort = () => resolve(ABORTED);
|
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
});
|
|
try {
|
|
return await Promise.race([operation, aborted]);
|
|
} finally {
|
|
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
}
|
|
}
|
|
|
|
const UNFRAMED_PROBLEM: ValidatorInvocation<never> = Object.freeze({
|
|
outcome: "INVALID" as const,
|
|
issues: Object.freeze([]),
|
|
});
|
|
|
|
async function admitProblem<Input, WireOutput, Problem>(
|
|
operation: InstalledHttpContract<Input, WireOutput, Problem>,
|
|
response: Response,
|
|
status: number,
|
|
metadata: SafeResponseMetadata,
|
|
attemptState: PhysicalAttemptState,
|
|
readResponseBytes: typeof readBoundedBytes,
|
|
signal: AbortSignal,
|
|
): Promise<AdmissionOutcome<WireOutput, Problem>> {
|
|
const contract = operation.contract;
|
|
const isCommand = contract.commandEffect !== null;
|
|
const retryable = isRetryableHttpStatus(status);
|
|
const enveloped = contract.responseEnvelope === "ENVELOPE_V1";
|
|
// 1101 README 14.3. A failure Envelope is bounded by the operation's
|
|
// response limit too, and never above the problem ceiling.
|
|
const problemByteLimit = enveloped
|
|
? Math.min(
|
|
HTTP_EXECUTION_CEILINGS.problemResponseBytes,
|
|
operation.frontend.responseByteLimit,
|
|
)
|
|
: HTTP_EXECUTION_CEILINGS.problemResponseBytes;
|
|
|
|
const bytes = await readResponseBytes(response, problemByteLimit, signal);
|
|
if (!bytes.ok || isEffectivelyEmpty(bytes.bytes)) {
|
|
// An unclassifiable failure stays uncertain for a command.
|
|
return Object.freeze({
|
|
result: violation<WireOutput, Problem>(
|
|
"PROBLEM_SCHEMA_INVALID",
|
|
"VALIDATION",
|
|
postDispatchEffect(isCommand),
|
|
metadata,
|
|
),
|
|
certainty: isCommand ? "MAYBE_APPLIED" : "NOT_STARTED",
|
|
retryHint: retryable,
|
|
retryAfterMs: metadata.retryAfterMs ?? null,
|
|
});
|
|
}
|
|
if (!isJsonMediaType(response.headers.get("content-type"))) {
|
|
return Object.freeze({
|
|
result: violation<WireOutput, Problem>(
|
|
"CONTENT_TYPE_MISMATCH",
|
|
"RESPONSE",
|
|
postDispatchEffect(isCommand),
|
|
metadata,
|
|
),
|
|
certainty: isCommand ? "MAYBE_APPLIED" : "NOT_STARTED",
|
|
retryHint: retryable,
|
|
retryAfterMs: metadata.retryAfterMs ?? null,
|
|
});
|
|
}
|
|
|
|
const decoded = decodeJsonBytes(bytes.bytes);
|
|
if (!decoded.ok) {
|
|
return Object.freeze({
|
|
result: violation<WireOutput, Problem>(
|
|
decoded.code,
|
|
"RESPONSE",
|
|
postDispatchEffect(isCommand),
|
|
metadata,
|
|
),
|
|
certainty: isCommand ? "MAYBE_APPLIED" : "NOT_STARTED",
|
|
retryHint: retryable,
|
|
retryAfterMs: metadata.retryAfterMs ?? null,
|
|
});
|
|
}
|
|
|
|
if (
|
|
!checkJsonStructure(decoded.value, responseValidationBudget(problemByteLimit))
|
|
.ok
|
|
) {
|
|
return Object.freeze({
|
|
result: violation<WireOutput, Problem>(
|
|
"PROBLEM_SCHEMA_INVALID",
|
|
"VALIDATION",
|
|
postDispatchEffect(isCommand),
|
|
metadata,
|
|
),
|
|
certainty: isCommand ? "MAYBE_APPLIED" : "NOT_STARTED",
|
|
retryHint: false,
|
|
retryAfterMs: metadata.retryAfterMs ?? null,
|
|
});
|
|
}
|
|
|
|
// 1101 README 14.3. An Envelope operation's problem is the `error` object.
|
|
// A body that is not a failure Envelope is an unreadable problem.
|
|
let validated: ValidatorInvocation<Problem>;
|
|
let backendEffect: "NOT_APPLIED" | "MAYBE_APPLIED" | undefined;
|
|
let refusalReason: IdempotencyRefusalReason | undefined;
|
|
if (enveloped) {
|
|
const framed = readFailureEnvelope(decoded.value);
|
|
validated = framed.ok
|
|
? invokeValidator(contract.problemValidator, framed.value)
|
|
: UNFRAMED_PROBLEM;
|
|
if (framed.ok) {
|
|
backendEffect = envelopeFailureEffect(status, framed.value);
|
|
refusalReason = idempotencyRefusalReason(framed.value.code, status);
|
|
}
|
|
} else {
|
|
validated = invokeValidator(contract.problemValidator, decoded.value);
|
|
}
|
|
if (validated.outcome !== "VALID") {
|
|
return Object.freeze({
|
|
result: violation<WireOutput, Problem>(
|
|
validated.outcome === "THROWN"
|
|
? "VALIDATOR_RUNTIME_FAILURE"
|
|
: "PROBLEM_SCHEMA_INVALID",
|
|
"VALIDATION",
|
|
postDispatchEffect(isCommand),
|
|
metadata,
|
|
),
|
|
certainty: isCommand ? "MAYBE_APPLIED" : "NOT_STARTED",
|
|
retryHint: retryable,
|
|
retryAfterMs: metadata.retryAfterMs ?? null,
|
|
});
|
|
}
|
|
|
|
// The backend's own verdict, when it has one, is the same for every
|
|
// operation. The package classifies the rest.
|
|
const classification =
|
|
isCommand && backendEffect !== undefined
|
|
? Object.freeze({ effect: backendEffect, contractRuntimeFailure: false })
|
|
: classifyProblemEffect({
|
|
status,
|
|
problem: validated.value,
|
|
descriptor: contract.commandEffect,
|
|
});
|
|
const effect = isCommand
|
|
? classification.effect
|
|
: certaintyForAbandonedAttempt(attemptState, false);
|
|
|
|
return Object.freeze({
|
|
result: Object.freeze({
|
|
kind: "PROBLEM" as const,
|
|
problem: validated.value,
|
|
metadata,
|
|
effect: (effect === "NOT_STARTED"
|
|
? "NOT_APPLIED"
|
|
: effect) as "NOT_APPLIED" | "APPLIED_CONFIRMED" | "MAYBE_APPLIED",
|
|
}),
|
|
certainty: effect,
|
|
retryHint: retryable && effect !== "MAYBE_APPLIED",
|
|
retryAfterMs: metadata.retryAfterMs ?? null,
|
|
...(isCommand && classification.contractRuntimeFailure
|
|
? { diagnosticReason: "CLASSIFIER_FAILED" as const }
|
|
: refusalReason === undefined
|
|
? {}
|
|
: { diagnosticReason: refusalReason }),
|
|
});
|
|
}
|
|
|
|
/** §7.12. No raw header map, URL, cookie, traceparent or ETag value escapes. */
|
|
function safeMetadata(
|
|
response: Response,
|
|
retryAfterMs: number | null,
|
|
): SafeResponseMetadata {
|
|
const correlation = response.headers.get("x-correlation-id");
|
|
return Object.freeze({
|
|
status: response.status,
|
|
...(correlation && /^[A-Za-z0-9._:-]{1,128}$/.test(correlation)
|
|
? { correlationReference: correlation }
|
|
: {}),
|
|
...(retryAfterMs === null ? {} : { retryAfterMs }),
|
|
});
|
|
}
|
|
|
|
function settled<Value, Problem>(
|
|
result: HttpExecutionOutcome<Value, Problem>,
|
|
certainty: string,
|
|
): AdmissionOutcome<Value, Problem> {
|
|
return Object.freeze({
|
|
result,
|
|
certainty,
|
|
retryHint: false,
|
|
retryAfterMs: null,
|
|
});
|
|
}
|
|
|
|
function violation<Value, Problem>(
|
|
kind: HttpContractViolationKind,
|
|
operation: HttpContractViolation["operation"],
|
|
effect: HttpEffectCertainty,
|
|
metadata?: SafeResponseMetadata,
|
|
): HttpExecutionOutcome<Value, Problem> {
|
|
return Object.freeze({
|
|
kind: "CONTRACT_VIOLATION" as const,
|
|
violation: Object.freeze({ kind, operation }),
|
|
...(metadata === undefined ? {} : { metadata }),
|
|
effect,
|
|
});
|
|
}
|
|
|
|
/** 03-02. A request refused before dispatch, with its cause. */
|
|
function refusedRequest<Value, Problem>(
|
|
reason: HttpRequestRejectionReason,
|
|
effect: HttpEffectCertainty,
|
|
): HttpExecutionOutcome<Value, Problem> {
|
|
return Object.freeze({
|
|
kind: "CONTRACT_VIOLATION" as const,
|
|
violation: Object.freeze({
|
|
kind: "FINAL_REQUEST_INVARIANT_FAILED" as const,
|
|
operation: "REQUEST" as const,
|
|
reason,
|
|
}),
|
|
effect,
|
|
});
|
|
}
|
|
|
|
function scopeFenced<Value, Problem>(
|
|
effect: HttpEffectCertainty,
|
|
): HttpExecutionOutcome<Value, Problem> {
|
|
return violation("SCOPE_FENCED", "RESPONSE", effect);
|
|
}
|
|
|
|
/**
|
|
* §7.7. A credential collaborator or profile-binding breach. It always resolves
|
|
* before dispatch, so the command effect is `NOT_STARTED` and fetch count zero.
|
|
*/
|
|
function authIntegrationFailure<Value, Problem>(
|
|
reason: AuthIntegrationFailureReason,
|
|
isCommand: boolean,
|
|
): HttpExecutionOutcome<Value, Problem> {
|
|
return Object.freeze({
|
|
kind: "AUTH_INTEGRATION_FAILURE" as const,
|
|
reason,
|
|
effect: isCommand ? ("NOT_STARTED" as const) : ("NOT_APPLICABLE" as const),
|
|
});
|
|
}
|
|
|
|
function preDispatchEffect(isCommand: boolean): HttpEffectCertainty {
|
|
return isCommand ? "NOT_STARTED" : "NOT_APPLICABLE";
|
|
}
|
|
|
|
function postDispatchEffect(isCommand: boolean): HttpEffectCertainty {
|
|
return isCommand ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
|
|
}
|
|
|
|
function unauthenticated<Value, Problem>(
|
|
effect: string,
|
|
isCommand: boolean,
|
|
metadata?: SafeResponseMetadata,
|
|
): HttpExecutionOutcome<Value, Problem> {
|
|
return Object.freeze({
|
|
kind: "UNAUTHENTICATED" as const,
|
|
...(metadata === undefined ? {} : { metadata }),
|
|
effect: normalizeOptionalEffect(effect, isCommand),
|
|
});
|
|
}
|
|
|
|
function forbidden<Value, Problem>(
|
|
effect: string,
|
|
isCommand: boolean,
|
|
metadata: SafeResponseMetadata,
|
|
): HttpExecutionOutcome<Value, Problem> {
|
|
return Object.freeze({
|
|
kind: "FORBIDDEN" as const,
|
|
metadata,
|
|
effect: normalizeOptionalEffect(effect, isCommand),
|
|
});
|
|
}
|
|
|
|
function cancelled<Value, Problem>(
|
|
effect: "NOT_STARTED" | "NOT_APPLIED" | "MAYBE_APPLIED" | "APPLIED_CONFIRMED",
|
|
): HttpExecutionOutcome<Value, Problem> {
|
|
return Object.freeze({
|
|
kind: "CANCELLED" as const,
|
|
effect: effect === "MAYBE_APPLIED" ? "MAYBE_APPLIED" : "NOT_STARTED",
|
|
});
|
|
}
|
|
|
|
function transportFailure<Value, Problem>(
|
|
kind: HttpTransportFailure["kind"],
|
|
retryable: boolean,
|
|
effect: MutationEffectCertainty,
|
|
): HttpExecutionOutcome<Value, Problem> {
|
|
return Object.freeze({
|
|
kind: "TRANSPORT_FAILURE" as const,
|
|
failure: Object.freeze({ kind, retryable }),
|
|
effect: effect === "MAYBE_APPLIED" ? "MAYBE_APPLIED" : "NOT_STARTED",
|
|
});
|
|
}
|
|
|
|
function normalizeOptionalEffect(
|
|
effect: string,
|
|
isCommand: boolean,
|
|
): "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED" {
|
|
if (!isCommand) return "NOT_APPLICABLE";
|
|
return effect === "MAYBE_APPLIED" ? "MAYBE_APPLIED" : "NOT_APPLIED";
|
|
}
|