Files
clean-architecture-frontend…/src/adapters/http/client.ts
T
DongHyeonka fc303d89bc refactor(contracts): 폐기 별칭 import를 새 이름으로 옮기고 lint로 막는다 (07-01)
문제
MappingResult라는 이름이 두 모양을 가리킨다. external-contract-runtime.ts의
MappingResult({ ok:false, error:{ kind, code } })는 주석이 "정본"이라고
부르지만 테스트 말고 쓰는 곳이 없다. boundary-mapper.ts는
{ ok:false, code } 모양을 BoundaryMappingResult로 이름 붙이고 같은 이름
MappingResult를 @deprecated 별칭으로 남겼는데, 실행 경로가 그 별칭을
요구한다(feature-http-binding mapSuccess, client.ts, resource-mapper,
참조 mapper, boundary-mapper 자신의 helper 반환 타입). 그래서 별칭의 제거
조건("이 파일에서 MappingResult를 import하는 모듈이 없을 때")이 충족될 수
없다. ApiFailure 별칭도 포트 2개와 참조 기능을 포함해 7개 파일이 쓴다.
eslint 설정에 폐기 검사가 없다.

고른 방법 (리뷰 최소 개선 (1)·(4)와 lint, 공개 이름은 그대로)
- boundary-mapper의 BoundaryMapper.map, mapWithBoundaryRegistry,
  mappingSuccess, mappingFailure와 바인딩 mapSuccess가
  BoundaryMappingResult를 반환한다. 참조 mapper·client·resource-mapper도
  옮겼다. ApiFailure를 쓰던 파일은 AppFailure를 쓴다. 타입이 같아서
  런타임과 공개 시그니처는 바뀌지 않는다.
- D-15 주석을 실제와 맞췄다. 기능 mapper와 HTTP 바인딩은
  BoundaryMappingResult(닫힌 실패 코드)를 반환하고, 계약 패키지 쪽 결과가
  필요하면 toContractMappingResult로 바꾼다. 참조 기능 README의 "ApiFailure는
  같은 type의 alias" 문장도 고쳤다.
- 폐기 검사: 이 repo의 ESLint는 babel 파서라 타입 정보가 없어
  @typescript-eslint/no-deprecated를 쓸 수 없다. 대신 core
  no-restricted-imports의 patterns.importNames로 boundary-mapper의
  MappingResult와 errors의 ApiFailure import를 src·tests 전체에서 막는다.
  층별 no-restricted-imports 설정이 같은 규칙을 덮어쓰므로
  restrictedImports()가 별칭 패턴을 항상 덧붙이고, 층 규칙이 없는 파일은
  그 앞에 둔 공통 블록이 받는다.

버린 대안
- 별칭 export 삭제와 정본 이름을 ContractMappingResult로 바꾸기(리뷰 (2)
  후반·(3)): 다운스트림 import를 깨는 공개 이름 변경이다. 이번 묶음 규칙상
  공개 시그니처를 깨는 변경은 하지 않는다. 별칭 주석에 "repo 안 사용 0,
  lint로 강제, 제거는 minor 릴리스 + CHANGELOG [계약] 행"을 적었다.
- typescript-eslint 도입 후 no-deprecated: 새 의존성과 type-aware lint
  설정(속도·설정 범위)이 필요하다.
- 바인딩이 정본 모양을 받게 바꾸기(리뷰 C): 실패 코드가 닫힌 3종에서 자유
  문자열로 넓어져 계약이 약해진다.

위험·한계
- 이름 MappingResult는 여전히 두 파일에서 export된다(한쪽은 폐기 별칭).
  리뷰 완료 기준("MappingResult export 하나, grep 0건")은 별칭을 지워야
  충족된다. 제거 시점은 릴리스 결정으로 남긴다.
- 다운스트림이 eslint.config.ts를 동기화하면 그쪽의 별칭 import가 lint
  오류가 된다. 이름만 바꾸면 된다(tech-log는 mappingSuccess를 쓰는데,
  반환 타입은 같은 모양이라 영향 없음).
- adapters/http의 client.ts·feature-http-binding.ts는 타입 이름만 바꿨다.
  같은 파일을 고치는 다른 수정과 합칠 때 줄 단위 충돌이 날 수 있다.

검증
- RED: 규칙만 먼저 넣고 eslint src tests -> 9개 파일 11 errors
  ("'MappingResult' import from '../../contracts/boundary-mapper.ts' is
  restricted ... deprecated alias: import BoundaryMappingResult", ApiFailure
  같은 꼴).
- GREEN: lint 전체 범위(src scripts tests recipes .storybook 설정 파일)
  --max-warnings=0 rc=0. src에서 별칭을 쓰는 곳은 정의 줄뿐(git grep).
- 회귀: tsc app/test/node rc=0. run-vitest tests/architecture tests/unit
  tests/features tests/platform tests/component tests/contract
  tests/runtime-schema tests/integration(pnpm·corepack을 띄우는 4파일 제외)
  273 files / 3136 tests 중 3135 통과. 실패 1건은
  provider-guardian-transaction(guardian exit=126, 단독 실행도 같음, 이
  변경과 무관한 scripts/lib 프로세스 테스트).
  check-registries PASS, verify-documentation-readiness PASS_SCOPED,
  check-adapter-inventory PASS.
- 미실행: check:architecture(pnpm 필요). depcruise 직접 실행은 0 modules로
  사실상 미검증.

Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md
2026-11-01 22:35:54 +09:00

1132 lines
35 KiB
TypeScript

import { systemClock } from "../platform/system-clock.ts";
import { getApiOperation } from "../../contracts/api-operations.ts";
import {
createFailure as failure,
kindForStatus as statusKind,
safeValidationIssues,
} from "../../contracts/errors.ts";
import { mapOperationPayload } from "./resource-mapper.ts";
import { retryDelay, shouldRetry } from "./retry-policy.ts";
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
import {
validateEnvelope,
validateOperationPayload,
validateOperationRequest,
} from "./schema-registry.ts";
import { buildRequestTarget } from "./request-builder.ts";
import {
attemptBucket,
durationBucket,
statusGroup,
} from "../../contracts/diagnostics.ts";
import type {
AuthSessionPort,
CredentialOperationContext,
} from "../../application/ports/auth-session-port.ts";
import { isValidIdempotencyKey } from "../../contracts/mutation-intent.ts";
/** Sentinel for a credential wait ended by the attempt lifetime. */
const ATTEMPT_ABORTED = Symbol("ATTEMPT_ABORTED");
/**
* LEG-02. The pre-V2 operations have no installed auth profile, so this is the
* legacy allowance the shared validator applies to them. It requires nothing,
* which preserves their existing behaviour exactly.
*/
const LEGACY_ALLOWED_CREDENTIAL_HEADERS = Object.freeze([
"authorization",
"x-csrf-token",
] as const);
import type { ClockPort } from "../../application/ports/clock-port.ts";
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts";
import type { TelemetryPort } from "../../application/ports/telemetry-port.ts";
import type { ApiOperation } from "../../contracts/api-operations.ts";
import type { AppFailure, FailureKind } from "../../contracts/errors.ts";
import type { OperationRequestInput } from "./request-builder.ts";
import { readBoundedJson } from "./bounded-json.ts";
import { admitCredentialHeaders } from "./http-contract-bridge.ts";
import type { BoundaryMappingResult } from "../../contracts/boundary-mapper.ts";
import {
createRestProviderProfile,
resolveRestSecurityProfiles,
INSTALLED_REST_AUTH_PROFILES,
REST_CSRF_PROFILES,
type RestAuthProfile,
type RestCsrfProfile,
type RestProviderProfile,
} from "../../contracts/rest-profiles.ts";
type HttpAuthSession = Pick<
AuthSessionPort,
"getState" | "credentialPatch" | "recover" | "onUnauthenticated"
>;
const noAuthSession: HttpAuthSession = Object.freeze({
getState: () => "integration-failed",
credentialPatch: async () => {
throw new TypeError("Auth session is not installed");
},
recover: async () => "no-session",
onUnauthenticated: () => {},
} satisfies HttpAuthSession);
export type HttpFailure = AppFailure;
export type Scheduler = Readonly<{
setTimeout(callback: () => void, milliseconds: number): unknown;
clearTimeout(handle: unknown): void;
}>;
export type HttpResult =
| Readonly<{
ok: true;
value: unknown;
meta: Readonly<Record<string, string>>;
}>
| Readonly<{ ok: false; error: HttpFailure }>;
type SchemaValidator = (
schemaId: string,
value: unknown,
) =>
| Readonly<{ success: true; data: unknown }>
| Readonly<{ success: false }>;
export type HttpClientDependencies = Readonly<{
baseUrl: string;
fetcher?: typeof fetch;
authSession?: AuthSessionPort;
clock?: ClockPort;
random?: () => number;
validatePayload?: SchemaValidator;
validateRequest?: SchemaValidator;
validatePath?: SchemaValidator;
mapPayload?: (
operationId: string,
payload: unknown,
) => BoundaryMappingResult<unknown>;
idempotencyKeyFactory?: () => string;
/**
* Default total deadline for an operation without its own `timeoutMs`. Not a
* ceiling: an operation may set a longer one. V3 treats `REQUEST_TIMEOUT_MS`
* as a ceiling instead (03-06).
*/
timeoutMs?: number;
maxRetryAttempts?: number;
scheduler?: Scheduler;
getOperation?: typeof getApiOperation;
diagnostics?: DiagnosticsPort;
telemetry?: TelemetryPort;
correlationIdFactory?: () => string;
providerProfile?: RestProviderProfile;
authProfiles?: Readonly<Record<string, RestAuthProfile>>;
csrfProfiles?: Readonly<Record<string, RestCsrfProfile>>;
maxCumulativeSleepMs?: number;
}>;
export type LegacyHttpInput = Readonly<{
body?: unknown;
routeId?: string;
pathParams?: Readonly<Record<string, string | number>>;
searchParams?: unknown;
signal?: AbortSignal;
idempotencyKey?: string;
correlationId?: string;
}>;
export type HttpClient = Readonly<{
execute(
request: string | OperationRequestInput,
legacyInput?: LegacyHttpInput,
): Promise<HttpResult>;
}>;
export function createHttpClient(
dependencies: HttpClientDependencies,
): HttpClient {
const fetcher = dependencies.fetcher ?? fetch;
const authSession = dependencies.authSession ?? noAuthSession;
const clock = dependencies.clock ?? systemClock;
const random = dependencies.random ?? Math.random;
const validatePayload =
dependencies.validatePayload ?? validateOperationPayload;
const validateRequest =
dependencies.validateRequest ?? validateOperationRequest;
const validatePath = dependencies.validatePath ?? validateRequest;
const mapPayload = dependencies.mapPayload ?? mapOperationPayload;
const idempotencyKeyFactory =
dependencies.idempotencyKeyFactory ?? (() => crypto.randomUUID());
const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000;
const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2;
const maxCumulativeSleepMs =
dependencies.maxCumulativeSleepMs ?? defaultTimeoutMs;
const selectOperation = dependencies.getOperation ?? getApiOperation;
const diagnostics = dependencies.diagnostics;
const telemetry = dependencies.telemetry;
const correlationIdFactory =
dependencies.correlationIdFactory ??
(() => `request-${Math.floor(random() * 1_000_000).toString(36)}`);
const scheduler =
dependencies.scheduler ??
({
setTimeout: (callback, milliseconds) =>
globalThis.setTimeout(callback, milliseconds),
clearTimeout: (handle) =>
globalThis.clearTimeout(
handle as ReturnType<typeof globalThis.setTimeout>,
),
} satisfies Scheduler);
async function execute(
request: string | OperationRequestInput,
legacyInput: LegacyHttpInput = {},
): Promise<HttpResult> {
const input =
typeof request === "string"
? {
operationId: request,
routeId: legacyInput.routeId ?? "UNSPECIFIED_ROUTE",
pathParams: legacyInput.pathParams,
searchParams: legacyInput.searchParams,
body: legacyInput.body,
signal: legacyInput.signal,
idempotencyKey: legacyInput.idempotencyKey,
correlationId: legacyInput.correlationId,
}
: request;
const startedAt = clock.now();
let correlationId: string;
try {
correlationId = correlationIdValue(
input.correlationId ?? correlationIdFactory(),
);
} catch {
correlationId = "client-generated";
}
let operation: ApiOperation;
try {
operation = selectOperation(input.operationId);
} catch {
return {
ok: false,
error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, {
code: "OPERATION_NOT_REGISTERED",
}),
};
}
const totalDeadlineMs = operation.timeoutMs ?? defaultTimeoutMs;
const deadlineAt = startedAt + totalDeadlineMs;
let physicalAttemptCount = 0;
function finalize(
outcome: HttpResult,
outcomeKind: "success" | "recovered" | "failed" | "aborted",
): HttpResult {
const error = outcome.ok ? undefined : outcome.error;
const context = {
route_id: input.routeId,
operation_id: input.operationId,
correlation_id: correlationId,
outcome: outcomeKind,
error_kind: error?.kind ?? "NONE",
http_status_group: statusGroup(
error?.httpStatus ??
(outcome.ok ? Number(outcome.meta.httpStatus) : undefined),
),
attempt_count_bucket: attemptBucket(
error?.attemptCount ?? Math.max(1, physicalAttemptCount),
),
duration_bucket: durationBucket(clock.now() - startedAt),
};
try {
diagnostics?.record({
level: error ? "warn" : "info",
eventId: "http.request.completed",
context,
});
} catch {
// Diagnostics cannot change the HTTP result.
}
if (error && outcomeKind !== "aborted") {
try {
telemetry?.emit("api.request.failed", {
error_kind: context.error_kind,
http_status_group: context.http_status_group,
attempt_count_bucket: context.attempt_count_bucket,
route_id: context.route_id,
operation_id: context.operation_id,
duration_bucket: context.duration_bucket,
});
} catch {
// Telemetry cannot change the HTTP result.
}
}
return outcome;
}
// N-06. A caller-supplied key is validated before credentials, timers or
// fetch. An invalid value is rejected outright rather than trimmed or
// replaced, so a keyed command can never replay with no key at all.
let logicalIdempotencyKey: string | undefined;
if (operation.idempotency === "keyed") {
if (input.idempotencyKey !== undefined) {
if (!isValidIdempotencyKey(input.idempotencyKey)) {
return finalize(
{
ok: false,
error: failure("VALIDATION_REJECTED", input.operationId, 0, {
code: "IDEMPOTENCY_KEY_INVALID",
}),
},
"failed",
);
}
logicalIdempotencyKey = input.idempotencyKey;
} else {
let generated: string;
try {
generated = idempotencyKeyFactory();
} catch {
return finalize(
{
ok: false,
error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, {
code: "IDEMPOTENCY_KEY_CREATION_FAILED",
}),
},
"failed",
);
}
if (!isValidIdempotencyKey(generated)) {
return finalize(
{
ok: false,
error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, {
code: "IDEMPOTENCY_KEY_CREATION_FAILED",
}),
},
"failed",
);
}
logicalIdempotencyKey = generated;
}
}
let retryCount = 0;
let recoveryUsed = false;
let cumulativeSleepMs = 0;
while (true) {
const attempt = physicalAttemptCount;
physicalAttemptCount += 1;
let outcome: HttpResult;
try {
outcome = await performAttempt({
operation,
input,
attempt,
idempotencyKey: logicalIdempotencyKey,
deadlineAt,
correlationId,
});
} catch {
outcome = {
ok: false,
error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, attempt, {
code: "HTTP_EXECUTION_CONTRACT_VIOLATION",
}),
};
}
if (outcome.ok) {
return finalize(
outcome,
retryCount > 0 || recoveryUsed ? "recovered" : "success",
);
}
// Q-6.3-11. Recovery is its own single replay, bounded by
// `recoveryUsed` and the deadline, not by the retry budget: a disabled
// or spent budget must not turn a recoverable 401 into a logout.
if (outcome.error.httpStatus === 401 && !recoveryUsed) {
recoveryUsed = true;
let recovered: SessionRecoveryOutcome;
// LEG-01. The recovery collaborator receives the request lifetime, and
// the transport races the same signal so a non-cooperative owner cannot
// hold the request open.
const recoveryLifetime = new AbortController();
try {
recovered = await withinLogicalDeadline(
recoverSession(
authSession,
operation,
outcome.error,
Object.freeze({
signal: recoveryLifetime.signal,
deadlineAtMonotonicMs: deadlineAt,
}),
),
deadlineAt,
input.signal,
);
} catch (error) {
// The request is over. Whatever the recovery answers next is observed
// by its own owner, never adopted here.
recoveryLifetime.abort();
return finalize(
{
ok: false,
error: failure(
error instanceof LogicalDeadlineError
? "REQUEST_TIMEOUT"
: "REQUEST_ABORTED",
operation.operationId,
attempt,
{
code:
error instanceof LogicalDeadlineError
? "OPERATION_DEADLINE_EXCEEDED"
: "REQUEST_ABORTED",
},
),
},
error instanceof LogicalDeadlineError ? "failed" : "aborted",
);
}
if (!recovered.ok) {
// The result is adopted here, so the notification happens here.
if (recovered.notifyUnauthenticated) authSession.onUnauthenticated();
return finalize(
{ ok: false, error: recovered.error },
"failed",
);
}
if (operation.idempotency === "none") {
return finalize(
{
ok: false,
error: {
...outcome.error,
retryable: false,
action: "retry",
},
},
"failed",
);
}
continue;
}
if (outcome.error.httpStatus === 401 && recoveryUsed) {
authSession.onUnauthenticated();
return finalize(outcome, "failed");
}
if (
!shouldRetry(
operation,
outcome.error,
retryCount,
maxRetryAttempts,
)
) {
return finalize(
outcome,
outcome.error.kind === "REQUEST_ABORTED" ? "aborted" : "failed",
);
}
const delay = retryDelay(outcome.error, retryCount, random, clock.now());
retryCount += 1;
cumulativeSleepMs += delay;
if (
clock.now() + delay >= deadlineAt ||
cumulativeSleepMs > maxCumulativeSleepMs
) {
return finalize(
{
ok: false,
error: failure("REQUEST_TIMEOUT", input.operationId, attempt, {
code: "OPERATION_DEADLINE_EXCEEDED",
}),
},
"failed",
);
}
try {
await clock.sleep(delay, input.signal);
} catch {
return finalize(
{
ok: false,
error: failure("REQUEST_ABORTED", input.operationId, retryCount, {
code: "REQUEST_ABORTED",
}),
},
"aborted",
);
}
}
}
async function performAttempt(
context: Readonly<{
operation: ApiOperation;
input: OperationRequestInput;
attempt: number;
idempotencyKey?: string;
deadlineAt: number;
correlationId: string;
}>,
): Promise<HttpResult> {
const {
operation,
input,
attempt,
idempotencyKey,
deadlineAt,
correlationId,
} = context;
if (clock.now() >= deadlineAt) {
return {
ok: false,
error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, {
code: "OPERATION_DEADLINE_EXCEEDED",
}),
};
}
let parsedSearch: unknown = {};
let parsedBody: unknown;
let parsedPath: Readonly<Record<string, string | number>> =
input.pathParams ?? {};
if (operation.pathSchema) {
const pathValidation = validatePath(
operation.pathSchema,
input.pathParams ?? {},
);
if (
!pathValidation.success ||
!isPathParameterRecord(pathValidation.data)
) {
return {
ok: false,
error: failure(
"VALIDATION_REJECTED",
operation.operationId,
attempt,
{ code: "PATH_SCHEMA_INVALID" },
),
};
}
parsedPath = pathValidation.data;
}
const requestValue =
operation.requestSource === "search"
? input.searchParams ?? {}
: operation.requestSource === "body"
? input.body
: {};
if (operation.requestSource !== "none") {
const requestValidation = validateRequest(
operation.requestSchema,
requestValue,
);
if (!requestValidation.success) {
return {
ok: false,
error: failure("VALIDATION_REJECTED", operation.operationId, attempt, {
code: "REQUEST_SCHEMA_INVALID",
}),
};
}
if (operation.requestSource === "search") {
parsedSearch = requestValidation.data;
} else {
parsedBody = requestValidation.data;
}
}
let target: ReturnType<typeof buildRequestTarget>;
let provider: RestProviderProfile | null = null;
let security:
| ReturnType<typeof resolveRestSecurityProfiles>
| undefined;
try {
provider =
dependencies.providerProfile ??
createRestProviderProfile(
operation.providerId ?? "LEGACY_API",
dependencies.baseUrl,
["omit", "same-origin"],
);
if (
operation.contractVersion === 2 &&
operation.providerId !== provider.providerId
) {
throw new TypeError("REST provider binding mismatch.");
}
if (operation.contractVersion === 2) {
security = resolveRestSecurityProfiles(
operation,
provider,
dependencies.authProfiles ?? INSTALLED_REST_AUTH_PROFILES,
dependencies.csrfProfiles ?? REST_CSRF_PROFILES,
);
}
target = buildRequestTarget(
provider.baseUrl,
operation,
parsedPath,
parsedSearch,
);
} catch {
target = { success: false, code: "BASE_URL_INVALID" };
}
if (!target.success || !provider) {
return {
ok: false,
error: failure("VALIDATION_REJECTED", operation.operationId, attempt, {
code: target.success ? "BASE_URL_INVALID" : target.code,
}),
};
}
const controller = new AbortController();
let timedOut = false;
const remainingMs = Math.max(1, deadlineAt - clock.now());
const timeout = scheduler.setTimeout(() => {
timedOut = true;
controller.abort("timeout");
}, remainingMs);
const onExternalAbort = () => controller.abort(input.signal?.reason);
input.signal?.addEventListener("abort", onExternalAbort, { once: true });
if (input.signal?.aborted) onExternalAbort();
try {
const headers = new Headers({
Accept: operation.responseMediaTypes?.join(", ") ?? "application/json",
"X-Correlation-ID": correlationIdValue(correlationId),
});
if (parsedBody !== undefined) headers.set("Content-Type", "application/json");
if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey);
if (operation.auth === "external-session") {
let sessionState: ReturnType<HttpAuthSession["getState"]>;
try {
sessionState = authSession.getState();
} catch {
return {
ok: false,
error: failure(
"AUTH_INTEGRATION_FAILURE",
operation.operationId,
attempt,
{ code: "AUTH_STATE_FAILED" },
),
};
}
if (sessionState === "unauthenticated") {
return {
ok: false,
error: failure("AUTH_REQUIRED", operation.operationId, attempt, {
code: "AUTH_REQUIRED",
}),
};
}
if (sessionState !== "authenticated") {
return {
ok: false,
error: failure(
"AUTH_INTEGRATION_FAILURE",
operation.operationId,
attempt,
{ code: "AUTH_SESSION_UNAVAILABLE" },
),
};
}
try {
// N-07. The credential owner is bounded by the attempt lifetime that
// already carries the total deadline and the caller signal, so a
// non-cooperative owner cannot hold the request open and no extra
// timer is introduced. A late completion is observed and discarded.
const raced = await raceAttemptSignal(
Promise.resolve(
authSession.credentialPatch(
{
origin: target.url.origin,
method: operation.method,
operationId: operation.operationId,
},
Object.freeze({
signal: controller.signal,
deadlineAtMonotonicMs: deadlineAt,
}),
),
),
controller.signal,
);
if (raced === ATTEMPT_ABORTED) {
return {
ok: false,
error: timedOut
? failure(
"REQUEST_TIMEOUT",
operation.operationId,
attempt,
{ code: "OPERATION_DEADLINE_EXCEEDED" },
)
: failure(
"REQUEST_ABORTED",
operation.operationId,
attempt,
{ code: "REQUEST_ABORTED" },
),
};
}
const patch = raced;
// LEG-02. The same admission validator V3 uses. Checking only the
// allowed set let a bearer profile dispatch with no Authorization at
// all, which is precisely the anonymous downgrade the required set
// exists to prevent.
const admission = admitCredentialHeaders(patch.headers, {
allowedCredentialHeaders:
security?.auth.allowedCredentialHeaders ??
LEGACY_ALLOWED_CREDENTIAL_HEADERS,
requiredCredentialHeaders:
security?.auth.requiredCredentialHeaders ?? [],
});
if (!admission.ok) {
return {
ok: false,
error: failure(
"AUTH_INTEGRATION_FAILURE",
operation.operationId,
attempt,
{ code: "AUTH_ATTACH_FAILED" },
),
};
}
for (const [name, value] of Object.entries(admission.headers)) {
headers.set(name, value);
}
} catch {
// An ordinary owner rejection stays an integration failure.
return {
ok: false,
error: failure("AUTH_INTEGRATION_FAILURE", operation.operationId, attempt, {
code: "AUTH_ATTACH_FAILED",
}),
};
}
}
const request = new Request(target.url, {
method: operation.method,
headers,
body: parsedBody === undefined ? undefined : JSON.stringify(parsedBody),
signal: controller.signal,
credentials: security?.auth.credentials ?? "same-origin",
cache: "no-store",
redirect: provider.redirect,
referrerPolicy: provider.referrerPolicy,
});
const response = await fetcher(request);
return await parseResponse(
response,
operation,
attempt,
validatePayload,
mapPayload,
clock.now(),
);
} catch {
if (timedOut) {
return {
ok: false,
error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, {
code: "REQUEST_TIMEOUT",
}),
};
}
if (controller.signal.aborted || input.signal?.aborted) {
const externalReason = input.signal?.reason;
if (externalReason === "timeout") {
return {
ok: false,
error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, {
code: "REQUEST_TIMEOUT",
}),
};
}
if (
externalReason !== undefined &&
!["navigation", "user", "superseded"].includes(String(externalReason))
) {
return {
ok: false,
error: failure("UNKNOWN_FAILURE", operation.operationId, attempt, {
code: "EXTERNAL_ABORT_UNRESOLVED",
}),
};
}
return {
ok: false,
error: failure("REQUEST_ABORTED", operation.operationId, attempt, {
code: "REQUEST_ABORTED",
}),
};
}
return {
ok: false,
error: failure("NETWORK_UNREACHABLE", operation.operationId, attempt, {
code: "NETWORK_UNREACHABLE",
}),
};
} finally {
scheduler.clearTimeout(timeout);
input.signal?.removeEventListener("abort", onExternalAbort);
}
}
return Object.freeze({ execute });
function raceAttemptSignal<Value>(
operation: Promise<Value>,
signal: AbortSignal,
): Promise<Value | typeof ATTEMPT_ABORTED> {
operation.catch(() => {});
if (signal.aborted) return Promise.resolve(ATTEMPT_ABORTED);
return new Promise<Value | typeof ATTEMPT_ABORTED>((resolve, reject) => {
const onAbort = () => resolve(ATTEMPT_ABORTED);
signal.addEventListener("abort", onAbort, { once: true });
operation.then(
(value) => {
signal.removeEventListener("abort", onAbort);
resolve(value);
},
(error: unknown) => {
signal.removeEventListener("abort", onAbort);
reject(error instanceof Error ? error : new Error("rejected"));
},
);
});
}
function withinLogicalDeadline<Value>(
promise: Promise<Value>,
deadlineAt: number,
externalSignal: AbortSignal | undefined,
): Promise<Value> {
const remaining = deadlineAt - clock.now();
if (remaining <= 0) return Promise.reject(new LogicalDeadlineError());
return new Promise<Value>((resolve, reject) => {
let settled = false;
const timeout = scheduler.setTimeout(
() => settle(() => reject(new LogicalDeadlineError())),
remaining,
);
const onAbort = () =>
settle(() => reject(new DOMException("Aborted", "AbortError")));
externalSignal?.addEventListener("abort", onAbort, { once: true });
const settle = (complete: () => void) => {
if (settled) return;
settled = true;
scheduler.clearTimeout(timeout);
externalSignal?.removeEventListener("abort", onAbort);
complete();
};
if (externalSignal?.aborted) {
onAbort();
return;
}
promise.then(
(value) => settle(() => resolve(value)),
(error: unknown) => settle(() => reject(error)),
);
});
}
}
class LogicalDeadlineError extends Error {}
/**
* Q-6.3-3b. A gateway 5xx/408/425 with an HTML, empty or broken body is a
* server outage, not a contract breach: it keeps its status and the normal
* SERVER_FAILURE retry rule instead of a non-retryable body error.
*/
function gatewayFailureOr(status: number, kind: FailureKind): FailureKind {
return status >= 500 || status === 408 || status === 425
? "SERVER_FAILURE"
: kind;
}
async function parseResponse(
response: Response,
operation: ApiOperation,
attempt: number,
validatePayload: SchemaValidator,
mapPayload: (
operationId: string,
payload: unknown,
) => BoundaryMappingResult<unknown>,
now: number,
): Promise<HttpResult> {
// R3-1. Retry-After is read only where the retry policy honors it; 502/504
// keep the local backoff.
const retryAfterMs = [408, 425, 429, 503].includes(response.status)
? (parseRetryAfterDelay(response.headers.get("retry-after"), now) ??
undefined)
: undefined;
const contentType = mediaType(response.headers.get("content-type"));
const acceptedMedia = operation.responseMediaTypes ?? ["application/json"];
if (!contentType || !acceptedMedia.includes(contentType)) {
// N-08. A rejected response still owns an open body stream. Cancellation is
// best-effort cleanup, so it is started but not awaited: the closed result
// must not depend on stream teardown settling.
void response.body?.cancel().catch(() => {});
return {
ok: false,
error: failure(
gatewayFailureOr(response.status, "CONTENT_TYPE_MISMATCH"),
operation.operationId,
attempt,
{
code: "CONTENT_TYPE_MISMATCH",
httpStatus: response.status,
retryAfterMs,
},
),
};
}
const decoded = await readBoundedJson(
response,
operation.maxResponseBytes ?? 1_048_576,
);
if (!decoded.ok) {
return {
ok: false,
error: failure(
gatewayFailureOr(response.status, decoded.code),
operation.operationId,
attempt,
{ code: decoded.code, httpStatus: response.status, retryAfterMs },
),
};
}
const envelope = decoded.value;
const envelopeValidation = validateEnvelope(envelope);
if (!envelopeValidation.success) {
return {
ok: false,
error: failure(
response.ok
? "ENVELOPE_MISMATCH"
: gatewayFailureOr(response.status, statusKind(response.status)),
operation.operationId,
attempt,
{
code: response.ok ? "ENVELOPE_MISMATCH" : "HTTP_FAILURE",
httpStatus: response.status,
retryAfterMs,
},
),
};
}
const envelopeRecord = envelopeValidation.data as Record<string, unknown>;
const successStatus = operation.successStatuses
? operation.successStatuses.includes(response.status)
: response.ok;
if (successStatus && envelopeRecord.success === true && "data" in envelopeRecord) {
const payload = validatePayload(operation.responseSchema, envelopeRecord.data);
if (!payload.success) {
return {
ok: false,
error: failure("SCHEMA_MISMATCH", operation.operationId, attempt, {
code: "SCHEMA_MISMATCH",
httpStatus: response.status,
}),
};
}
try {
const mapped = mapPayload(operation.operationId, payload.data);
if (!mapped.ok) {
return {
ok: false,
error: failure(
"MAPPING_CONTRACT_VIOLATION",
operation.operationId,
attempt,
{
code: mapped.code,
httpStatus: response.status,
},
),
};
}
return {
ok: true,
value: mapped.value,
meta: {
...safeMeta(envelopeRecord.meta),
httpStatus: String(response.status),
},
};
} catch {
return {
ok: false,
error: failure(
"MAPPING_CONTRACT_VIOLATION",
operation.operationId,
attempt,
{
code: "MAPPING_CONTRACT_VIOLATION",
httpStatus: response.status,
},
),
};
}
}
if (successStatus !== response.ok || (successStatus && envelopeRecord.success !== true)) {
return {
ok: false,
error: failure("ENVELOPE_MISMATCH", operation.operationId, attempt, {
code: "STATUS_ENVELOPE_MISMATCH",
httpStatus: response.status,
}),
};
}
// R3-1. V2 treats a 408/425 error envelope as the same server failure as a
// gateway body; the shared status map in contracts is not changed.
const kind = gatewayFailureOr(response.status, statusKind(response.status));
const backendError =
envelopeRecord.error && typeof envelopeRecord.error === "object"
? (envelopeRecord.error as Record<string, unknown>)
: {};
return {
ok: false,
error: failure(kind, operation.operationId, attempt, {
code: safeBackendCode(envelope),
httpStatus: response.status,
requestId: safeMeta(envelopeRecord.meta).requestId,
traceId: safeMeta(envelopeRecord.meta).traceId,
retryAfterMs,
validationIssues:
response.status === 422
? safeValidationIssues(backendError.details)
: undefined,
}),
};
}
/**
* LEG-01. Recovery returns data only.
*
* The sign-out notification is a user-visible side effect, so it belongs to
* whoever adopts this result — not to the raw recovery call. A recovery that
* loses the race against the deadline or a caller abort still settles, and
* signing the user out then would attribute a request nobody is waiting on to
* an expired session.
*/
type SessionRecoveryOutcome =
| Readonly<{ ok: true }>
| Readonly<{
ok: false;
error: HttpFailure;
notifyUnauthenticated: boolean;
}>;
async function recoverSession(
authSession: HttpAuthSession,
operation: ApiOperation,
originalFailure: HttpFailure,
context: CredentialOperationContext,
): Promise<SessionRecoveryOutcome> {
try {
const result = await authSession.recover(context);
if (result === "restored") return { ok: true };
if (result === "no-session") {
return {
ok: false,
notifyUnauthenticated: true,
error: failure("AUTH_REQUIRED", operation.operationId, originalFailure.attemptCount - 1, {
code: "AUTH_REQUIRED",
httpStatus: 401,
}),
};
}
} catch {
// Normalized below.
}
return {
ok: false,
notifyUnauthenticated: false,
error: failure(
"AUTH_INTEGRATION_FAILURE",
operation.operationId,
originalFailure.attemptCount - 1,
{ code: "AUTH_RECOVERY_FAILED" },
),
};
}
function safeBackendCode(envelope: unknown): string {
if (!envelope || typeof envelope !== "object") return "HTTP_FAILURE";
const error = (envelope as Record<string, unknown>).error;
if (!error || typeof error !== "object") return "HTTP_FAILURE";
const code = (error as Record<string, unknown>).code;
return typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code)
? code
: "HTTP_FAILURE";
}
function safeMeta(meta: unknown): Record<string, string> {
if (!meta || typeof meta !== "object") return {};
const metaRecord = meta as Record<string, unknown>;
return {
...(typeof metaRecord.requestId === "string"
? safeIdentifier(metaRecord.requestId, "requestId")
: {}),
...(typeof metaRecord.traceId === "string"
? safeIdentifier(metaRecord.traceId, "traceId")
: {}),
};
}
function safeIdentifier(
value: string,
property: "requestId" | "traceId",
): Record<string, string> {
return /^[A-Za-z0-9._:-]{1,128}$/.test(value) ? { [property]: value } : {};
}
function mediaType(value: string | null): string | null {
if (!value) return null;
const selected = value.split(";", 1)[0]?.trim().toLowerCase();
return selected && /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(selected)
? selected
: null;
}
function correlationIdValue(value: string | undefined): string {
return value && /^[A-Za-z0-9._:-]{1,128}$/.test(value)
? value
: "client-generated";
}
function isPathParameterRecord(
value: unknown,
): value is Readonly<Record<string, string | number>> {
return (
value !== null &&
typeof value === "object" &&
!Array.isArray(value) &&
Object.values(value).every(
(item) => typeof item === "string" || typeof item === "number",
)
);
}