Files
clean-architecture-frontend…/tests/unit/backend-envelope.test.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

178 lines
7.2 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
envelopeFailureEffect,
envelopeFailureReading,
idempotencyRefusalReason,
invitesKeyedResend,
} from "../../src/adapters/http/backend-envelope.ts";
/**
* 1103/10-02. The backend's refusal table, read status by status. The
* integration test sends each table code with its own status; these rows pin
* the edges it does not reach: a table code under another status, a 422
* outside the table, and the gateway statuses that keep the server-failure
* kind.
*/
describe("backend Envelope failure table", () => {
it.each([
[400, "VALIDATION_FAILED", undefined],
[400, "IDEMPOTENCY_KEY_INVALID", "IDEMPOTENCY_KEY_RULE_MISMATCH"],
[422, "IDEMPOTENT_REQUEST_MISMATCH", "IDEMPOTENT_REQUEST_MISMATCH"],
] as const)("reads %i %s as refused before the write", (status, code, reason) => {
expect(envelopeFailureEffect(status, { code })).toBe("NOT_APPLIED");
expect(idempotencyRefusalReason(code, status)).toBe(reason);
});
// The table names a status and a code together. The same code under
// another status is not the refusal the backend documents.
it.each([
[409, "VALIDATION_FAILED"],
[422, "VALIDATION_FAILED"],
[400, "IDEMPOTENT_REQUEST_MISMATCH"],
[409, "IDEMPOTENT_REQUEST_MISMATCH"],
[422, "IDEMPOTENCY_KEY_INVALID"],
] as const)("reads a table code under another status (%i %s) as maybe applied", (status, code) => {
expect(envelopeFailureEffect(status, { code })).toBe("MAYBE_APPLIED");
expect(idempotencyRefusalReason(code, status)).toBeUndefined();
});
it.each([
[400, "BAD_PARAMETER"],
[409, "IDEMPOTENT_IN_FLIGHT"],
[409, "RESOURCE_CONFLICT"],
// A 422 outside the table stays with the backend's verdict, never with a
// package that reads every 422 as refused (fileserver writes first).
[422, "INTEGRITY_MISMATCH"],
] as const)("keeps %i %s, outside the table, maybe applied", (status, code) => {
expect(envelopeFailureEffect(status, { code })).toBe("MAYBE_APPLIED");
});
// 1105/03-02. http-contract.md §4: the edge rate limiter answers before the
// controller runs. Status and code together, like the other rows.
it.each(["RATE_LIMIT_UNAVAILABLE", "RATE_LIMIT_INCOMPATIBLE"])(
"reads the edge's 503 %s as refused before the write",
(code) => {
expect(envelopeFailureEffect(503, { code })).toBe("NOT_APPLIED");
expect(invitesKeyedResend(503, { code })).toBe(false);
expect(idempotencyRefusalReason(code, 503)).toBeUndefined();
expect(envelopeFailureReading(503, { code }).kind).toBe("SERVER_FAILURE");
expect(envelopeFailureEffect(500, { code })).toBeUndefined();
},
);
// 1103/03-04. http-contract.md §2 and §4: the command may have run.
it.each([
[503, "IDEMPOTENCY_UNAVAILABLE", true],
[503, "IDEMPOTENCY_COMPLETION_UNKNOWN", false],
[500, "IDEMPOTENCY_RECOVERY_REQUIRED", false],
[503, "REQUEST_TIMEOUT", false],
] as const)("reads %i %s as maybe applied", (status, code, resend) => {
expect(envelopeFailureEffect(status, { code })).toBe("MAYBE_APPLIED");
expect(invitesKeyedResend(status, { code })).toBe(resend);
});
// 1103/03-01. An operation names the codes its endpoint raises only before
// it writes (`commandEffect.refusedBeforeWrite`).
describe("with the operation's declared pre-write refusals", () => {
const declared = ["WORKLOG_INVALID", "POSTER_ALREADY_EXISTS", "VALIDATION_FAILED"];
it.each([
[400, "WORKLOG_INVALID"],
[409, "POSTER_ALREADY_EXISTS"],
[422, "WORKLOG_INVALID"],
] as const)("reads a declared %i %s as not applied", (status, code) => {
expect(envelopeFailureEffect(status, { code }, declared)).toBe("NOT_APPLIED");
});
it("keeps every code the operation did not declare maybe applied", () => {
expect(envelopeFailureEffect(400, { code: "BAD_PARAMETER" }, declared)).toBe(
"MAYBE_APPLIED",
);
expect(envelopeFailureEffect(400, { code: "WORKLOG_INVALID" })).toBe("MAYBE_APPLIED");
});
it("never lets a declaration decide an idempotency answer or a table code", () => {
const reckless = [
"IDEMPOTENT_IN_FLIGHT",
"IDEMPOTENCY_UNAVAILABLE",
"IDEMPOTENCY_COMPLETION_UNKNOWN",
"VALIDATION_FAILED",
];
expect(envelopeFailureEffect(409, { code: "IDEMPOTENT_IN_FLIGHT" }, reckless)).toBe(
"MAYBE_APPLIED",
);
expect(
envelopeFailureEffect(503, { code: "IDEMPOTENCY_UNAVAILABLE" }, reckless),
).toBe("MAYBE_APPLIED");
expect(
envelopeFailureEffect(503, { code: "IDEMPOTENCY_COMPLETION_UNKNOWN" }, reckless),
).toBe("MAYBE_APPLIED");
// The table's status rule still holds for its own code.
expect(envelopeFailureEffect(409, { code: "VALIDATION_FAILED" }, reckless)).toBe(
"MAYBE_APPLIED",
);
});
// 1105/03-01. The runtime's own fail-close for an executor called without
// composition: a platform code 6.1 reads as possibly after the write
// stays maybe applied, declared or not.
it.each([
[400, "BAD_PARAMETER"],
[400, "MAPPING_FAILED"],
[409, "DB_UNIQUE_VIOLATION"],
[409, "LOCK_ACQUISITION_TIMEOUT"],
[422, "INTEGRITY_MISMATCH"],
] as const)("keeps a declared platform code %i %s maybe applied", (status, code) => {
expect(envelopeFailureEffect(status, { code }, [code])).toBe("MAYBE_APPLIED");
});
it("does not reach statuses outside 400, 409 and 422", () => {
expect(envelopeFailureEffect(500, { code: "WORKLOG_INVALID" }, declared)).toBeUndefined();
expect(envelopeFailureEffect(503, { code: "REQUEST_TIMEOUT" }, ["REQUEST_TIMEOUT"])).toBe(
"MAYBE_APPLIED",
);
});
});
it("leaves a status the table does not speak for to the package", () => {
expect(envelopeFailureEffect(404, { code: "NOT_FOUND" })).toBeUndefined();
expect(envelopeFailureEffect(500, { code: "INTERNAL_ERROR" })).toBeUndefined();
// Status and code together: these codes under another 5xx are not the
// backend's documented answers.
expect(
envelopeFailureEffect(500, { code: "IDEMPOTENCY_COMPLETION_UNKNOWN" }),
).toBeUndefined();
expect(envelopeFailureEffect(502, { code: "REQUEST_TIMEOUT" })).toBeUndefined();
});
// 1103/08-05. Only a field list makes a 422 an input error.
it("reads a 422 without a field list as a client failure, not an input error", () => {
expect(
envelopeFailureReading(422, { code: "IDEMPOTENT_REQUEST_MISMATCH" }),
).toEqual({ kind: "UNKNOWN_CLIENT_FAILURE", code: "IDEMPOTENT_REQUEST_MISMATCH" });
expect(envelopeFailureReading(422, { code: "INTEGRITY_MISMATCH" }).kind).toBe(
"UNKNOWN_CLIENT_FAILURE",
);
expect(
envelopeFailureReading(422, {
code: "INVALID_INPUT",
details: { issues: [{ path: "name", code: "REQUIRED" }] },
}),
).toEqual({
kind: "VALIDATION_REJECTED",
code: "INVALID_INPUT",
validationIssues: [{ path: "name", code: "REQUIRED" }],
});
});
it.each([408, 425, 500, 502, 503, 504])(
"reads a gateway %i as a server failure, not a client one",
(status) => {
expect(envelopeFailureReading(status, { code: "GATEWAY_REFUSED" }).kind).toBe(
"SERVER_FAILURE",
);
},
);
});