feat: execute route and release recovery contracts

This commit is contained in:
donghyeon-ka
2026-07-26 14:26:39 +09:00
parent a33e93d4d4
commit ce0040e407
49 changed files with 1761 additions and 373 deletions
@@ -0,0 +1,66 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
ChunkRecoveryBoundary,
isChunkLoadFailure,
} from "../../src/presentation/boundaries/chunk-recovery-boundary.js";
import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.jsx";
function ChunkDefect(): never {
throw new TypeError("Failed to fetch dynamically imported module");
}
function RenderDefect(): never {
throw new Error("ordinary render defect");
}
describe("chunk recovery boundary classification", () => {
it("recognizes lazy module failures without classifying ordinary render errors", () => {
expect(
isChunkLoadFailure(
new TypeError("Failed to fetch dynamically imported module"),
),
).toBe(true);
expect(isChunkLoadFailure(new Error("ordinary render defect"))).toBe(false);
});
it("runs the recovery input only for a lazy chunk rejection", async () => {
const recover = vi.fn(async () => ({
action: "support" as const,
reason: "reload-already-attempted",
}));
render(
<ChunkRecoveryBoundary chunkId="route-home" recover={recover}>
<ChunkDefect />
</ChunkRecoveryBoundary>,
);
expect(
await screen.findByRole("heading", {
name: "화면 자산을 복구하지 못했습니다.",
}),
).toBeVisible();
expect(recover).toHaveBeenCalledOnce();
expect(recover).toHaveBeenCalledWith({
chunkId: "route-home",
failureKind: "CHUNK_LOAD_FAILURE",
});
});
it("rethrows an ordinary component defect to the local render boundary", () => {
const recover = vi.fn();
render(
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
<ChunkRecoveryBoundary chunkId="route-home" recover={recover}>
<RenderDefect />
</ChunkRecoveryBoundary>
</FeatureBoundary>,
);
expect(screen.getByRole("alert")).toHaveTextContent("error.render_failure");
expect(recover).not.toHaveBeenCalled();
});
});
+30
View File
@@ -91,4 +91,34 @@ describe("render recovery boundaries", () => {
);
expect(screen.getByText("recovered")).toBeVisible();
});
it("resets a route failure when the registered location key changes", async () => {
let shouldThrow = true;
function RouteContent() {
if (shouldThrow) throw new Error("route defect");
return <p>next route</p>;
}
const view = render(
<FeatureBoundary
routeId="APP_HOME"
buildId="build-a"
resetKey="/first"
>
<RouteContent />
</FeatureBoundary>,
);
expect(screen.getByRole("alert")).toBeVisible();
shouldThrow = false;
view.rerender(
<FeatureBoundary
routeId="APP_HOME"
buildId="build-a"
resetKey="/second"
>
<RouteContent />
</FeatureBoundary>,
);
expect(await screen.findByText("next route")).toBeVisible();
});
});
+37 -3
View File
@@ -2,7 +2,7 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import {
createAnonymousSessionAdapter,
@@ -14,10 +14,13 @@ import { createTestApplication } from "../helpers/create-test-application.js";
/**
* @param {import("../../src/application/ports/auth-session-port.js").AuthSessionPort} session
* @param {Parameters<typeof createTestApplication>[0]} [overrides]
*/
function renderRouter(session) {
function renderRouter(session, overrides = {}) {
return render(
<ApplicationProvider application={createTestApplication({ session })}>
<ApplicationProvider
application={createTestApplication({ ...overrides, session })}
>
<AppRouter />
</ApplicationProvider>,
);
@@ -50,6 +53,10 @@ describe("application router", () => {
await screen.findByRole("heading", { name: "UI 구성요소", level: 1 }),
).toBeVisible();
expect(window.location.pathname).toBe("/examples/ui");
expect(document.title).toBe("UI 구성요소 · Frontend Skeleton");
expect(
screen.getByRole("heading", { name: "UI 구성요소", level: 1 }),
).toHaveFocus();
});
it("reacts to demo sign-in and opens the protected integration route", async () => {
@@ -82,4 +89,31 @@ describe("application router", () => {
screen.getByRole("heading", { name: "세션이 필요합니다." }),
).toBeVisible();
});
it("rejects invalid route search before any application query runs", async () => {
const getCurrent = vi.fn(async () => ({
buildId: "test-build",
releaseId: "test-release",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
routeChunks: { "route-sample-resources": "assets/sample.js" },
}));
window.history.pushState({}, "", "/sample/resources?limit=invalid");
renderRouter(createDemoSessionAdapter("authenticated"), {
releaseInfo: { getCurrent, refresh: getCurrent },
});
expect(
await screen.findByRole("heading", {
name: "올바르지 않은 주소입니다.",
}),
).toBeVisible();
expect(screen.getAllByRole("heading", { level: 1 })).toHaveLength(1);
expect(screen.getByText("안전한 탐색 링크를 사용해 주세요.")).toHaveAttribute(
"data-route-error",
"ROUTE_SEARCH_INVALID",
);
expect(getCurrent).not.toHaveBeenCalled();
});
});
@@ -30,6 +30,14 @@ const releaseManifest = {
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-sample-resources": "assets/sample.js",
"route-not-found": "assets/not-found.js",
},
};
describe("production runtime application tree", () => {
+59
View File
@@ -0,0 +1,59 @@
{
"schemaVersion": 1,
"sourceDirectories": [],
"registries": [
{
"registryId": "ROUTES",
"path": "tests/fixtures/registry/routes/invalid-routes.js",
"exportName": "INVALID_ROUTES",
"owner": "fixture",
"requiredFields": [
"routeId",
"path",
"paramsSchema",
"searchSchema",
"loadingSurface",
"errorSurface",
"chunkId"
],
"uniqueFields": ["routeId", "path", "chunkId"],
"allowedValues": {
"paramsSchema": [null],
"searchSchema": [null],
"loadingSurface": ["app-shell"],
"errorSurface": ["route-boundary"],
"chunkId": ["route-home"]
},
"references": [
{
"field": "routeId",
"registryId": "RUNTIME",
"targetField": "routeId"
}
]
},
{
"registryId": "RUNTIME",
"path": "tests/fixtures/registry/routes/invalid-routes.js",
"exportName": "INVALID_RUNTIME",
"owner": "fixture",
"requiredFields": ["routeId", "moduleId", "paramsCodec", "searchCodec"],
"allowedValues": {
"moduleId": ["home-page"],
"paramsCodec": ["none"],
"searchCodec": ["none"]
},
"references": [
{
"field": "routeId",
"registryId": "ROUTES",
"targetField": "routeId"
}
]
}
],
"compatibilityImpact": {
"allowed": ["none", "additive", "behavior-change", "breaking"],
"current": "breaking"
}
}
+29
View File
@@ -0,0 +1,29 @@
export const INVALID_ROUTES = {
FIRST: {
routeId: "DUPLICATE",
path: "/duplicate",
paramsSchema: "UnknownParams",
searchSchema: "UnknownSearch",
loadingSurface: "unknown-loading",
errorSurface: "unknown-error",
chunkId: "unknown-chunk",
},
SECOND: {
routeId: "DUPLICATE",
path: "/duplicate",
paramsSchema: null,
searchSchema: null,
loadingSurface: "app-shell",
errorSurface: "route-boundary",
chunkId: "route-home",
},
};
export const INVALID_RUNTIME = {
ORPHAN: {
routeId: "ORPHAN",
moduleId: "unknown-module",
paramsCodec: "none",
searchCodec: "none",
},
};
+14
View File
@@ -0,0 +1,14 @@
import { ROUTE_RUNTIME_CONTRACT } from "../../../src/contracts/route-runtime-contract.js";
type RouteId = keyof typeof ROUTE_RUNTIME_CONTRACT;
export const missingRuntime = {
APP_HOME: true,
} satisfies Record<RouteId, boolean>;
export const orphanRuntime = {
...Object.fromEntries(
Object.keys(ROUTE_RUNTIME_CONTRACT).map((routeId) => [routeId, true]),
),
ORPHAN_ROUTE: true,
} satisfies Record<RouteId, boolean>;
+18 -1
View File
@@ -6,7 +6,8 @@ import { createApplication } from "../../src/application/create-application.js";
* session?: import("../../src/application/ports/auth-session-port.js").AuthSessionPort,
* preferences?: import("../../src/application/ports/storage-port.js").StoragePort,
* diagnostics?: import("../../src/application/ports/telemetry-port.js").TelemetryPort,
* releaseInfo?: import("../../src/application/ports/release-info-port.js").ReleaseInfoPort
* releaseInfo?: import("../../src/application/ports/release-info-port.js").ReleaseInfoPort,
* navigation?: { reload(): void }
* }} [overrides]
*/
export function createTestApplication(overrides = {}) {
@@ -29,7 +30,23 @@ export function createTestApplication(overrides = {}) {
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
routeChunks: {
"route-home": "assets/home.js",
"route-sample-resources": "assets/sample.js",
},
}),
refresh: async () => ({
buildId: "test-build",
releaseId: "test-release",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
routeChunks: {
"route-home": "assets/home.js",
"route-sample-resources": "assets/sample.js",
},
}),
},
navigation: overrides.navigation ?? { reload: () => {} },
});
}
@@ -25,6 +25,7 @@ const manifest = {
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
};
describe("release manifest boot boundary", () => {
@@ -46,6 +47,62 @@ describe("release manifest boot boundary", () => {
new Response(JSON.stringify({ ...manifest, buildId: "build-b" })),
},
),
).rejects.toMatchObject({
kind: "BUILD_MISMATCH",
code: "MANIFEST_BUILD_MISMATCH",
});
});
it.each([
[
{ configSchemaVersion: "2" },
{},
"CONFIG_MISMATCH",
"MANIFEST_CONFIG_SCHEMA_MISMATCH",
],
[
{ apiContractVersion: "2" },
{},
"API_CONTRACT_MISMATCH",
"MANIFEST_API_CONTRACT_MISMATCH",
],
[
{ releaseId: "release-b" },
{},
"RELEASE_MISMATCH",
"MANIFEST_RELEASE_MISMATCH",
],
[
{},
{ expectedAssetManifestHash: "different" },
"ASSET_MISMATCH",
"MANIFEST_ASSET_MISMATCH",
],
])(
"classifies tuple mismatch %# without a generic deploy error",
async (manifestOverride, options, kind, code) => {
await expect(
loadReleaseManifest(
/** @type {Parameters<typeof loadReleaseManifest>[0]} */ (runtime),
{
fetcher: async () =>
Response.json({ ...manifest, ...manifestOverride }),
...options,
},
),
).rejects.toMatchObject({ kind, code });
},
);
it("rejects a manifest without a complete route chunk map", async () => {
const malformed = Object.fromEntries(
Object.entries(manifest).filter(([key]) => key !== "routeChunks"),
);
await expect(
loadReleaseManifest(
/** @type {Parameters<typeof loadReleaseManifest>[0]} */ (runtime),
{ fetcher: async () => Response.json(malformed) },
),
).rejects.toBeInstanceOf(ReleaseManifestError);
});
});
+11
View File
@@ -15,6 +15,7 @@ describe("application input/output boundary", () => {
"preferences",
"diagnostics",
"runtime",
"recovery",
]);
expect(application).not.toHaveProperty("storage");
expect(application).not.toHaveProperty("telemetry");
@@ -51,8 +52,18 @@ describe("application input/output boundary", () => {
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "hash-a",
routeChunks: { "route-home": "assets/home.js" },
}),
refresh: async () => ({
buildId: "build-a",
releaseId: "release-a",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "hash-a",
routeChunks: { "route-home": "assets/home.js" },
}),
},
navigation: { reload: () => {} },
} satisfies ApplicationOutputPorts;
const application = createApplication(ports);
+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it, vi } from "vitest";
import { createApplication } from "../../src/application/create-application.js";
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js";
import type { StoragePort } from "../../src/application/ports/storage-port.js";
type ReleaseFixture = {
buildId: string;
releaseId: string;
configSchemaVersion: string;
apiContractVersion: string;
assetManifestHash: string;
routeChunks: Record<string, string>;
};
function release(buildId: string, releaseId: string): ReleaseFixture {
return {
buildId,
releaseId,
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: `${buildId}-assets`,
routeChunks: { "route-home": `assets/${buildId}-home.js` },
};
}
function memoryStorage(): StoragePort {
let value: unknown;
return {
read: () => ({ ok: true, value }),
write: (_name, next) => {
value = next;
return { ok: true };
},
remove: () => ({ ok: true }),
};
}
function applicationWith(options: {
storage?: StoragePort;
refresh?: () => Promise<ReturnType<typeof release>>;
reload?: () => void;
}) {
const current = release("build-a", "release-a");
return createApplication({
session: createAnonymousSessionAdapter(),
preferences: options.storage ?? memoryStorage(),
diagnostics: { emit: () => {} },
releaseInfo: {
getCurrent: async () => current,
refresh:
options.refresh ??
(async () => release("build-b", "release-b")),
},
navigation: { reload: options.reload ?? (() => {}) },
});
}
describe("production chunk recovery application input", () => {
it("reloads exactly once for one active build/release pair", async () => {
const reload = vi.fn();
const application = applicationWith({ reload });
const input = {
chunkId: "route-home",
failureKind: "CHUNK_LOAD_FAILURE" as const,
};
await expect(application.recovery.recoverChunk(input)).resolves.toEqual({
action: "reload-once",
releasePair: "build-a/release-a->build-b/release-b",
});
await expect(application.recovery.recoverChunk(input)).resolves.toEqual({
action: "support",
reason: "reload-already-attempted",
});
expect(reload).toHaveBeenCalledOnce();
});
it.each([
[
{
refresh: async () => {
throw new Error("offline");
},
},
"manifest-unavailable",
],
[
{
refresh: async () => ({
...release("build-b", "release-b"),
routeChunks: {},
}),
},
"active-chunk-unknown",
],
[
{
storage: {
read: () => ({
ok: false as const,
error: {
kind: "STORAGE_UNAVAILABLE",
code: "STORAGE_UNAVAILABLE",
retryable: false,
operationId: "STORAGE",
attemptCount: 1,
userMessageKey: "error.storage_unavailable",
action: "none" as const,
},
}),
write: () => ({ ok: true as const }),
remove: () => ({ ok: true as const }),
},
},
"guard-read-failed",
],
])("fails closed for recovery dependency case %#", async (options, reason) => {
const reload = vi.fn();
const application = applicationWith({ ...options, reload });
await expect(
application.recovery.recoverChunk({
chunkId: "route-home",
failureKind: "CHUNK_LOAD_FAILURE",
}),
).resolves.toEqual({ action: "support", reason });
expect(reload).not.toHaveBeenCalled();
});
});
+9 -2
View File
@@ -22,12 +22,14 @@ describe("controlled chunk recovery", () => {
failureKind: "CHUNK_LOAD_FAILURE",
manifestLoaded: true,
currentBuildId: "build-a",
currentReleaseId: "release-a",
activeBuildId: "build-b",
activeReleaseId: "release-b",
storage,
};
expect(decideChunkRecovery(input)).toEqual({
action: "reload-once",
releasePair: "build-a->release-b",
releasePair: "build-a/release-a->build-b/release-b",
});
expect(decideChunkRecovery(input)).toEqual({
action: "support",
@@ -38,12 +40,17 @@ describe("controlled chunk recovery", () => {
it.each([
[{ failureKind: "SERVER_FAILURE" }, "not-recoverable"],
[{ manifestLoaded: false }, "manifest-unavailable"],
[{ activeReleaseId: "build-a" }, "same-release"],
[
{ activeBuildId: "build-a", activeReleaseId: "release-a" },
"same-release",
],
])("stops when a recovery invariant fails: %#", (override, reason) => {
const result = decideChunkRecovery({
failureKind: "DEPLOY_MISMATCH",
manifestLoaded: true,
currentBuildId: "build-a",
currentReleaseId: "release-a",
activeBuildId: "build-b",
activeReleaseId: "release-b",
storage: memoryStorage(),
...override,
+1 -1
View File
@@ -9,7 +9,7 @@ import {
describe("frontend failure classification", () => {
it("defines all 26 stable error kinds with the seven contract fields", () => {
expect(Object.keys(ERROR_REGISTRY)).toHaveLength(26);
expect(Object.keys(ERROR_REGISTRY)).toHaveLength(31);
for (const definition of Object.values(ERROR_REGISTRY)) {
expect(definition).toEqual(
expect.objectContaining({
+5 -2
View File
@@ -72,7 +72,7 @@ describe("route registry", () => {
"loadingSurface": "none",
"navigationLabel": null,
"navigationOrder": null,
"paramsSchema": null,
"paramsSchema": "NotFoundSplat",
"path": "*",
"routeId": "NOT_FOUND",
"searchSchema": null,
@@ -121,9 +121,12 @@ describe("route registry", () => {
});
it("allows at most one automatic redirect per source-target pair", () => {
const guard = createRedirectLoopGuard();
const guard = createRedirectLoopGuard(2);
expect(guard.allow("/private", "/signin")).toBe(true);
expect(guard.allow("/private", "/signin")).toBe(false);
expect(guard.allow("/signin", "/signin")).toBe(false);
expect(guard.allow("/signin", "/continue")).toBe(true);
expect(guard.allow("/continue", "/final")).toBe(false);
expect(guard.hopCount).toBe(2);
});
});
+3 -3
View File
@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
describe("registry governance manifest", () => {
it("declares exactly eight single-owner registries and impact labels", async () => {
it("declares exactly nine single-owner registries and impact labels", async () => {
const governance = JSON.parse(
await readFile("config/contracts/registry-governance.json", "utf8"),
);
@@ -10,9 +10,9 @@ describe("registry governance manifest", () => {
/** @type {Array<{registryId: string, owner: string}>} */ (
governance.registries
);
expect(governance.registries).toHaveLength(8);
expect(governance.registries).toHaveLength(9);
expect(new Set(registries.map((entry) => entry.registryId)).size).toBe(
8,
9,
);
expect(registries.every((entry) => entry.owner)).toBe(true);
expect(governance.compatibilityImpact.allowed).toEqual([
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vitest";
import { ROUTE_RUNTIME_CONTRACT } from "../../src/contracts/route-runtime-contract.js";
import { ROUTE_REGISTRY } from "../../src/contracts/routes.js";
import {
buildRouteUrl,
parseRouteInput,
} from "../../src/presentation/routes/route-codecs.js";
import { ROUTE_RUNTIME } from "../../src/presentation/routes/route-runtime.js";
describe("typed route contract and runtime", () => {
it("keeps contract, runtime contribution, and executable module complete", () => {
expect(Object.keys(ROUTE_RUNTIME_CONTRACT).sort()).toEqual(
Object.keys(ROUTE_REGISTRY).sort(),
);
expect(Object.keys(ROUTE_RUNTIME).sort()).toEqual(
Object.keys(ROUTE_REGISTRY).sort(),
);
});
it("round-trips canonical search through the registered codec", () => {
const url = buildRouteUrl("SAMPLE_RESOURCE_LIST", {
search: {
tags: ["open", "new"],
cursor: "a/b",
limit: 5,
},
});
expect(url).toBe(
"/sample/resources?cursor=a%2Fb&limit=5&tags=open&tags=new",
);
const parsedUrl = new URL(url, "https://app.test");
expect(
parseRouteInput(
"SAMPLE_RESOURCE_LIST",
{},
parsedUrl.searchParams,
),
).toEqual({
success: true,
data: {
routeId: "SAMPLE_RESOURCE_LIST",
params: {},
search: {
cursor: "a/b",
limit: 5,
tags: ["open", "new"],
},
},
});
});
it("rejects unknown search and accepts the not-found splat owner", () => {
expect(
parseRouteInput(
"SAMPLE_RESOURCE_LIST",
{},
new URLSearchParams("unknown=value"),
),
).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" });
expect(
parseRouteInput(
"NOT_FOUND",
{ "*": "missing/path" },
new URLSearchParams(),
),
).toMatchObject({ success: true });
});
});
+30
View File
@@ -13,6 +13,7 @@ const runtime = {
AUTH_MODE: "demo",
REQUEST_TIMEOUT_MS: 4321,
MAX_RETRY_ATTEMPTS: 0,
RELEASE_MANIFEST_URL: "/release-manifest.json",
},
};
const release = /** @type {const} */ ({
@@ -25,6 +26,7 @@ const release = /** @type {const} */ ({
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
});
describe("runtime adapter composition", () => {
@@ -59,6 +61,34 @@ describe("runtime adapter composition", () => {
expect(adapters.outputPorts.session.getState()).toBe("integration-failed");
});
it("refetches the active release manifest with no-store semantics", async () => {
const activeRelease = {
...release,
buildId: "build-b",
releaseId: "release-b",
routeChunks: { "route-home": "assets/home-b.js" },
};
const fetcher = vi.fn(async () => Response.json(activeRelease));
const adapters = await createRuntimeAdapters({
runtime:
/** @type {Parameters<typeof createRuntimeAdapters>[0]["runtime"]} */ (
runtime
),
release,
fetcher,
host: {},
});
await expect(adapters.outputPorts.releaseInfo.refresh()).resolves.toMatchObject({
buildId: "build-b",
releaseId: "release-b",
});
expect(fetcher).toHaveBeenCalledWith("/release-manifest.json", {
cache: "no-store",
headers: { Accept: "application/json" },
});
});
it("injects runtime timeout and max-attempt policy into HTTP execution", async () => {
const scheduled =
/** @type {Array<{callback: () => void, milliseconds: number}>} */ ([]);