문제 commandEffect.refusedBeforeWrite의 조립 검사는 code 문법, 멱등성 접두사, 중복, Envelope 여부만 본다. 계약 문서 6.1절은 BAD_PARAMETER(어느 층이든 IllegalArgumentException), MAPPING_FAILED(멱등성 응답 직렬화는 action 뒤), DB_* 8개, LOCK_ACQUISITION_TIMEOUT, fileserver code를 "쓰기 뒤 가능"으로 적는다. 이 code를 목록에 적어도 조립이 통과하고, 그 code로 온 400·409·422가 NOT_APPLIED가 된다. 쓰기 뒤에 난 실패를 사용자가 다시 저장하면 새 키나 키 없는 새 요청이 나가 같은 항목이 둘 생길 수 있다(리뷰 실험 X2: 네 code가 조립을 통과하고 모두 NOT_APPLIED). 고른 방법 6.1절의 "쓰기 뒤 가능" 플랫폼 code를 src/contracts/external-contract-runtime.ts에 PLATFORM_CODES_POSSIBLY_AFTER_WRITE로 두고, assertRefusedBeforeWrite가 그 code의 선언을 6.1절을 이유로 거절한다. 실행기의 fail-close(조립 없이 부른 경우)도 같은 목록을 무시한다. 목록을 adapters가 아니라 contracts에 둔 것은 조립 검사가 adapters를 import할 수 없기 때문이다(리뷰 문서의 최소 개선은 backend-envelope.ts에 두라고 했다). backend-contract-pin.test.ts가 계약 문서 6.1절 표의 "쓰기 뒤 가능" 행을 읽어 목록과 양방향으로 대조한다. 참조 도메인 code와 web-advanced patch code는 엔드포인트가 단계를 정하므로 테스트의 예외 목록에 적고 선언할 수 있게 둔다. 버린 대안 - 매뉴얼 문장만 둔다(현상 유지): 폼을 막는 code를 넣고 싶어지는 바로 그 자리에 통제가 없다. - 업무 code 접두사 규칙(<FEATURE>_로 시작하는 code만 허용): 다운스트림 code 이름을 강제해 과하다. 위험·한계 - 이미 이 code를 적은 다운스트림 계약은 부팅에서 조립이 실패한다. 의도한 실패다. - 6.1절 표에 플랫폼 code가 더해지면 목록도 같이 고쳐야 한다. 대조 테스트가 알린다. 백엔드가 code를 더한 것은 pin을 올릴 때 6.1절을 다시 읽어야 안다. - 업무 code를 잘못 선언하는 것은 여전히 막지 못한다(기능 작성자의 판단). - 대조 테스트는 계약 문서를 읽으므로, 문서를 복사하지 않는 기능 제거 드릴(FE-GATE-020의 optional-recipe·browser-file-storage·realtime)에서는 돌지 않는다. `scripts/lib/removal-fixture.ts`의 문서 테스트 목록에 `tests/unit/backend-contract-pin.test.ts`를 더했다. 저장소 자신의 test:unit은 그대로 돌린다. 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/external-contract-runtime.test.ts tests/unit/backend-envelope.test.ts tests/unit/backend-contract-pin.test.ts corepack pnpm test:optional-recipe-removal BREAKING CHANGE: refusedBeforeWrite에 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(PLATFORM_CODES_POSSIBLY_AFTER_WRITE)를 적으면 composeContractContributions가 거절한다. 그 code를 목록에서 지운다. 그 code의 실패는 결과 불명으로 남는다. Refs: 1105/03-01
402 lines
13 KiB
TypeScript
402 lines
13 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.
|
|
*/
|
|
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",
|
|
}),
|
|
});
|
|
|
|
/**
|
|
* 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) }
|
|
: {}),
|
|
});
|
|
}
|