Files
DongHyeonka 73bad4c9f9 test(opfs): 다른 탭 시험이 lease 대기열에 B 탭 하나만 있는지 본다
af5b8e1f의 두 탭 시험은 Web Locks 대기열에 「origin lease exclusive」가
하나라도 있으면 B 탭이 왔다고 봤다. origin lease는 origin 전체가 쓰는 이름
하나라, 다른 탭이나 worker가 같은 lease를 기다리면 B 탭 대신 그 요청이
조건을 채운다(새 눈 리뷰 Low). 지금 시험에는 탭이 둘뿐이라 실제로 거짓
통과가 나지는 않았다.

고른 방법: `queuedOpfsLocks`가 그 이름·mode의 pending 수를 돌려준다.
B를 시작하기 직전에 0인지 보고, B를 시작한 뒤 poll은 정확히 1을 기다린다.
1만 보면 셋째 요청자가 B보다 먼저 줄에 섰을 때, poll의 첫 측정이 B 전에
일어나 그 하나로 통과한다. 그래서 앞의 0 확인을 같이 둔다.

위험·한계: 0 확인과 B의 요청 사이에 셋째가 끼어들고 poll이 B 전에 재면
여전히 통과한다. B의 요청을 따로 알아볼 방법(clientId 등)은 쓰지 않았다.
purge(객체 0)가 기다리는 partition 잠금은 그 시험의 scope에만 있어 이
문제가 없다.

검증(desktop, CI env, FE-GATE-008 설정으로 그 spec만):
- 셋째 탭이 origin lease를 exclusive로 요청하는 스위치(B 뒤·B 앞)를 켠
  실험 사본: 고치기 전 spec은 둘 다 9 passed(빈틈). 고친 spec은 둘 다
  4 failed(purge 3·reconcile × chromium·firefox, B 뒤는 Received 2,
  B 앞은 Received 1). 스위치를 끄면 9 passed.
- 고친 spec `-g "in another tab" --repeat-each=30` 270 passed.
- 최종 트리 b038c8b3: opfs spec 12 passed, preload-use spec 21 passed.
  노트북 scripts/verify.sh docs, laptop-gate lint·check:types:test rc=0.
- preload 지연 시험의 `delayed` toBe(1)은 `-g "deepest preloaded chunk"
  --repeat-each=30` 90 passed라 그대로 둔다(리뷰 Low 둘째).

Refs: REV-FE-0017
2026-11-23 17:07:02 +09:00

641 lines
23 KiB
TypeScript

import { expect, test } from "../support/browser/strict-browser-test.ts";
test("runs put, open, remove and reconcile through a native DedicatedWorker, OPFS and IndexedDB", async ({
page,
}) => {
await page.goto("/");
const result = await page.evaluate(async () => {
const runtimeModulePath =
"/src/adapters/storage/opfs/browser-opfs-runtime.ts";
const policyModulePath =
"/src/adapters/storage/opfs/opfs-policy.ts";
const journalModulePath =
"/src/adapters/storage/opfs/indexeddb-opfs-journal.ts";
const {
createBrowserOpfsRuntime,
inspectBrowserOpfsSupport,
} = (await import(
/* @vite-ignore */ runtimeModulePath
)) as typeof import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts");
const {
DEFAULT_OPFS_RUNTIME_POLICY,
resolveOpfsRuntimePolicy,
} = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/storage/opfs/opfs-policy.ts");
const { opfsJournalDatabaseName } = (await import(
/* @vite-ignore */ journalModulePath
)) as typeof import("../../src/adapters/storage/opfs/indexeddb-opfs-journal.ts");
const policy = resolveOpfsRuntimePolicy();
const support = inspectBrowserOpfsSupport(policy);
if (!support.ok) {
return {
nativeSupport: false as const,
capabilities: support,
};
}
const suffix = crypto.randomUUID().replaceAll("-", "");
const scope = {
namespace: "durable-objects",
authorityToken: `authority_${suffix}`,
namespaceToken: `namespace_${suffix}`,
partitionToken: `partition_${suffix}`,
} as const;
const storagePolicy = {
owner: "browser-capability",
namespace: scope.namespace,
classification: "PERSONAL",
authority: "LOCAL_FIRST",
accountScope: "OPAQUE_PARTITION",
retention: { kind: "EXPLICIT_DELETE" },
softBudgetBytes: 1024 * 1024,
hardBudgetBytes: 2 * 1024 * 1024,
evictionPriority: "USER_AUTHORED",
logoutAction: "EXPORT_THEN_PURGE",
accountDeletionAction: "PURGE_PARTITION",
pressureAction: "RETAIN",
unavailableFallback: "EXPORT_REQUIRED",
} as const;
const runtime = createBrowserOpfsRuntime({
workerUrl: new URL(
"/tests/browser-capabilities/opfs-test.worker.ts",
location.href,
),
workerName: `opfs-capability-${suffix}`,
scope,
storagePolicy,
policy,
});
const bytes = new Uint8Array([3, 1, 4, 1, 5, 9]);
let capabilities: unknown;
let put: unknown;
let opened:
| Awaited<ReturnType<typeof runtime.objects.open>>
| undefined;
let readBytes: number[] = [];
let removed: unknown;
let afterRemove: unknown;
let reconciled: unknown;
try {
capabilities = await runtime.objects.capabilities();
put = await runtime.objects.put({
objectId: "object_browser_12345678",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: {
byteLength: bytes.byteLength,
async *stream(signal: AbortSignal) {
if (signal.aborted) {
yield {
ok: false as const,
error: {
code: "ABORTED" as const,
operation: "OBJECT_WRITE" as const,
retryable: false,
recovery: "NONE" as const,
},
};
return;
}
yield { ok: true as const, value: Uint8Array.from(bytes) };
},
},
});
opened = await runtime.objects.open({
objectId: "object_browser_12345678",
});
if (
opened &&
typeof opened === "object" &&
"ok" in opened &&
opened.ok
) {
for await (const chunk of opened.value.source.stream(
new AbortController().signal,
)) {
if (!chunk.ok) throw new Error(chunk.error.code);
readBytes.push(...chunk.value);
}
}
removed = await runtime.objects.remove({
objectId: "object_browser_12345678",
expectedGeneration: 1,
});
afterRemove = await runtime.objects.open({
objectId: "object_browser_12345678",
});
reconciled = await runtime.maintenance.reconcile({
budgetMs: 5_000,
maxTransactions: 100,
});
} finally {
runtime.close();
}
const deletion = await new Promise<string>((resolve) => {
const request = indexedDB.deleteDatabase(
opfsJournalDatabaseName(scope.authorityToken),
);
request.onsuccess = () => resolve("DELETED");
request.onerror = () =>
resolve(request.error?.name ?? "UNKNOWN_ERROR");
request.onblocked = () => resolve("BLOCKED");
});
let opfsCleanup = "ABSENT";
try {
const originRoot = await navigator.storage.getDirectory();
const runtimeRoot = await originRoot.getDirectoryHandle(
DEFAULT_OPFS_RUNTIME_POLICY.rootDirectoryName,
);
const authorities = await runtimeRoot.getDirectoryHandle(
"authorities",
);
await authorities.removeEntry(scope.authorityToken, {
recursive: true,
});
opfsCleanup = "DELETED";
} catch (error) {
if (!(error instanceof DOMException) || error.name !== "NotFoundError") {
throw error;
}
}
return {
nativeSupport: true as const,
capabilities,
put,
opened:
opened &&
typeof opened === "object" &&
"ok" in opened &&
opened.ok
? {
ok: true,
generation: opened.value.descriptor.generation,
}
: opened,
readBytes,
removed,
afterRemove,
reconciled,
deletion,
opfsCleanup,
};
});
if (!result.nativeSupport) {
expect(result.capabilities).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED" },
});
return;
}
expect(result.capabilities).toMatchObject({
ok: true,
value: {
available: true,
dedicatedWorkerRequired: true,
crossContextMutationLockAvailable: true,
},
});
expect(result.put).toMatchObject({
ok: true,
value: { generation: 1, byteLength: 6 },
});
expect(result.opened).toEqual({ ok: true, generation: 1 });
expect(result.readBytes).toEqual([3, 1, 4, 1, 5, 9]);
expect(result.removed).toEqual({ ok: true });
expect(result.afterRemove).toMatchObject({
ok: false,
error: { code: "NOT_FOUND" },
});
expect(result.reconciled).toMatchObject({
ok: true,
value: {
inspectedTransactions: 0,
orphanGcStatus: "COMPLETED",
},
});
expect(result.deletion).toBe("DELETED");
expect(["DELETED", "ABSENT"]).toContain(result.opfsCleanup);
});
type OpfsTabScope = Readonly<{
namespace: string;
authorityToken: string;
namespaceToken: string;
partitionToken: string;
}>;
/**
* Installs an OPFS runtime for `scope` in this tab and keeps it on
* `globalThis.__opfsTab` for later evaluate calls. `approvePurges` stands in
* for an authority that approves every LOGOUT and ACCOUNT_DELETION.
*/
async function installOpfsTab(
page: import("@playwright/test").Page,
scope: OpfsTabScope,
approvePurges = false,
): Promise<boolean> {
return await page.evaluate(async ({ tabScope, approvePurges }) => {
const runtimeModulePath =
"/src/adapters/storage/opfs/browser-opfs-runtime.ts";
const policyModulePath = "/src/adapters/storage/opfs/opfs-policy.ts";
const { createBrowserOpfsRuntime, inspectBrowserOpfsSupport } =
(await import(
/* @vite-ignore */ runtimeModulePath
)) as typeof import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts");
const { resolveOpfsRuntimePolicy } = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/storage/opfs/opfs-policy.ts");
const policy = resolveOpfsRuntimePolicy();
if (!inspectBrowserOpfsSupport(policy).ok) return false;
(globalThis as unknown as { __opfsTab: unknown }).__opfsTab =
createBrowserOpfsRuntime({
workerUrl: new URL(
"/tests/browser-capabilities/opfs-test.worker.ts",
location.href,
),
workerName: `opfs-tab-${crypto.randomUUID()}`,
scope: tabScope,
storagePolicy: {
owner: "browser-capability",
namespace: tabScope.namespace,
classification: "PERSONAL",
authority: "LOCAL_FIRST",
accountScope: "OPAQUE_PARTITION",
retention: { kind: "EXPLICIT_DELETE" },
softBudgetBytes: 1024 * 1024,
hardBudgetBytes: 2 * 1024 * 1024,
evictionPriority: "USER_AUTHORED",
logoutAction: "EXPORT_THEN_PURGE",
accountDeletionAction: "PURGE_PARTITION",
pressureAction: "RETAIN",
unavailableFallback: "EXPORT_REQUIRED",
},
policy,
...(approvePurges
? {
requestMaintenanceAuthority: () => ({
authorized: true as const,
proofToken: `proof_${crypto.randomUUID().replaceAll("-", "")}`,
expiresAtEpochMs: Date.now() + 60_000,
}),
consumeMaintenanceAuthority: () => true,
}
: {}),
});
return true;
}, { tabScope: scope, approvePurges });
}
/** Deletes everything the OPFS runtime wrote for `scope`'s authority. */
async function removeOpfsAuthority(
page: import("@playwright/test").Page,
scope: OpfsTabScope,
): Promise<string> {
return await page.evaluate(async (tabScope) => {
const journalModulePath =
"/src/adapters/storage/opfs/indexeddb-opfs-journal.ts";
const policyModulePath = "/src/adapters/storage/opfs/opfs-policy.ts";
const { opfsJournalDatabaseName } = (await import(
/* @vite-ignore */ journalModulePath
)) as typeof import("../../src/adapters/storage/opfs/indexeddb-opfs-journal.ts");
const { DEFAULT_OPFS_RUNTIME_POLICY } = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/storage/opfs/opfs-policy.ts");
const deletion = await new Promise<string>((resolve) => {
const request = indexedDB.deleteDatabase(
opfsJournalDatabaseName(tabScope.authorityToken),
);
request.onsuccess = () => resolve("DELETED");
request.onerror = () => resolve(request.error?.name ?? "UNKNOWN");
request.onblocked = () => resolve("BLOCKED");
});
try {
const root = await (
await navigator.storage.getDirectory()
).getDirectoryHandle(DEFAULT_OPFS_RUNTIME_POLICY.rootDirectoryName);
await (
await root.getDirectoryHandle("authorities")
).removeEntry(tabScope.authorityToken, { recursive: true });
} catch {
// Nothing was written for this authority.
}
return deletion;
}, scope);
}
/**
* How many Web Locks requests are still queued for one lock of the OPFS
* runtime of `scope` in `mode`: the workers' origin lease, or this partition's
* lock. Every tab and worker of a context shares one lock manager, so either
* tab sees what the other tab's maintenance waits for.
*
* 2026-11-23. The two-tab tests below waited a fixed 250 ms for tab B to get
* there before letting tab A's put finish. When tab B was slower, the put
* finished first and the test failed on an outcome it never set up. They now
* wait for tab B's request in this queue. The lease has one name for the whole
* origin, so another tab or worker waiting for it looked just like tab B. The
* queue must be empty before tab B starts and then hold exactly one request;
* another waiter fails the test instead of standing in for tab B.
*/
async function queuedOpfsLocks(
page: import("@playwright/test").Page,
scope: OpfsTabScope,
lock: "origin lease" | "partition",
mode: LockMode,
): Promise<number> {
return await page.evaluate(
async ({ tabScope, lock, mode }) => {
const policyModulePath = "/src/adapters/storage/opfs/opfs-policy.ts";
const { DEFAULT_OPFS_RUNTIME_POLICY } = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/storage/opfs/opfs-policy.ts");
const lease = DEFAULT_OPFS_RUNTIME_POLICY.mutationLockName;
const name =
lock === "origin lease"
? lease
: `${lease}:partition:${tabScope.authorityToken}:${tabScope.namespaceToken}:${tabScope.partitionToken}`;
const { pending = [] } = await navigator.locks.query();
return pending.filter(
(request) => request.name === name && request.mode === mode,
).length;
},
{ tabScope: scope, lock, mode },
);
}
// 2026-11-03 05-01 X1. The purge used to report a completed sweep while the
// other tab's put landed, and the object stayed readable after the account
// deletion. It now waits for that put and takes it with the partition.
// 1103/05-01 rest. That fix still reported a completed sweep, with the new
// object readable, once the purged partition held three or more objects:
// each remove waits for the origin lease the put holds, so the put settled
// before the purge counted the journal. A purge that walked every object now
// always ends in the partition delete.
for (const committedObjects of [0, 3]) {
test(`05-01 an approved purge in another tab waits for a live put and takes it with the partition (${committedObjects} committed objects)`, async ({
page,
browserName,
}) => {
const secondPage = await page.context().newPage();
const suffix = crypto.randomUUID().replaceAll("-", "");
const scope: OpfsTabScope = {
namespace: "durable-objects",
authorityToken: `authority_${suffix}`,
namespaceToken: `namespace_${suffix}`,
partitionToken: `partition_${suffix}`,
};
type Tab = import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts").BrowserOpfsRuntime;
try {
await Promise.all([page.goto("/"), secondPage.goto("/")]);
// 1112/03-02. An early return here passed with no assertion on an engine
// the support check refused, while the evidence said zero skipped.
// Playwright's WebKit is refused (the first test asserts its UNSUPPORTED
// result), so there this asserts the refusal; every other engine must
// open the runtime. A skip is no way out: the capability evidence
// refuses skipped cases (scripts/verify-browser-capability-evidence.ts).
const installed = await installOpfsTab(page, scope);
if (browserName === "webkit") {
expect(installed, "the OPFS support check refuses Playwright's WebKit").toBe(false);
return;
}
expect(installed, "OPFS runtime supported in this engine").toBe(true);
expect(await installOpfsTab(secondPage, scope, true)).toBe(true);
const seeded = await secondPage.evaluate(async (count) => {
const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab;
const codes: string[] = [];
for (let index = 0; index < count; index += 1) {
const put = await runtime.objects.put({
objectId: `object_secret_${String(index).padStart(4, "0")}`,
expectedGeneration: null,
mediaType: "application/octet-stream",
source: {
byteLength: 1,
async *stream() {
yield { ok: true as const, value: new Uint8Array([index + 1]) };
},
},
});
codes.push(put.ok ? "OK" : put.error.code);
}
return codes;
}, committedObjects);
expect(seeded).toEqual(Array.from({ length: committedObjects }, () => "OK"));
await page.evaluate(async () => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__release?: () => void;
__put?: Promise<unknown>;
};
let streaming!: () => void;
const started = new Promise<void>((resolve) => {
streaming = resolve;
});
const gate = new Promise<void>((resolve) => {
state.__release = resolve;
});
state.__put = state.__opfsTab.objects.put({
objectId: "object_tab_12345678",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: {
byteLength: 4,
async *stream() {
streaming();
await gate;
yield { ok: true as const, value: new Uint8Array([2, 7, 1, 8]) };
},
},
});
await started;
});
const waitedLock = committedObjects === 0 ? "partition" : "origin lease";
expect(
await queuedOpfsLocks(secondPage, scope, waitedLock, "exclusive"),
`nothing waits for the ${waitedLock} before tab B's purge`,
).toBe(0);
await secondPage.evaluate(() => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__purge?: Promise<unknown>;
};
state.__purge = state.__opfsTab.maintenance.enforcePolicies({
reason: "ACCOUNT_DELETION",
});
});
// Tab B's purge has listed the partition and waits for what tab A's put
// holds: the partition lock it takes exclusive when nothing is left to
// remove, or the origin lease its first remove needs.
await expect
.poll(
() => queuedOpfsLocks(secondPage, scope, waitedLock, "exclusive"),
{ message: "tab B's purge, and nothing else, waits for tab A's put" },
)
.toBe(1);
const put = await page.evaluate(async () => {
const state = globalThis as unknown as {
__release: () => void;
__put: Promise<unknown>;
};
state.__release();
return await state.__put;
});
const report = await secondPage.evaluate(
async () =>
await (globalThis as unknown as { __purge: Promise<unknown> }).__purge,
);
const opened = await secondPage.evaluate(async () => {
const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab;
const result = await runtime.objects.open({
objectId: "object_tab_12345678",
});
return result.ok ? "OPENED" : result.error.code;
});
expect(put).toMatchObject({ ok: true, value: { generation: 1 } });
expect(report).toMatchObject({
ok: true,
value: {
removedObjects: committedObjects,
moreObjectsAvailable: false,
partitionDeleted: true,
},
});
expect(opened).toBe("NOT_FOUND");
} finally {
for (const tab of [page, secondPage]) {
await tab.evaluate(() =>
(globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(),
);
}
expect(await removeOpfsAuthority(page, scope)).toBe("DELETED");
await secondPage.close();
}
});
}
test("05-01 a reconcile in another tab skips a live put and the put stays readable", async ({
page,
browserName,
}) => {
const secondPage = await page.context().newPage();
const suffix = crypto.randomUUID().replaceAll("-", "");
const scope: OpfsTabScope = {
namespace: "durable-objects",
authorityToken: `authority_${suffix}`,
namespaceToken: `namespace_${suffix}`,
partitionToken: `partition_${suffix}`,
};
type Tab = import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts").BrowserOpfsRuntime;
try {
await Promise.all([page.goto("/"), secondPage.goto("/")]);
// 1112/03-02. Asserted, not returned early: see the purge test above.
const installed = await installOpfsTab(page, scope);
if (browserName === "webkit") {
expect(installed, "the OPFS support check refuses Playwright's WebKit").toBe(false);
return;
}
expect(installed, "OPFS runtime supported in this engine").toBe(true);
expect(await installOpfsTab(secondPage, scope)).toBe(true);
// Tab A starts a put whose source stalls, so its journal row stays
// PREPARING and its worker holds the OPFS mutation lock.
await page.evaluate(async () => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__release?: () => void;
__put?: Promise<unknown>;
};
let streaming!: () => void;
const started = new Promise<void>((resolve) => {
streaming = resolve;
});
const gate = new Promise<void>((resolve) => {
state.__release = resolve;
});
state.__put = state.__opfsTab.objects.put({
objectId: "object_tab_12345678",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: {
byteLength: 4,
async *stream() {
streaming();
await gate;
yield { ok: true as const, value: new Uint8Array([2, 7, 1, 8]) };
},
},
});
await started;
});
expect(
await queuedOpfsLocks(page, scope, "origin lease", "exclusive"),
"nothing waits for the origin lease before tab B's reconcile",
).toBe(0);
// Tab B reconciles while tab A's put is in flight.
await secondPage.evaluate(() => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__reconcile?: Promise<unknown>;
};
state.__reconcile = state.__opfsTab.maintenance.reconcile();
});
// Tab B's reconcile has tried the row's lock and gone on to the orphan
// sweep, which waits for the origin lease tab A's put holds. So its
// result cannot be awaited before the put is released: it comes after.
await expect
.poll(() => queuedOpfsLocks(page, scope, "origin lease", "exclusive"), {
message: "tab B's reconcile, and nothing else, waits for tab A's put",
})
.toBe(1);
const put = await page.evaluate(async () => {
const state = globalThis as unknown as {
__release: () => void;
__put: Promise<unknown>;
};
state.__release();
return await state.__put;
});
const reconciled = await secondPage.evaluate(
async () =>
await (globalThis as unknown as { __reconcile: Promise<unknown> })
.__reconcile,
);
const opened = await page.evaluate(async () => {
const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab;
const result = await runtime.objects.open({
objectId: "object_tab_12345678",
});
if (!result.ok) return result.error.code;
const bytes: number[] = [];
for await (const chunk of result.value.source.stream(
new AbortController().signal,
)) {
if (!chunk.ok) return chunk.error.code;
bytes.push(...chunk.value);
}
return bytes;
});
expect(put).toMatchObject({ ok: true, value: { generation: 1 } });
expect(reconciled).toMatchObject({
ok: true,
value: { skippedLiveTransactions: 1, rolledBackTransactions: 0 },
});
expect(opened).toEqual([2, 7, 1, 8]);
} finally {
for (const tab of [page, secondPage]) {
await tab.evaluate(() =>
(globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(),
);
}
expect(await removeOpfsAuthority(page, scope)).toBe("DELETED");
await secondPage.close();
}
});