Files
clean-architecture-frontend…/tests/unit/legacy-and-optional-network-remediation.test.ts
T
DongHyeonka 93782b0fce fix(http): 멱등성 거절 422·400을 적용 안 됨으로 보고 원인을 남긴다 (백엔드 1101/02-01)
문제
짝 백엔드는 KEYED 요청을 실행하기 전에 두 가지를 거절한다(백엔드
docs/web/http-contract.md §2).
- 422 IDEMPOTENT_REQUEST_MISMATCH: 같은 키에 다른 본문. 클라이언트 버그.
- 400 IDEMPOTENCY_KEY_INVALID(details.reason MISSING·MALFORMED): 키 누락·
  형식 오류.
둘 다 이 요청은 적용되지 않았고, 그대로 다시 보내면 같은 답이 온다.
- V2(client.ts)는 이 실패에 effect를 붙이지 않는다. mutation 코디네이터는
  effect가 없으면 MAYBE_APPLIED로 보고(application-query.ts
  mutationFailureWithEffect) 키를 붙든다. 400은 결과 불명 화면으로 가고,
  같은 입력을 다시 저장하면 같은 키로 같은 400·422를 계속 받는다. 진단
  이벤트(http.request.completed)에는 원인이 없다.
- V3 참조 기능은 분류기가 400·422를 이미 NOT_APPLIED로 본다. 다만
  mapProblem이 400을 다루지 않아 code가 CONTRACT_PROBLEM으로 바뀌고
  서버의 IDEMPOTENCY_KEY_INVALID가 사라진다.

고른 방법
- V2: 문서에 적힌 status와 code가 둘 다 맞을 때만 effect NOT_APPLIED를
  붙인다(IDEMPOTENCY_REFUSALS 표). 같은 표가 진단 reason을 준다.
  - 422 → reason IDEMPOTENT_REQUEST_MISMATCH
  - 400 → reason IDEMPOTENCY_KEY_RULE_MISMATCH. 프론트는 보내기 전에
    isValidIdempotencyKey로 키를 검사한다. 서버의 400은 두 키 규칙이
    어긋났다는 뜻이라 그 이름으로 남긴다. 보내기 전 거절(VALIDATION_
    REJECTED, httpStatus 없음)은 표에 걸리지 않는다.
  reason은 diagnostics에만 넣는다. telemetry 속성은 그대로다(VD-07).
- V3 참조 mapProblem: 400 + IDEMPOTENCY_KEY_INVALID만 UNKNOWN_CLIENT_
  FAILURE와 서버 code로 둔다. 다른 400은 기존 fallback 그대로다.
- kind는 바꾸지 않았다(422 VALIDATION_REJECTED, 400 UNKNOWN_CLIENT_
  FAILURE). 둘 다 retryable:false이고 V2 재시도 대상이 아니다.
- 키 문법은 백엔드 IdempotencyKeyHeader([\x21-\x7E]{1,256}, trim 없음)와
  같다. 1자 키를 받는 행을 더해 경계를 고정했다.

버린 대안
- code만 보고 판정: 다른 status에 같은 code가 오면 NOT_APPLIED를 잘못
  붙인다. NOT_APPLIED는 다음 저장이 새 키를 쓰게 하는 판정이라 문서의
  짝(status+code)만 믿는다.
- 422 mismatch를 UNKNOWN_CLIENT_FAILURE로 바꾸기: 화면 문구가 바뀐다.
  요구는 재전송 금지·결과 불명 화면 금지·원인 code 보존이라 kind는 두었다.
- 서버 code를 진단 reason에 그대로 넣기: 서버 code는 무제한이라 진단
  cardinality 규칙(taxonomy)을 깬다. 표에 있는 두 값만 넣는다.

위험·한계
- 422 mismatch를 NOT_APPLIED로 보면 다음 저장이 새 키를 쓴다. 같은 키의
  앞선 요청이 적용됐을 수 있지만, 프론트는 canonical 입력이 같을 때만 키를
  재사용하므로 mismatch는 지문 규칙이 어긋난 버그다. 결정(15절)대로 이번
  요청은 적용되지 않았다고 본다.
- 422 화면 문구는 "입력값을 다시 확인해 주세요."다. 사용자가 고칠 입력이
  아니지만 다시 저장하면 새 키로 나간다.
- V3 실행기의 진단은 problem code를 모른다(Problem 타입은 계약 패키지
  소유). V3에서 원인은 AppFailure.code·httpStatus로만 보인다.

검증
- RED: tests/integration/http-diagnostics.test.ts 새 2행 실패(effect
  undefined, reason 없음). tests/features/reference-feature/reference-http-
  problem-mapping.test.ts 400 IDEMPOTENCY_KEY_INVALID 행 실패(code
  CONTRACT_PROBLEM). 422 mismatch 매핑, 분류기 2행, 1자 키 행은 처음부터
  통과(이미 맞는 동작을 고정).
- GREEN: 위 파일과 tests/features/reference-feature, tests/integration/
  http-client·http-execution-contract·auth-recovery·legacy-http-credential-
  authority, tests/contract/reusable-capability/feature-http-binding 24 files
  207 tests 통과. tests/unit/legacy-and-optional-network-remediation 6/6.
  tsc app·test 통과, 바꾼 파일 eslint 통과.

Refs: clean-architecture-backend-template docs/reviews/2026-11-01-maturity-review/README.md 14.3, 15
2026-11-03 02:00:45 +09:00

169 lines
5.2 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, it, vi } from "vitest";
import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/index.ts";
import {
defineMutationIntent,
isValidIdempotencyKey,
} from "../../src/contracts/mutation-intent.ts";
import type {
CursorPage,
CursorPaginationProfile,
} from "../../src/adapters/query-cache/index.ts";
import type { Result } from "../../src/contracts/result.ts";
const PROFILE: CursorPaginationProfile = Object.freeze({
profileId: "TEST_PAGINATION_V1",
maxPages: 3,
maxTotalItems: 30,
maxEstimatedBytes: 32_768,
maxCursorBytes: 512,
allowSparsePage: false,
});
function page(
items: readonly number[],
nextCursor: string | null,
): CursorPage<number> {
return Object.freeze({
items: Object.freeze([...items]),
nextCursor,
hasMore: nextCursor !== null,
snapshotToken: "snapshot-1",
});
}
/**
* OPT-NET-01. A loader rejection is evidence about the data source. Reporting
* it as `PAGINATION_ABORTED` because a signal merely *exists* erases a real
* network or contract failure and files it under a user decision nobody made.
*/
describe("OPT-NET-01 cursor pagination abort classification", () => {
it("preserves a loader rejection while the signal is still live", async () => {
const controller = new AbortController();
const runtime = createCursorPaginationRuntime<number>({
definitionId: "TEST_PAGINATION",
profile: PROFILE,
loadPage: async () => {
throw new TypeError("upstream exploded");
},
});
await expect(
runtime.loadAll({ signal: controller.signal }),
).rejects.toThrow("upstream exploded");
});
it("keeps the same rejection when no signal is supplied", async () => {
const runtime = createCursorPaginationRuntime<number>({
definitionId: "TEST_PAGINATION",
profile: PROFILE,
loadPage: async () => {
throw new TypeError("upstream exploded");
},
});
await expect(runtime.loadAll({})).rejects.toThrow("upstream exploded");
});
it("classifies a rejection during a real abort as PAGINATION_ABORTED", async () => {
const controller = new AbortController();
const runtime = createCursorPaginationRuntime<number>({
definitionId: "TEST_PAGINATION",
profile: PROFILE,
loadPage: async () => {
controller.abort();
throw new TypeError("cancelled upstream");
},
});
const result = await runtime.loadAll({ signal: controller.signal });
expect(result.ok).toBe(false);
expect(result.ok ? null : result.error.code).toBe("PAGINATION_ABORTED");
});
it("does not admit a page that resolves after the abort", async () => {
const controller = new AbortController();
const loadPage = vi.fn(
async (): Promise<Result<CursorPage<number>>> => {
controller.abort();
await new Promise((resolve) => setTimeout(resolve, 5));
return { ok: true, value: page([1, 2], null) };
},
);
const runtime = createCursorPaginationRuntime<number>({
definitionId: "TEST_PAGINATION",
profile: PROFILE,
loadPage,
});
const result = await runtime.loadAll({ signal: controller.signal });
expect(result.ok).toBe(false);
expect(result.ok ? null : result.error.code).toBe("PAGINATION_ABORTED");
});
});
/**
* OPT-NET-02. One idempotency-key authority. Two validators drift, and the
* looser one becomes the way a control character reaches a request header.
*/
describe("OPT-NET-02 shared idempotency key validation", () => {
const rejected = [
"",
" ",
"key\nwith-newline",
"key\u0000null",
"key\u007fdelete",
"key\u009fc1",
"a".repeat(257),
// R-7.1. fetch strips surrounding whitespace, so " order-1 " would reach
// the wire as "order-1" and collide with another command's key.
" order-1 ",
"order-1\t",
"key with-space",
// R-7.1. A non-ByteString value makes Headers.set throw a TypeError that
// the client reports as a retryable network failure.
"키-값",
"ключ",
"key nbsp",
];
it("rejects the same values at intent definition and at admission", () => {
for (const value of rejected) {
expect(isValidIdempotencyKey(value), JSON.stringify(value)).toBe(false);
expect(() =>
defineMutationIntent({
intentId: "intent-1",
operationId: "OP",
canonicalInputIdentity: "identity",
idempotencyKey: value,
createdAtMonotonicMs: 1,
}),
).toThrow(TypeError);
}
});
// 백엔드 1101/02-01. The paired backend's IdempotencyKeyHeader grammar is
// the same: [\x21-\x7E]{1,256}, never trimmed. A key it refuses with
// 400 IDEMPOTENCY_KEY_INVALID never left this client.
it("accepts the bounded visible-ASCII values both sides allow", () => {
for (const value of [
"k",
"key-1",
"a".repeat(256),
"0f8fad5b-d9cb-469f-a165-70867728950e",
"!~",
]) {
expect(isValidIdempotencyKey(value)).toBe(true);
expect(
defineMutationIntent({
intentId: "intent-1",
operationId: "OP",
canonicalInputIdentity: "identity",
idempotencyKey: value,
createdAtMonotonicMs: 1,
}).idempotencyKey,
).toBe(value);
}
});
});