Files
clean-architecture-frontend…/tests/integration/http-diagnostics.test.ts
T
DongHyeonka 64e98ee2fa fix(http): V2 검증 거절을 적용 안 됨으로 보고 고친 값을 다시 저장하게 한다 (백엔드 1101/02-01)
문제
V2 클라이언트(client.ts)는 필드 검증 거절(422, 짝 백엔드의 400
VALIDATION_FAILED + 필드 목록)에 effect를 붙이지 않는다. mutation
코디네이터(application-query.ts mutationFailureWithEffect)는 effect가 없으면
MAYBE_APPLIED로 보고 admission을 UNKNOWN으로 붙든다. 폼은 VALIDATION_
REJECTED를 필드 오류로 보여 주지만, 참조 폼 페이지는 코디네이터가 결과 불명을
들고 있으면 저장 버튼을 끈다(reference-resource-form-page.tsx
mutationBlocked). 사용자가 필드를 고쳐도 다시 저장할 수 없다. use-app-form
자체는 VALIDATION_REJECTED에서 unknownSubmissionRef를 비우므로 막지 않는다.
막는 것은 코디네이터 상태다.
V3 참조 기능은 재현되지 않는다. 생성 분류기가 400·422를 NOT_APPLIED로
본다(reference-feature-contract-contribution.ts classifyProblem).

고른 방법
V2에서 필드 검증 거절(fieldValidation: 422, 또는 400 VALIDATION_FAILED +
배열 details)에 effect NOT_APPLIED를 붙인다. 멱등성 거절(IDEMPOTENCY_
REFUSALS)과 같은 자리에서 붙이고, 진단 reason은 멱등성 거절에만 남긴다.

근거(백엔드 계약)
- docs/web/http-contract.md 4절과 web adapter README 예외 표가 VALIDATION_
  FAILED의 출처를 적는다: 요청 본문 바인딩(MethodArgumentNotValid
  Exception), 컨트롤러 파라미터 제약(HandlerMethodValidationException),
  Bean Validation(ConstraintViolationException), 페이지 파라미터, 읽을 수
  없는 본문. 모두 요청을 묶는 단계에서 컨트롤러·use case보다 먼저 거절한다.
- 4절에 "상태를 바꾸지 않는다"는 문장은 없다. 이 판정은 위 출처에서
  끌어낸 것이다.

버린 대안
- 코디네이터가 effect 없는 VALIDATION_REJECTED를 모두 NOT_APPLIED로 보기:
  거절을 판정하는 곳은 응답을 읽는 클라이언트다. 코디네이터의 "모르면
  MAYBE_APPLIED" 규칙은 그대로 둔다.
- 폼 페이지가 VALIDATION_REJECTED 뒤 결과 불명을 무시하기: 키가 붙은 채
  남아 같은 입력을 다시 저장하면 같은 키가 나간다.

위험·한계
- application 층에서 쓰기 뒤에 VALIDATION_FAILED를 던지는 백엔드 코드가
  있다면 이 판정은 틀린다. 짝 백엔드 IdempotencyExecutor는 실행 중 예외를
  EFFECT_UNKNOWN_ABANDONED로 기록한다. 이 경우 같은 키 재전송은 500
  IDEMPOTENCY_RECOVERY_REQUIRED를 받는다. NOT_APPLIED면 다음 저장이 새 키를
  쓰므로 그 경로를 타지 않는다.
- 필드 목록 없는 400 VALIDATION_FAILED({cause}, 본문 파싱 실패)와 그 밖의
  400·409는 effect 없이 둔다(결과 불명으로 붙듦). 이번 범위 밖이다.
- 422 IDEMPOTENT_REQUEST_MISMATCH는 원래 NOT_APPLIED였고 그대로다.

검증
- RED: tests/component/form-foundation.test.tsx "saves the corrected value
  after a $status field error" 2행(422, 400 VALIDATION_FAILED) 실패. 필드
  오류 뒤 저장 버튼이 disabled다.
- V3: tests/features/reference-feature/reference-production-vertical.test.tsx
  "saves the corrected value after a server 422 field error"는 수정 전에도
  통과한다(재현 안 됨, 동작 고정).
- GREEN: 위 행 통과. tests/integration/http-diagnostics.test.ts의 "unrelated
  422" 행은 effect가 없다고 기대하던 것을 NOT_APPLIED로 바꾸고, 409 행을
  더해 다른 거절은 effect가 없음을 고정했다. tests/integration/http-client.
  test.ts에 400 VALIDATION_FAILED effect 단언을 더했다.
  tests/unit·contract·runtime-schema·integration·component·features·platform
  3398 tests 통과, 1개 실패(tests/unit/second-api-feature-registries.test.ts,
  기준 3b7d73a에서도 같은 메시지로 실패). tsc app·test, 바꾼 파일 eslint
  통과.

Refs: clean-architecture-backend-template docs/web/http-contract.md 4절, src/adapter/inbound/web/README.md 예외 표
2026-11-03 02:16:49 +09:00

286 lines
8.1 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([
// A field validation refusal is not applied, but names no idempotency cause.
{ status: 422, code: "INVALID_INPUT", effect: "NOT_APPLIED" },
// 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");
});
});