Files
clean-architecture-frontend…/tests/features/reference-feature/reference-production-vertical.test.tsx
T
DongHyeonka 849d000342 fix(http): 결과 불명 쓰기에 보낸 요청 id를 지원 참조로 싣는다 (0929/03-04)
문제: 바인딩은 서버가 돌려준 x-correlation-id만 AppFailure.requestId로
싣는다. 마감 초과·연결 끊김(TRANSPORT_FAILURE)과 취소에는 응답이 없고,
헤더를 노출하지 않는 서버·게이트웨이의 504에도 반사값이 없다. 실행기는
보낸 id를 알지만 observation(기본 sink 없는 메모리 diagnostics)에만
넣었다. 그래서 e54fbf2(0929/08-04)가 결과 불명 화면에 더한 "지원 참조"
줄이 가장 흔한 결과 불명 경우(마감 초과)에 비어 있었다. 요청은 id를
싣고 서버 로그에 남는데도 지원 담당은 시각·사용자로 찾아야 했다.

고른 방법: 리뷰의 최소 개선 방향 ①을 한다. ②(화면)는 e54fbf2가 이미
했다.
- V3 실행 결과(HttpExecutionOutcome)의 모든 가지에 선택 필드
  sentRequestId를 더한다. finish()가 요청에 넣은 x-correlation-id를
  싣는다. observation의 correlationId와 같은 값이다.
- 바인딩은 반사값이 없으면 sentRequestId를 requestId로 쓴다.
- 런북 5.2-6과 백엔드 계약 5절에 "반사값이 없으면 보낸 값" 한 줄씩.
버린 대안: metadata 없는 가지에만 필드 두기 — 반사 헤더 없는 504는
metadata가 있어 빠진다. 바인딩이 id를 만들어 실행기에 넘기기 — 실행기가
이미 id를 만들고 재시도에 공유하므로 생성 지점이 둘이 된다.

위험·한계: 공개 결과 타입에 선택 필드 하나가 붙는다(추가만). 요청을
조립하기 전에 끝난 실패(자격 증명 없음, 입력 거절)와 id 생성 실패(보안
컨텍스트 아님)에는 값이 없다. 서버가 id를 바꿔 쓰면 반사값을 우선하므로
두 값이 다를 수 있다. telemetry에는 넣지 않는다(VD-07). 초기 JS gzip은
이 커밋 단독으로 재지 않았다(두 커밋 뒤 함께 잼).

검증:
- RED: reference-production-vertical에 새 테스트. REQUEST_TIMEOUT_MS
  200, MSW가 abort까지 응답하지 않는다. 수정 전 "변경 결과를 확인할 수
  없습니다."는 보이지만 "Unable to find an element with the text: 지원
  참조: 29d7f444-…"로 실패.
- GREEN: 같은 테스트 통과(화면 식별자 = 요청 헤더 x-correlation-id).
  tests/features·unit·integration·component 242 files 2975 tests,
  tests/contract·runtime-schema·architecture 13 files 109 tests 통과.
  tsc app·test, eslint(바꾼 파일), verify-documentation-readiness,
  check-adapter-inventory, check-registries 통과.

Refs: docs/reviews/2026-09-29-maturity-review/03-adapters-http-state.md 03-04
2026-11-03 00:53:16 +09:00

381 lines
14 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import {
afterAll,
afterEach,
beforeAll,
describe,
expect,
it,
vi,
} from "vitest";
import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts";
import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx";
import { createBootstrapHandlers } from "../../mocks/handlers/bootstrap.ts";
import { createReferenceScenarioHandlers } from "../../mocks/handlers/reference-resources.ts";
import { createStrictMockServer } from "../../mocks/server.ts";
const runtimeConfig = {
APP_ENV: "local",
API_BASE_URL: "https://api.test",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 0,
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "1",
API_CONTRACT_VERSION: "1",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "local-build",
RELEASE_ID: "local-release",
};
const releaseManifest = {
schemaVersion: 1,
appVersion: "0.2.0",
buildId: "local-build",
commitSha: "local",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
releaseId: "local-release",
builtAt: "2026-07-26T00:00:00.000Z",
routeChunks: {
"route-home": "assets/home.js",
"route-examples-ui": "assets/ui.js",
"route-examples-states": "assets/states.js",
"route-examples-auth": "assets/auth.js",
"route-reference-resources": "assets/reference.js",
"route-reference-resource-detail": "assets/reference-detail.js",
"route-reference-resource-form": "assets/reference-form.js",
"route-reference-resource-status": "assets/reference-status.js",
"route-not-found": "assets/not-found.js",
},
};
const listRequests = vi.fn();
const createRequests = vi.fn();
const resources = [{ id: "reference-1", name: "Existing" }];
const mockApi = createStrictMockServer(
...createBootstrapHandlers(runtimeConfig, releaseManifest),
...createReferenceScenarioHandlers({
resources,
onList: listRequests,
onCreate: createRequests,
}),
);
beforeAll(mockApi.listen);
afterEach(() => {
mockApi.reset();
listRequests.mockClear();
createRequests.mockClear();
resources.splice(1);
});
afterAll(mockApi.close);
const absoluteFetch: typeof fetch = (input, init) => {
if (input instanceof Request) return fetch(input, init);
const url = new URL(
input instanceof URL ? input.href : input,
"http://app.test",
);
return fetch(url, init);
};
describe("reference feature production vertical path", () => {
it("traverses bootstrap, router, application, HTTP schema/mapper and query cache", async () => {
const user = userEvent.setup();
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState(
{},
"",
"/examples/reference-resources?tags=open&tags=new&limit=5",
);
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
expect(await screen.findByText("Existing")).toBeVisible();
expect(listRequests).toHaveBeenCalledWith(
"?limit=5&tags=open&tags=new",
);
await user.click(screen.getByRole("button", { name: "새 항목 만들기" }));
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
" Created ",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText("저장했습니다.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" }));
expect(await screen.findByText("Created")).toBeVisible();
expect(createRequests).toHaveBeenCalledWith({ name: "Created" });
expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2);
});
it("resends a create whose 504 lost the response with the same Idempotency-Key", async () => {
const user = userEvent.setup();
const idempotencyKeys: (string | null)[] = [];
mockApi.server.use(
http.post("https://api.test/api/reference-resources", async ({ request }) => {
idempotencyKeys.push(request.headers.get("idempotency-key"));
// The first request reaches the server; only its response is lost.
if (idempotencyKeys.length === 1) {
return new HttpResponse(null, { status: 504 });
}
const body = (await request.json()) as { name: string };
return HttpResponse.json(
{
id: "reference-created",
name: body.name,
createdAt: "2026-07-26T00:00:00.000Z",
},
{ status: 201 },
);
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Lost response",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
expect(await screen.findByText("저장했습니다.")).toBeVisible();
expect(idempotencyKeys).toHaveLength(2);
expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u);
expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]);
});
// 0929/03-04. A write past its deadline has no server answer to echo an
// id, so the screen shows the id the request itself carried.
it("shows the sent x-correlation-id for a create past its deadline", async () => {
const user = userEvent.setup();
const sentIds: (string | null)[] = [];
mockApi.server.use(
http.get("http://app.test/config.json", () =>
HttpResponse.json({ ...runtimeConfig, REQUEST_TIMEOUT_MS: 200 }),
),
http.post("https://api.test/api/reference-resources", async ({ request }) => {
sentIds.push(request.headers.get("x-correlation-id"));
// The server is still working when the client deadline ends.
await new Promise<void>((resolve) => {
request.signal.addEventListener("abort", () => resolve(), { once: true });
});
return new HttpResponse(null, { status: 504 });
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Past the deadline",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(
await screen.findByText("변경 결과를 확인할 수 없습니다."),
).toBeVisible();
expect(sentIds).toHaveLength(1);
expect(sentIds[0]).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u);
expect(screen.getByText(`지원 참조: ${sentIds[0]}`)).toBeVisible();
});
it("keeps the key when the resend meets the first attempt still in flight (0929/03-01)", async () => {
const user = userEvent.setup();
const idempotencyKeys: (string | null)[] = [];
// A server that deduplicates by key: one receipt per created resource.
const receipts = new Map<string, Record<string, string>>();
let firstAttemptRunning = true;
mockApi.server.use(
http.post("https://api.test/api/reference-resources", async ({ request }) => {
const key = request.headers.get("idempotency-key") ?? "";
idempotencyKeys.push(key);
const receipt = receipts.get(key);
if (receipt) {
if (firstAttemptRunning) {
// The paired backend answers a same-key request while the first
// attempt still runs with 409 IDEMPOTENT_IN_FLIGHT.
firstAttemptRunning = false;
return HttpResponse.json(
{
type: "https://api.test/problems/idempotent_in_flight",
title: "IDEMPOTENT_IN_FLIGHT",
status: 409,
code: "IDEMPOTENT_IN_FLIGHT",
},
{
status: 409,
headers: { "content-type": "application/problem+json" },
},
);
}
return HttpResponse.json(receipt, { status: 201 });
}
const body = (await request.json()) as { name: string };
const resource = {
id: `reference-created-${receipts.size + 1}`,
name: body.name,
createdAt: "2026-07-26T00:00:00.000Z",
};
receipts.set(key, resource);
// The first attempt reaches the server; only its response is lost.
if (receipts.size === 1) return new HttpResponse(null, { status: 504 });
return HttpResponse.json(resource, { status: 201 });
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Slow write",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
await waitFor(() => expect(idempotencyKeys).toHaveLength(2));
// After the 409 the user takes the next step the screen offers.
const next = await waitFor(() => {
const resend = screen.queryByRole("button", {
name: "같은 요청으로 다시 보내기",
});
if (resend) return resend;
const save = screen.getByRole("button", { name: "저장" });
expect(save).toBeEnabled();
return save;
});
const shownAfterInFlight = {
unknown: screen.queryByText("변경 결과를 확인할 수 없습니다.") !== null,
conflict: screen.queryAllByText(/충돌/).length > 0,
};
await user.click(next);
await waitFor(() => expect(idempotencyKeys).toHaveLength(3));
const [first] = idempotencyKeys;
expect(idempotencyKeys).toEqual([first, first, first]);
expect(receipts.size).toBe(1);
expect(shownAfterInFlight).toEqual({ unknown: true, conflict: false });
expect(await screen.findByText("저장했습니다.")).toBeVisible();
});
it.each([
// The demo session treats a server 401 as signed out; the route guard
// then asks for sign-in and the form is gone.
[401, "세션이 필요합니다."],
[403, "이 작업을 수행할 권한이 없습니다."],
[429, "요청이 많습니다. 잠시 후 다시 시도해 주세요."],
])(
"treats a create rejected with %i as not applied, not unknown",
async (status, guidance) => {
const user = userEvent.setup();
mockApi.server.use(
http.post(
"https://api.test/api/reference-resources",
() => new HttpResponse(null, { status }),
),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Rejected",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText(guidance)).toBeVisible();
expect(
screen.queryByText("변경 결과를 확인할 수 없습니다."),
).not.toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }),
).not.toBeInTheDocument();
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
},
);
it("shows a server 422 field error on its field (03-04)", async () => {
const user = userEvent.setup();
mockApi.server.use(
http.post("https://api.test/api/reference-resources", () =>
HttpResponse.json(
{
type: "https://api.test/problems/validation_rejected",
title: "VALIDATION_REJECTED",
status: 422,
code: "VALIDATION_REJECTED",
issues: [
{ path: "name", code: "too_big", message: "backend copy" },
{ path: "serverOnly", code: "REQUIRED" },
],
},
{ status: 422 },
),
),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
await user.type(name, "Too long for the server");
await user.click(screen.getByRole("button", { name: "저장" }));
const summary = await screen.findByRole("alert");
expect(summary).toHaveTextContent("새 항목 이름: 입력값이 너무 깁니다.");
expect(summary).toHaveTextContent("서버가 확인하지 못한 입력 항목이 있습니다.");
expect(name).toHaveAttribute("aria-invalid", "true");
expect(document.body).not.toHaveTextContent("backend copy");
});
});