Files
clean-architecture-frontend…/tests/recipes/browser-file-storage-contracts.test.ts
T
DongHyeonka 36ff633794 fix(recipes): OPFS fake가 FILES_READY에서 멈춘 put을 runtime처럼 commit한다
문제: recipe fake MemoryDurableObjectStore의 reconcile은 멈춘 put 행을
모두 rollback으로 센다. runtime은 FILES_READY 행을 다시 검증한 뒤
commit하고 finalize한다(runbook, 설계 문서의 roll-forward). recipe 테스트
주석은 "Like the runtime, reconcile rolls a stopped put back"이라고 적는다.
이 fake로 쓴 다운스트림 테스트는 "멈춘 업로드는 reconcile 뒤 사라진다"를
통과하지만 실제로는 객체가 다시 생긴다. fake의 LOGOUT·ACCOUNT_DELETION도
멈춘 행을 보지 않아 05-01을 fake 테스트로 찾을 수 없었다.

고른 방법: fake가 멈춘 단계를 기억한다. FILES_READY까지 간 행은 commit될
객체를 함께 둔다. reconcile은 그 행을 runtime과 같은 generation 검사로
commit하고(committedTransactions), PREPARING 행은 rollback한다.
LOGOUT·ACCOUNT_DELETION은 멈춘 행도 지우고, 그런 행이 있었으면 runtime처럼
chunkSweep 대신 partitionDeleted를 보고한다. 같은 네 시나리오(두 단계 ×
reconcile 전 계정 삭제 여부)를 메모리 OPFS·IndexedDB 위의 실제 runtime과
fake에 돌려 결과가 같은지 보는 parity 테스트를 tests/recipes에 더했다.
unit 테스트가 recipe를 import하면 optional-recipe 제거 드릴이 깨지므로
parity 테스트는 recipe 쪽에 두었다(앞 커밋이 메모리 OPFS를 helper로
옮긴 이유).

위험·한계: 이 fake를 쓰는 다운스트림 테스트 중 FILES_READY 멈춤 뒤
rollback을 기대하던 것은 기대값이 바뀐다. 기존 recipe 테스트는 같은
흐름을 유지하려고 PREPARING 멈춤으로 바꿨다. fake는 runtime의 재검증
실패(digest 불일치) 경로는 흉내 내지 않는다.

검증:
- RED: parity 테스트 4건 중 3건 실패(fake가 FILES_READY를 rollback,
  계정 삭제가 partitionDeleted 없이 COMPLETED). runtime 쪽 기대값은
  처음부터 통과.
- GREEN: tests/recipes 24건 통과. check:types, 바꾼 파일 eslint,
  check:optional-recipes:source PASS.

Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 05-04
2026-11-04 20:46:30 +09:00

961 lines
29 KiB
TypeScript

import { describe, expect, expectTypeOf, it } from "vitest";
import {
MemoryDurableObjectStore,
MemoryBrowserFilePolicyRegistry,
MemoryExampleQuarantinedUploadAdapter,
MemoryFileSelectionAdapter,
MemoryPublicResponseCache,
MemoryStorageDurabilityAdapter,
MemoryStructuredOfflineStore,
MemoryTransientPreviewAdapter,
RecordingDownloadDeliveryAdapter,
asByteCount,
asBrowserManagedDownloadCapabilityReceipt,
asDurableObjectId,
asLocalFileRef,
asObjectGeneration,
browserFilePolicyReference,
sanitizeDownloadFileName,
} from "../../recipes/frontend-capabilities/index.ts";
import type {
BrowserFileComposition,
BrowserPersistencePolicy,
DurableObjectStorageComposition,
ExampleBackendUploadComposition,
PublicResponseCacheComposition,
StorageDurabilityComposition,
StructuredOfflineStorageComposition,
} from "../../recipes/frontend-capabilities/index.ts";
import type {
BrowserStoragePolicy,
DownloadDeliveryPort,
DurableObjectMaintenancePort,
DurableObjectStorePort,
FileContentPort,
FilePickerPort,
StorageDurabilityPort,
TransientPreviewPort,
} from "../../src/application/ports/browser-file-storage/index.ts";
import { browserDataFailure } from "../../src/adapters/browser-file-storage/result.ts";
import {
createIndexedDbOpfsJournal,
createOpfsByteStoreAdapter,
createOpfsWorkerGateway,
createOpfsWorkerRuntime,
createWebLockLeaseManager,
resolveOpfsRuntimePolicy,
} from "../../src/adapters/storage/opfs/index.ts";
import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts";
import { MemoryDirectory } from "../helpers/memory-opfs.ts";
async function* byteChunks(
...values: ReadonlyArray<string>
): AsyncIterable<Readonly<{ ok: true; value: Uint8Array }>> {
for (const value of values) {
yield {
ok: true,
value: new TextEncoder().encode(value),
};
}
}
async function* failedByteChunks() {
yield {
ok: false,
error: {
code: "NOT_READABLE",
operation: "OBJECT_WRITE",
retryable: true,
recovery: "RETRY",
},
} as const;
}
describe("production browser file and storage recipe contracts", () => {
it("separates picker dismissal, metadata policy and bounded content reads", async () => {
const ref = asLocalFileRef("opaque-local-1");
const selectionPolicy = {
policyId: "support-attachment-v1",
purpose: "support-attachment",
classification: "PERSONAL" as const,
multiple: false,
maxCount: 1,
maxFileBytes: asByteCount(10),
maxTotalBytes: asByteCount(10),
allowEmpty: false,
accept: [{ mediaType: "text/plain", extensions: [".txt"] }],
};
const filePolicy = browserFilePolicyReference(
"support-attachment",
"select-inspect-preview-text",
);
const policies = new MemoryBrowserFilePolicyRegistry([
{
reference: filePolicy,
selection: selectionPolicy,
inspection: {
policyId: selectionPolicy.policyId,
maxInspectionBytes: asByteCount(1_445),
acceptedSignatures: [
{
mediaType: "text/plain",
extensions: [".txt"],
patterns: [
{
offset: asByteCount(0),
bytes: [104],
},
],
},
],
},
preview: {
allowedMediaTypes: ["text/plain"],
maxPreviewBytes: asByteCount(10),
},
},
]);
const adapter = new MemoryFileSelectionAdapter(
[
{
ref,
displayName: "notes.txt",
bytes: new TextEncoder().encode("hello"),
reportedMediaType: "text/plain",
detectedMediaType: "text/plain",
signature: "MATCHED",
},
],
policies,
);
adapter.setNextOutcome("DISMISSED");
expect(await adapter.select({ policy: filePolicy })).toEqual({
ok: true,
value: { kind: "DISMISSED" },
});
const selected = await adapter.select({ policy: filePolicy });
expect(selected.ok && selected.value.kind).toBe("SELECTED");
expect(
await adapter.select({
policy: browserFilePolicyReference(
"support-attachment",
"select-inspect-preview-text",
),
}),
).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED", operation: "FILE_SELECT" },
});
const inspected = await adapter.inspect({
ref,
policy: filePolicy,
signal: new AbortController().signal,
});
expect(inspected).toMatchObject({
ok: true,
value: {
detectedMediaType: "text/plain",
signature: "MATCHED",
},
});
if (!inspected.ok || !inspected.value.verificationReceipt) return;
expect(
await adapter.readRange({
ref,
offset: asByteCount(1),
length: asByteCount(3),
signal: new AbortController().signal,
}),
).toEqual({
ok: true,
value: new TextEncoder().encode("ell"),
});
const previews = new MemoryTransientPreviewAdapter(
adapter,
policies,
);
const preview = await previews.create({
ref,
verificationReceipt: inspected.value.verificationReceipt,
policy: filePolicy,
maxPreviewBytes: asByteCount(10),
signal: new AbortController().signal,
});
expect(preview.ok).toBe(true);
expect(previews.activeLeaseCount).toBe(1);
if (preview.ok) {
preview.value.release();
preview.value.release();
}
expect(previews.activeLeaseCount).toBe(0);
previews.dispose();
expect(
await previews.create({
ref,
verificationReceipt: inspected.value.verificationReceipt,
policy: filePolicy,
maxPreviewBytes: asByteCount(10),
signal: new AbortController().signal,
}),
).toMatchObject({
ok: false,
error: { code: "UNAVAILABLE", operation: "PREVIEW" },
});
adapter.release(ref);
expect(
(
await adapter.readRange({
ref,
offset: asByteCount(0),
length: asByteCount(1),
signal: new AbortController().signal,
})
).ok,
).toBe(false);
});
it("keeps the optional backend upload example resumable and quarantined", async () => {
const adapter = new MemoryExampleQuarantinedUploadAdapter(
asByteCount(16),
asByteCount(4),
() => Date.parse("2026-07-27T00:00:00.000Z"),
);
const signal = new AbortController().signal;
const created = await adapter.create({
purpose: "avatar",
byteLength: asByteCount(4),
detectedMediaType: "image/png",
signal,
});
expect(created.ok).toBe(true);
if (!created.ok) return;
const part = await adapter.uploadPart({
sessionId: created.value.sessionId,
partNumber: 1,
offset: asByteCount(0),
bytes: new Uint8Array([1, 2, 3, 4]),
checksumSha256: "part-checksum",
idempotencyKey: "part-one-attempt",
signal,
});
expect(part.ok).toBe(true);
const replay = await adapter.uploadPart({
sessionId: created.value.sessionId,
partNumber: 1,
offset: asByteCount(0),
bytes: new Uint8Array([1, 2, 3, 4]),
checksumSha256: "part-checksum",
idempotencyKey: "part-one-attempt",
signal,
});
expect(replay).toEqual(part);
expect(
await adapter.uploadPart({
sessionId: created.value.sessionId,
partNumber: 1,
offset: asByteCount(0),
bytes: new Uint8Array([9, 9, 9, 9]),
checksumSha256: "different-request-body",
idempotencyKey: "part-one-attempt",
signal,
}),
).toMatchObject({ ok: false, failure: { code: "CONFLICT" } });
if (!part.ok) return;
expect(
await adapter.complete({
sessionId: created.value.sessionId,
parts: [part.value],
signal,
}),
).toMatchObject({
ok: true,
value: { state: "QUARANTINED" },
});
});
// [0929] 05-03. The fakes the catalog names for a runtime port implement
// that `src` port, not a recipe copy of it.
it("fakes the src runtime ports themselves", () => {
expectTypeOf<MemoryFileSelectionAdapter>().toMatchTypeOf<
FilePickerPort & FileContentPort
>();
expectTypeOf<MemoryTransientPreviewAdapter>().toMatchTypeOf<TransientPreviewPort>();
expectTypeOf<RecordingDownloadDeliveryAdapter>().toMatchTypeOf<DownloadDeliveryPort>();
expectTypeOf<MemoryStorageDurabilityAdapter>().toMatchTypeOf<StorageDurabilityPort>();
expectTypeOf<MemoryDurableObjectStore>().toMatchTypeOf<
DurableObjectStorePort & DurableObjectMaintenancePort
>();
});
it("keeps each browser technology independently composable", () => {
expectTypeOf<keyof BrowserFileComposition>().toEqualTypeOf<
"picker" | "content" | "previews" | "downloads"
>();
expectTypeOf<
keyof StructuredOfflineStorageComposition<unknown>
>().toEqualTypeOf<"store" | "maintenance">();
expectTypeOf<
keyof StorageDurabilityComposition
>().toEqualTypeOf<"durability">();
expectTypeOf<
keyof DurableObjectStorageComposition
>().toEqualTypeOf<"store" | "maintenance">();
expectTypeOf<
keyof PublicResponseCacheComposition
>().toEqualTypeOf<"cache">();
expectTypeOf<
keyof ExampleBackendUploadComposition
>().toEqualTypeOf<"upload">();
expectTypeOf<
BrowserPersistencePolicy["logoutAction"]
>().toEqualTypeOf<
"KEEP_ORIGIN_SHARED" | "PURGE_PARTITION" | "EXPORT_THEN_PURGE"
>();
expectTypeOf<
BrowserPersistencePolicy["accountDeletionAction"]
>().toEqualTypeOf<"KEEP_ORIGIN_SHARED" | "PURGE_PARTITION">();
expectTypeOf<
BrowserPersistencePolicy["pressureAction"]
>().toEqualTypeOf<"EVICT_RECONSTRUCTABLE" | "RETAIN">();
});
it("distinguishes browser handoff from a verified streamed save", async () => {
const browserPolicy = browserFilePolicyReference(
"reports",
"browser-managed-pdf",
);
const streamPolicy = browserFilePolicyReference(
"exports",
"stream-text",
);
const policies = new MemoryBrowserFilePolicyRegistry([
{
reference: browserPolicy,
download: {
strategy: "BROWSER_MANAGED",
mediaType: "application/pdf",
safeExtension: ".pdf",
maxTransferBytes: asByteCount(10),
maxBufferedBytes: asByteCount(10),
integrity: "OPTIONAL",
},
},
{
reference: streamPolicy,
download: {
strategy: "PROMPT_AND_STREAM",
mediaType: "text/plain",
safeExtension: ".txt",
maxTransferBytes: asByteCount(10),
maxBufferedBytes: asByteCount(10),
integrity: "REQUIRED",
},
},
]);
const capabilityReceipt =
asBrowserManagedDownloadCapabilityReceipt(
"capability:report",
);
const adapter = new RecordingDownloadDeliveryAdapter(
policies,
{
resolve(input) {
return {
ok: true,
value: {
capabilityReceipt,
href: "/downloads/report",
resourceId: input.resourceId,
mediaType: "application/pdf",
safeExtension: ".pdf",
maxBytes: asByteCount(10),
expiresAtEpochMs: 2_000,
},
};
},
},
() => 1_000,
);
const progress: number[] = [];
expect(sanitizeDownloadFileName("../CON\u202e.exe")).toBe("download.bin");
const handedOff = await adapter.deliver({
policy: browserPolicy,
source: {
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "opaque-resource",
capabilityReceipt,
},
suggestedFileName: "report.pdf",
maxTransferBytes: asByteCount(10),
maxBufferedBytes: asByteCount(10),
signal: new AbortController().signal,
onProgress() {},
});
expect(handedOff).toMatchObject({
ok: true,
value: { kind: "BROWSER_HANDOFF" },
});
expect(
await adapter.deliver({
policy: browserPolicy,
source: {
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "opaque-resource",
capabilityReceipt:
asBrowserManagedDownloadCapabilityReceipt(
"capability:forged",
),
},
suggestedFileName: "report.pdf",
signal: new AbortController().signal,
onProgress() {},
}),
).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED", operation: "DOWNLOAD" },
});
const saved = await adapter.deliver({
policy: streamPolicy,
source: {
kind: "GENERATED",
bytes: {
byteLength: asByteCount(4),
stream: () => byteChunks("ab", "cd"),
},
expectedSha256:
"88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589",
},
suggestedFileName: "safe.txt",
maxTransferBytes: asByteCount(10),
maxBufferedBytes: asByteCount(10),
signal: new AbortController().signal,
onProgress(value) {
progress.push(value.transferredBytes);
},
});
expect(saved).toMatchObject({
ok: true,
value: {
kind: "SAVED",
bytesWritten: 4,
integrity: "VERIFIED",
},
});
expect(progress).toEqual([2, 4, 4]);
});
it("commits IndexedDB-like mutations atomically with CAS and idempotency", async () => {
const store = new MemoryStructuredOfflineStore<{ title: string }>({
maxBytes: 10_000,
now: () => 1_000,
});
expect(
(
await store.open({
partitionKey: "opaque-account-partition",
onLifecycle() {},
})
).ok,
).toBe(true);
const createMutation = {
kind: "PUT",
id: "one",
value: { title: "first" },
payloadVersion: 1,
expiresAtEpochMs: null,
revision: { kind: "MUST_NOT_EXIST" },
} as const;
const committed = await store.commit({
idempotencyKey: "create-one",
mutations: [createMutation],
});
expect(committed).toMatchObject({
ok: true,
value: { replayed: false, revisions: { one: 1 } },
});
expect(await store.commit({
idempotencyKey: "create-one",
mutations: [createMutation],
})).toMatchObject({ ok: true, value: { replayed: true } });
expect(
await store.commit({
idempotencyKey: "create-one",
mutations: [
{
kind: "DELETE",
id: "one",
revision: { kind: "ANY" },
},
],
}),
).toMatchObject({ ok: false, failure: { code: "CONFLICT" } });
const rejectedBatch = await store.commit({
idempotencyKey: "atomic-conflict",
mutations: [
{
kind: "PUT",
id: "two",
value: { title: "must-not-commit" },
payloadVersion: 1,
expiresAtEpochMs: null,
revision: { kind: "MUST_NOT_EXIST" },
},
{
kind: "PUT",
id: "one",
value: { title: "stale" },
payloadVersion: 1,
expiresAtEpochMs: null,
revision: { kind: "MATCH", revision: 999 },
},
],
});
expect(rejectedBatch).toMatchObject({
ok: false,
failure: { code: "CONFLICT" },
});
expect(await store.read("two")).toEqual({ ok: true, value: null });
});
it("makes quota and persistence downgrade explicit", async () => {
const store = new MemoryStructuredOfflineStore<{ value: string }>({
maxBytes: 16,
});
await store.open({ partitionKey: "partition", onLifecycle() {} });
expect(
await store.commit({
idempotencyKey: "too-large",
mutations: [
{
kind: "PUT",
id: "one",
value: { value: "far larger than the approved storage budget" },
payloadVersion: 1,
expiresAtEpochMs: null,
revision: { kind: "MUST_NOT_EXIST" },
},
],
}),
).toMatchObject({
ok: false,
failure: { code: "QUOTA_EXCEEDED" },
});
const durability = new MemoryStorageDurabilityAdapter(
70,
100,
"DENIED",
);
expect(await durability.inspect()).toMatchObject({
ok: true,
value: { pressure: "PRESSURE" },
});
expect(
await durability.requestPersistence({
reason: "PROTECT_UNSYNCED_USER_DATA",
userInitiated: true,
}),
).toEqual({ ok: true, value: "DENIED" });
});
it("keeps partially written OPFS objects invisible until logical commit", async () => {
const storagePolicy: BrowserStoragePolicy = {
owner: "recipe-test",
namespace: "durable-objects",
classification: "PERSONAL",
authority: "LOCAL_FIRST",
accountScope: "OPAQUE_PARTITION",
retention: { kind: "EXPLICIT_DELETE" },
softBudgetBytes: 32,
hardBudgetBytes: 64,
evictionPriority: "USER_AUTHORED",
logoutAction: "EXPORT_THEN_PURGE",
accountDeletionAction: "PURGE_PARTITION",
pressureAction: "RETAIN",
unavailableFallback: "EXPORT_REQUIRED",
};
const store = new MemoryDurableObjectStore({
scope: {
namespace: "durable-objects",
authorityToken: "authority_12345678",
namespaceToken: "namespace_12345678",
partitionToken: "partition_12345678",
},
storagePolicy,
maxObjectBytes: 32,
});
// The recipe brands are still accepted by the runtime port.
const objectId = asDurableObjectId("object_opaque_0001");
const source = (...values: ReadonlyArray<string>) => ({
byteLength: values.join("").length,
stream: () => byteChunks(...values),
});
store.failNextPutAfter("PREPARING");
expect(
await store.put({
objectId,
expectedGeneration: null,
mediaType: "application/octet-stream",
source: source("ab", "cd"),
}),
).toMatchObject({
ok: false,
error: { code: "UNAVAILABLE", recovery: "RECONCILE" },
});
expect(await store.open({ objectId })).toMatchObject({
ok: false,
error: { code: "NOT_FOUND" },
});
// Like the runtime, reconcile rolls a put that stopped before FILES_READY
// back. One that stopped after it is committed (2026-11-03 05-04, below).
expect(await store.reconcile()).toMatchObject({
ok: true,
value: { rolledBackTransactions: 1, moreTransactionsAvailable: false },
});
expect(
await store.put({
objectId,
expectedGeneration: null,
mediaType: "application/octet-stream",
source: { byteLength: 4, stream: failedByteChunks },
}),
).toMatchObject({
ok: false,
error: { code: "NOT_READABLE", operation: "OBJECT_WRITE" },
});
// A put that fails on its own compensates, so nothing is left behind.
expect(await store.reconcile()).toMatchObject({
ok: true,
value: { rolledBackTransactions: 0 },
});
expect(
await store.put({
objectId,
expectedGeneration: null,
mediaType: "application/octet-stream",
source: source("abcd"),
}),
).toMatchObject({
ok: true,
value: {
objectId,
generation: 1,
byteLength: 4,
integrity: { algorithm: "SHA-256-TREE-V1" },
},
});
const opened = await store.open({ objectId });
expect(opened.ok).toBe(true);
if (opened.ok) {
const bytes: number[] = [];
for await (const chunk of opened.value.source.stream(
new AbortController().signal,
)) {
expect(chunk.ok).toBe(true);
if (chunk.ok) bytes.push(...chunk.value);
}
expect(new TextDecoder().decode(new Uint8Array(bytes))).toBe("abcd");
}
expect(
await store.remove({
objectId,
expectedGeneration: asObjectGeneration(2),
}),
).toMatchObject({ ok: false, error: { code: "CONFLICT" } });
expect(
await store.enforcePolicies({ reason: "ACCOUNT_DELETION" }),
).toMatchObject({
ok: true,
value: { removedObjects: 1, chunkSweep: "COMPLETED" },
});
expect(await store.open({ objectId })).toMatchObject({
ok: false,
error: { code: "NOT_FOUND" },
});
});
it("stages and activates only exact public Cache Storage representations", async () => {
const cache = new MemoryPublicResponseCache({
origin: "https://app.example.test",
maxEntryBytes: 1_000,
allowedMediaTypes: new Set(["text/javascript"]),
});
const entry = {
url: "https://app.example.test/assets/app.js?v=1#ignored",
byteLength: asByteCount(100),
mediaType: "text/javascript",
integritySha256: "sha256-entry",
requestCredentials: "OMIT" as const,
dataClass: "PUBLIC" as const,
};
expect(
await cache.stageRelease({
releaseId: "release-1",
manifestDigest: "manifest-1",
entries: [entry],
signal: new AbortController().signal,
}),
).toEqual({ ok: true, value: undefined });
expect(
await cache.activateRelease({
releaseId: "release-1",
manifestDigest: "manifest-1",
expectedPreviousReleaseId: null,
}),
).toEqual({ ok: true, value: undefined });
expect(
await cache.lookup({
url: "https://app.example.test/assets/app.js?v=1",
requestCredentials: "OMIT",
hasAuthorization: false,
}),
).toMatchObject({ ok: true, value: { kind: "HIT" } });
expect(
await cache.lookup({
url: "https://app.example.test/assets/app.js?v=2",
requestCredentials: "OMIT",
hasAuthorization: false,
}),
).toEqual({
ok: true,
value: { kind: "MISS", reason: "NOT_FOUND" },
});
expect(
await cache.stageRelease({
releaseId: "poisoned",
manifestDigest: "bad",
entries: [{ ...entry, url: "https://app.example.test/config.json" }],
signal: new AbortController().signal,
}),
).toMatchObject({
ok: false,
failure: { code: "POLICY_REJECTED" },
});
// [0929] 05-03. Reported in the runtime's `PublicCacheInspection` shape.
expect(await cache.inspect()).toEqual({
ok: true,
value: {
activePointer: "READABLE",
activeReleaseRegistryId: "release-1",
ownedCacheCount: 1,
unreadableOwnedCacheCount: 0,
releaseCandidates: [],
},
});
});
});
/**
* 2026-11-03 05-04. The fake rolled every stopped put back, while the runtime
* commits one that stopped after FILES_READY and rolls back one that stopped
* while PREPARING. A downstream test written against the fake then passed
* "a stopped upload is gone after reconcile" although the runtime brings the
* file back. The same scenarios now run on both and must agree.
*/
describe("the durable object fake reconciles a stopped put like the runtime (2026-11-03 05-04)", () => {
type StoppablePhase = "PREPARING" | "FILES_READY";
type StoppableStore = Readonly<{
store: DurableObjectStorePort & DurableObjectMaintenancePort;
stopNextPutAfter(phase: StoppablePhase): void;
}>;
const scope = Object.freeze({
namespace: "durable-objects",
authorityToken: "authority_12345678",
namespaceToken: "namespace_12345678",
partitionToken: "partition_12345678",
});
const storagePolicy: BrowserStoragePolicy = Object.freeze({
owner: "recipe-test",
namespace: "durable-objects",
classification: "PERSONAL",
authority: "LOCAL_FIRST",
accountScope: "OPAQUE_PARTITION",
retention: Object.freeze({ kind: "EXPLICIT_DELETE" }),
softBudgetBytes: 32,
hardBudgetBytes: 64,
evictionPriority: "USER_AUTHORED",
logoutAction: "EXPORT_THEN_PURGE",
accountDeletionAction: "PURGE_PARTITION",
pressureAction: "RETAIN",
unavailableFallback: "EXPORT_REQUIRED",
});
function fake(): StoppableStore {
const store = new MemoryDurableObjectStore({
scope,
storagePolicy,
maxObjectBytes: 32,
});
return { store, stopNextPutAfter: (phase) => store.failNextPutAfter(phase) };
}
/** The reference runtime on an in-memory OPFS root and IndexedDB. */
function runtime(): StoppableStore {
const policy = resolveOpfsRuntimePolicy({
chunkSizeBytes: 64 * 1024,
maxObjectBytes: 64 * 1024,
maxChunkCount: 1,
});
const worker = createOpfsWorkerRuntime({
root: new MemoryDirectory() as unknown as FileSystemDirectoryHandle,
crypto: globalThis.crypto,
policy,
leaseManager: createWebLockLeaseManager(
navigator.locks,
`${policy.mutationLockName}:${crypto.randomUUID()}`,
),
dedicatedWorker: true,
supportsSynchronousAccessHandles: false,
});
let listener: ((event: MessageEvent<unknown>) => void) | undefined;
const gateway = createOpfsWorkerGateway({
worker: {
postMessage(message) {
void worker
.handleRequest(message)
.then((response) => listener?.({ data: response } as MessageEvent<unknown>));
},
addEventListener(_type, next) {
listener = next;
},
removeEventListener() {
listener = undefined;
},
},
policy,
});
const idb = new MemoryIndexedDbFactory();
const journal = createIndexedDbOpfsJournal({
authorityToken: scope.authorityToken,
factory: idb.factory,
keyRange: idb.keyRange,
});
let stopAfter: StoppablePhase | null = null;
let compensationLost = false;
// The tab closes at this step: the journal write never lands and, before
// commit, neither does its compensation.
const crashed = async () => {
compensationLost = stopAfter === "PREPARING";
stopAfter = null;
return browserDataFailure("UNAVAILABLE", "INDEXEDDB_WRITE", {
retryable: true,
recovery: "RETRY",
});
};
const { objects, maintenance } = createOpfsByteStoreAdapter({
journal: {
...journal,
markFilesReady: (...input) =>
stopAfter === "PREPARING" ? crashed() : journal.markFilesReady(...input),
commitPut: (...input) =>
stopAfter === "FILES_READY" ? crashed() : journal.commitPut(...input),
},
worker: {
...gateway,
async abortPreparedPut(input) {
if (!compensationLost) return await gateway.abortPreparedPut(input);
compensationLost = false;
return browserDataFailure("UNAVAILABLE", "OBJECT_WRITE", {
retryable: true,
recovery: "RETRY",
});
},
},
scope,
storagePolicy,
policy,
requestMaintenanceAuthority: () => ({
authorized: true as const,
proofToken: "proof_token_1234567890",
expiresAtEpochMs: Date.now() + 60_000,
}),
consumeMaintenanceAuthority: () => true,
});
return {
store: { ...objects, ...maintenance },
stopNextPutAfter(phase) {
stopAfter = phase;
},
};
}
async function stoppedPut(
{ store, stopNextPutAfter }: StoppableStore,
phase: StoppablePhase,
purgeBeforeReconcile: boolean,
) {
const objectId = asDurableObjectId("object_opaque_0001");
const opened = async () => {
const result = await store.open({ objectId });
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 new TextDecoder().decode(new Uint8Array(bytes));
};
stopNextPutAfter(phase);
const put = await store.put({
objectId,
expectedGeneration: null,
mediaType: "application/octet-stream",
source: { byteLength: 4, stream: () => byteChunks("ab", "cd") },
});
const beforeReconcile = await opened();
const purge = purgeBeforeReconcile
? await store.enforcePolicies({ reason: "ACCOUNT_DELETION" })
: null;
const reconciled = await store.reconcile();
if (!reconciled.ok || (purge && !purge.ok)) {
throw new Error("maintenance failed");
}
return {
putSucceeded: put.ok,
beforeReconcile,
purge: purge && {
partitionDeleted: purge.value.partitionDeleted ?? false,
chunkSweep: purge.value.chunkSweep ?? null,
},
committedTransactions: reconciled.value.committedTransactions,
rolledBackTransactions: reconciled.value.rolledBackTransactions,
afterReconcile: await opened(),
};
}
it.each([
["FILES_READY", false, { committed: 1, rolledBack: 0, after: "abcd" }],
["PREPARING", false, { committed: 0, rolledBack: 1, after: "NOT_FOUND" }],
["FILES_READY", true, { committed: 0, rolledBack: 0, after: "NOT_FOUND" }],
["PREPARING", true, { committed: 0, rolledBack: 0, after: "NOT_FOUND" }],
] as const)(
"agrees on a put stopped after %s (account deleted before reconcile: %s)",
async (phase, purge, expected) => {
const fromRuntime = await stoppedPut(runtime(), phase, purge);
expect(fromRuntime).toEqual({
putSucceeded: false,
beforeReconcile: "NOT_FOUND",
purge: purge ? { partitionDeleted: true, chunkSweep: null } : null,
committedTransactions: expected.committed,
rolledBackTransactions: expected.rolledBack,
afterReconcile: expected.after,
});
expect(await stoppedPut(fake(), phase, purge)).toEqual(fromRuntime);
},
);
});