Files
clean-architecture-frontend…/src/contracts/errors.ts
T
DongHyeonka 42aa93d4c7
frontend-quality-gates / merge / static checks (pull_request) Successful in 2m56s
frontend-quality-gates / merge / tests (pull_request) Failing after 14m26s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 9m20s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
frontend-quality-gates / main / checker self-tests (pull_request) Skipped
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
fix(errors): 재전송이 결과 불명을 푸는지는 백엔드가 보낸 code로 정한다
isRefusedOnEveryAttempt는 failure.code를 읽는데, 그 값은 기능의 mapProblem이
정한다(1112/01-06). 그래서 둘이 틀린다.

- 기능이 백엔드 400 VALIDATION_FAILED를 자기 code로 바꾸면 모든 시도가 받는
  거절인데도 결과 불명이 풀리지 않는다.
- 기능이 시각·데이터베이스를 읽는 자기 거절(400)을 VALIDATION_FAILED로 바꾸면
  첫 요청이 반영됐을 수 있는데도 결과 불명이 풀린다.

AppFailure에 backendCode를 더한다(선택 칸, 추가만). HTTP 바인딩이 ENVELOPE_V1
operation의 PROBLEM에서 백엔드 error.code를 그대로 싣고, 판정은 이 칸과
status만 읽는다. Envelope가 없는 operation의 실패에는 싣지 않아 결과 불명이
풀리지 않는다(안전한 쪽). 버린 대안: 판정 표를 기능 code에 맞춰 늘리기(기능이
code를 바꿀 때마다 표가 어긋난다).

위험·한계: createFailure로 실패를 직접 만들어 재전송 거절을 흉내 내던 코드는
backendCode를 함께 줘야 결과 불명이 풀린다. 템플릿 안에서는 코디네이터 시험
넷뿐이고 고쳤다. 다운스트림 시험이 같은 방식이면 CHANGELOG [계약]에 적는다.
mapProblem이 예외를 던져 MAPPING_CONTRACT_VIOLATION이 된 실패에는 싣지 않는다.

Refs: 1112/01-06, 1106/03-01
2026-11-12 23:31:50 +09:00

369 lines
13 KiB
TypeScript

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<Kind extends string> = Readonly<{
kind: Kind;
defaultRetryable: boolean;
userMessageKey: string;
action: ErrorAction;
}>;
const row = <Kind extends string>(
kind: Kind,
defaultRetryable: boolean,
action: ErrorAction,
): ErrorDefinition<Kind> =>
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<FailureKind> = 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<FailureEffectCertainty, "NOT_APPLICABLE">,
): 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<Record<string, number>> =
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<Record<string, unknown>>).field,
code: (entry as Readonly<Record<string, unknown>>).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 },
);
}