Files
clean-architecture-frontend…/src/adapters/http/backend-envelope.ts
T
DongHyeonka c6c37f395b fix(http): 백엔드 rate-limit 503 두 code를 쓰기 전 거절로 읽는다
문제
짝 백엔드 http-contract.md §4는 web 전용 code 넷을 적는다. 그중 503
RATE_LIMIT_UNAVAILABLE(저장소 응답 없음, retryable, Retry-After 있음)과 503
RATE_LIMIT_INCOMPATIBLE(제공자 불일치)이 답 표 사본에도 프론트 판정 표에도
없다. 그래서 이 503은 기능 분류기가 정하고, create:feature가 만든 쓰기의
분류기는 늘 MAYBE_APPLIED다. 아무 일도 일어나지 않은 저장이 결과 불명이 되고,
NEVER 쓰기는 사실과 다른 "변경됨으로 확인"을 눌러야 폼이 풀린다(리뷰 실험 X4:
429는 NOT_APPLIED, 503 둘은 SERVER_FAILURE/MAYBE_APPLIED). pin은 §4를
대조했다고 적었지만 사본에는 REQUEST_TIMEOUT 한 행만 있었다.

고른 방법
백엔드 45d2a478을 읽기만 해서 code마다 판정했다. 두 code는
RateLimitInterceptor.preHandle이 false를 돌려주며 쓰고(Unavailable·
Indeterminate → RATE_LIMIT_UNAVAILABLE, Incompatible →
RATE_LIMIT_INCOMPATIBLE), main 소스에서 두 code를 내는 곳은 그 두 줄뿐이다.
preHandle이 false면 handler를 부르지 않으므로 둘 다 쓰기 전이다. 백엔드는 같은
키 재전송을 요구하지 않는다(멱등성 executor 전). 그래서 답 표 사본에
refusedBeforeWrite: true, sameKeyResend: false로 두 행을 더하고, 프론트 거절 표
REFUSED_BEFORE_WRITE에 status 503과 함께 더했다. pin 테스트의 "답 표대로 읽는다"
규칙이 그대로 NOT_APPLIED를 요구하고 양방향 대조가 두 표를 함께 지킨다. kind는
지금처럼 SERVER_FAILURE(action retry)이고, KEYED도 자동 재전송은 없다(같은 키를
요구하는 답은 503 IDEMPOTENCY_UNAVAILABLE 하나다). pin의 comparedOn을 §4를 다시
대조한 날짜로 올렸다. 계약 문서 4.1·6.1절과 매뉴얼 01·02의 5xx 행 수를 고쳤다.

버린 대안
생성기 분류기가 503을 code별로 보게 한다: 생성 기능에만 고쳐지고 손으로 쓴
Envelope operation은 그대로 남는다. 판정은 백엔드 답 표 한 곳이 정한다는 지금
규칙을 따랐다.

위험·한계
- 추론(실행 확인 안 함): Spring MVC는 비동기 처리(Callable·DeferredResult) 뒤
  ASYNC 재디스패치에서도 interceptor의 preHandle을 다시 부르고, 이 interceptor는
  dispatcher 종류를 보지 않는다. 비동기 쓰기 컨트롤러라면 이 503(그리고 429)이
  쓰기 뒤에도 나올 수 있다. 45d2a478에는 Envelope을 돌려주는 비동기 쓰기
  컨트롤러가 없다(web-advanced 스트리밍과 fileserver 전송뿐). 계약 6.1절에 적었다.
  백엔드에 넘길 요청: RateLimitInterceptor가 DispatcherType.REQUEST에서만
  평가하게 한다.
- fileserver-upload.ts는 같은 백엔드 답을 자기 표로 따로 판정한다(01 영역).
  여기서는 바꾸지 않았다.
- NOT_APPLIED가 되면서 IDEMPOTENT 쓰기는 이 503에 retryBudget 안에서 자동으로
  다시 보낼 수 있게 됐다(503은 재시도 status다). 쓰기 전 거절이라 중복은 없다.
  RATE_LIMIT_INCOMPATIBLE은 백엔드가 retryable false로 보내지만 실행기는 status로
  판단하므로 같은 답을 한 번 더 받을 수 있다. KEYED·NEVER는 자동 재전송이 없다.

검증
desktop batch에서 확인:
node scripts/run-vitest.ts run tests/unit/backend-envelope.test.ts
tests/unit/backend-contract-pin.test.ts
tests/integration/http-execution-v3-envelope.test.ts

Refs: 1105/03-02
2026-11-06 02:33:16 +09:00

411 lines
14 KiB
TypeScript

import {
kindForStatus,
safeValidationIssues,
type FailureKind,
type ValidationIssue,
} from "../../contracts/errors.ts";
import { PLATFORM_CODES_POSSIBLY_AFTER_WRITE } from "../../contracts/external-contract-runtime.ts";
import { z } from "../../contracts/zod.ts";
/**
* 1101 README 14.3. How this client reads the paired backend's Envelope
* (clean-architecture-backend-template docs/web/http-contract.md §1, §2, §4)
* for a V3 operation that declares `responseEnvelope: "ENVELOPE_V1"`.
*/
/**
* 1103/03-02. A page list's `meta.page` (§1): the 0-based page `number`, the
* `size` the backend applied (it caps it at 1..100), the `total` across all
* pages, and the applied `sort` in Spring form (`field,direction`), null or
* absent when unsorted.
*/
const pageSchema = z
.object({
number: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
size: z.number().int().min(1).max(100),
total: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
sort: z.string().min(1).max(256).nullable().optional(),
})
.strip();
export type EnvelopePage = Readonly<{
number: number;
size: number;
total: number;
sort?: string;
}>;
/**
* 백엔드 1101/02-02. The paired backend drops a null field together with its
* key (§1). The id keys are absent on an answer written before its request id
* filter, so they are optional here too. A `page` outside the backend's own
* bounds is dropped rather than failing the answer, like any `meta` key this
* client does not read.
*/
const metaSchema = z
.object({
requestId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
traceId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
correlationId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
page: pageSchema.optional().catch(undefined),
})
.strip();
export const successEnvelopeSchema = z
.object({
success: z.literal(true),
// A missing `data` is the null the backend dropped.
data: z.unknown().default(null),
meta: metaSchema,
})
.strict();
export const failureEnvelopeSchema = z
.object({
success: z.literal(false),
error: z
.object({
code: z.string().regex(/^[A-Z0-9_]{1,64}$/),
category: z.string().min(1).max(64).optional(),
message: z.string().max(1_024).optional(),
retryable: z.boolean().optional(),
details: z.unknown().optional(),
})
.strict(),
meta: metaSchema,
})
.strict();
export type EnvelopeError = Readonly<{
code: string;
category?: string;
message?: string;
retryable?: boolean;
details?: unknown;
}>;
export type EnvelopeRead<Value> =
| Readonly<{ ok: true; value: Value }>
| Readonly<{ ok: false }>;
const ENVELOPE_INVALID: EnvelopeRead<never> = Object.freeze({ ok: false });
/**
* The success `data`. A missing key is the null the backend dropped.
* 1103/03-02. A page list's `meta.page` comes with it.
*/
export function readSuccessEnvelope(
value: unknown,
): Readonly<{ ok: true; value: unknown; page?: EnvelopePage }> | Readonly<{ ok: false }> {
const parsed = successEnvelopeSchema.safeParse(value);
if (!parsed.success) return ENVELOPE_INVALID;
const page = parsed.data.meta.page;
return Object.freeze({
ok: true as const,
value: parsed.data.data,
...(page === undefined
? {}
: {
page: Object.freeze({
number: page.number,
size: page.size,
total: page.total,
...(typeof page.sort === "string" ? { sort: page.sort } : {}),
}),
}),
});
}
/**
* The failure `error` object, as the backend sent it.
* 1103/03-06. With the backend's `meta.traceId`, when it sent one.
*/
export function readFailureEnvelope(
value: unknown,
):
| Readonly<{ ok: true; value: EnvelopeError; traceId?: string }>
| Readonly<{ ok: false }> {
const parsed = failureEnvelopeSchema.safeParse(value);
if (!parsed.success) return ENVELOPE_INVALID;
const traceId = parsed.data.meta.traceId;
return Object.freeze({
ok: true as const,
value: parsed.data.error,
...(traceId === undefined ? {} : { traceId }),
});
}
/**
* 1101/14.4. The 400, 409 and 422 codes the paired backend raises only before
* it writes, read code by code into the frontend contract
* (docs/architecture/backend-api-and-server-state-contract.md 6.1) at the
* backend commit config/contracts/backend-contract-pin.json names. When that
* commit moves, recheck this table with that section;
* tests/unit/backend-contract-pin.test.ts holds it to the copied backend
* answer table. Only the status and code together count. `reason` is the
* diagnostics name of an idempotency refusal, named for what is wrong on
* this side.
*
* 1105/03-02. And the edge rate limiter's two 503s (§4): its interceptor
* answers in `preHandle`, before the controller runs, so the command did not
* run whatever the operation's own classifier says.
*/
export type IdempotencyRefusalReason =
| "IDEMPOTENT_REQUEST_MISMATCH"
| "IDEMPOTENCY_KEY_RULE_MISMATCH";
const REFUSED_BEFORE_WRITE: Readonly<
Record<
string,
Readonly<{ status: number; reason?: IdempotencyRefusalReason }>
>
> = Object.freeze({
// Request binding and validation, whatever the details: the field list, a
// body that did not parse (`{cause}` or none), a page or sort parameter.
VALIDATION_FAILED: Object.freeze({ status: 400 }),
// `isValidIdempotencyKey` passed the key before sending, so the client and
// server key rules disagree.
IDEMPOTENCY_KEY_INVALID: Object.freeze({
status: 400,
reason: "IDEMPOTENCY_KEY_RULE_MISMATCH",
}),
// The same key went out with another body.
IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({
status: 422,
reason: "IDEMPOTENT_REQUEST_MISMATCH",
}),
// §4. The rate-limit store did not answer (retryable, with Retry-After),
// or the rate-limit provider does not match the contract. Both come from
// RateLimitInterceptor.preHandle, before any handler.
RATE_LIMIT_UNAVAILABLE: Object.freeze({ status: 503 }),
RATE_LIMIT_INCOMPATIBLE: Object.freeze({ status: 503 }),
});
/**
* 1103/12-06. The table's rows, for the test that holds them to the backend's
* own answer table copied at the pinned commit
* (config/contracts/backend-contract-pin.json).
*/
export function refusedBeforeWriteRows(): readonly Readonly<{
code: string;
status: number;
}>[] {
return Object.freeze(
Object.entries(REFUSED_BEFORE_WRITE).map(([code, refusal]) =>
Object.freeze({ code, status: refusal.status }),
),
);
}
function refusedBeforeWrite(code: string, status: number | undefined) {
const refusal = Object.hasOwn(REFUSED_BEFORE_WRITE, code)
? REFUSED_BEFORE_WRITE[code]
: undefined;
return refusal !== undefined && refusal.status === status
? refusal
: undefined;
}
export function idempotencyRefusalReason(
code: string,
status: number | undefined,
): IdempotencyRefusalReason | undefined {
return refusedBeforeWrite(code, status)?.reason;
}
/**
* 백엔드 1101/02-01 후속. A failure the form shows on its fields: the paired
* backend's 400 VALIDATION_FAILED whose details is the field list (§4), or a
* 422 that carries a field list. This decides the kind and the issues only,
* not whether it applied.
*
* 1103/08-05. A 422 without one is not an input error: the paired backend's
* 422 IDEMPOTENT_REQUEST_MISMATCH (the same key went out with another body)
* and fileserver's 422s leave the user nothing to correct.
*/
export function isFieldValidationFailure(
status: number,
error: EnvelopeError,
): boolean {
return status === 422
? safeValidationIssues(error.details).length > 0
: status === 400 &&
error.code === "VALIDATION_FAILED" &&
Array.isArray(error.details);
}
/**
* 1103/03-05. Why a backend answer left a command's result unknown, a closed
* set for diagnostics `reason`: the key is still running (`IN_FLIGHT`), one of
* the backend's own 5xx answers below, or a 400, 409 or 422 whose code does
* not say whether it came before or after the write (`STAGE_UNKNOWN`).
*/
export type UnknownEffectReason =
| "IN_FLIGHT"
| "IDEMPOTENCY_UNAVAILABLE"
| "COMPLETION_UNKNOWN"
| "RECOVERY_REQUIRED"
| "SERVER_TIMEOUT"
| "STAGE_UNKNOWN";
/**
* 1103/03-04. The backend's answers outside 400, 409 and 422 that it defines
* itself (§2, §4), each with its status. None of them lets a client say the
* command did not run, and none takes a new key.
*/
const MAYBE_APPLIED_ANSWERS: Readonly<
Record<string, Readonly<{ status: number; reason: UnknownEffectReason }>>
> = Object.freeze({
// §2. Refused before the action, but to be resent with the same key, which
// only an unknown result keeps.
IDEMPOTENCY_UNAVAILABLE: Object.freeze({
status: 503,
reason: "IDEMPOTENCY_UNAVAILABLE",
}),
// §2. The action ran and recording its result failed: same key later,
// never a new one.
IDEMPOTENCY_COMPLETION_UNKNOWN: Object.freeze({
status: 503,
reason: "COMPLETION_UNKNOWN",
}),
// §2. An earlier attempt's effect cannot be proven. Not resent on its own;
// the user checks the data.
IDEMPOTENCY_RECOVERY_REQUIRED: Object.freeze({
status: 500,
reason: "RECOVERY_REQUIRED",
}),
// §4. An async request ran past its time; the work may still go on.
REQUEST_TIMEOUT: Object.freeze({ status: 503, reason: "SERVER_TIMEOUT" }),
});
function maybeAppliedAnswer(code: string, status: number) {
const answer = Object.hasOwn(MAYBE_APPLIED_ANSWERS, code)
? MAYBE_APPLIED_ANSWERS[code]
: undefined;
return answer !== undefined && answer.status === status ? answer : undefined;
}
function mayHaveApplied(code: string, status: number): boolean {
return maybeAppliedAnswer(code, status) !== undefined;
}
/** 1103/12-06. The rows above, for the same comparison as the refusal table. */
export function maybeAppliedAnswerRows(): readonly Readonly<{
code: string;
status: number;
}>[] {
return Object.freeze(
Object.entries(MAYBE_APPLIED_ANSWERS).map(([code, answer]) =>
Object.freeze({ code, status: answer.status }),
),
);
}
/**
* 1103/03-05. The cause behind a `MAYBE_APPLIED` the table gave, or
* `undefined` when the answer did not leave the result unknown.
*/
export function unknownEffectReason(
status: number,
error: EnvelopeError,
declaredRefusals?: readonly string[],
): UnknownEffectReason | undefined {
if (envelopeFailureEffect(status, error, declaredRefusals) !== "MAYBE_APPLIED") {
return undefined;
}
if (status === 409 && error.code === "IDEMPOTENT_IN_FLIGHT") return "IN_FLIGHT";
return maybeAppliedAnswer(error.code, status)?.reason ?? "STAGE_UNKNOWN";
}
/**
* 1103/03-01. A code the operation declares as refused before its write
* (`commandEffect.refusedBeforeWrite`). Composition already refuses an
* idempotency code in that list; this is the runtime's own fail-close for an
* executor called without composition. The table's own codes keep its status
* rule. 1105/03-01. So do the platform codes contract 6.1 reads as possibly
* raised after the write.
*/
function declaredBeforeWrite(
code: string,
declared: readonly string[] | undefined,
): boolean {
return (
declared !== undefined &&
!Object.hasOwn(REFUSED_BEFORE_WRITE, code) &&
!/^IDEMPOTEN(?:T|CY)_/.test(code) &&
!PLATFORM_CODES_POSSIBLY_AFTER_WRITE.includes(code) &&
declared.includes(code)
);
}
/**
* The verdict the backend contract gives, or `undefined` when the
* operation's own classifier decides.
*
* - Not applied: a code in the refusal table above, or a 400, 409 or 422
* whose code the operation declared as refused before its write.
* - Maybe applied: every other 400, 409 and 422, including 409
* IDEMPOTENT_IN_FLIGHT (an earlier request with the key still runs); the
* backend can raise them after a write and the code does not say which.
* And the answers in `MAYBE_APPLIED_ANSWERS`, status and code together.
*/
export function envelopeFailureEffect(
status: number,
error: EnvelopeError,
declaredRefusals?: readonly string[],
): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined {
if (refusedBeforeWrite(error.code, status) !== undefined) return "NOT_APPLIED";
if (status === 400 || status === 409 || status === 422) {
return declaredBeforeWrite(error.code, declaredRefusals)
? "NOT_APPLIED"
: "MAYBE_APPLIED";
}
return mayHaveApplied(error.code, status) ? "MAYBE_APPLIED" : undefined;
}
/**
* §2. The one answer after which the backend asks for the same request again
* with the same key: 503 IDEMPOTENCY_UNAVAILABLE, refused before the command
* ran. A KEYED command may be resent on it automatically (runtime design
* §8.3: only on a known answer that says resending is safe).
*/
export function invitesKeyedResend(
status: number,
error: EnvelopeError,
): boolean {
return status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE";
}
/**
* Q-6.3-3b. A gateway 5xx/408/425 is a server outage, not a contract breach:
* it keeps the SERVER_FAILURE retry rule.
*/
export function gatewayFailureOr(status: number, kind: FailureKind): FailureKind {
return status >= 500 || status === 408 || status === 425
? "SERVER_FAILURE"
: kind;
}
/** The failure kind, code and field issues an unmapped problem reads as. */
export function envelopeFailureReading(
status: number,
error: EnvelopeError,
): Readonly<{
kind: FailureKind;
code: string;
validationIssues?: readonly ValidationIssue[];
}> {
const fieldValidation = isFieldValidationFailure(status, error);
return Object.freeze({
kind: fieldValidation
? "VALIDATION_REJECTED"
: status === 422
? "UNKNOWN_CLIENT_FAILURE"
: gatewayFailureOr(status, kindForStatus(status)),
code: error.code,
...(fieldValidation
? { validationIssues: safeValidationIssues(error.details) }
: {}),
});
}