Files
clean-architecture-frontend…/tests/unit/product-session-owner-context.test.ts
DongHyeonka d02efe7bc9 feat(bootstrap): 세션 owner context에 시간 제한 있는 fetch와 페이지를 준다
문제: composeProductSessionOwner는 config와 raw fetcher만 받는다. owner는
http보다 먼저 만들어져 세션 조회·토큰 호출을 직접 해야 하는데, 응답하지
않는 호출 하나가 세션을 recovery-pending에 영원히 둔다. 픽스처의 쿠키
owner 스케치가 바로 그렇게 쓴다. 로그인 리다이렉트에 필요한 페이지
(location·history)와 sessionStorage도 bootstrap lint가 전역 접근을 막아
제품 파일에서 얻을 길이 없다.

고른 방법: ProductSessionOwnerContext에 넷을 더한다.
- fetch: 헤더와 본문 전체에 마감 하나(REQUEST_TIMEOUT_MS가 상한, 호출이
  줄일 수만 있다). 본문은 64 KiB까지 메모리로 읽어 새 Response로 준다.
  redirect는 항상 error. fetcher가 signal을 무시해도 경합으로 끝난다.
- readCookie: composeProduct와 같은 host cookie 읽기.
- page: href·replaceUrl·assign. host에 없으면 throw로 닫힌다.
  replaceUrl은 라우터의 history state를 그대로 둔다.
- redirectStorage: host sessionStorage. 토큰이 아니라 리다이렉트 한 번
  동안의 상태만 둔다고 계약에 적었다.
조립은 새 파일 product-session-owner-context.ts에 두고
runtime-adapters.ts는 호출 한 곳만 바꿨다. fetch 구현
(session-owner-fetch.ts)은 처음 쓸 때 동적 import로 읽는다. 초기 번들
여유가 3 KB 남짓이라 demo 모드나 owner 없는 제품이 이 코드를 내려받지
않게 했다.
버린 대안:
- platform 커널 createAbortableOperation 사용. 커널이 boot가 이미 읽는
  배럴과 같은 청크로 묶여 지연 청크로 빼도 초기 번들에 남았다(빌드로
  확인). 그래서 read-bounded-boot-json.ts와 같은 마감 방식을 쓴다.
- 마감만 주고 본문은 owner가 읽게 두기. 본문이 멈추면 다시 무한 대기다.

위험·한계: fetch는 필수 필드라 ProductSessionOwnerContext를 직접 만드는
제품 테스트는 컴파일이 깨진다. 기존 fetcher는 그대로 둔다. 지연 청크
적재 시간은 마감에 들어가지 않는다(라우트 청크와 같다).

검증: tests/unit/product-session-owner-context.test.ts 12건(구현 전 모듈
없음으로 실패 확인), product-composition-fixture·runtime-adapters 테스트
통과, check:types, eslint 통과. build + check:bundle: initial JS
202,242 / 204,800 B gzip(09-11 포함, 기준 201,848), 지연 청크
session-owner-fetch 0.81 kB gzip.

Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-03
2026-11-04 20:46:40 +09:00

274 lines
9.4 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import type { ProductSessionOwnerContext } from "../../src/bootstrap/product-composition-contract.ts";
import {
createSessionOwnerFetch,
SESSION_OWNER_FETCH_MAXIMUM_BYTES,
} from "../../src/bootstrap/session-owner-fetch.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts";
/**
* 1103/09-03. A session owner is asked for at boot, before `http` exists, and
* the shipped context gave it a raw `fetcher`: a session probe or a token call
* that never answered left the session `recovery-pending` for good. The
* context now carries a fetch with one deadline over the whole exchange.
*/
const fixture = vi.hoisted(() => ({
context: undefined as ProductSessionOwnerContext | undefined,
}));
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
composeProductSessionOwner(context: ProductSessionOwnerContext) {
fixture.context = context;
return null;
},
composeProduct: () => ({ capabilities: {}, credentialProviders: {} }),
}));
const never = () => new Promise<Response>(() => {});
/** A body that sends one chunk and then nothing. */
function stalledBody(): ReadableStream<Uint8Array> {
return new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode("{"));
},
});
}
describe("createSessionOwnerFetch", () => {
it("answers with the whole body read, status and headers kept", async () => {
const fetcher = vi.fn(async () =>
Response.json({ sub: "user-1" }, { status: 201, headers: { "x-extra": "1" } }),
);
const bounded = createSessionOwnerFetch({ fetcher, timeoutMs: 1_000 });
const response = await bounded("https://idp.example/token", {
method: "POST",
credentials: "omit",
});
expect(response.status).toBe(201);
expect(response.headers.get("x-extra")).toBe("1");
await expect(response.json()).resolves.toEqual({ sub: "user-1" });
const [, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit];
expect(init).toMatchObject({
method: "POST",
credentials: "omit",
cache: "no-store",
redirect: "error",
});
expect(init.signal).toBeInstanceOf(AbortSignal);
});
it("refuses to follow a redirect even when asked", async () => {
const fetcher = vi.fn(async () => new Response("{}"));
const bounded = createSessionOwnerFetch({ fetcher, timeoutMs: 1_000 });
await bounded("https://api.example/session", {
redirect: "follow",
} as unknown as Parameters<typeof bounded>[1]);
expect((fetcher.mock.calls[0] as unknown as [string, RequestInit])[1].redirect).toBe("error");
});
it("times out a request that never answers", async () => {
const bounded = createSessionOwnerFetch({ fetcher: never, timeoutMs: 20 });
await expect(bounded("https://api.example/session")).rejects.toMatchObject({
name: "TimeoutError",
});
});
it("times out a body that stops arriving: the deadline covers the body", async () => {
const bounded = createSessionOwnerFetch({
fetcher: async () => new Response(stalledBody()),
timeoutMs: 20,
});
await expect(bounded("https://api.example/session")).rejects.toMatchObject({
name: "TimeoutError",
});
});
it("lets one call shorten the deadline but never extend it", async () => {
const shorter = createSessionOwnerFetch({ fetcher: never, timeoutMs: 10_000 });
const started = Date.now();
await expect(
shorter("https://api.example/session", { timeoutMs: 20 }),
).rejects.toMatchObject({ name: "TimeoutError" });
expect(Date.now() - started).toBeLessThan(5_000);
const capped = createSessionOwnerFetch({ fetcher: never, timeoutMs: 20 });
await expect(
capped("https://api.example/session", { timeoutMs: 60_000 }),
).rejects.toMatchObject({ name: "TimeoutError" });
});
it("stops when the caller aborts", async () => {
const bounded = createSessionOwnerFetch({ fetcher: never, timeoutMs: 10_000 });
const caller = new AbortController();
const pending = bounded("https://api.example/session", { signal: caller.signal });
caller.abort();
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
});
it("refuses a body over the cap and cancels it", async () => {
const cancel = vi.fn();
const chunk = new Uint8Array(SESSION_OWNER_FETCH_MAXIMUM_BYTES);
const body = new ReadableStream<Uint8Array>({
pull(controller) {
controller.enqueue(chunk);
},
cancel,
});
const bounded = createSessionOwnerFetch({
fetcher: async () => new Response(body),
timeoutMs: 1_000,
});
await expect(bounded("https://api.example/session")).rejects.toBeInstanceOf(RangeError);
expect(cancel).toHaveBeenCalled();
});
it("passes the fetcher's own rejection through", async () => {
const bounded = createSessionOwnerFetch({
fetcher: async () => {
throw new TypeError("Failed to fetch");
},
timeoutMs: 1_000,
});
await expect(bounded("https://api.example/session")).rejects.toThrow("Failed to fetch");
});
it("answers a body-less status without a body", async () => {
const bounded = createSessionOwnerFetch({
fetcher: async () => new Response(null, { status: 204 }),
timeoutMs: 1_000,
});
const response = await bounded("https://api.example/sign-out", { method: "POST" });
expect(response.status).toBe(204);
expect(response.body).toBeNull();
});
});
const CONFIG = {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
REQUEST_TIMEOUT_MS: 150,
TELEMETRY_ENABLED: false,
AUTH_MODE: "external",
CONFIG_SCHEMA_VERSION: "2.0",
RELEASE_MANIFEST_URL: "/release-manifest.json",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
} as const;
describe("the session owner context the composition root builds", () => {
let dispose: (() => void) | undefined;
afterEach(() => {
dispose?.();
dispose = undefined;
fixture.context = undefined;
});
async function compose(host: Record<string, unknown>, fetcher: typeof fetch) {
const validated = validateRuntimeConfig(CONFIG);
if (!validated.success) throw new Error(JSON.stringify(validated.issues));
const adapters = await createRuntimeAdapters({
runtime: {
config: validated.data,
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
},
release: {
schemaVersion: 2,
appVersion: "0.1.0",
buildId: "build-a",
commitSha: "abc123",
configSchemaVersion: "2.0",
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: `sha256:${"0".repeat(64)}`,
packages: [],
},
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
},
host,
fetcher,
});
dispose = () => adapters.infrastructure.dispose();
const context = fixture.context;
if (!context) throw new Error("the session owner was not asked");
return context;
}
it("bounds the owner's fetch by REQUEST_TIMEOUT_MS", async () => {
const context = await compose({}, never as unknown as typeof fetch);
await expect(context.fetch("http://localhost:8080/session")).rejects.toMatchObject({
name: "TimeoutError",
});
});
it("reads the page, its session storage and its cookies through the host", async () => {
const replaceState = vi.fn();
const assign = vi.fn();
const storage = new Map<string, string>();
const sessionStorage = {
getItem: (key: string) => storage.get(key) ?? null,
setItem: (key: string, value: string) => void storage.set(key, value),
removeItem: (key: string) => void storage.delete(key),
};
const context = await compose(
{
location: { href: "http://localhost:5173/callback?code=c&state=s", assign },
history: { state: { idx: 3 }, replaceState },
sessionStorage,
document: { cookie: "theme=dark; XSRF-TOKEN=xsrf-1" },
},
(async () => new Response("{}")) as unknown as typeof fetch,
);
expect(context.page.href()).toBe("http://localhost:5173/callback?code=c&state=s");
context.page.replaceUrl("/items?limit=1");
// The router's own history state is kept, so its index survives.
expect(replaceState).toHaveBeenCalledWith({ idx: 3 }, "", "/items?limit=1");
context.page.assign("https://idp.example/auth");
expect(assign).toHaveBeenCalledWith("https://idp.example/auth");
context.redirectStorage?.setItem("k", "v");
expect(storage.get("k")).toBe("v");
expect(context.readCookie("XSRF-TOKEN")).toBe("xsrf-1");
});
it("fails closed when the host has no page", async () => {
const context = await compose({}, (async () => new Response("{}")) as unknown as typeof fetch);
expect(context.redirectStorage).toBeUndefined();
expect(() => context.page.href()).toThrow("page is unavailable");
expect(() => context.page.assign("https://idp.example/auth")).toThrow("page is unavailable");
expect(context.readCookie("XSRF-TOKEN")).toBeUndefined();
});
});