문제 V2 클라이언트는 보낸 KEYED 요청이 503·408·425·502·504·network·timeout으로 끝나면 같은 키로 자동 재시도했다. 048f490으로 그 동작이 없어졌다. 설계 정본 (2026-07-30 closed deep design 8.3)은 KEYED 자동 재시도를 "known response status가 retry 가능하다고 package가 명시한 경우만" 허용하고, 응답 없는 network·timeout 뒤에는 금지한다. V2는 응답 없는 실패 뒤에도 보내 정본과 어긋났고, V3는 응답이 재시도를 허락해도 보내지 않아 정본보다 좁았다. 짝 백엔드는 503 IDEMPOTENCY_UNAVAILABLE을 "작업 실행 전에 거부됐다. 같은 키로 나중에 다시 보낸다"로 정한다(http-contract.md §2). 고른 방법 - backend-envelope.ts의 invitesKeyedResend: 503 + IDEMPOTENCY_UNAVAILABLE. - Envelope operation의 실패 해석에서 KEYED 명령이 그 답을 받으면 AdmissionOutcome에 keyedResend를 싣는다. 재시도 루프는 그때 retryBudget· MAX_RETRY_ATTEMPTS·상한 2 안에서 같은 frozen 요청(같은 Idempotency-Key)을 다시 보낸다. certainty는 MAYBE_APPLIED로 두어, 다 쓰면 결과 불명으로 끝나고 키를 지킨다. 버린 대안 - V2처럼 KEYED의 모든 재시도 가능 status·network 실패에서 재시도: 정본 8.3이 응답 없는 실패 뒤 재시도를 금지한다. - 409 IDEMPOTENT_IN_FLIGHT도 자동 재시도: 처리 중 요청은 47fec5c의 사용자 재전송(Retry-After 대기)이 이미 같은 키로 다룬다. V2도 409는 자동으로 다시 보내지 않았다. 위험·한계 - retryBudget이 0인 명령(참조 기능 CREATE)은 그대로 다시 보내지 않는다. - Envelope가 아닌 operation은 백엔드 code를 몰라 이 재전송이 없다. 검증 - RED: tests/integration/http-execution-v3-envelope.test.ts "KEYED resend on the backend's pre-execution refusal" 3건 중 2건 실패(한 번만 보내고 PROBLEM). 다른 503(REQUEST_TIMEOUT)을 다시 보내지 않는 행은 처음부터 통과. - GREEN: 같은 파일 35건 통과. 두 번 보낸 키가 같다. - check:types, lint, check:architecture, test:unit 2,568, test:integration 117, test:component 245, tests/features 99 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.7
219 lines
6.9 KiB
TypeScript
219 lines
6.9 KiB
TypeScript
import {
|
|
kindForStatus,
|
|
safeValidationIssues,
|
|
type FailureKind,
|
|
type ValidationIssue,
|
|
} from "../../contracts/errors.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"`.
|
|
*/
|
|
|
|
/**
|
|
* 백엔드 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.
|
|
*/
|
|
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(),
|
|
})
|
|
.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. */
|
|
export function readSuccessEnvelope(value: unknown): EnvelopeRead<unknown> {
|
|
const parsed = successEnvelopeSchema.safeParse(value);
|
|
return parsed.success
|
|
? Object.freeze({ ok: true as const, value: parsed.data.data })
|
|
: ENVELOPE_INVALID;
|
|
}
|
|
|
|
/** The failure `error` object, as the backend sent it. */
|
|
export function readFailureEnvelope(
|
|
value: unknown,
|
|
): EnvelopeRead<EnvelopeError> {
|
|
const parsed = failureEnvelopeSchema.safeParse(value);
|
|
return parsed.success
|
|
? Object.freeze({ ok: true as const, value: parsed.data.error })
|
|
: ENVELOPE_INVALID;
|
|
}
|
|
|
|
/**
|
|
* 1101/14.4. The 400, 409 and 422 codes the paired backend raises only before
|
|
* it writes. Backend 5786126c, read code by code into the frontend contract
|
|
* (docs/architecture/backend-api-and-server-state-contract.md 6.1); recheck
|
|
* this table with that section when the backend SHA there moves. Only the
|
|
* status and code together count. `reason` is the diagnostics name of an
|
|
* idempotency refusal, named for what is wrong on this side.
|
|
*/
|
|
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",
|
|
}),
|
|
});
|
|
|
|
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: a 422, or
|
|
* the paired backend's 400 VALIDATION_FAILED whose details is the field list
|
|
* (§4). This decides the kind and the issues only, not whether it applied.
|
|
*/
|
|
export function isFieldValidationFailure(
|
|
status: number,
|
|
error: EnvelopeError,
|
|
): boolean {
|
|
return (
|
|
status === 422 ||
|
|
(status === 400 &&
|
|
error.code === "VALIDATION_FAILED" &&
|
|
Array.isArray(error.details))
|
|
);
|
|
}
|
|
|
|
/**
|
|
* The verdict the backend contract gives whatever the operation is, or
|
|
* `undefined` when the operation's own classifier decides.
|
|
*
|
|
* - Not applied: a code in the table above.
|
|
* - 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 503 IDEMPOTENCY_UNAVAILABLE: §2 says to resend it with the same key,
|
|
* which only an unknown result keeps.
|
|
*/
|
|
export function envelopeFailureEffect(
|
|
status: number,
|
|
error: EnvelopeError,
|
|
): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined {
|
|
if (refusedBeforeWrite(error.code, status) !== undefined) return "NOT_APPLIED";
|
|
return status === 400 ||
|
|
status === 409 ||
|
|
status === 422 ||
|
|
(status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE")
|
|
? "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"
|
|
: gatewayFailureOr(status, kindForStatus(status)),
|
|
code: error.code,
|
|
...(fieldValidation
|
|
? { validationIssues: safeValidationIssues(error.details) }
|
|
: {}),
|
|
});
|
|
}
|