문제: browser-files runtime은 세션을 모르고, 닫는 수단은 runtime.dispose() 하나다. 설계 문서는 로그아웃·계정 전환에 "server-state scope reset participant로 dispose()를 등록하라"며 템플릿 소유 파일 runtime-adapters.ts를 가리키는데, 매뉴얼은 제품이 그 파일을 고치지 않는다고 한다(09-02). 제품 확장 지점 composeProduct는 부팅 때 한 번 불리고, context에 participant 등록도 lifecycle 구독도 없다. 그래서 연결하지 않으면 이전 사용자가 고른 File, preview blob URL, 진행 중 download가 다음 세션까지 남는다(공유 기기에서 이전 사용자 파일이 메모리와 다운로드 폴더에 남을 수 있다). 고른 방법(리뷰 5.3절 (다) + 레시피 예제): - ProductComposition에 선택 칸 scopeParticipants(ProductScopeParticipant: label, close)를 둔다. 템플릿은 scope reset의 §10.6 10단계(offline lease 해제) 자리에 "product" participant 하나를 두고, composeProduct가 돌려준 것을 순서대로 부른다. 하나가 실패해도 나머지를 부르고, 실패가 있으면 template participant와 같이 READY로 가지 않는다(FAILED). composeProduct는 scope가 생긴 뒤 불리므로(context가 fence를 쓴다) 이 자리를 미리 만들고 나중에 채운다. - recipes/frontend-capabilities/browser-file-session-capability.ts: 기능에는 runtime 대신 current() getter를 주고, participant가 dispose한 뒤 다음 호출에서 새 runtime을 만든다. indexeddb 레시피와 같은 자리다. - 설계 문서와 매뉴얼 03 C절이 이 방법을 가리킨다. 제거 드릴이 새 레시피 파일도 같이 지운다. 버린 대안: (가) 문서만 고침 — feature presentation은 adapter를 만들 수 없어 제품마다 factory를 다시 설계한다. (나) context에 lifecycle 구독 위임 — FENCED → participant → READY 순서와 "실패는 READY를 막는다"를 제품이 직접 지켜야 한다. (라) runtime이 세대 AbortSignal을 받음 — adapter가 세대를 알게 되고 다른 opt-in runtime도 따로 받아야 한다. 위험·한계: - 제품 계약 표면이 하나 는다(선택 칸이라 기존 제품 파일은 그대로 컴파일된다, [계약]). - 기능은 current()를 작업마다 불러야 한다. 이전 세대에서 받은 runtime을 들고 있으면 UNAVAILABLE을 받는다. FENCED 동안 current()를 부르면 다음 세대 runtime이 미리 만들어진다(빈 runtime이라 이전 사용자 데이터는 없다). - app dispose(infrastructure.dispose)는 제품 participant를 부르지 않는다. - 실제 브라우저 2탭 로그아웃 E2E는 없다(조립된 화면이 없다). - scripts/test-browser-file-storage-runtime-removal.ts는 02-06 담당 작업도 고칠 수 있는 파일이다. runtimePaths에 한 줄만 더했다. 검증: - RED: tests/recipes/browser-file-session-capability.test.ts가 계정 전환 뒤에도 이전 runtime의 readRange가 ok로 실패. - GREEN: 같은 테스트에서 계정 전환 뒤 ① 이전 runtime readRange UNAVAILABLE ② 진행 중 bounded download ABORTED, handoff 0회 ③ 새 세대 runtime의 파일 선택 SELECTED. tests/unit/runtime-adapters-product-scope- participants.test.ts 2건(순서, 실패 시 FAILED와 나머지 실행). - 변이 4개(등록 누락, 실패 삼킴, 첫 실패에서 멈춤, 레시피 dispose 누락) 모두 새 테스트가 잡았다. - runtime-adapters 관련 unit 3파일 + tests/recipes 47건 통과. check:types, 바꾼 파일 eslint, check:architecture, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 02-01
285 lines
8.4 KiB
TypeScript
285 lines
8.4 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import type { LocalFileRef } from "../../src/application/ports/browser-file-storage/index.ts";
|
|
import {
|
|
browserFilePolicyReference,
|
|
createBrowserFileRuntime,
|
|
type BrowserFilePolicyProfile,
|
|
} from "../../src/adapters/browser-files/index.ts";
|
|
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
|
|
import { createSessionBrowserFileCapability } from "../../recipes/frontend-capabilities/browser-file-session-capability.ts";
|
|
|
|
/**
|
|
* 2026-11-03 02-01. A product wires the browser file runtime to the session by
|
|
* filling only its own `product-composition.ts`: the recipe capability goes to
|
|
* features, its scope participant to the template. The real
|
|
* `createRuntimeAdapters` runs; only the product-owned file is replaced, with
|
|
* what a product would write in it.
|
|
*/
|
|
|
|
const selectPolicy = browserFilePolicyReference("session-file", "select-text");
|
|
const downloadPolicy = browserFilePolicyReference(
|
|
"session-download",
|
|
"bounded-generated-bin",
|
|
);
|
|
const policies: readonly BrowserFilePolicyProfile[] = [
|
|
{
|
|
reference: selectPolicy,
|
|
selection: {
|
|
policyId: "attachment-v1",
|
|
purpose: "attachment",
|
|
classification: "PERSONAL",
|
|
multiple: false,
|
|
maxCount: 1,
|
|
maxFileBytes: 8,
|
|
maxTotalBytes: 8,
|
|
allowEmpty: false,
|
|
accept: [{ mediaType: "text/plain", extensions: [".txt"] }],
|
|
},
|
|
},
|
|
{
|
|
reference: downloadPolicy,
|
|
download: {
|
|
strategy: "BOUNDED_OBJECT_URL",
|
|
mediaType: "application/octet-stream",
|
|
safeExtension: ".bin",
|
|
maxTransferBytes: 8,
|
|
maxBufferedBytes: 8,
|
|
integrity: "OPTIONAL",
|
|
},
|
|
},
|
|
];
|
|
|
|
const fixture = vi.hoisted(() => ({
|
|
files: undefined as
|
|
| ReturnType<typeof createSessionBrowserFileCapability>["files"]
|
|
| undefined,
|
|
inputs: [] as HTMLInputElement[],
|
|
handoffs: 0,
|
|
owner: undefined as
|
|
| Readonly<{ switchUser(subject: string): void }>
|
|
| undefined,
|
|
}));
|
|
|
|
function fileInput(): HTMLInputElement {
|
|
const input = document.createElement("input");
|
|
input.type = "file";
|
|
input.setAttribute("aria-label", "Attachment");
|
|
Object.defineProperty(input, "click", { configurable: true, value: vi.fn() });
|
|
document.body.append(input);
|
|
fixture.inputs.push(input);
|
|
return input;
|
|
}
|
|
|
|
function externalOwner() {
|
|
const listeners = new Set<() => void>();
|
|
let subject = "user-a";
|
|
return {
|
|
readState: () => "authenticated",
|
|
readSubject: () => subject,
|
|
subscribe(listener: () => void) {
|
|
listeners.add(listener);
|
|
return () => listeners.delete(listener);
|
|
},
|
|
beginSignIn: async () => {},
|
|
signOut: async () => {},
|
|
attachCredential: async () => ({ headers: {} }),
|
|
recoverSession: async () => "no-session",
|
|
notifyUnauthenticated: () => {},
|
|
switchUser(next: string) {
|
|
subject = next;
|
|
for (const listener of listeners) listener();
|
|
},
|
|
};
|
|
}
|
|
|
|
/** The product-owned file, filled the way a product fills it. */
|
|
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
|
|
composeProductSessionOwner: () => {
|
|
const owner = externalOwner();
|
|
fixture.owner = owner;
|
|
return owner;
|
|
},
|
|
composeProduct: () => {
|
|
const browserFiles = createSessionBrowserFileCapability(() =>
|
|
createBrowserFileRuntime({
|
|
input: fileInput(),
|
|
policies,
|
|
limits: {
|
|
hardMaxPreviewBytes: 8,
|
|
hardMaxObjectUrlBytes: 8,
|
|
hardMaxTransferBytes: 16,
|
|
},
|
|
objectUrlApi: {
|
|
createObjectURL: () => "blob:session-download",
|
|
revokeObjectURL() {},
|
|
},
|
|
download: {
|
|
host: {
|
|
handoff() {
|
|
fixture.handoffs += 1;
|
|
},
|
|
},
|
|
browserManagedCapabilities: {
|
|
resolve: () => ({
|
|
ok: false as const,
|
|
error: {
|
|
code: "POLICY_REJECTED" as const,
|
|
operation: "DOWNLOAD" as const,
|
|
retryable: false,
|
|
recovery: "NONE" as const,
|
|
},
|
|
}),
|
|
},
|
|
},
|
|
}),
|
|
);
|
|
fixture.files = browserFiles.files;
|
|
return {
|
|
capabilities: {},
|
|
credentialProviders: {},
|
|
scopeParticipants: [browserFiles.scopeParticipant],
|
|
};
|
|
},
|
|
}));
|
|
|
|
let current: Awaited<ReturnType<typeof createRuntimeAdapters>> | undefined;
|
|
afterEach(() => {
|
|
current?.infrastructure.dispose();
|
|
current = undefined;
|
|
for (const input of fixture.inputs.splice(0)) input.remove();
|
|
fixture.files = undefined;
|
|
fixture.handoffs = 0;
|
|
});
|
|
|
|
async function compose() {
|
|
current = await createRuntimeAdapters({
|
|
runtime: {
|
|
config: {
|
|
APP_ENV: "local",
|
|
API_BASE_URL: "http://localhost:8080",
|
|
TELEMETRY_ENABLED: false,
|
|
AUTH_MODE: "external",
|
|
REQUEST_TIMEOUT_MS: 10_000,
|
|
MAX_RETRY_ATTEMPTS: 0,
|
|
RELEASE_MANIFEST_URL: "/release-manifest.json",
|
|
CONFIG_SCHEMA_VERSION: "2.0",
|
|
CAPABILITY_OVERRIDES: {
|
|
REALTIME: "DEFAULT",
|
|
WEB_WORKER: "DEFAULT",
|
|
SERVICE_WORKER: "DEFAULT",
|
|
OFFLINE_COMMANDS: "DEFAULT",
|
|
},
|
|
FEATURE_OVERRIDES: {},
|
|
},
|
|
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: {},
|
|
});
|
|
const files = fixture.files;
|
|
const owner = fixture.owner;
|
|
if (!files || !owner) throw new Error("The product composition did not run");
|
|
return { adapters: current, files, owner };
|
|
}
|
|
|
|
async function selectOne(
|
|
runtime: ReturnType<NonNullable<typeof fixture.files>["current"]>,
|
|
name: string,
|
|
) {
|
|
const pending = runtime.baselinePicker.select({ policy: selectPolicy });
|
|
const input = fixture.inputs.at(-1)!;
|
|
Object.defineProperty(input, "files", {
|
|
configurable: true,
|
|
value: [new File(["text"], name, { type: "text/plain", lastModified: 1 })],
|
|
});
|
|
input.dispatchEvent(new Event("change"));
|
|
return await pending;
|
|
}
|
|
|
|
describe("a session-scoped browser file runtime (2026-11-03 02-01)", () => {
|
|
it("closes the previous user's files and downloads on an account switch and serves the next session a new runtime", async () => {
|
|
const { adapters, files, owner } = await compose();
|
|
const previous = files.current();
|
|
const selected = await selectOne(previous, "user-a.txt");
|
|
if (!selected.ok || selected.value.kind !== "SELECTED") {
|
|
throw new Error(`The first selection failed: ${JSON.stringify(selected)}`);
|
|
}
|
|
const ref: LocalFileRef = selected.value.files[0]!.ref;
|
|
let producing!: () => void;
|
|
const started = new Promise<void>((resolve) => {
|
|
producing = resolve;
|
|
});
|
|
const download = previous.downloads.deliver({
|
|
policy: downloadPolicy,
|
|
source: {
|
|
kind: "GENERATED",
|
|
bytes: {
|
|
byteLength: 1,
|
|
async *stream() {
|
|
producing();
|
|
await new Promise(() => {});
|
|
yield { ok: true as const, value: new Uint8Array([1]) };
|
|
},
|
|
},
|
|
},
|
|
suggestedFileName: "user-a-report",
|
|
maxTransferBytes: 8,
|
|
maxBufferedBytes: 8,
|
|
signal: new AbortController().signal,
|
|
onProgress() {},
|
|
});
|
|
await started;
|
|
|
|
owner.switchUser("user-b");
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
|
|
expect(
|
|
await previous.content.readRange({
|
|
ref,
|
|
offset: 0,
|
|
length: 1,
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toMatchObject({ ok: false, error: { code: "UNAVAILABLE" } });
|
|
expect(await download).toMatchObject({
|
|
ok: false,
|
|
error: { code: "ABORTED", operation: "DOWNLOAD" },
|
|
});
|
|
expect(fixture.handoffs).toBe(0);
|
|
|
|
const next = files.current();
|
|
expect(next).not.toBe(previous);
|
|
expect(await selectOne(next, "user-b.txt")).toMatchObject({
|
|
ok: true,
|
|
value: { kind: "SELECTED" },
|
|
});
|
|
});
|
|
});
|