V3 read the response x-correlation-id and dropped it, and untraced requests sent no id, so a support reference could not be matched to a server log. Each logical execution now sends one x-correlation-id; failures carry the echoed value as requestId and diagnostics record it as correlation_id. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
480 lines
15 KiB
TypeScript
480 lines
15 KiB
TypeScript
import type {
|
|
InstalledHttpContract,
|
|
} from "../../contracts/external-contract-runtime.ts";
|
|
import type { Result } from "../../contracts/result.ts";
|
|
import type { MappingResult } from "../../contracts/boundary-mapper.ts";
|
|
import {
|
|
createFailure,
|
|
kindForStatus,
|
|
type ApiFailure,
|
|
type FailureEffectCertainty,
|
|
type FailureKind,
|
|
} from "../../contracts/errors.ts";
|
|
import type { MutationIntent } from "../../contracts/mutation-intent.ts";
|
|
import type { ExecutionContext } from "../../platform/execution/execution-context.ts";
|
|
import type {
|
|
HttpExecutionOutcome,
|
|
SafeResponseMetadata,
|
|
} from "./http-execution-v3.ts";
|
|
|
|
type ValidatorValue<Validator> =
|
|
Validator extends Readonly<{
|
|
safeParse(value: unknown): infer ParseResult;
|
|
}>
|
|
? Extract<
|
|
ParseResult,
|
|
Readonly<{ success: true; data: unknown }>
|
|
> extends Readonly<{ data: infer Value }>
|
|
? Value
|
|
: never
|
|
: never;
|
|
|
|
export type HttpContractInput<Contract> =
|
|
Contract extends Readonly<{
|
|
contract: Readonly<{ inputValidator: infer Validator }>;
|
|
}>
|
|
? ValidatorValue<Validator>
|
|
: never;
|
|
|
|
export type HttpContractWireOutput<Contract> =
|
|
Contract extends Readonly<{
|
|
contract: Readonly<{ outputValidator: infer Validator }>;
|
|
}>
|
|
? ValidatorValue<Validator>
|
|
: never;
|
|
|
|
export type HttpContractProblem<Contract> =
|
|
Contract extends Readonly<{
|
|
contract: Readonly<{ problemValidator: infer Validator }>;
|
|
}>
|
|
? ValidatorValue<Validator>
|
|
: never;
|
|
|
|
export type HttpContractOperationId<Contract> =
|
|
Contract extends Readonly<{
|
|
contract: Readonly<{ operationId: infer OperationId extends string }>;
|
|
}>
|
|
? OperationId
|
|
: never;
|
|
|
|
export type InstalledHttpOperationExecutor = Readonly<{
|
|
execute<Input, WireOutput, Problem>(
|
|
contract: InstalledHttpContract<Input, WireOutput, Problem>,
|
|
input: Input,
|
|
context: Readonly<{
|
|
routeId: string;
|
|
signal?: AbortSignal;
|
|
intent?: MutationIntent;
|
|
execution?: ExecutionContext;
|
|
}>,
|
|
): Promise<HttpExecutionOutcome<WireOutput, Problem>>;
|
|
}>;
|
|
|
|
export type FeatureHttpProblemMapping = Readonly<{
|
|
kind: FailureKind;
|
|
code: string;
|
|
}>;
|
|
|
|
type FeatureHttpOperationSpec<
|
|
Contract,
|
|
Value,
|
|
RouteId extends string,
|
|
> = Readonly<{
|
|
contract: Contract;
|
|
routeId: RouteId;
|
|
mapSuccess(
|
|
value: HttpContractWireOutput<Contract>,
|
|
): MappingResult<Value>;
|
|
mapProblem?(
|
|
problem: HttpContractProblem<Contract>,
|
|
metadata: SafeResponseMetadata,
|
|
): FeatureHttpProblemMapping | undefined;
|
|
}>;
|
|
|
|
export type FeatureHttpOperation<
|
|
Contract,
|
|
Value,
|
|
RouteId extends string = string,
|
|
> = FeatureHttpOperationSpec<Contract, Value, RouteId> &
|
|
Readonly<{
|
|
operationId: HttpContractOperationId<Contract>;
|
|
/**
|
|
* Compile-time only carrier. The runtime object has no extra type payload;
|
|
* the contract remains the authority for input/wire/problem types.
|
|
*/
|
|
__types?: Readonly<{
|
|
value: Value;
|
|
}>;
|
|
}>;
|
|
|
|
type ContractValidity<Contract> =
|
|
HttpContractOperationId<Contract> extends never
|
|
? never
|
|
: HttpContractInput<Contract> extends never
|
|
? never
|
|
: HttpContractWireOutput<Contract> extends never
|
|
? never
|
|
: HttpContractProblem<Contract> extends never
|
|
? never
|
|
: unknown;
|
|
|
|
function defineFeatureHttpOperationForRoute<
|
|
const RouteId extends string,
|
|
const Contract,
|
|
Value,
|
|
>(
|
|
spec: FeatureHttpOperationSpec<Contract, Value, RouteId> &
|
|
ContractValidity<Contract>,
|
|
): FeatureHttpOperation<Contract, Value, RouteId> {
|
|
return Object.freeze({
|
|
...spec,
|
|
operationId: (spec.contract as Readonly<{
|
|
contract: Readonly<{ operationId: HttpContractOperationId<Contract> }>;
|
|
}>).contract.operationId,
|
|
}) as FeatureHttpOperation<Contract, Value, RouteId>;
|
|
}
|
|
|
|
export function defineFeatureHttpOperation<
|
|
const Contract,
|
|
Value,
|
|
const RouteId extends string,
|
|
>(
|
|
spec: FeatureHttpOperationSpec<Contract, Value, RouteId> &
|
|
ContractValidity<Contract>,
|
|
): FeatureHttpOperation<Contract, Value, RouteId> {
|
|
return defineFeatureHttpOperationForRoute(spec);
|
|
}
|
|
|
|
/**
|
|
* Feature-local route typing without introducing a dependency from the HTTP
|
|
* capability to the presentation route registry.
|
|
*/
|
|
export function defineFeatureHttpOperationForRoutes<
|
|
const RouteId extends string,
|
|
>() {
|
|
return function defineRouteBoundFeatureHttpOperation<
|
|
const Contract,
|
|
Value,
|
|
>(
|
|
spec: FeatureHttpOperationSpec<Contract, Value, RouteId> &
|
|
ContractValidity<Contract>,
|
|
): FeatureHttpOperation<Contract, Value, RouteId> {
|
|
return defineFeatureHttpOperationForRoute(spec);
|
|
};
|
|
}
|
|
|
|
type FeatureHttpOperationShape = Readonly<{
|
|
contract: object;
|
|
operationId: string;
|
|
routeId: string;
|
|
mapSuccess: (...args: never[]) => unknown;
|
|
mapProblem?: (...args: never[]) => unknown;
|
|
}>;
|
|
|
|
type OperationContract<Operation> =
|
|
Operation extends Readonly<{ contract: infer Contract }> ? Contract : never;
|
|
|
|
type OperationInput<Operation> = HttpContractInput<OperationContract<Operation>>;
|
|
type OperationWireOutput<Operation> =
|
|
HttpContractWireOutput<OperationContract<Operation>>;
|
|
type OperationProblem<Operation> =
|
|
HttpContractProblem<OperationContract<Operation>>;
|
|
|
|
type OperationValue<Operation> =
|
|
Operation extends FeatureHttpOperation<infer _Contract, infer Value, string>
|
|
? Value
|
|
: never;
|
|
|
|
type InvalidOperationRegistryKeys<
|
|
Operations extends Readonly<Record<string, FeatureHttpOperationShape>>,
|
|
> = {
|
|
[OperationId in keyof Operations & string]:
|
|
OperationId extends Operations[OperationId]["operationId"]
|
|
? Operations[OperationId]["operationId"] extends OperationId
|
|
? never
|
|
: OperationId
|
|
: OperationId;
|
|
}[keyof Operations & string];
|
|
|
|
type ValidOperationRegistry<
|
|
Operations extends Readonly<Record<string, FeatureHttpOperationShape>>,
|
|
> = InvalidOperationRegistryKeys<Operations> extends never
|
|
? unknown
|
|
: Readonly<{
|
|
__operationRegistryKeyMismatch: InvalidOperationRegistryKeys<Operations>;
|
|
}>;
|
|
|
|
export type FeatureHttpBinding<
|
|
Operations extends Readonly<Record<string, FeatureHttpOperationShape>>,
|
|
> = Readonly<{
|
|
execute<OperationId extends keyof Operations & string>(
|
|
operationId: OperationId,
|
|
input: OperationInput<Operations[OperationId]>,
|
|
context?: Readonly<{
|
|
signal?: AbortSignal;
|
|
intent?: MutationIntent;
|
|
execution?: ExecutionContext;
|
|
}>,
|
|
): Promise<Result<OperationValue<Operations[OperationId]>, ApiFailure>>;
|
|
}>;
|
|
|
|
/**
|
|
* Capability-specific feature binding for the installed HTTP runtime.
|
|
*
|
|
* The installed contract is the single type authority. A feature contributes
|
|
* only a route identity plus wire-to-domain/problem interpretation. Transport,
|
|
* retry, validation and effect-certainty stay in the reusable HTTP capability.
|
|
*/
|
|
export function createFeatureHttpBinding<
|
|
const Operations extends Readonly<Record<string, FeatureHttpOperationShape>>,
|
|
>(
|
|
executor: InstalledHttpOperationExecutor,
|
|
operations: Operations & ValidOperationRegistry<Operations>,
|
|
): FeatureHttpBinding<Operations> {
|
|
for (const [registryId, operation] of Object.entries(operations)) {
|
|
if (registryId !== operation.operationId) {
|
|
throw new TypeError(
|
|
`Feature HTTP operation key mismatch: ${registryId} !== ${operation.operationId}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
return Object.freeze({
|
|
async execute<OperationId extends keyof Operations & string>(
|
|
operationId: OperationId,
|
|
input: OperationInput<Operations[OperationId]>,
|
|
context: Readonly<{
|
|
signal?: AbortSignal;
|
|
intent?: MutationIntent;
|
|
execution?: ExecutionContext;
|
|
}> = {},
|
|
): Promise<Result<OperationValue<Operations[OperationId]>, ApiFailure>> {
|
|
const operation = operations[operationId];
|
|
type SelectedOperation = Operations[OperationId];
|
|
type Input = OperationInput<SelectedOperation>;
|
|
type WireOutput = OperationWireOutput<SelectedOperation>;
|
|
type Problem = OperationProblem<SelectedOperation>;
|
|
type Value = OperationValue<SelectedOperation>;
|
|
|
|
const contract = operation.contract as InstalledHttpContract<
|
|
Input,
|
|
WireOutput,
|
|
Problem
|
|
>;
|
|
const outcome = await executor.execute(contract, input, {
|
|
routeId: operation.routeId,
|
|
...(context.signal === undefined ? {} : { signal: context.signal }),
|
|
...(context.intent === undefined ? {} : { intent: context.intent }),
|
|
...(context.execution === undefined
|
|
? {}
|
|
: { execution: context.execution }),
|
|
});
|
|
return projectExecutionOutcome(
|
|
operation.operationId,
|
|
operation.mapSuccess as (value: WireOutput) => MappingResult<Value>,
|
|
operation.mapProblem as
|
|
| ((
|
|
problem: Problem,
|
|
metadata: SafeResponseMetadata,
|
|
) => FeatureHttpProblemMapping | undefined)
|
|
| undefined,
|
|
outcome,
|
|
);
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 03-03. A failure carries the server's echoed correlation id as `requestId`,
|
|
* so the support reference a user reports points at one server log entry.
|
|
*/
|
|
function projectExecutionOutcome<WireOutput, Problem, Value>(
|
|
operationId: string,
|
|
mapSuccess: (value: WireOutput) => MappingResult<Value>,
|
|
mapProblem:
|
|
| ((
|
|
problem: Problem,
|
|
metadata: SafeResponseMetadata,
|
|
) => FeatureHttpProblemMapping | undefined)
|
|
| undefined,
|
|
outcome: HttpExecutionOutcome<WireOutput, Problem>,
|
|
): Result<Value, ApiFailure> {
|
|
const projected = projectOutcome(operationId, mapSuccess, mapProblem, outcome);
|
|
const requestId =
|
|
"metadata" in outcome
|
|
? outcome.metadata?.correlationReference
|
|
: undefined;
|
|
return projected.ok || requestId === undefined
|
|
? projected
|
|
: Object.freeze({
|
|
ok: false as const,
|
|
error: Object.freeze({ ...projected.error, requestId }),
|
|
});
|
|
}
|
|
|
|
function projectOutcome<WireOutput, Problem, Value>(
|
|
operationId: string,
|
|
mapSuccess: (value: WireOutput) => MappingResult<Value>,
|
|
mapProblem:
|
|
| ((
|
|
problem: Problem,
|
|
metadata: SafeResponseMetadata,
|
|
) => FeatureHttpProblemMapping | undefined)
|
|
| undefined,
|
|
outcome: HttpExecutionOutcome<WireOutput, Problem>,
|
|
): Result<Value, ApiFailure> {
|
|
// A throwing feature mapper is a mapping defect, not a transport failure: it
|
|
// must not reject and lose the effect the server already confirmed.
|
|
const mapperThrew = (
|
|
effect: FailureEffectCertainty,
|
|
httpStatus: number,
|
|
): Result<Value, ApiFailure> =>
|
|
failure(
|
|
"MAPPING_CONTRACT_VIOLATION",
|
|
operationId,
|
|
"MAPPING_CONTRACT_VIOLATION",
|
|
{ httpStatus, effect },
|
|
);
|
|
switch (outcome.kind) {
|
|
case "SUCCESS": {
|
|
let mapped: MappingResult<Value>;
|
|
try {
|
|
mapped = mapSuccess(outcome.value);
|
|
} catch {
|
|
return mapperThrew(outcome.effect, outcome.metadata.status);
|
|
}
|
|
return mapped.ok
|
|
? Object.freeze({ ok: true as const, value: mapped.value })
|
|
: failure(
|
|
"MAPPING_CONTRACT_VIOLATION",
|
|
operationId,
|
|
mapped.code,
|
|
{ effect: outcome.effect },
|
|
);
|
|
}
|
|
case "PROBLEM": {
|
|
let mapped: FeatureHttpProblemMapping | undefined;
|
|
try {
|
|
mapped = mapProblem?.(outcome.problem, outcome.metadata);
|
|
} catch {
|
|
return mapperThrew(outcome.effect, outcome.metadata.status);
|
|
}
|
|
return failure(
|
|
mapped?.kind ?? kindForStatus(outcome.metadata.status),
|
|
operationId,
|
|
mapped?.code ?? "CONTRACT_PROBLEM",
|
|
{ httpStatus: outcome.metadata.status, effect: outcome.effect },
|
|
);
|
|
}
|
|
case "UNAUTHENTICATED":
|
|
return failure("AUTH_REQUIRED", operationId, "UNAUTHENTICATED", {
|
|
effect: outcome.effect,
|
|
});
|
|
case "FORBIDDEN":
|
|
return failure("FORBIDDEN", operationId, "FORBIDDEN", {
|
|
effect: outcome.effect,
|
|
});
|
|
case "RATE_LIMITED":
|
|
return failure("RATE_LIMITED", operationId, "RATE_LIMITED", {
|
|
...(outcome.retryAfterMs === undefined
|
|
? {}
|
|
: { retryAfterMs: outcome.retryAfterMs }),
|
|
effect: outcome.effect,
|
|
});
|
|
case "CANCELLED":
|
|
return failure("REQUEST_ABORTED", operationId, "REQUEST_ABORTED", {
|
|
effect: outcome.effect,
|
|
});
|
|
case "AUTH_INTEGRATION_FAILURE":
|
|
return failure(
|
|
"AUTH_INTEGRATION_FAILURE",
|
|
operationId,
|
|
outcome.reason,
|
|
{ effect: outcome.effect },
|
|
);
|
|
case "TRANSPORT_FAILURE":
|
|
return failure(
|
|
outcome.failure.kind === "TIMEOUT"
|
|
? "REQUEST_TIMEOUT"
|
|
: outcome.failure.kind === "ABORTED_BY_SCOPE"
|
|
? "SCOPE_GENERATION_CHANGED"
|
|
: "NETWORK_UNREACHABLE",
|
|
operationId,
|
|
outcome.failure.kind,
|
|
{ effect: outcome.effect },
|
|
);
|
|
case "CONTRACT_VIOLATION": {
|
|
const httpStatus = outcome.metadata?.status;
|
|
// R-3.3. A gateway 5xx/408/425 with an HTML or empty body is a server
|
|
// outage: keep its status and retryability instead of "contact support".
|
|
if (httpStatus !== undefined && isServerFailureStatus(httpStatus)) {
|
|
return failure("SERVER_FAILURE", operationId, outcome.violation.kind, {
|
|
httpStatus,
|
|
effect: outcome.effect,
|
|
});
|
|
}
|
|
return failure(
|
|
failureKindForViolation(outcome.violation.kind),
|
|
operationId,
|
|
outcome.violation.kind,
|
|
{
|
|
...(httpStatus === undefined ? {} : { httpStatus }),
|
|
effect: outcome.effect,
|
|
},
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
function isServerFailureStatus(status: number): boolean {
|
|
return status >= 500 || status === 408 || status === 425;
|
|
}
|
|
|
|
function failureKindForViolation(
|
|
violation: Extract<
|
|
HttpExecutionOutcome<unknown, unknown>,
|
|
{ kind: "CONTRACT_VIOLATION" }
|
|
>["violation"]["kind"],
|
|
): FailureKind {
|
|
switch (violation) {
|
|
case "CONTENT_TYPE_MISMATCH":
|
|
return "CONTENT_TYPE_MISMATCH";
|
|
case "RESPONSE_TOO_LARGE":
|
|
return "RESPONSE_BODY_LIMIT";
|
|
case "UTF8_INVALID":
|
|
case "JSON_INVALID":
|
|
return "MALFORMED_JSON";
|
|
case "MAPPING_CONTRACT_VIOLATION":
|
|
return "MAPPING_CONTRACT_VIOLATION";
|
|
case "SCOPE_FENCED":
|
|
return "SCOPE_GENERATION_CHANGED";
|
|
case "SUCCESS_SCHEMA_INVALID":
|
|
case "PROBLEM_SCHEMA_INVALID":
|
|
case "VALIDATOR_RUNTIME_FAILURE":
|
|
return "SCHEMA_MISMATCH";
|
|
// Rejected before dispatch: the request, not the server answer, was wrong.
|
|
case "FINAL_REQUEST_INVARIANT_FAILED":
|
|
case "MISSING_IDEMPOTENCY_KEY":
|
|
case "UNEXPECTED_IDEMPOTENCY_KEY":
|
|
return "VALIDATION_REJECTED";
|
|
default:
|
|
return "ENVELOPE_MISMATCH";
|
|
}
|
|
}
|
|
|
|
function failure(
|
|
kind: FailureKind,
|
|
operationId: string,
|
|
code: string,
|
|
details: Readonly<{
|
|
httpStatus?: number;
|
|
retryAfterMs?: number;
|
|
effect?: FailureEffectCertainty;
|
|
}> = {},
|
|
): Result<never, ApiFailure> {
|
|
return Object.freeze({
|
|
ok: false as const,
|
|
error: createFailure(kind, operationId, 0, { code, ...details }),
|
|
});
|
|
}
|