fix(http): 거절의 적용 여부를 백엔드 기준 표 하나로 V2·V3가 판정한다

문제
계약 문서 6.1절(ed0e4b1, 백엔드 5786126c 코드 기준)은 400·409·422 code마다
쓰기 전 거절인지를 정했다. 쓰기 전이라 적용 안 됨인 것은 400
VALIDATION_FAILED(details 모양과 상관없음), 400 IDEMPOTENCY_KEY_INVALID,
422 IDEMPOTENT_REQUEST_MISMATCH뿐이고, 표에 없는 400·409·422는 쓰기 뒤에도
나올 수 있어 결과 불명이다. 지금 판정은 이 표와 세 곳이 다르다.
- V2: 필드 목록 없는 400 VALIDATION_FAILED({cause}, details 없음,
  {field, code})에 effect가 없다. 결과 불명으로 붙들려 다시 저장할 수 없다.
- V2: 422는 code와 상관없이 적용 안 됨이다. fileserver의 422
  INTEGRITY_MISMATCH·MALWARE_DETECTED는 레코드를 쓴 뒤 던진다.
- V3 Envelope operation(7db32e1): 위 V2 규칙을 같이 쓰고, 표 밖 400·409·422는
  classifyProblem에 맡긴다. 400·422를 모두 적용 안 됨으로 보는 분류기면
  BAD_PARAMETER·도메인 400이 틀린다.

고른 방법
- backend-envelope.ts에 표 REFUSED_BEFORE_WRITE(code → status, 진단
  reason)를 하나 두고 V2 client.ts, V3 실행기가 envelopeFailureEffect로
  같이 읽는다. 표에 있으면 NOT_APPLIED, 그 밖의 400·409·422와 503
  IDEMPOTENCY_UNAVAILABLE은 MAYBE_APPLIED, 나머지 status는 undefined
  (V2는 effect 없음, V3는 classifyProblem)다. 진단 reason도 같은 표에서
  읽는다.
- kind와 validationIssues 판정(isFieldValidationFailure)은 그대로 둔다.
  필드 목록 없는 400 VALIDATION_FAILED는 UNKNOWN_CLIENT_FAILURE, 422는
  VALIDATION_REJECTED다. 적용 여부만 바뀐다.
- V3 Envelope operation에서는 400·409·422를 표가 정하고 classifyProblem이
  바꾸지 못한다.

버린 대안
- V2와 V3에 표를 따로 두기: 7db32e1 전처럼 두 벌이 갈라진다.
- 표 밖 400·409·422를 classifyProblem에 맡기기: 6.1절이 표 밖은
  MAYBE_APPLIED로 정했고, 적용 안 됨을 잘못 내면 다음 저장이 새 키를 써
  같은 작업이 두 번 적용된다. 잘못된 MAYBE_APPLIED는 결과 불명 화면만 남긴다.
- 422 전부를 필드 검증(적용 안 됨)으로 남기기: 짝 백엔드는 필드 검증을
  400으로 보내고, fileserver 422는 쓴 뒤 던진다.
- V3 참조 기능 분류기 고치기: 참조 기능은 Envelope operation이 아니고
  fixture가 problem details라 이 표의 대상이 아니다. 고치지 않았다.

위험·한계
- 필드 검증을 422로 보내는 다른 백엔드를 V2로 쓰는 프로젝트는 422 뒤에
  폼에서 다시 저장할 수 없다(결과 불명). 프론트 계약 문서 4.2절의 "422
  field validation" 행과 어긋난다. 그 문서는 이 커밋에서 고치지 않았다.
- 표는 백엔드 5786126c 기준이다. 백엔드가 쓰기 전 거절 code를 새로 만들면
  6.1절과 이 표를 함께 고쳐야 한다. 두 repo를 비교하는 검사는 없다.
- 6.1절의 남은 위험: 백엔드가 use case 안에서 VALIDATION_FAILED를 내게 되면
  적용 안 됨 판정이 틀린다.

검증
- RED: 바뀐 행 8건 실패. tests/integration/http-client.test.ts 필드 목록
  없는 400 VALIDATION_FAILED 3모양의 effect, http-diagnostics.test.ts의
  "unrelated 422"(effect NOT_APPLIED), http-execution-v3-envelope.test.ts의
  고정 판정 2건(VALIDATION_FAILED 3모양 NOT_APPLIED, BAD_PARAMETER·도메인
  409·fileserver 422 MAYBE_APPLIED), form-foundation.test.tsx 2건({cause}
  실패 뒤 다시 저장, 422 뒤 저장 버튼 꺼짐).
- GREEN: 위 4개 파일 128건 통과. V2와 V3에 같은 응답 11가지를 보내 판정을
  비교하는 행이 모두 같다.
- check:types, lint, check:architecture, check:diagnostics, check:ci,
  check:registries, check:adapter-inventory 통과. test:unit 2,604,
  test:integration 209, test:component 245, tests/features·tests/contract
  124건 통과. check:bundle 203,354 / 204,800 B.

Refs: docs/architecture/backend-api-and-server-state-contract.md 6.1 (ed0e4b1),
docs/reviews/2026-11-01-maturity-review/README.md 14.4, 14.6
This commit is contained in:
DongHyeonka
2026-11-03 20:26:28 +09:00
parent f3b87b3f02
commit 326120867c
6 changed files with 203 additions and 76 deletions
+43 -34
View File
@@ -50,48 +50,59 @@ export function readFailureEnvelope(
}
/**
* 백엔드 1101/02-01. Refusals the paired backend answers before it runs the
* command (§2): the request was not applied and sending it again unchanged
* gets the same answer. Only the documented status and code together count.
* The value is the diagnostics `reason`, named for what is wrong on this side.
* 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 IDEMPOTENCY_REFUSALS: Readonly<
Record<string, Readonly<{ status: number; reason: IdempotencyRefusalReason }>>
const REFUSED_BEFORE_WRITE: Readonly<
Record<
string,
Readonly<{ status: number; reason?: IdempotencyRefusalReason }>
>
> = Object.freeze({
// The same key went out with another body.
IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({
status: 422,
reason: "IDEMPOTENT_REQUEST_MISMATCH",
}),
// 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 {
const refusal = Object.hasOwn(IDEMPOTENCY_REFUSALS, code)
? IDEMPOTENCY_REFUSALS[code]
: undefined;
return refusal !== undefined && refusal.status === status
? refusal.reason
: undefined;
return refusedBeforeWrite(code, status)?.reason;
}
/**
* 백엔드 1101/02-01 후속. A field validation failure: a 422, or the paired
* backend's 400 VALIDATION_FAILED whose details is the field list (§4). A 400
* VALIDATION_FAILED whose body did not parse carries `{cause}`, not a list,
* and is not one.
* 백엔드 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,
@@ -109,25 +120,23 @@ export function isFieldValidationFailure(
* The verdict the backend contract gives whatever the operation is, or
* `undefined` when the operation's own classifier decides.
*
* - Not applied: a field validation failure, checked when the request is
* bound, before the command runs (64e98ee), and an idempotency refusal.
* - Maybe applied: 409 IDEMPOTENT_IN_FLIGHT (the first request still runs)
* and 503 IDEMPOTENCY_UNAVAILABLE. §2 says to resend both with the same
* key, which only an unknown result keeps.
* - 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 (
(status === 409 && error.code === "IDEMPOTENT_IN_FLIGHT") ||
if (refusedBeforeWrite(error.code, status) !== undefined) return "NOT_APPLIED";
return status === 400 ||
status === 409 ||
status === 422 ||
(status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE")
) {
return "MAYBE_APPLIED";
}
return isFieldValidationFailure(status, error) ||
idempotencyRefusalReason(error.code, status) !== undefined
? "NOT_APPLIED"
? "MAYBE_APPLIED"
: undefined;
}
+6 -4
View File
@@ -198,10 +198,12 @@ export interface InstalledHttpContract<Input, WireOutput, Problem> {
* the body is the DTO, and a failure body is the problem. `"ENVELOPE_V1"`:
* the paired backend's `{ success, data | error, meta }`
* (clean-architecture-backend-template docs/web/http-contract.md §1).
* `outputValidator` then sees `data` (`null` when the key is absent),
* `problemValidator` sees `error`, and the backend's operation-independent
* verdicts (§2, §4) come before `commandEffect.classifyProblem`. A body
* that is empty by `emptyBodyStatuses` has no Envelope.
* `outputValidator` then sees `data` (`null` when the key is absent) and
* `problemValidator` sees `error`. Whether a 400, 409, 422 or 503
* `IDEMPOTENCY_UNAVAILABLE` applied comes from the backend's own table
* (`src/adapters/http/backend-envelope.ts`, the frontend contract's 6.1),
* not from `commandEffect.classifyProblem`, which decides every other
* status. A body that is empty by `emptyBodyStatuses` has no Envelope.
*/
responseEnvelope?: ResponseEnvelope;
commandRecovery: CommandRecoveryDescriptor | null;
+60 -14
View File
@@ -645,20 +645,8 @@ describe("correcting a field after a V2 validation refusal", () => {
const meta = { requestId: "request-1", traceId: "trace-1" };
// 백엔드 1101/02-01 후속. A 422 in the frontend contract's shape, and the
// paired backend's 400 VALIDATION_FAILED (its docs/web/http-contract.md §4).
it.each([
{ status: 422, error: { code: "INVALID_INPUT", details: { issues: [{ path: "name", code: "REQUIRED" }] } } },
{
status: 400,
error: {
code: "VALIDATION_FAILED",
details: [{ field: "name", code: "NOT_BLANK", message: "필수 값이 없습니다." }],
},
},
])("saves the corrected value after a $status field error", async ({ status, error }) => {
const user = userEvent.setup();
const fetcher = vi
function answerFirst(status: number, error: unknown) {
return vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
Response.json({ success: false, error, meta }, { status }),
@@ -670,6 +658,16 @@ describe("correcting a field after a V2 validation refusal", () => {
meta,
}),
);
}
// 백엔드 1101/02-01 후속. The paired backend's 400 VALIDATION_FAILED with
// the field list (its docs/web/http-contract.md §4).
it("saves the corrected value after a 400 field error", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, {
code: "VALIDATION_FAILED",
details: [{ field: "name", code: "NOT_BLANK", message: "필수 값이 없습니다." }],
});
render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
@@ -689,4 +687,52 @@ describe("correcting a field after a V2 validation refusal", () => {
);
expect(fetcher).toHaveBeenCalledTimes(2);
});
// 1101/14.4. A body the backend could not read is refused while binding,
// before any write (frontend contract 6.1), so the save is not held.
it("saves again after a 400 VALIDATION_FAILED whose body did not parse", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, {
code: "VALIDATION_FAILED",
details: { cause: "JsonParseException" },
});
render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Fixed");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
await waitFor(() =>
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled(),
);
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(fetcher).toHaveBeenCalledTimes(2);
});
// 1101/14.4. Outside IDEMPOTENT_REQUEST_MISMATCH a 422 may come after a
// write (fileserver INTEGRITY_MISMATCH), so the coordinator holds it as an
// unknown result even though the form shows the field.
it("keeps the save off after a 422 the backend may have applied", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(422, {
code: "INVALID_INPUT",
details: { issues: [{ path: "name", code: "REQUIRED" }] },
});
render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(name).toHaveAttribute("aria-invalid", "true"));
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(fetcher).toHaveBeenCalledTimes(1);
});
});
+21 -12
View File
@@ -674,19 +674,28 @@ describe("paired backend 400 VALIDATION_FAILED", () => {
expect(JSON.stringify(result)).not.toContain("raw backend copy");
});
// 1101/14.4. The backend raises every VALIDATION_FAILED while it binds the
// request, before it writes (frontend contract 6.1, backend 5786126c), so
// it is not applied whatever its details are. BAD_PARAMETER can come from
// any layer, after a write too.
it.each([
// A body that did not parse: details names the cause, not a field.
{ code: "VALIDATION_FAILED", details: { cause: "JsonParseException" } },
{ code: "VALIDATION_FAILED", details: undefined },
{ code: "BAD_PARAMETER", details: { parameter: "limit" } },
])("keeps a 400 $code with details $details as before", async ({ code, details }) => {
const result = await answer400(code, details);
{ code: "VALIDATION_FAILED", details: { cause: "JsonParseException" }, effect: "NOT_APPLIED" },
{ code: "VALIDATION_FAILED", details: undefined, effect: "NOT_APPLIED" },
// A page or sort parameter: one {field, code}, not a list.
{ code: "VALIDATION_FAILED", details: { field: "size", code: "MAX" }, effect: "NOT_APPLIED" },
{ code: "BAD_PARAMETER", details: { parameter: "limit" }, effect: undefined },
])(
"reads a 400 $code with details $details as a client failure, effect $effect",
async ({ code, details, effect }) => {
const result = await answer400(code, details);
expect(result).toMatchObject({
ok: false,
error: { kind: "UNKNOWN_CLIENT_FAILURE", code, httpStatus: 400 },
});
expect(result.ok ? null : result.error.validationIssues).toBeUndefined();
expect(result.ok ? null : result.error.effect).toBeUndefined();
});
expect(result).toMatchObject({
ok: false,
error: { kind: "UNKNOWN_CLIENT_FAILURE", code, httpStatus: 400 },
});
expect(result.ok ? null : result.error.validationIssues).toBeUndefined();
expect(result.ok ? null : result.error.effect).toBe(effect);
},
);
});
+3 -2
View File
@@ -256,8 +256,9 @@ describe("HTTP diagnostics and terminal telemetry", () => {
);
it.each([
// A field validation refusal is not applied, but names no idempotency cause.
{ status: 422, code: "INVALID_INPUT", effect: "NOT_APPLIED" },
// 1101/14.4. Only IDEMPOTENT_REQUEST_MISMATCH is a 422 refused before a
// write (frontend contract 6.1); fileserver's 422s come after one.
{ status: 422, code: "INVALID_INPUT", effect: undefined },
// Any other refusal keeps no effect: the coordinator holds it as unknown.
{ status: 409, code: "SOMETHING_NEW", effect: undefined },
])("gives an unrelated $status $code no reason", async ({ status, code, effect }) => {
@@ -157,15 +157,14 @@ const CREATE_CONTRACT = Object.freeze({
EnvelopeProblem
>;
/** A package that reads every 409 as a domain conflict refused untouched. */
const CREATE_CONFLICT_NOT_APPLIED_CONTRACT = Object.freeze({
/** A package that reads every problem as refused untouched. */
const CREATE_LENIENT_CONTRACT = Object.freeze({
...CREATE_CONTRACT,
contract: Object.freeze({
...CREATE_CONTRACT.contract,
commandEffect: Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem: ({ status }: Readonly<{ status: number }>) =>
status === 409 || status === 503 ? "NOT_APPLIED" : "MAYBE_APPLIED",
classifyProblem: () => "NOT_APPLIED" as const,
}) satisfies CommandEffectDescriptor<EnvelopeProblem>,
}),
});
@@ -188,9 +187,9 @@ const OPERATIONS = Object.freeze({
}),
});
const CONFLICT_OPERATIONS = Object.freeze({
const LENIENT_OPERATIONS = Object.freeze({
ENVELOPE_CREATE_ITEM: defineFeatureHttpOperation({
contract: CREATE_CONFLICT_NOT_APPLIED_CONTRACT,
contract: CREATE_LENIENT_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
@@ -538,7 +537,7 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () =>
},
],
[
"400 VALIDATION_FAILED without a field list",
"400 VALIDATION_FAILED for an unreadable body",
{
status: 400,
body: failure("VALIDATION_FAILED", "VALIDATION", false, {
@@ -546,10 +545,32 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () =>
}),
},
],
[
"400 VALIDATION_FAILED without details",
{ status: 400, body: failure("VALIDATION_FAILED", "VALIDATION", false) },
],
[
"400 VALIDATION_FAILED for a page parameter",
{
status: 400,
body: failure("VALIDATION_FAILED", "VALIDATION", false, {
field: "size",
code: "MAX",
}),
},
],
[
"400 BAD_PARAMETER",
{ status: 400, body: failure("BAD_PARAMETER", "VALIDATION", false) },
],
[
"409 domain conflict",
{ status: 409, body: failure("RESOURCE_CONFLICT", "CONFLICT", false) },
],
[
"422 INTEGRITY_MISMATCH",
{ status: 422, body: failure("INTEGRITY_MISMATCH", "VALIDATION", false) },
],
];
it.each(cases)("%s", async (_label, response) => {
@@ -591,10 +612,35 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () =>
effect: "NOT_APPLIED",
validationIssues: [{ path: "name", code: "NOT_BLANK" }],
});
// 1101/14.4. Every VALIDATION_FAILED is raised before a write.
for (const label of [
"400 VALIDATION_FAILED for an unreadable body",
"400 VALIDATION_FAILED without details",
"400 VALIDATION_FAILED for a page parameter",
]) {
await expect(read(byLabel.get(label)!)).resolves.toMatchObject({
kind: "UNKNOWN_CLIENT_FAILURE",
code: "VALIDATION_FAILED",
effect: "NOT_APPLIED",
});
}
// Codes the backend can raise after a write.
for (const label of [
"400 BAD_PARAMETER",
"409 domain conflict",
"422 INTEGRITY_MISMATCH",
]) {
await expect(read(byLabel.get(label)!)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
}
});
it("keeps an in-flight 409 and an idempotency 503 uncertain even when the package calls them not applied", async () => {
const conflict = createFeatureHttpBinding(v3Executor(), CONFLICT_OPERATIONS);
// 1101/14.4. For an Envelope operation the table decides 400, 409 and 422
// (frontend contract 6.1) and 503 IDEMPOTENCY_UNAVAILABLE; the package
// classifies every other status.
it("keeps 400, 409, 422 outside the table and an idempotency 503 uncertain even when the package calls them not applied", async () => {
const conflict = createFeatureHttpBinding(v3Executor(), LENIENT_OPERATIONS);
answer(
"post",
"/api/envelope-items",
@@ -615,10 +661,24 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () =>
effect: "MAYBE_APPLIED",
});
// A domain 409 is the package's to classify.
answer("post", "/api/envelope-items", failure("RESOURCE_CONFLICT", "CONFLICT", false), {
status: 409,
});
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
answer("post", "/api/envelope-items", failure("BAD_PARAMETER", "VALIDATION", false), {
status: 400,
});
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
// A 404 is the package's to classify.
answer("post", "/api/envelope-items", failure("NOT_FOUND", "NOT_FOUND", false), {
status: 404,
});
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "NOT_APPLIED",
});