Files
clean-architecture-frontend…/src/adapters/http/feature-http-binding.ts
T
DongHyeonka 631ce339b9 fix(http): 실패 Envelope의 meta.traceId를 AppFailure.traceId로 싣는다
문제
AppFailure와 createFailure는 traceId를 받는다. 이를 채우던 곳은 V2
client.ts의 Envelope meta.traceId였고, 048f490이 V2를 지운 뒤 src에서
traceId를 넘기는 곳이 없다. 빈 칸을 믿고 만든 화면·진단 코드는 늘
undefined를 받는다. 짝 백엔드는 모든 실패 Envelope의 meta에 W3C trace id를
싣는다(http-contract.md §1).

고른 방법
- readFailureEnvelope가 error와 함께 meta.traceId를 돌려준다. 값은 이미
  meta 스키마의 id 문법([A-Za-z0-9._:-]{1,128})을 통과한 것이다.
- 실행기가 그 값을 PROBLEM 결과의 SafeResponseMetadata.traceReference에
  싣고, 바인딩이 AppFailure.traceId로 옮긴다. requestId 경로(반사 헤더 →
  보낸 id)는 그대로다.
- 계약 문서 5절의 correlation 문단에 한 줄 더했다.

버린 대안
traceId를 타입에서 지우기(리뷰의 다른 선택지): 다운스트림이 쓰는지 확인이
필요하고, 백엔드가 이미 주는 지원용 id를 버린다.

위험·한계
- Envelope operation의 실패 응답만 채운다. 성공 뒤 매핑 실패, 전송 실패,
  Envelope 없는 operation은 traceId가 없다.
- 텔레메트리에는 싣지 않는다(요청 단위 값).
- 같은 발견의 VD-23 401 문장은 다른 작업 몫이라 건드리지 않았다.

검증
- RED: envelope 통합 1건 실패(404 실패의 traceId 없음).
- GREEN: meta.traceId가 있으면 그 값, 없으면 칸 없음. tests/unit·
  integration·component·features·contract·runtime-schema 253파일 중 252파일
  통과. 남은 1건(provider-guardian-transaction "cleans a linked raw inode")은
  이 기계의 inotify 한도(ENOSPC watch)로 단독 실행에서도 실패하며 이 변경과
  무관하다.
- check:types, lint, verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-06
2026-11-04 20:49:30 +09:00

592 lines
19 KiB
TypeScript

import type {
InstalledHttpContract,
} from "../../contracts/external-contract-runtime.ts";
import type { Result } from "../../contracts/result.ts";
import type { BoundaryMappingResult } from "../../contracts/boundary-mapper.ts";
import {
createFailure,
kindForStatus,
type AppFailure,
type FailureEffectCertainty,
type FailureKind,
type ValidationIssue,
} from "../../contracts/errors.ts";
import type { MutationIntent } from "../../contracts/mutation-intent.ts";
import type { ExecutionContext } from "../../platform/execution/execution-context.ts";
import {
envelopeFailureReading,
type EnvelopePage,
} from "./backend-envelope.ts";
import type {
HttpContractViolation,
HttpExecutionOutcome,
HttpRequestRejectionReason,
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;
/**
* 03-04. Field issues read from the problem body. Only `path` and `code`
* survive; `createFailure` bounds them with `projectValidationIssues`.
*/
validationIssues?: readonly ValidationIssue[];
}>;
/**
* 1103/03-02. What a success answer carries besides its validated value.
*/
export type FeatureHttpSuccessContext = Readonly<{
/**
* An Envelope page list's `meta.page` (the paired backend's offset page:
* `number`, `size`, `total`, `sort`). Absent on every other answer.
*/
page?: EnvelopePage;
}>;
const NO_SUCCESS_CONTEXT: FeatureHttpSuccessContext = Object.freeze({});
type FeatureHttpOperationSpec<
Contract,
Value,
RouteId extends string,
> = Readonly<{
contract: Contract;
routeId: RouteId;
mapSuccess(
value: HttpContractWireOutput<Contract>,
context: FeatureHttpSuccessContext,
): BoundaryMappingResult<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]>, AppFailure>>;
}>;
/**
* 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]>, AppFailure>> {
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,
context: FeatureHttpSuccessContext,
) => BoundaryMappingResult<Value>,
problemMapper(
operation.mapProblem as
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
contract.contract.responseEnvelope === "ENVELOPE_V1",
),
outcome,
);
},
});
}
/**
* 1101 README 14.3. An Envelope operation's problem is the backend `error`
* object, so what the feature does not map still reads as the backend means
* it: its code, field issues from a validation failure, and the status kind.
*/
function problemMapper<Problem>(
mapProblem:
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
enveloped: boolean,
):
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined {
if (!enveloped) return mapProblem;
return (problem, metadata) =>
mapProblem?.(problem, metadata) ??
envelopeProblemMapping(problem, metadata.status);
}
function envelopeProblemMapping(
problem: unknown,
status: number,
): FeatureHttpProblemMapping | undefined {
if (!problem || typeof problem !== "object") return undefined;
const { code, details } = problem as Readonly<Record<string, unknown>>;
return typeof code === "string" && /^[A-Z0-9_]{1,64}$/u.test(code)
? envelopeFailureReading(status, { code, details })
: undefined;
}
/**
* 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.
* 0929/03-04. Without an echo (timeout, lost connection, a gateway that drops
* the header) it is the id the request carried.
* 1103/03-06. A failure Envelope's `meta.traceId` becomes `traceId`.
*/
function projectExecutionOutcome<WireOutput, Problem, Value>(
operationId: string,
mapSuccess: (
value: WireOutput,
context: FeatureHttpSuccessContext,
) => BoundaryMappingResult<Value>,
mapProblem:
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
outcome: HttpExecutionOutcome<WireOutput, Problem>,
): Result<Value, AppFailure> {
const projected = projectOutcome(operationId, mapSuccess, mapProblem, outcome);
const metadata = "metadata" in outcome ? outcome.metadata : undefined;
const requestId = metadata?.correlationReference ?? outcome.sentRequestId;
const traceId = metadata?.traceReference;
return projected.ok || (requestId === undefined && traceId === undefined)
? projected
: Object.freeze({
ok: false as const,
error: Object.freeze({
...projected.error,
...(requestId === undefined ? {} : { requestId }),
...(traceId === undefined ? {} : { traceId }),
}),
});
}
function projectOutcome<WireOutput, Problem, Value>(
operationId: string,
mapSuccess: (
value: WireOutput,
context: FeatureHttpSuccessContext,
) => BoundaryMappingResult<Value>,
mapProblem:
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
outcome: HttpExecutionOutcome<WireOutput, Problem>,
): Result<Value, AppFailure> {
// 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, AppFailure> =>
failure(
"MAPPING_CONTRACT_VIOLATION",
operationId,
"MAPPING_CONTRACT_VIOLATION",
{ httpStatus, effect },
);
switch (outcome.kind) {
case "SUCCESS": {
let mapped: BoundaryMappingResult<Value>;
try {
mapped = mapSuccess(
outcome.value,
outcome.page === undefined
? NO_SUCCESS_CONTEXT
: Object.freeze({ page: outcome.page }),
);
} 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,
// 백엔드 1101/02-01. A resend of an unknown answer waits on it.
...(outcome.metadata.retryAfterMs === undefined
? {}
: { retryAfterMs: outcome.metadata.retryAfterMs }),
effect: outcome.effect,
...(mapped?.validationIssues === undefined
? {}
: { validationIssues: mapped.validationIssues }),
},
);
}
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),
operationId,
outcome.violation.kind,
{
...(httpStatus === undefined ? {} : { httpStatus }),
effect: outcome.effect,
},
);
}
}
}
function isServerFailureStatus(status: number): boolean {
return status >= 500 || status === 408 || status === 425;
}
/**
* 03-02. Pre-dispatch refusals the user can fix by changing what they entered.
* Every other refusal reason is a wiring defect in this client, and a refusal
* without a reason keeps the input reading it always had.
*/
const USER_INPUT_REJECTIONS: ReadonlySet<HttpRequestRejectionReason> = new Set([
"INPUT_INVALID",
"PATH_VALUE_INVALID",
"QUERY_TOO_LARGE",
"URL_TOO_LARGE",
"REQUEST_BODY_TOO_LARGE",
]);
function failureKindForViolation(violation: HttpContractViolation): FailureKind {
switch (violation.kind) {
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.
// 03-02. Only input the user can change is "input rejected"; a client
// wiring defect (contract not installed, path template and projection
// disagree, intent policy disagrees with the contract) cannot be fixed by
// the user.
case "FINAL_REQUEST_INVARIANT_FAILED":
return violation.reason === undefined ||
USER_INPUT_REJECTIONS.has(violation.reason)
? "VALIDATION_REJECTED"
: "UNKNOWN_CLIENT_FAILURE";
case "MISSING_IDEMPOTENCY_KEY":
case "UNEXPECTED_IDEMPOTENCY_KEY":
return "UNKNOWN_CLIENT_FAILURE";
default:
return "ENVELOPE_MISMATCH";
}
}
function failure(
kind: FailureKind,
operationId: string,
code: string,
details: Readonly<{
httpStatus?: number;
retryAfterMs?: number;
effect?: FailureEffectCertainty;
validationIssues?: readonly ValidationIssue[];
}> = {},
): Result<never, AppFailure> {
return Object.freeze({
ok: false as const,
error: createFailure(kind, operationId, 0, { code, ...details }),
});
}