Files
clean-architecture-frontend…/src/contracts/errors.ts
T
DongHyeonka c99b7a7f63 docs(contracts): 두 오류 어휘와 commandRecovery를 누가 읽는지 타입 옆에 적는다
문제
- AppFailure(닫힌 kind, retryable, action)와 AppError(열린 owner.reason
  kind, retryability)의 관계가 타입 옆에 없다. AppFailure.retryable과
  action "retry"는 뜻이 다른데(CONFLICT는 retryable false, action retry)
  설명이 없어 모순으로 읽고 "고치는" 변경이 나올 수 있다(1101/07-05).
- CommandRecoveryDescriptor는 KEYED 쓰기에 필수지만 HTTP 실행기는 읽지
  않는다. 결과 불명 쓰기를 기능 gateway가 수습한다는 것은 설계서 4.4절에만
  있다(1101/07-07).
- 07-01(c)에서 더한 읽기 retrySemantics 거절 문구가 errors.md reason 표에
  없다.

고른 방법
주석만 더한다. AppFailure 위에 어느 경계에서 어느 어휘를 쓰는지와, 둘 다
재시도 동작을 바꾸지 않는다는 것. retryable 칸에 "src에서 읽는 곳이 없고,
화면 버튼은 action"이라는 것. CommandRecoveryDescriptor 위에 실행기가 읽지
않고 기능 gateway가 재전송·조회를 정한다는 것. errors.md reason 표에 한 행.

버린 대안
- retryable을 autoRetryable 같은 이름으로 바꾸기: 다운스트림 import를 깨는
  비용에 비해 얻는 것이 작다.

위험·한계
- 동작은 바뀌지 않는다. "src에서 읽는 곳이 없다"는 grep으로 확인한 지금
  상태다.

검증
- grep: src/presentation·bootstrap·features·application에서
  AppFailure.retryable을 읽는 곳 0. commandRecovery를 읽는 곳은 플랫폼 개요
  화면뿐.
- eslint, verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 1101/07-05, 1101/07-07
2026-11-04 20:38:14 +09:00

318 lines
11 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;
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;
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,
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 }
: {}),
});
}
/**
* 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 },
);
}