문제: 짝 백엔드 Fileserver는 검증기가 거절한 업로드를 202 성공 Envelope(state REJECTED)로 답한다. client는 이 답을 FILE_REJECTED 실패로 바꾸는데, readSuccessEnvelope가 meta.traceId를 버려서 실패에 traceId가 없다. 같은 client의 Envelope 실패는 traceId를 싣는다 (1105/01-03). 서버가 정상으로 답해 trace 값이 손에 있는데도, 지원 담당이 이 거절을 서버 로그나 REJECTED 레코드와 잇지 못한다. 고른 방법: readSuccessEnvelope가 readFailureEnvelope처럼 meta.traceId가 있으면 traceId로 함께 돌려준다. Fileserver client는 202 REJECTED 실패에 그 값을 싣는다. V3 실행기는 value와 page만 읽으므로 동작이 같다. 매뉴얼 7절 결과 읽기 줄에 적었다. 버린 대안: fileserver-upload가 successEnvelopeSchema를 직접 파싱하면 Envelope 읽기가 backend-envelope.ts 밖으로 갈라진다. traceId만 읽는 함수를 따로 두면 같은 답을 두 번 파싱한다. 반환 칸이 늘어 readSuccessEnvelope 결과를 toEqual로 보는 테스트 두 곳(tests/runtime-schema/http-schema.test.ts, tests/unit/a11y-api-answers.test.ts)의 기대값에 traceId를 더했다. 기대를 넓힌 것이 아니라 새 칸의 값까지 고정한 것이다. 위험·한계: 거절 이유는 여전히 없다. 프론트로는 고칠 수 없어 백엔드로 넘긴다. - 사실(백엔드 45d2a478): FinalizeUploadApplicationUseCase #applyNonAcceptVerdict는 REJECT 판정의 code(FILE_TOO_LARGE, DIGEST_MALFORMED, 제품 검증기 code 등)를 FileRecordMutation.failure로 레코드의 lastErrorCode에만 쓴다. FileUploadController#created는 UploadedFileResponse 7칸(fileId, state, filename, mediaType, size, sha256, etag)을 202로 답한다. 이유 칸이 없다. - 요청: REJECT를 실패 Envelope(422, error.code = 판정 code, retryable false)로 답하거나, 202 REJECTED 응답에 판정 code 칸을 더한다. 앞의 것이면 프론트의 기존 422 경로가 code와 traceId를 그대로 싣고 NOT_APPLIED로 읽는다. 그때 FILE_REJECTED 분기는 지운다. - CHANGELOG의 "백엔드로 넘김" 목록에 이 항목을 더하는 일은 CHANGELOG 담당에게 남긴다. 실제 배포 응답의 성공 meta에 traceId가 있는지는 백엔드 문서 (docs/web/http-contract.md §1 meta 키)와 EnvelopeBodyAdvice 코드로만 확인했다. backend-envelope.ts는 초기 번들에 있어 초기 JS가 수십 B 늘 수 있다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/integration/fileserver-upload.test.ts tests/runtime-schema/http-schema.test.ts tests/unit/a11y-api-answers.test.ts RED(이 커밋의 테스트 + 부모 src): "reads 202 REJECTED as a refused file, not as a broken answer"가 traceId "trace-1"이 없어 실패한다. "reads data, and a dropped data key as null"과 "answers an Envelope list read with an empty list inside the Envelope"는 결과에 traceId 칸이 없어 실패한다. Refs: 1106/01-01
422 lines
14 KiB
TypeScript
422 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.
|
|
* 1106/01-01. And the backend's `meta.traceId`, when it sent one, as
|
|
* `readFailureEnvelope` gives it, for a client that turns a well-formed
|
|
* answer into a failure (Fileserver's 202 `REJECTED`).
|
|
*/
|
|
export function readSuccessEnvelope(
|
|
value: unknown,
|
|
):
|
|
| Readonly<{
|
|
ok: true;
|
|
value: unknown;
|
|
page?: EnvelopePage;
|
|
traceId?: string;
|
|
}>
|
|
| Readonly<{ ok: false }> {
|
|
const parsed = successEnvelopeSchema.safeParse(value);
|
|
if (!parsed.success) return ENVELOPE_INVALID;
|
|
const { page, traceId } = parsed.data.meta;
|
|
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 } : {}),
|
|
}),
|
|
}),
|
|
...(traceId === undefined ? {} : { traceId }),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 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) }
|
|
: {}),
|
|
});
|
|
}
|