import { MAX_VALIDATION_ISSUE_CANDIDATES, projectValidationIssues, type ValidationIssue, } from "./validation-issues.ts"; export type { ValidationIssue } from "./validation-issues.ts"; export type ErrorAction = | "retry" | "reauth" | "navigate" | "reload-once" | "contact-support" | "none"; /** * 07-04. Every field has a reader: `createFailure` copies `defaultRetryable`, * `userMessageKey` and `action`. Severity, telemetry event and redaction * fields were removed because nothing read them — telemetry names its own * events and `createFailure` drops sensitive details by copying an allowlist. */ export type ErrorDefinition = Readonly<{ kind: Kind; defaultRetryable: boolean; userMessageKey: string; action: ErrorAction; }>; const row = ( kind: Kind, defaultRetryable: boolean, action: ErrorAction, ): ErrorDefinition => Object.freeze({ kind, defaultRetryable, userMessageKey: `error.${kind.toLowerCase()}`, action, }); export const ERROR_REGISTRY = Object.freeze({ NETWORK_UNREACHABLE: row("NETWORK_UNREACHABLE", true, "retry"), REQUEST_TIMEOUT: row("REQUEST_TIMEOUT", true, "retry"), REQUEST_ABORTED: row("REQUEST_ABORTED", false, "none"), CONTENT_TYPE_MISMATCH: row("CONTENT_TYPE_MISMATCH", false, "contact-support"), MALFORMED_JSON: row("MALFORMED_JSON", false, "contact-support"), RESPONSE_BODY_LIMIT: row("RESPONSE_BODY_LIMIT", false, "contact-support"), ENVELOPE_MISMATCH: row("ENVELOPE_MISMATCH", false, "contact-support"), SCHEMA_MISMATCH: row("SCHEMA_MISMATCH", false, "contact-support"), MAPPING_CONTRACT_VIOLATION: row( "MAPPING_CONTRACT_VIOLATION", false, "contact-support", ), RESULT_LIMIT_EXCEEDED: row("RESULT_LIMIT_EXCEEDED", false, "contact-support"), SCOPE_GENERATION_CHANGED: row("SCOPE_GENERATION_CHANGED", false, "none"), IDENTITY_INTERN_LIMIT_EXCEEDED: row( "IDENTITY_INTERN_LIMIT_EXCEEDED", false, "retry", ), DUPLICATE_IN_FLIGHT: row("DUPLICATE_IN_FLIGHT", false, "none"), PAGINATION_CONTRACT_VIOLATION: row( "PAGINATION_CONTRACT_VIOLATION", false, "contact-support", ), AUTH_REQUIRED: row("AUTH_REQUIRED", false, "reauth"), AUTH_INTEGRATION_FAILURE: row( "AUTH_INTEGRATION_FAILURE", false, "contact-support", ), FORBIDDEN: row("FORBIDDEN", false, "navigate"), NOT_FOUND: row("NOT_FOUND", false, "navigate"), CONFLICT: row("CONFLICT", false, "retry"), VALIDATION_REJECTED: row("VALIDATION_REJECTED", false, "none"), UNKNOWN_CLIENT_FAILURE: row( "UNKNOWN_CLIENT_FAILURE", false, "contact-support", ), RATE_LIMITED: row("RATE_LIMITED", true, "retry"), SERVER_FAILURE: row("SERVER_FAILURE", true, "retry"), CHUNK_LOAD_FAILURE: row("CHUNK_LOAD_FAILURE", false, "reload-once"), BOOT_CONFIG_FAILURE: row("BOOT_CONFIG_FAILURE", false, "contact-support"), RELEASE_MANIFEST_FAILURE: row( "RELEASE_MANIFEST_FAILURE", false, "contact-support", ), DEPLOY_MISMATCH: row("DEPLOY_MISMATCH", false, "reload-once"), BUILD_MISMATCH: row("BUILD_MISMATCH", false, "reload-once"), CONFIG_MISMATCH: row("CONFIG_MISMATCH", false, "contact-support"), API_CONTRACT_MISMATCH: row("API_CONTRACT_MISMATCH", false, "contact-support"), RELEASE_MISMATCH: row("RELEASE_MISMATCH", false, "reload-once"), ASSET_MISMATCH: row("ASSET_MISMATCH", false, "reload-once"), STORAGE_UNAVAILABLE: row("STORAGE_UNAVAILABLE", false, "none"), STORAGE_QUOTA_EXCEEDED: row("STORAGE_QUOTA_EXCEEDED", false, "none"), RENDER_FAILURE: row("RENDER_FAILURE", false, "reload-once"), TELEMETRY_FAILURE: row("TELEMETRY_FAILURE", false, "none"), QUERY_CACHE_FAILURE: row("QUERY_CACHE_FAILURE", false, "retry"), UNKNOWN_FAILURE: row("UNKNOWN_FAILURE", false, "contact-support"), }); /** * Every failure crossing an application input boundary must use one of the * registry-owned kinds. Adapters may accept untrusted backend codes, but must * map those codes to this closed vocabulary before returning. */ export type FailureKind = keyof typeof ERROR_REGISTRY; export type FailureEffectCertainty = | "NOT_APPLICABLE" | "NOT_STARTED" | "NOT_APPLIED" | "APPLIED_CONFIRMED" | "MAYBE_APPLIED"; /** * 1101/07-05. The failure that crosses an application input boundary: a * gateway result, a query or mutation error. Its `kind` is the closed set * above. `AppError` (`src/platform/errors/app-error.ts`) is the other * vocabulary: an open `owner.reason` kind a feature uses inside its own * domain, mapped from an `AppFailure` where the feature needs it. Neither * changes how a request is retried; the HTTP executor follows the * operation's `retrySemantics` and `retryBudget`. */ export type AppFailure = Readonly<{ kind: FailureKind; code: string; /** * 1112/01-06. The code the paired backend's Envelope carried, as it came: * a feature's `mapProblem` may change `code`, never this. Only the HTTP * binding sets it, for an `ENVELOPE_V1` operation's problem; elsewhere it * is absent. */ backendCode?: string; httpStatus?: number; /** * Whether sending the same operation again is safe as far as this failure * tells: the registry default, forced `false` once a write may have * applied. Nothing in src reads it today. What the screen offers is * `action`: `"retry"` shows a retry button even when this is `false` * (`CONFLICT`, `QUERY_CACHE_FAILURE`): the user, not the runtime, sends * again. */ retryable: boolean; operationId: string; attemptCount: number; requestId?: string; traceId?: string; retryAfterMs?: number; effect?: FailureEffectCertainty; validationIssues?: readonly ValidationIssue[]; userMessageKey: string; action: ErrorAction; causeClass?: string; }>; /** * Backward-compatible transport-facing name. * * @deprecated Use `AppFailure`. Nothing in this repository imports it (07-01, * enforced by `no-restricted-imports` in eslint.config.ts). Removing it breaks * downstream importers; do it in a minor release with a CHANGELOG [계약] * entry (owner: frontend-platform). */ export type ApiFailure = AppFailure; export type FailureDetails = Readonly<{ code?: string; backendCode?: string; httpStatus?: number; requestId?: string; traceId?: string; retryAfterMs?: number; effect?: FailureEffectCertainty; validationIssues?: readonly ValidationIssue[]; causeClass?: string; }>; export function createFailure( kind: FailureKind, operationId: string, attempt: number, details: FailureDetails = {}, ): AppFailure { const definition: ErrorDefinition = ERROR_REGISTRY[kind]; return Object.freeze({ kind: definition.kind, code: typeof details.code === "string" ? details.code : definition.kind, ...(typeof details.backendCode === "string" ? { backendCode: details.backendCode } : {}), retryable: details.effect === "MAYBE_APPLIED" || details.effect === "APPLIED_CONFIRMED" ? false : definition.defaultRetryable, operationId, attemptCount: Math.max(1, attempt + 1), ...(Number.isInteger(details.httpStatus) ? { httpStatus: details.httpStatus } : {}), ...(typeof details.requestId === "string" ? { requestId: details.requestId } : {}), ...(typeof details.traceId === "string" ? { traceId: details.traceId } : {}), ...(typeof details.retryAfterMs === "number" ? { retryAfterMs: details.retryAfterMs } : {}), ...(details.effect === undefined ? {} : { effect: details.effect }), ...(Array.isArray(details.validationIssues) ? { validationIssues: projectValidationIssues(details.validationIssues) } : {}), ...(typeof details.causeClass === "string" ? { causeClass: details.causeClass } : {}), userMessageKey: definition.userMessageKey, action: details.effect === "MAYBE_APPLIED" ? unknownEffectAction(definition.action) : details.effect === "APPLIED_CONFIRMED" ? "none" : definition.action, }); } /** * D-2. An unknown effect sends the user to support, except when the session * itself is the problem: signing in again comes first either way. */ function unknownEffectAction(action: ErrorAction): ErrorAction { return action === "reauth" ? "reauth" : "contact-support"; } /** * Adds controller-owned mutation effect knowledge without weakening the * fail-safe handling required for an unknown server-side outcome. */ export function withFailureEffect( failure: AppFailure, effect: Exclude, ): AppFailure { return Object.freeze({ ...failure, effect, ...(effect === "MAYBE_APPLIED" ? { retryable: false as const, action: unknownEffectAction(failure.action) } : effect === "APPLIED_CONFIRMED" ? { retryable: false as const, action: "none" as const } : {}), }); } /** * 1106/03-01 (D10 supplement). The paired backend's pre-write refusals that * every attempt of one request gets, code and status: binding and * validation of the request (400 VALIDATION_FAILED, whatever its details) * and a key its rule rejects (400 IDEMPOTENCY_KEY_INVALID). Both are rows of * the refusal table in `src/adapters/http/backend-envelope.ts` * (tests/unit/backend-envelope.test.ts holds them to it). Its other rows are * not: 422 IDEMPOTENT_REQUEST_MISMATCH comes only once the key reached the * server, and the 503 RATE_LIMIT_* answers come before the idempotency * check and change over time. */ export const REFUSALS_OF_EVERY_ATTEMPT: Readonly> = Object.freeze({ VALIDATION_FAILED: 400, IDEMPOTENCY_KEY_INVALID: 400, }); /** * 1106/03-01 (D10 supplement and its second fix). A `NOT_APPLIED` refusal * the same request gets on every attempt: a row above, code and status * together. A resend of an unknown request that meets one shows the first * attempt was refused too, so the request is settled. Not one: a refusal * before the idempotency check or one that changes over time (429, 401, * 403, 503 RATE_LIMIT_*), a code a feature declared refused before its * write (it may be a rule on changing state), any other code, and * `NOT_STARTED`. The kind is not read: a feature's `mapProblem` sets it, and * it maps its own codes, or every 422, to `VALIDATION_REJECTED`. 1112/01-06. * Nor is `code`, for the same reason: the answer is `backendCode`, the code * the backend's Envelope carried. A failure without it is not settled. */ export function isRefusedOnEveryAttempt(failure: AppFailure): boolean { if (failure.effect !== "NOT_APPLIED") return false; const code = failure.backendCode; return ( code !== undefined && Object.hasOwn(REFUSALS_OF_EVERY_ATTEMPT, code) && REFUSALS_OF_EVERY_ATTEMPT[code] === failure.httpStatus ); } /** * Projects an untrusted validation details payload into the only validation * metadata allowed to cross the HTTP boundary. Backend copy and additional * values are deliberately discarded. * * 백엔드 1101/02-01 후속. The paired backend's details is the list itself, * one `{field, code, message}` per violation (its docs/web/http-contract.md * §4); `field` is read as the path. The scan stays bounded. */ export function safeValidationIssues( value: unknown, ): readonly ValidationIssue[] { if (Array.isArray(value)) { return projectValidationIssues( value .slice(0, MAX_VALIDATION_ISSUE_CANDIDATES) .map((entry: unknown) => entry && typeof entry === "object" ? { path: (entry as Readonly>).field, code: (entry as Readonly>).code, } : entry, ), ); } if (!value || typeof value !== "object") return Object.freeze([]); const candidate = value as Readonly<{ issues?: unknown; fieldErrors?: unknown; }>; const issues = Array.isArray(candidate.issues) ? candidate.issues : Array.isArray(candidate.fieldErrors) ? candidate.fieldErrors : []; return projectValidationIssues(issues); } export function kindForStatus(status: number): FailureKind { if (status === 401) return "AUTH_REQUIRED"; if (status === 403) return "FORBIDDEN"; if (status === 404) return "NOT_FOUND"; if (status === 409) return "CONFLICT"; if (status === 422) return "VALIDATION_REJECTED"; if (status === 429) return "RATE_LIMITED"; if (status >= 500) return "SERVER_FAILURE"; if (status >= 400) return "UNKNOWN_CLIENT_FAILURE"; return "ENVELOPE_MISMATCH"; } /** * Total catch-all that intentionally discards the thrown value. * */ export function normalizeUnknownFailure( value: unknown, context: Readonly<{ operationId?: string; attempt?: number }> = {}, ): AppFailure { const causeClass = value instanceof Error ? value.name : value === null ? "null" : typeof value; return createFailure( "UNKNOWN_FAILURE", context.operationId ?? "UNKNOWN_OPERATION", context.attempt ?? 0, { code: "UNKNOWN_FAILURE", causeClass }, ); }