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
This commit is contained in:
@@ -12,6 +12,28 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts";
|
||||
* profiles and runtime-config keys) and never edits `runtime-adapters.ts`.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 1103/09-03. A fetch with one deadline over the whole exchange (at most
|
||||
* `REQUEST_TIMEOUT_MS`; `timeoutMs` may shorten it) and the body read into
|
||||
* memory, at most 64 KiB. Rejects with a `TimeoutError` or `AbortError`
|
||||
* DOMException, or a `RangeError` for a larger body. Redirects are refused.
|
||||
*/
|
||||
export type SessionOwnerFetch = (
|
||||
input: string | URL,
|
||||
init?: Omit<RequestInit, "signal" | "redirect"> &
|
||||
Readonly<{ signal?: AbortSignal; timeoutMs?: number }>,
|
||||
) => Promise<Response>;
|
||||
|
||||
/** The page a sign-in redirect leaves and returns to. Each throws without one. */
|
||||
export type ProductSessionOwnerPage = Readonly<{
|
||||
/** The current URL. */
|
||||
href(): string;
|
||||
/** Replaces the current entry without loading, e.g. to drop a sign-in callback query. */
|
||||
replaceUrl(url: string): void;
|
||||
/** Loads another page: the identity provider's sign-in or sign-out. */
|
||||
assign(url: string): void;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* What a product session owner is built from. It is asked first, before
|
||||
* `http` exists (`http` needs the session), so it gets no capability.
|
||||
@@ -19,7 +41,19 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts";
|
||||
export type ProductSessionOwnerContext = Readonly<{
|
||||
/** Validated runtime config, product keys included. */
|
||||
config: RuntimeConfig;
|
||||
/** Unbounded; prefer `fetch`. */
|
||||
fetcher?: typeof fetch;
|
||||
/** 1103/09-03. Use this one: a probe or token call cannot hang the session. */
|
||||
fetch: SessionOwnerFetch;
|
||||
/** A cookie of the page (double-submit CSRF), read when called. */
|
||||
readCookie(name: string): string | undefined;
|
||||
page: ProductSessionOwnerPage;
|
||||
/**
|
||||
* The page's session storage, when there is one: what must survive a
|
||||
* sign-in redirect and nothing longer. Never a token (`AUTH_TOKEN` is
|
||||
* `forbidden` in `src/contracts/storage-keys.ts`).
|
||||
*/
|
||||
redirectStorage?: Pick<Storage, "getItem" | "setItem" | "removeItem">;
|
||||
}>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import type {
|
||||
ProductSessionOwnerContext,
|
||||
ProductSessionOwnerPage,
|
||||
SessionOwnerFetch,
|
||||
} from "./product-composition-contract.ts";
|
||||
import type { RuntimeConfig } from "./runtime-config-schema.ts";
|
||||
|
||||
/**
|
||||
* 1103/09-03. What the composition root hands a product session owner. The
|
||||
* owner is asked at boot, before `http` exists, so it talks to its session
|
||||
* endpoint or identity provider itself; these are the host facilities it needs
|
||||
* for that, each bounded or fail-closed.
|
||||
*/
|
||||
|
||||
/**
|
||||
* `session-owner-fetch.ts` on first use. The initial bundle has no headroom
|
||||
* for code only an external-mode product owner runs; the chunk is the size of
|
||||
* a route chunk and loads the same way.
|
||||
*/
|
||||
function lazySessionOwnerFetch(
|
||||
options: Readonly<{ fetcher?: typeof fetch; timeoutMs: number }>,
|
||||
): SessionOwnerFetch {
|
||||
let loaded: Promise<SessionOwnerFetch> | null = null;
|
||||
return (input, init) => {
|
||||
loaded ??= import("./session-owner-fetch.ts").then(
|
||||
({ createSessionOwnerFetch }) => createSessionOwnerFetch(options),
|
||||
(error: unknown) => {
|
||||
loaded = null;
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
return loaded.then((bounded) => bounded(input, init));
|
||||
};
|
||||
}
|
||||
|
||||
function hostMember(target: unknown, name: string): unknown {
|
||||
if (!target || typeof target !== "object") return undefined;
|
||||
try {
|
||||
return Reflect.get(target, name);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The page, read from the host when called. A host without `location` or
|
||||
* `history` (a worker, a test) throws, so an owner that needs the page fails
|
||||
* closed instead of signing in somewhere else.
|
||||
*/
|
||||
function hostPage(host: Record<string, unknown>): ProductSessionOwnerPage {
|
||||
const unavailable = (): never => {
|
||||
throw new TypeError("The page is unavailable to the session owner.");
|
||||
};
|
||||
const location = () => hostMember(host, "location");
|
||||
return Object.freeze({
|
||||
href() {
|
||||
const href = hostMember(location(), "href");
|
||||
return typeof href === "string" ? href : unavailable();
|
||||
},
|
||||
replaceUrl(url: string) {
|
||||
const history = hostMember(host, "history");
|
||||
const replaceState = hostMember(history, "replaceState");
|
||||
if (typeof replaceState !== "function") unavailable();
|
||||
// The router keeps its own entry state; replacing it would lose its index.
|
||||
Reflect.apply(replaceState as (...args: unknown[]) => void, history, [
|
||||
hostMember(history, "state") ?? null,
|
||||
"",
|
||||
url,
|
||||
]);
|
||||
},
|
||||
assign(url: string) {
|
||||
const page = location();
|
||||
const assign = hostMember(page, "assign");
|
||||
if (typeof assign !== "function") unavailable();
|
||||
Reflect.apply(assign as (url: string) => void, page, [url]);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function createProductSessionOwnerContext(
|
||||
host: Record<string, unknown>,
|
||||
input: Readonly<{
|
||||
config: RuntimeConfig;
|
||||
fetcher?: typeof fetch;
|
||||
readCookie(name: string): string | undefined;
|
||||
redirectStorage?: Storage;
|
||||
}>,
|
||||
): ProductSessionOwnerContext {
|
||||
return Object.freeze({
|
||||
config: input.config,
|
||||
...(input.fetcher === undefined ? {} : { fetcher: input.fetcher }),
|
||||
fetch: lazySessionOwnerFetch({
|
||||
...(input.fetcher === undefined ? {} : { fetcher: input.fetcher }),
|
||||
timeoutMs: input.config.REQUEST_TIMEOUT_MS,
|
||||
}),
|
||||
readCookie: input.readCookie,
|
||||
page: hostPage(host),
|
||||
...(input.redirectStorage === undefined
|
||||
? {}
|
||||
: { redirectStorage: input.redirectStorage }),
|
||||
});
|
||||
}
|
||||
@@ -63,6 +63,7 @@ import {
|
||||
composeProductSessionOwner,
|
||||
} from "./product-composition.ts";
|
||||
import type { ProductComposition } from "./product-composition-contract.ts";
|
||||
import { createProductSessionOwnerContext } from "./product-session-owner-context.ts";
|
||||
import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts";
|
||||
import {
|
||||
indexInvalidationRegistry,
|
||||
@@ -284,10 +285,15 @@ export async function createRuntimeAdapters(
|
||||
const externalOwner =
|
||||
config.AUTH_MODE === "demo"
|
||||
? null
|
||||
: (composeProductSessionOwner({
|
||||
config,
|
||||
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
|
||||
}) ?? externalOwnerFrom(host));
|
||||
: (composeProductSessionOwner(
|
||||
// 1103/09-03. A bounded fetch, the page and its cookies.
|
||||
createProductSessionOwnerContext(host, {
|
||||
config,
|
||||
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
|
||||
readCookie: (name) => hostCookie(host, name),
|
||||
redirectStorage: storageOrUndefined(hostValue(host, "sessionStorage")),
|
||||
}),
|
||||
) ?? externalOwnerFrom(host));
|
||||
const authSession =
|
||||
config.AUTH_MODE === "demo"
|
||||
? createDemoSessionAdapter()
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { SessionOwnerFetch } from "./product-composition-contract.ts";
|
||||
|
||||
/**
|
||||
* 1103/09-03. The fetch a product session owner gets. Loaded on first use,
|
||||
* from `product-session-owner-context.ts`, so it costs the initial bundle
|
||||
* nothing in demo mode or without a product owner. It does not use the
|
||||
* platform kernel's `createAbortableOperation`: the kernel shares a chunk
|
||||
* with the barrel boot already imports, so it would land in the initial
|
||||
* bundle after all. The deadline is the one `read-bounded-boot-json.ts` uses.
|
||||
*/
|
||||
|
||||
/** A session or token response is a few KiB; this is the most an owner buffers. */
|
||||
export const SESSION_OWNER_FETCH_MAXIMUM_BYTES = 65_536;
|
||||
|
||||
/** Statuses whose `Response` cannot carry a body. */
|
||||
const NULL_BODY_STATUSES: ReadonlySet<number> = new Set([101, 103, 204, 205, 304]);
|
||||
|
||||
/**
|
||||
* One deadline over the whole exchange, headers and body. The body is read
|
||||
* into memory up to `maximumBytes` and handed back as a fresh `Response`, so
|
||||
* the owner reads it without a second, unbounded wait. `timeoutMs` is a
|
||||
* ceiling: a call may shorten it, never extend it. Redirects are refused: a
|
||||
* session endpoint that redirects to a sign-in page must not read as an
|
||||
* answer.
|
||||
*/
|
||||
export function createSessionOwnerFetch(
|
||||
options: Readonly<{
|
||||
fetcher?: typeof fetch;
|
||||
timeoutMs: number;
|
||||
maximumBytes?: number;
|
||||
}>,
|
||||
): SessionOwnerFetch {
|
||||
const fetcher = options.fetcher ?? fetch;
|
||||
const maximumBytes = options.maximumBytes ?? SESSION_OWNER_FETCH_MAXIMUM_BYTES;
|
||||
return async (input, init = {}) => {
|
||||
const { signal, timeoutMs, ...request } = init;
|
||||
const controller = new AbortController();
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(
|
||||
() => {
|
||||
timedOut = true;
|
||||
controller.abort();
|
||||
},
|
||||
Math.min(timeoutMs ?? options.timeoutMs, options.timeoutMs),
|
||||
);
|
||||
const forwardAbort = () => controller.abort();
|
||||
if (signal?.aborted) controller.abort();
|
||||
else signal?.addEventListener("abort", forwardAbort, { once: true });
|
||||
// Raced, not only signalled: a fetcher that ignores the signal is still
|
||||
// bounded, and so is a body stream that stops sending.
|
||||
const stopped = new Promise<never>((_, reject) => {
|
||||
const stop = () =>
|
||||
reject(
|
||||
timedOut
|
||||
? new DOMException("The session owner request timed out.", "TimeoutError")
|
||||
: new DOMException("The session owner request was aborted.", "AbortError"),
|
||||
);
|
||||
if (controller.signal.aborted) stop();
|
||||
else controller.signal.addEventListener("abort", stop, { once: true });
|
||||
});
|
||||
stopped.catch(() => undefined);
|
||||
const sending = Promise.resolve().then(() =>
|
||||
fetcher(input, {
|
||||
cache: "no-store",
|
||||
...request,
|
||||
redirect: "error",
|
||||
signal: controller.signal,
|
||||
}),
|
||||
);
|
||||
// A response that lands after the deadline is released, not left open.
|
||||
void sending.then(
|
||||
(late) => {
|
||||
if (controller.signal.aborted) void late.body?.cancel().catch(() => undefined);
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
try {
|
||||
const response = await Promise.race([sending, stopped]);
|
||||
const reading = readBody(response, maximumBytes, controller.signal);
|
||||
reading.catch(() => undefined);
|
||||
const bytes = await Promise.race([reading, stopped]);
|
||||
return new Response(NULL_BODY_STATUSES.has(response.status) ? null : bytes, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: response.headers,
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", forwardAbort);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function readBody(
|
||||
response: Response,
|
||||
maximumBytes: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<Uint8Array<ArrayBuffer>> {
|
||||
const declared = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(declared) && declared > maximumBytes) {
|
||||
void response.body?.cancel().catch(() => undefined);
|
||||
throw new RangeError("The session owner response is too large.");
|
||||
}
|
||||
const body = response.body;
|
||||
if (!body) return new Uint8Array(0);
|
||||
const reader = body.getReader();
|
||||
// The deadline releases the stream even when the fetcher ignored the signal.
|
||||
signal.addEventListener("abort", () => void reader.cancel().catch(() => undefined), {
|
||||
once: true,
|
||||
});
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
total += value.byteLength;
|
||||
if (total > maximumBytes) {
|
||||
throw new RangeError("The session owner response is too large.");
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} catch (error) {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
Reference in New Issue
Block a user