문제
짝 백엔드는 같은 키의 첫 요청이 아직 실행 중이면 409
IDEMPOTENT_IN_FLIGHT, retryable=true, Retry-After: 2를 준다(백엔드
docs/web/http-contract.md §2). 클라이언트 행동은 "같은 키로 Retry-After 뒤
재전송"이다.
- 같은 키: 0929/03-01이 이 409를 MAYBE_APPLIED로 두어 코디네이터가 intent를
붙든다. 재전송은 같은 키를 쓴다(기존 vertical 테스트가 [K, K, K]를
고정). 이 부분은 이미 맞다.
- Retry-After: 지키지 않는다. V3는 응답 metadata에 retryAfterMs를 읽지만
feature binding이 PROBLEM을 AppFailure로 옮길 때 버린다. V2는 409의
Retry-After를 읽지 않는다. 그래서 결과 불명 화면의 "같은 요청으로 다시
보내기"(또는 같은 입력 다시 저장)를 바로 누르면 즉시 나가서 같은 409를
한 번 더 받는다.
고른 방법
재전송이 그 시각 전이면 기다렸다 보낸다.
- feature binding이 PROBLEM의 metadata.retryAfterMs를 AppFailure에 싣는다.
V2는 409의 Retry-After도 읽는다(409는 여전히 자동 재시도하지 않는다).
- mutation 코디네이터(application-query.ts)가 MAYBE_APPLIED로 남기는
admission에 resendNotBefore = 지금 + min(retryAfterMs, 5초)를 적는다.
같은 intent를 다시 쓰는 submit(재전송 버튼, 같은 입력 저장)이 그 시각까지
기다린 뒤 보낸다. 기다리는 동안 admission이 ACTIVE라 화면은 pending이다.
scope가 바뀌면 기존 mutationFn 검사가 NOT_STARTED로 막는다.
- 상한 5초는 V3 실행기의 Retry-After 상한(RETRY_AFTER_CEILING_MS)과 같다.
더 일찍 보내도 같은 키라 서버가 다시 409를 줄 뿐 두 번 적용하지 않으므로,
긴 Retry-After를 다 기다리게 하지 않는다.
버린 대안
- Retry-After 전에는 버튼을 막기: 화면과 시각 회귀 골든이 바뀌고, 다시
열어 줄 타이머와 문구가 더 든다. 기다렸다 보내는 쪽이 변경이 작다.
- V3 실행기가 키별 "이 시각 전 금지" 표를 들기: 실행기에 키를 기억하는
상태와 정리 규칙이 생긴다. 재전송을 만드는 곳은 코디네이터 하나다.
- 그대로 두기(이른 재전송은 409를 한 번 더 받을 뿐): 서버 문서가 허용하는
동작이지만 사용자는 같은 결과 불명 화면을 한 번 더 본다. 요구는
Retry-After를 지키는 것이다.
위험·한계
- AppFailure.retryAfterMs가 V3 PROBLEM에도 실린다(추가 필드). 이 값을 읽는
곳은 코디네이터뿐이다.
- 기다림은 MAYBE_APPLIED로 남은 admission을 다시 보낼 때만 생긴다. 다른
상태(NOT_APPLIED 등)는 그대로다.
- 시계는 performance.now(), 대기는 setTimeout이다. 탭이 백그라운드면
브라우저가 타이머를 늦출 수 있다(더 늦게 보낼 뿐이다).
검증
- RED: 4행 실패.
- tests/features/reference-feature/reference-production-vertical.test.tsx
처리 중 409(Retry-After: 1) 뒤 재전송 간격 39.7ms(기대 990ms 이상)
- tests/component/application-mutation-admission.test.tsx 재전송이
retryAfterMs 300을 기다리지 않음
- tests/features/reference-feature/reference-http-problem-mapping.test.ts
retryAfterMs 없음
- tests/integration/http-client.test.ts V2 409 retryAfterMs 없음
상한 행은 수정 전에도 통과하고, 상한을 뺀 변이에서 시간 초과로 실패하는
것을 확인했다.
- GREEN: 위 행 모두 통과. tests/component·features·contract/reusable-
capability, tests/integration/http-client·http-diagnostics, tests/unit/
http-execution-v3 62 files 491 tests 통과. tsc app·test 통과, 바꾼 파일
eslint 통과.
Refs: clean-architecture-backend-template docs/reviews/2026-11-01-maturity-review/README.md 14.3, 15
392 lines
14 KiB
TypeScript
392 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 { createReferenceResourceHandlers } from "./reference-resource-handlers.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),
|
|
...createReferenceResourceHandlers({
|
|
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)[] = [];
|
|
const sentAt: number[] = [];
|
|
// 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);
|
|
sentAt.push(performance.now());
|
|
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 and
|
|
// Retry-After (2 there; 1 here to keep the test short).
|
|
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",
|
|
"retry-after": "1",
|
|
},
|
|
},
|
|
);
|
|
}
|
|
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), {
|
|
timeout: 3_000,
|
|
});
|
|
|
|
const [first] = idempotencyKeys;
|
|
expect(idempotencyKeys).toEqual([first, first, first]);
|
|
expect(receipts.size).toBe(1);
|
|
expect(shownAfterInFlight).toEqual({ unknown: true, conflict: false });
|
|
// 백엔드 1101/02-01. The click came right after the 409; the resend
|
|
// waited out its Retry-After instead of meeting the same 409 again.
|
|
expect((sentAt[2] ?? 0) - (sentAt[1] ?? 0)).toBeGreaterThanOrEqual(990);
|
|
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");
|
|
});
|
|
});
|