Files
memento-frontend/src/adapters/http/feature-http-binding.ts
T

238 lines
7.1 KiB
TypeScript

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 { HttpExecutionOutcome } from "./http-execution-v3.ts";
export type InstalledHttpOperationExecutor = Readonly<{
execute(
operationId: string,
input: unknown,
context: Readonly<{
routeId: string;
signal?: AbortSignal;
intent?: MutationIntent;
}>,
): Promise<HttpExecutionOutcome<unknown, unknown>>;
}>;
type FeatureHttpOperationSpec<Value> = Readonly<{
operationId: string;
routeId: string;
mapSuccess(value: unknown): MappingResult<Value>;
}>;
export type FeatureHttpOperation<Input, Value> =
FeatureHttpOperationSpec<Value> &
Readonly<{
/**
* Compile-time only carrier. Feature bindings remain plain frozen objects
* at runtime while preserving each operation's input/value pair.
*/
__types?: Readonly<{
input: Input;
value: Value;
}>;
}>;
export function defineFeatureHttpOperation<Input, Value>(
spec: FeatureHttpOperationSpec<Value>,
): FeatureHttpOperation<Input, Value> {
return Object.freeze(spec) as FeatureHttpOperation<Input, Value>;
}
type OperationInput<Operation> =
Operation extends FeatureHttpOperation<infer Input, unknown> ? Input : never;
type OperationValue<Operation> =
Operation extends FeatureHttpOperation<unknown, infer Value> ? Value : never;
export type FeatureHttpBinding<
Operations extends Readonly<
Record<string, FeatureHttpOperation<unknown, unknown>>
>,
> = Readonly<{
execute<OperationId extends keyof Operations & string>(
operationId: OperationId,
input: OperationInput<Operations[OperationId]>,
context?: Readonly<{
signal?: AbortSignal;
intent?: MutationIntent;
}>,
): Promise<Result<OperationValue<Operations[OperationId]>, ApiFailure>>;
}>;
/**
* Capability-specific feature binding for the installed HTTP runtime.
*
* The platform owns transport/outcome normalization. A feature contributes only
* operation identity, route identity, typed input and its wire-to-domain mapper.
* This keeps HTTP lifecycle/failure semantics out of feature application code
* without collapsing storage/realtime/transfer into a universal repository.
*/
export function createFeatureHttpBinding<
const Operations extends Readonly<
Record<string, FeatureHttpOperation<unknown, unknown>>
>,
>(
executor: InstalledHttpOperationExecutor,
operations: 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;
}> = {},
): Promise<Result<OperationValue<Operations[OperationId]>, ApiFailure>> {
const operation = operations[operationId];
const outcome = await executor.execute(operation.operationId, input, {
routeId: operation.routeId,
...(context.signal === undefined ? {} : { signal: context.signal }),
...(context.intent === undefined ? {} : { intent: context.intent }),
});
return projectExecutionOutcome<
OperationValue<Operations[OperationId]>
>(
operation.operationId,
operation.mapSuccess as (
value: unknown,
) => MappingResult<OperationValue<Operations[OperationId]>>,
outcome,
);
},
});
}
function projectExecutionOutcome<Value>(
operationId: string,
mapSuccess: (value: unknown) => MappingResult<Value>,
outcome: HttpExecutionOutcome<unknown, unknown>,
): Result<Value, ApiFailure> {
switch (outcome.kind) {
case "SUCCESS": {
const mapped = mapSuccess(outcome.value);
return mapped.ok
? Object.freeze({ ok: true as const, value: mapped.value })
: failure(
"MAPPING_CONTRACT_VIOLATION",
operationId,
mapped.code,
{ effect: outcome.effect },
);
}
case "PROBLEM":
return failure(
kindForStatus(outcome.metadata.status),
operationId,
"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":
return failure(
failureKindForViolation(outcome.violation.kind),
operationId,
outcome.violation.kind,
{ effect: outcome.effect },
);
}
}
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";
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 }),
});
}