문제
짝 백엔드는 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
281 lines
7.8 KiB
TypeScript
281 lines
7.8 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
|
import type { DiagnosticRecordInput } from "../../src/contracts/diagnostics.ts";
|
|
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
|
|
|
function successResponse(data: unknown) {
|
|
return Response.json({
|
|
success: true,
|
|
data,
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
});
|
|
}
|
|
|
|
function failureResponse(status: number) {
|
|
return Response.json(
|
|
{
|
|
success: false,
|
|
error: { code: "TEMPORARY" },
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
},
|
|
{ status },
|
|
);
|
|
}
|
|
|
|
type EmittedEvent = Readonly<{
|
|
eventName: string;
|
|
attributes: Readonly<Record<string, unknown>>;
|
|
}>;
|
|
|
|
function harness(fetcher: typeof fetch, maxRetryAttempts = 1) {
|
|
const records: DiagnosticRecordInput[] = [];
|
|
const emitted: EmittedEvent[] = [];
|
|
let currentTime = 0;
|
|
const client = createHttpClient({
|
|
...TEST_HTTP_CONTRACT,
|
|
baseUrl: "https://api.test",
|
|
fetcher,
|
|
maxRetryAttempts,
|
|
clock: {
|
|
now: () => currentTime,
|
|
sleep: async () => {
|
|
currentTime += 150;
|
|
},
|
|
},
|
|
scheduler: {
|
|
setTimeout: () => 1,
|
|
clearTimeout: () => {},
|
|
},
|
|
correlationIdFactory: () => "correlation-fixed",
|
|
diagnostics: {
|
|
record(input) {
|
|
records.push(structuredClone(input));
|
|
},
|
|
},
|
|
telemetry: {
|
|
emit(eventName, attributes) {
|
|
emitted.push({
|
|
eventName,
|
|
attributes: structuredClone(attributes),
|
|
});
|
|
},
|
|
},
|
|
});
|
|
return { client, records, emitted };
|
|
}
|
|
|
|
describe("HTTP diagnostics and terminal telemetry", () => {
|
|
it("records one successful reference route outcome and no failure event", async () => {
|
|
const { client, records, emitted } = harness(
|
|
vi.fn(async () => successResponse([])),
|
|
);
|
|
|
|
await expect(
|
|
client.execute({
|
|
operationId: "LIST_ENTITIES",
|
|
routeId: "TEST_ROUTE",
|
|
}),
|
|
).resolves.toMatchObject({ ok: true });
|
|
|
|
expect(records).toEqual([
|
|
{
|
|
level: "info",
|
|
eventId: "http.request.completed",
|
|
context: {
|
|
route_id: "TEST_ROUTE",
|
|
operation_id: "LIST_ENTITIES",
|
|
correlation_id: "correlation-fixed",
|
|
outcome: "success",
|
|
error_kind: "NONE",
|
|
http_status_group: "2xx",
|
|
attempt_count_bucket: "1",
|
|
duration_bucket: "lt100ms",
|
|
},
|
|
},
|
|
]);
|
|
expect(emitted).toEqual([]);
|
|
});
|
|
|
|
it("summarizes retry recovery once without a terminal failure event", async () => {
|
|
const fetcher = vi
|
|
.fn<typeof fetch>()
|
|
.mockResolvedValueOnce(failureResponse(503))
|
|
.mockResolvedValueOnce(successResponse([]));
|
|
const { client, records, emitted } = harness(fetcher);
|
|
|
|
await expect(
|
|
client.execute({
|
|
operationId: "LIST_ENTITIES",
|
|
routeId: "TEST_ROUTE",
|
|
}),
|
|
).resolves.toMatchObject({ ok: true });
|
|
|
|
expect(fetcher).toHaveBeenCalledTimes(2);
|
|
expect(records).toHaveLength(1);
|
|
expect(records[0]).toMatchObject({
|
|
eventId: "http.request.completed",
|
|
context: {
|
|
outcome: "recovered",
|
|
correlation_id: "correlation-fixed",
|
|
duration_bucket: "100-499ms",
|
|
},
|
|
});
|
|
expect(emitted).toEqual([]);
|
|
});
|
|
|
|
it("emits one bounded terminal failure after all attempts", async () => {
|
|
const fetcher = vi.fn(async () => failureResponse(503));
|
|
const { client, records, emitted } = harness(fetcher);
|
|
|
|
await expect(
|
|
client.execute({
|
|
operationId: "CREATE_ENTITY",
|
|
routeId: "TEST_ROUTE",
|
|
body: { name: "private user input" },
|
|
idempotencyKey: "private-idempotency-key",
|
|
}),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "SERVER_FAILURE" },
|
|
});
|
|
|
|
expect(fetcher).toHaveBeenCalledTimes(2);
|
|
expect(records).toHaveLength(1);
|
|
expect(emitted).toEqual([
|
|
{
|
|
eventName: "api.request.failed",
|
|
attributes: {
|
|
error_kind: "SERVER_FAILURE",
|
|
http_status_group: "5xx",
|
|
attempt_count_bucket: "2",
|
|
route_id: "TEST_ROUTE",
|
|
operation_id: "CREATE_ENTITY",
|
|
duration_bucket: "100-499ms",
|
|
},
|
|
},
|
|
]);
|
|
expect(JSON.stringify({ records, emitted })).not.toMatch(
|
|
/private user input|private-idempotency-key/,
|
|
);
|
|
});
|
|
|
|
it("records navigation abort without failure telemetry", async () => {
|
|
const caller = new AbortController();
|
|
caller.abort("navigation");
|
|
const fetcher = vi.fn(async (request: RequestInfo | URL) => {
|
|
const signal = (request as Request).signal;
|
|
if (signal.aborted) throw new DOMException("aborted", "AbortError");
|
|
return successResponse([]);
|
|
});
|
|
const { client, records, emitted } = harness(
|
|
fetcher as unknown as typeof fetch,
|
|
);
|
|
|
|
await expect(
|
|
client.execute({
|
|
operationId: "LIST_ENTITIES",
|
|
routeId: "TEST_ROUTE",
|
|
signal: caller.signal,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "REQUEST_ABORTED" },
|
|
});
|
|
|
|
expect(records).toHaveLength(1);
|
|
expect(records[0]).toMatchObject({
|
|
eventId: "http.request.completed",
|
|
context: { outcome: "aborted", error_kind: "REQUEST_ABORTED" },
|
|
});
|
|
expect(emitted).toEqual([]);
|
|
});
|
|
|
|
// 백엔드 1101/02-01. The paired backend refuses these before it runs the
|
|
// command (its docs/web/http-contract.md §2): not applied, not resent, and
|
|
// diagnostics name the cause.
|
|
it.each([
|
|
{
|
|
status: 422,
|
|
code: "IDEMPOTENT_REQUEST_MISMATCH",
|
|
kind: "VALIDATION_REJECTED",
|
|
details: undefined,
|
|
reason: "IDEMPOTENT_REQUEST_MISMATCH",
|
|
},
|
|
{
|
|
status: 400,
|
|
code: "IDEMPOTENCY_KEY_INVALID",
|
|
kind: "UNKNOWN_CLIENT_FAILURE",
|
|
details: { reason: "MALFORMED" },
|
|
// This client checked the key before sending, so the two rules disagree.
|
|
reason: "IDEMPOTENCY_KEY_RULE_MISMATCH",
|
|
},
|
|
])(
|
|
"reports a $status $code as not applied, sent once, with reason $reason",
|
|
async ({ status, code, kind, details, reason }) => {
|
|
const fetcher = vi.fn(async () =>
|
|
Response.json(
|
|
{
|
|
success: false,
|
|
error: {
|
|
code,
|
|
category: "VALIDATION",
|
|
message: "요청을 처리할 수 없습니다.",
|
|
retryable: false,
|
|
...(details === undefined ? {} : { details }),
|
|
},
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
},
|
|
{ status },
|
|
),
|
|
);
|
|
const { client, records } = harness(fetcher);
|
|
|
|
await expect(
|
|
client.execute({
|
|
operationId: "CREATE_ENTITY",
|
|
routeId: "TEST_ROUTE",
|
|
body: { name: "n" },
|
|
idempotencyKey: "key-1",
|
|
}),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
kind,
|
|
code,
|
|
httpStatus: status,
|
|
retryable: false,
|
|
effect: "NOT_APPLIED",
|
|
},
|
|
});
|
|
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
expect(records).toMatchObject([
|
|
{ context: { outcome: "failed", error_kind: kind, reason } },
|
|
]);
|
|
},
|
|
);
|
|
|
|
it("keeps an unrelated 422 effect-free and reason-free", async () => {
|
|
const fetcher = vi.fn(async () =>
|
|
Response.json(
|
|
{
|
|
success: false,
|
|
error: { code: "INVALID_INPUT" },
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
},
|
|
{ status: 422 },
|
|
),
|
|
);
|
|
const { client, records } = harness(fetcher);
|
|
|
|
const result = await client.execute({
|
|
operationId: "CREATE_ENTITY",
|
|
routeId: "TEST_ROUTE",
|
|
body: { name: "n" },
|
|
});
|
|
|
|
expect(result.ok ? undefined : result.error.effect).toBeUndefined();
|
|
expect(records[0]?.context).not.toHaveProperty("reason");
|
|
});
|
|
});
|