refactor: 리펙토링

This commit is contained in:
DongHyeonka
2026-08-01 19:39:59 +09:00
parent 9c959ea2a5
commit c6da03369c
171 changed files with 20329 additions and 782 deletions
+332
View File
@@ -20,10 +20,44 @@ import {
type QueryInvalidationCoordinator,
} from "../../src/contracts/query-invalidation.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
import {
bindQuery,
type QueryResultMeasure,
} from "../../src/contracts/server-state.ts";
import type { CacheScopeSnapshot } from "../../src/contracts/server-state-scope.ts";
const RESOURCE_INVALIDATION_TOPIC =
defineQueryInvalidationTopic("resource");
/**
* §24.12: the scope-bound commit fence is common runtime, so it is verified
* here with a local scope fixture rather than through the removable sample
* feature.
*/
function scopeSnapshot(): CacheScopeSnapshot & { fence(): void } {
let current = true;
const lifetime = new AbortController();
const identities = createRuntimeIdentityRegistry({
tokenFactory: () => "scope-identity-token-0001",
});
return {
generation: 1,
fingerprint: "scope-fingerprint-0001",
identities,
signal: lifetime.signal,
isCurrent: () => current,
fence() {
current = false;
lifetime.abort();
},
};
}
function measureOne(): QueryResultMeasure {
return { itemCount: 1, estimatedBytes: 8 };
}
function queryClient() {
return new QueryClient({
defaultOptions: {
@@ -181,7 +215,303 @@ describe("application query inbound bridge", () => {
});
});
describe("scope-bound query commit fence", () => {
it("discards a successful result whose scope was fenced during execution", async () => {
const client = queryClient();
const scope = scopeSnapshot();
let complete: (value: ApplicationResult<string>) => void = () => {};
const hook = renderHook(
() =>
useApplicationQuery(
bindQuery(
{
definitionId: "fenced-detail-v1",
definitionVersion: 1,
owner: "platform-test",
namespace: "fenced",
namespaceVersion: 1,
operationId: "GET_FENCED",
profileId: "DETAIL_STANDARD",
measureResult: measureOne,
execute: () =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
},
"input",
scope,
),
),
{ wrapper: wrapper(client) },
);
// §10.8: the scope goes stale after dispatch but before commit.
scope.fence();
await act(async () => {
complete({ ok: true, value: "late" });
});
await waitFor(() =>
expect(hook.result.current.state.failure?.kind).toBe(
"SCOPE_GENERATION_CHANGED",
),
);
expect(hook.result.current.data).toBeUndefined();
});
it("refuses to start when the captured scope is already stale", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const execute = vi.fn(async () => ({ ok: true as const, value: "v" }));
scope.fence();
const hook = renderHook(
() =>
useApplicationQuery(
bindQuery(
{
definitionId: "stale-detail-v1",
definitionVersion: 1,
owner: "platform-test",
namespace: "stale",
namespaceVersion: 1,
operationId: "GET_STALE",
profileId: "DETAIL_STANDARD",
measureResult: measureOne,
execute,
},
"input",
scope,
),
),
{ wrapper: wrapper(client) },
);
await waitFor(() =>
expect(hook.result.current.state.failure?.kind).toBe(
"SCOPE_GENERATION_CHANGED",
),
);
expect(execute).not.toHaveBeenCalled();
});
it("rejects a result that exceeds the profile budget instead of caching it", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const hook = renderHook(
() =>
useApplicationQuery(
bindQuery(
{
definitionId: "oversized-list-v1",
definitionVersion: 1,
owner: "platform-test",
namespace: "oversized",
namespaceVersion: 1,
operationId: "LIST_OVERSIZED",
profileId: "VOLATILE_STATUS",
// §10.4: VOLATILE_STATUS admits 1 item and 64KiB.
measureResult: (): QueryResultMeasure => ({
itemCount: 2,
estimatedBytes: 8,
}),
execute: async () => ({ ok: true as const, value: "value" }),
},
"input",
scope,
),
),
{ wrapper: wrapper(client) },
);
await waitFor(() =>
expect(hook.result.current.state.failure?.kind).toBe(
"RESULT_LIMIT_EXCEEDED",
),
);
expect(hook.result.current.data).toBeUndefined();
});
it("treats a throwing measurement as a measurement failure, not a cache commit", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const hook = renderHook(
() =>
useApplicationQuery(
bindQuery(
{
definitionId: "unmeasurable-v1",
definitionVersion: 1,
owner: "platform-test",
namespace: "unmeasurable",
namespaceVersion: 1,
operationId: "GET_UNMEASURABLE",
profileId: "DETAIL_STANDARD",
measureResult: (): QueryResultMeasure => {
throw new Error("estimator defect");
},
execute: async () => ({ ok: true as const, value: "value" }),
},
"input",
scope,
),
),
{ wrapper: wrapper(client) },
);
await waitFor(() =>
expect(hook.result.current.state.failure?.kind).toBe(
"RESULT_LIMIT_EXCEEDED",
),
);
expect(hook.result.current.data).toBeUndefined();
});
});
describe("scope-bound mutation fence", () => {
it("rejects a submit whose scope is already fenced", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const execute = vi.fn(async () => ({ ok: true as const, value: "v" }));
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "fenced-mutation-v1",
definitionVersion: 1,
operationId: "CREATE_FENCED",
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
scope.fence();
const outcome = await hook.result.current.submit("value");
expect(outcome).toMatchObject({
ok: false,
error: { kind: "SCOPE_GENERATION_CHANGED" },
});
expect(execute).not.toHaveBeenCalled();
});
it("discards a mutation result whose scope was fenced after dispatch", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const execute = vi.fn(async () => {
scope.fence();
return { ok: true as const, value: "committed" };
});
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "late-mutation-v1",
definitionVersion: 1,
operationId: "CREATE_LATE",
owner: "platform-test",
duplicatePolicy: "ALLOW_PARALLEL",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
const outcome = await hook.result.current.submit("value");
expect(outcome).toMatchObject({
ok: false,
error: { kind: "SCOPE_GENERATION_CHANGED" },
});
expect(execute).toHaveBeenCalledOnce();
});
it("aborts a hung mutation when its captured scope is fenced", async () => {
const client = queryClient();
const scope = scopeSnapshot();
let observedSignal: AbortSignal | undefined;
const execute = vi.fn(
(_input: string, context: Readonly<{ signal: AbortSignal }>) =>
new Promise<ApplicationResult<string>>((resolve) => {
observedSignal = context.signal;
context.signal.addEventListener(
"abort",
() =>
resolve({
ok: false,
error: createFailure("REQUEST_ABORTED", "CREATE_HUNG", 0),
}),
{ once: true },
);
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "hung-mutation-v1",
definitionVersion: 1,
operationId: "CREATE_HUNG",
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
const outcome = hook.result.current.submit("value");
await waitFor(() => expect(observedSignal).toBe(scope.signal));
scope.fence();
expect(observedSignal?.aborted).toBe(true);
await expect(outcome).resolves.toMatchObject({
ok: false,
error: {
kind: "SCOPE_GENERATION_CHANGED",
effect: "MAYBE_APPLIED",
retryable: false,
action: "contact-support",
},
});
});
});
describe("application mutation inbound bridge", () => {
it("rejects a duplicate submit by default while one is active", async () => {
const client = queryClient();
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() => useApplicationMutation<string, string>({ execute }),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | null = null;
let duplicate: Promise<ApplicationResult<string>> | null = null;
act(() => {
first = hook.result.current.submit("created");
duplicate = hook.result.current.submit("created");
});
if (!first || !duplicate) throw new Error("expected two submissions");
await expect(duplicate).resolves.toMatchObject({
ok: false,
error: { kind: "DUPLICATE_IN_FLIGHT" },
});
expect(execute).toHaveBeenCalledOnce();
complete({ ok: true, value: "created" });
await act(() => first as Promise<ApplicationResult<string>>);
});
it("deduplicates submit and commits one optimistic mutation", async () => {
const client = queryClient();
const key = ["resource", "list"];
@@ -196,6 +526,8 @@ describe("application mutation inbound bridge", () => {
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
// §11.2: joining is opt-in. The default is REJECT_WHILE_ACTIVE.
duplicatePolicy: "JOIN_IDENTICAL",
execute,
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: client.getQueryData(key),
@@ -0,0 +1,164 @@
// @vitest-environment jsdom
import { render, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { SERVER_STATE_PROFILES } from "../../src/contracts/server-state.ts";
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/installed-contract-contributions.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import PlatformOverviewPage from "../../src/presentation/examples/platform-overview-page.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
import { createRuntimeCapabilitiesStub } from "../helpers/runtime-capabilities-stub.ts";
/**
* The page must stay a projection of the installed registries. Every assertion
* below derives its expectation from the same registry the page reads, so a
* template that removes its sample feature still satisfies this suite.
*/
function renderPage() {
return render(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<PlatformOverviewPage />
</LocaleProvider>
</ApplicationProvider>,
);
}
function tableByCaption(caption: string): HTMLElement {
return screen.getByRole("table", { name: caption });
}
/** A metric is a `dt`/`dd` pair, which carries no ARIA role to query by. */
function metricByLabel(scope: HTMLElement, label: string): HTMLElement {
const term = within(scope).getByText(label).closest(".platform-metric");
if (!(term instanceof HTMLElement)) {
throw new Error(`No metric is labelled ${label}`);
}
return term;
}
describe("platform overview page", () => {
it("renders one route row per installed route registry entry", () => {
renderPage();
const table = tableByCaption("설치된 라우트 목록");
const dataRows = within(table).getAllByRole("row").slice(1);
expect(dataRows).toHaveLength(Object.keys(ROUTE_REGISTRY).length);
for (const definition of Object.values(ROUTE_REGISTRY)) {
expect(
within(table).getByText(definition.routeId),
).toBeInTheDocument();
}
});
it("renders one operation row per installed HTTP contract", () => {
const operationIds = [
...COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.keys(),
];
renderPage();
if (operationIds.length === 0) {
expect(
screen.getByRole("heading", {
name: "설치된 HTTP 오퍼레이션이 없습니다.",
}),
).toBeVisible();
return;
}
const table = tableByCaption("설치된 HTTP 오퍼레이션");
expect(within(table).getAllByRole("row").slice(1)).toHaveLength(
operationIds.length,
);
for (const operationId of operationIds) {
expect(within(table).getByText(operationId)).toBeInTheDocument();
}
});
it("renders every fixed server-state profile with its own budget", () => {
renderPage();
const table = tableByCaption("서버 상태 프로파일");
for (const profile of Object.values(SERVER_STATE_PROFILES)) {
expect(within(table).getByText(profile.profileId)).toBeInTheDocument();
}
expect(within(table).getAllByRole("row").slice(1)).toHaveLength(
Object.keys(SERVER_STATE_PROFILES).length,
);
});
it("labels a capability that was never selected as unselected", () => {
renderPage();
const region = screen.getByRole("region", { name: "선택적 런타임 능력" });
expect(within(region).getAllByText("미선택")).toHaveLength(4);
expect(within(region).queryByText("운영자가 비활성화함")).toBeNull();
});
it("separates an operator disable from a capability that was never selected", () => {
render(
<ApplicationProvider
application={createTestApplication({
runtimeCapabilities: createRuntimeCapabilitiesStub({
SERVICE_WORKER: { selected: 1, active: 0, override: "DISABLED" },
OFFLINE_COMMANDS: { selected: 1, active: 1 },
}),
})}
>
<LocaleProvider>
<PlatformOverviewPage />
</LocaleProvider>
</ApplicationProvider>,
);
const region = screen.getByRole("region", { name: "선택적 런타임 능력" });
expect(within(region).getByText("운영자가 비활성화함")).toBeVisible();
expect(within(region).getByText("활성 (1)")).toBeVisible();
expect(within(region).getAllByText("미선택")).toHaveLength(2);
});
it("counts installed contract packages separately from template fixtures", () => {
const fixtures = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.filter(
(contribution) => contribution.source.kind === "TEMPLATE_FIXTURE",
).length;
renderPage();
const summary = screen.getByRole("region", { name: "설치 요약" });
const packages = metricByLabel(summary, "외부 계약 패키지");
expect(
within(packages).getByText(
`${COMPOSED_CONTRACT_CONTRIBUTIONS.externalPackages.length}`,
),
).toBeVisible();
expect(
within(packages).getByText(`템플릿 픽스처 ${fixtures}`),
).toBeVisible();
expect(
within(metricByLabel(summary, "라우트")).getByText(
`${Object.keys(ROUTE_REGISTRY).length}`,
),
).toBeVisible();
});
it("renders the verified release identity once the runtime resolves it", async () => {
renderPage();
const region = screen.getByRole("region", { name: "릴리스 신원" });
await waitFor(() =>
expect(
within(metricByLabel(region, "빌드")).getByText("test-build"),
).toBeVisible(),
);
expect(
within(metricByLabel(region, "릴리스")).getByText("test-release"),
).toBeVisible();
});
});
+48 -4
View File
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
@@ -22,6 +22,29 @@ function renderRouter() {
}
describe("generic application router", () => {
it("reaches the platform overview from the home starter actions", async () => {
const user = userEvent.setup();
window.history.pushState({}, "", "/");
renderRouter();
// The starter action lives inside the lazily loaded home chunk, so this is
// the first wait in the file that has to outlast a chunk load rather than
// an already-mounted shell element.
await user.click(
await screen.findByRole(
"link",
{ name: "플랫폼 구성 보기" },
{ timeout: 5000 },
),
);
await waitFor(() =>
expect(
screen.getByRole("heading", { name: "플랫폼 구성", level: 1 }),
).toHaveFocus(),
);
});
it("renders the app shell and not-found route without a feature input", async () => {
window.history.pushState({}, "", "/missing");
renderRouter();
@@ -49,8 +72,29 @@ describe("generic application router", () => {
).toBeVisible();
expect(window.location.pathname).toBe("/examples/ui");
expect(document.title).toBe("UI 구성요소 · Frontend Skeleton");
expect(
screen.getByRole("heading", { name: "UI 구성요소", level: 1 }),
).toHaveFocus();
await waitFor(() =>
expect(
screen.getByRole("heading", { name: "UI 구성요소", level: 1 }),
).toHaveFocus(),
);
});
it("focuses the route heading again when the lazy chunk is already cached", async () => {
// §9.7. The first visit resolves the route module asynchronously, so the
// router lifecycle and the page header commit separately. A later visit
// renders the cached module in the same commit, which is the ordering that
// must still hand focus to the heading rather than leaving it on main.
const user = userEvent.setup();
window.history.pushState({}, "", "/");
renderRouter();
for (const label of ["UI 구성요소", "화면 상태", "UI 구성요소"]) {
await user.click(await screen.findByRole("link", { name: label }));
await waitFor(() =>
expect(
screen.getByRole("heading", { name: label, level: 1 }),
).toHaveFocus(),
);
}
});
});
@@ -0,0 +1,74 @@
// @vitest-environment jsdom
import { act, render, waitFor } from "@testing-library/react";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { createServerStateScopeRuntime } from "../../src/adapters/query-cache/server-state-scope-runtime.ts";
import { createServerStateGenerationStore } from "../../src/bootstrap/server-state-generation-store.ts";
import { ServerStateGenerationProvider } from "../../src/presentation/adapters/query/server-state-generation-provider.tsx";
describe("server-state generation provider", () => {
it("remounts consumers with the QueryClient owned by the READY generation", async () => {
const store = createServerStateGenerationStore(() => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
return {
queryClient,
queryInvalidation: {
invalidate: async () => {},
beginMutation: () => ({ release: async () => {} }),
resetLocal: async () => {
await queryClient.cancelQueries();
queryClient.clear();
},
dispose() {},
},
crossContextStatus: () => "DEGRADED_LOCAL_ONLY" as const,
};
});
let sessionListener: () => void = () => {};
let token = 0;
const scope = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: { resetLocal: () => store.resetCurrent() },
activateNextGeneration: () => store.activateNext(),
tokenFactory: () =>
`scope-generation-provider-${String(token++).padStart(4, "0")}`,
});
const renderedClients: QueryClient[] = [];
function Probe() {
renderedClients.push(useQueryClient());
return <div>generation-content</div>;
}
render(
<ServerStateGenerationProvider
store={store}
scope={scope}
transitionFallback={<div>scope-transition</div>}
>
<Probe />
</ServerStateGenerationProvider>,
);
const firstClient = renderedClients.at(-1);
if (!firstClient) throw new Error("expected initial QueryClient");
act(() => sessionListener());
await waitFor(() => expect(scope.getPhase()).toBe("READY"));
await waitFor(() =>
expect(renderedClients.at(-1)).toBe(store.getSnapshot().queryClient),
);
expect(renderedClients.at(-1)).not.toBe(firstClient);
scope.dispose();
store.dispose();
});
});
@@ -0,0 +1,83 @@
// @vitest-environment jsdom
import { act, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { createServerStateScopeRuntime } from "../../src/adapters/query-cache/server-state-scope-runtime.ts";
import { ServerStateScopeProvider } from "../../src/presentation/adapters/query/server-state-scope-provider.tsx";
const activeRuntimes: Array<{ dispose(): void }> = [];
afterEach(() => {
for (const runtime of activeRuntimes.splice(0)) runtime.dispose();
});
function scopeFixture(resetLocal: () => Promise<void>) {
let sessionListener: () => void = () => {};
let token = 0;
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: {
resetLocal,
},
tokenFactory: () => `scope-provider-token-${String(token++).padStart(4, "0")}`,
});
activeRuntimes.push(runtime);
return { runtime, triggerSessionChange: () => sessionListener() };
}
describe("server-state scope provider", () => {
it("removes previous-scope children synchronously while reset is pending", async () => {
let completeReset: () => void = () => {};
const reset = new Promise<void>((resolve) => {
completeReset = resolve;
});
const fixture = scopeFixture(async () => reset);
render(
<ServerStateScopeProvider
runtime={fixture.runtime}
transitionFallback={<div>scope-transition</div>}
>
<div>previous-account-secret</div>
</ServerStateScopeProvider>,
);
expect(screen.getByText("previous-account-secret")).toBeVisible();
act(() => fixture.triggerSessionChange());
expect(screen.queryByText("previous-account-secret")).toBeNull();
expect(screen.getByText("scope-transition")).toBeVisible();
completeReset();
await waitFor(() =>
expect(screen.getByText("previous-account-secret")).toBeVisible(),
);
});
it("never remounts previous-scope children after mandatory cleanup failure", async () => {
const fixture = scopeFixture(async () => {
throw new Error("reset failed");
});
render(
<ServerStateScopeProvider
runtime={fixture.runtime}
transitionFallback={<div>scope-transition</div>}
>
<div>previous-account-secret</div>
</ServerStateScopeProvider>,
);
act(() => fixture.triggerSessionChange());
await waitFor(() => expect(fixture.runtime.getPhase()).toBe("FAILED"));
expect(screen.queryByText("previous-account-secret")).toBeNull();
expect(screen.getByText("scope-transition")).toBeVisible();
});
});