diff --git a/src/application/ports/browser-file-storage/opfs-ports.ts b/src/application/ports/browser-file-storage/opfs-ports.ts index 7091ab07..b0971694 100644 --- a/src/application/ports/browser-file-storage/opfs-ports.ts +++ b/src/application/ports/browser-file-storage/opfs-ports.ts @@ -85,6 +85,14 @@ export interface DurableObjectStorePort { put( request: PutDurableObjectRequest, ): Promise>; + /** + * 05-14. `open` checks the manifest; the bytes are read and verified while + * the source streams. A put that replaces the object meanwhile leaves the + * older generation's chunks to orphan GC, whose grace counts from when a + * chunk was written, not from when it lost its last reference. A stream + * that reaches a chunk GC already took ends with `NOT_FOUND` / `REHYDRATE`. + * Nothing is lost: open again to read the generation that replaced it. + */ open( request: OpenDurableObjectRequest, ): Promise>; diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index d1b1bae3..b36b5115 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -2454,3 +2454,54 @@ describe("05-10 the object id grammar is the prepared-object grammar", () => { ).toThrow(TypeError); }); }); + +describe("05-14 a read that outlives its generation", () => { + it("ends with NOT_FOUND / REHYDRATE once GC took the replaced chunks, and a reopen reads the new generation", async () => { + const { root, tab } = sharedRootTabs(); + const store = tab("r"); + const put = (bytes: number[], expectedGeneration: number | null) => + store.objects.put({ + objectId: "object_12345678", + expectedGeneration, + mediaType: "application/octet-stream", + source: bytesSource(new Uint8Array(bytes)), + }); + expect(await put([1], null)).toMatchObject({ ok: true }); + const opened = await store.objects.open({ objectId: "object_12345678" }); + if (!opened.ok) throw new Error(opened.error.code); + + // Generation 2 replaces it, and its old chunk is past the GC grace. + expect(await put([2], 1)).toMatchObject({ ok: true }); + const digest = Array.from( + new Uint8Array( + await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array([1])), + ), + (byte) => byte.toString(16).padStart(2, "0"), + ).join(""); + memoryFileAt(root, chunkFilePath(scopeA, digest)).lastModified = 0; + expect(await store.maintenance.reconcile()).toMatchObject({ + ok: true, + value: { deletedOrphanChunks: 1 }, + }); + + const chunks = []; + for await (const chunk of opened.value.source.stream( + new AbortController().signal, + )) { + chunks.push(chunk); + } + expect(chunks).toEqual([ + expect.objectContaining({ + ok: false, + error: expect.objectContaining({ + code: "NOT_FOUND", + recovery: "REHYDRATE", + }), + }), + ]); + expect(await openedBytes(store, "object_12345678")).toEqual({ + generation: 2, + bytes: [2], + }); + }); +});