Files
clean-architecture-frontend…/tests/integration/http-diagnostics.test.ts
T
DongHyeonka 326120867c 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
2026-11-03 20:26:28 +09:00

287 lines
8.2 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.each([
// 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 }) => {
const fetcher = vi.fn(async () =>
Response.json(
{
success: false,
error: { code },
meta: { requestId: "request-1", traceId: "trace-1" },
},
{ status },
),
);
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).toBe(effect);
expect(records[0]?.context).not.toHaveProperty("reason");
});
});