Files
clean-architecture-frontend…/tests/unit/backend-envelope.test.ts
T
DongHyeonka 80e7f1d63a fix(query): 같은 요청이 매번 받는 거절로 끝난 재전송은 결과 불명을 푼다
문제: 1106/03-01(2568587)은 결과 불명 요청을 같은 키로 다시 보낸 시도가
NOT_APPLIED·NOT_STARTED로 끝나면 이유와 상관없이 결과 불명과 키를 남긴다.
같은 요청이 매번 받는 거절(400 VALIDATION_FAILED, 400 IDEMPOTENCY_KEY_INVALID,
필드 목록이 있는 입력 검증)도 같다. 폼은 필드 오류를 버리고 "잠시 뒤 같은
요청으로 다시 보내 주세요"만 보인다. 저장은 꺼져 있고 다시 보내면 같은 400이
온다. 출구는 사실이 아닌 "변경됨으로 확인"이나 새로고침뿐이다. 815ea58
(1106/03-03)이 같은 길을 IDEMPOTENT 쓰기로 넓혔다(diff 리뷰 DR-01).

고른 방법(메인 세션 결정, D10 보충): 같은 키 재전송은 그 결과가 첫 요청에
무슨 일이 있었는지 보여 줄 때만 결과 불명을 푼다.
- 성공·APPLIED_CONFIRMED: 저장된 답의 재생이다. 지금처럼 푼다.
- 같은 요청이라 첫 요청도 받았을 거절: 푼다. src/contracts/errors.ts에
  isRefusedOnEveryAttempt를 두었다. effect NOT_APPLIED이고, kind
  VALIDATION_REJECTED(필드 목록이 있는 입력 검증)이거나 code·status가
  REFUSALS_OF_EVERY_ATTEMPT(400 VALIDATION_FAILED, 400 IDEMPOTENCY_KEY_INVALID)다.
- 그 밖(429, 401, 403, 503 RATE_LIMIT_*, 422 IDEMPOTENT_REQUEST_MISMATCH(키가
  이미 서버에 닿아야 나온다), 기능이 선언한 code(바뀌는 상태의 규칙일 수
  있다), IDEMPOTENT 쓰기의 404·412 같은 다른 code, NOT_STARTED): 지금처럼
  결과 불명과 키를 남긴다. 어느 쪽인지 모르는 code는 남긴다.
훅(resendLeavesUnknown)과 폼(resendLeftUnknown)이 같은 함수를 부른다. 폼은 푼
경우 처음 저장과 같이 보인다(필드 오류, 다시 받는 저장, 고친 값은 새 키).
남긴 경우 결과 불명 화면(확인·다시 보내기)이 그대로라 폼이 영영 막히지
않는다. 표는 backend-envelope.ts REFUSED_BEFORE_WRITE의 부분집합이어야 하고,
표의 나머지 행은 다른 쪽으로 분류된다. backend-envelope 단위 테스트가 둘을
대조해, 표에 새 행이 생기면 이 분류를 정할 때까지 실패한다. presentation은
adapters를 import할 수 없어(.dependency-cruiser.json) 판정을 contracts에 둔다.
버린 대안: 일시 거절(NOT_STARTED, retryable, RATE_LIMITED, RATE_LIMIT_*)만
남기기(diff 리뷰 안). 401·403과 422 IDEMPOTENT_REQUEST_MISMATCH, 기능 선언
code를 풀어 버린다. AppFailure에 새 칸을 더해 실행기가 표시하기(계약 타입과
실행기·바인딩을 함께 바꾼다).

위험·한계: 기능이 선언한 결정적 거절(생성 기능의 400 <FEATURE>_INVALID)은
어느 쪽인지 알 수 없어 결과 불명으로 남는다. 출구는 결과 불명 화면의
확인이다. 필드 목록이 있는 NOT_APPLIED는 기능 선언 code여도 입력 검증으로
본다. 리뷰 실험 03-R1 X1~X3·X5(503·429·NOT_STARTED)는 그대로 키가 모두
key-1이어야 한다. 런북 6.3-4를 고쳤다. CHANGELOG는 다음 커밋이 적는다.

검증: desktop batch에서 확인. node scripts/run-vitest.ts run
tests/component/application-mutation-admission.test.tsx
tests/component/form-foundation.test.tsx
tests/features/reference-feature/reference-page.test.tsx
tests/unit/backend-envelope.test.ts, 리뷰 실험 03-R1 패치를 이 커밋에 적용

Refs: 1106/03-01 (diff review DR-01)
2026-11-06 08:00:56 +09:00

233 lines
9.6 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
envelopeFailureEffect,
envelopeFailureReading,
idempotencyRefusalReason,
invitesKeyedResend,
refusedBeforeWriteRows,
} from "../../src/adapters/http/backend-envelope.ts";
import {
createFailure,
isRefusedOnEveryAttempt,
REFUSALS_OF_EVERY_ATTEMPT,
} from "../../src/contracts/errors.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",
);
},
);
});
/**
* 1106/03-01 (D10 supplement). The refusals every attempt of one request
* gets (`REFUSALS_OF_EVERY_ATTEMPT`, which the mutation coordinator and the
* form read) are rows of this table. Every other row is sorted to the other
* side here, so a new row fails this test until someone decides it.
*/
describe("refusals every attempt of a request gets", () => {
it("are rows of the refusal table, code and status", () => {
for (const [code, status] of Object.entries(REFUSALS_OF_EVERY_ATTEMPT)) {
expect(refusedBeforeWriteRows()).toContainEqual({ code, status });
}
});
it("leave the table's other rows to keep a resent request unknown", () => {
expect(
refusedBeforeWriteRows()
.filter(({ code }) => !Object.hasOwn(REFUSALS_OF_EVERY_ATTEMPT, code))
.map(({ code }) => code),
).toEqual([
"IDEMPOTENT_REQUEST_MISMATCH",
"RATE_LIMIT_UNAVAILABLE",
"RATE_LIMIT_INCOMPATIBLE",
]);
});
// The failure the binding builds from each answer: kind from
// envelopeFailureReading, effect from envelopeFailureEffect.
it.each([
["400 VALIDATION_FAILED with a field list", 400, "VALIDATION_FAILED", [{ field: "name", code: "NOT_BLANK" }], undefined, true],
["400 VALIDATION_FAILED whose body did not parse", 400, "VALIDATION_FAILED", { cause: "JsonParseException" }, undefined, true],
["400 IDEMPOTENCY_KEY_INVALID", 400, "IDEMPOTENCY_KEY_INVALID", undefined, undefined, true],
["422 IDEMPOTENT_REQUEST_MISMATCH", 422, "IDEMPOTENT_REQUEST_MISMATCH", undefined, undefined, false],
["503 RATE_LIMIT_UNAVAILABLE", 503, "RATE_LIMIT_UNAVAILABLE", undefined, undefined, false],
["a code the operation declared", 400, "WORKLOG_INVALID", undefined, ["WORKLOG_INVALID"], false],
] as const)("decides whether %s is refused on every attempt", (_label, status, code, details, declared, expected) => {
const error = { code, ...(details === undefined ? {} : { details }) };
const effect = envelopeFailureEffect(status, error, declared);
expect(effect).toBe("NOT_APPLIED");
const failure = createFailure(
envelopeFailureReading(status, error).kind,
"ENVELOPE_OPERATION",
0,
{ code, httpStatus: status, effect: "NOT_APPLIED" },
);
expect(isRefusedOnEveryAttempt(failure)).toBe(expected);
});
});