Files
unkernel/test/opfs-disk.test.ts

499 lines
21 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Unit tests for OpfsDisk (core/opfs-disk.ts) and the OPFS data disk
// (web/disk.ts openDataDisk({ backend: "opfs" }), importDataDisk) over an
// in-memory directory that stands in for OPFS: extents, the two-slot
// header, lazy handles and request order, discard, flush and crashes,
// write generations and snapshots, seeding cut off by a crash, growing,
// the lock, export, detach and failed writes.
//
// node --test test/opfs-disk.test.ts
import test from "node:test";
import assert from "node:assert/strict";
import { CowDisk, ZeroBase, type OverlayStore, type StoreIndex } from "../js/core/block.ts";
import { decodeKwsparse, encodeKwsparse } from "../js/core/kwsparse.ts";
import { DiskInUseError, OPFS_EXTENT, OpfsDisk, decodeHeader, encodeHeaderSlot, type OpfsDiskDir, type OpfsHeader, type OpfsSyncFile } from "../js/core/opfs-disk.ts";
import { DATA_DISK_FENCE, fencedIdentity, importDataDisk, isFencedIdentity, openDataDisk } from "../js/web/disk.ts";
const B = 4096;
const E = OPFS_EXTENT;
const MiB = 1048576;
/** One file: its bytes now, and what a crash leaves (the bytes at its last flush). */
class FakeFile {
data = new Uint8Array(0);
durable = new Uint8Array(0);
open = false;
flushes = 0;
}
const named = (name: string, msg: string) => Object.assign(new Error(msg), { name });
/**
* An OpfsDiskDir in memory. Opening is asynchronous (a macrotask) and can be
* held until the test releases it; writes can fail (a quota on the sum of
* lengths, as Chromium charges it). crash() drops everything not flushed.
*/
class FakeDir implements OpfsDiskDir {
files = new Map<string, FakeFile>();
holdOpens = false;
pending: Array<() => void> = [];
opens = 0;
quota = Infinity;
failFlush = false;
async list(): Promise<string[]> {
return [...this.files.keys()];
}
open(name: string, create: boolean): Promise<OpfsSyncFile> {
const run = (): OpfsSyncFile => {
let f = this.files.get(name);
if (!f) {
if (!create) throw named("NotFoundError", `${name}: not found`);
f = new FakeFile();
this.files.set(name, f);
}
if (f.open) throw new DiskInUseError(`${name}: open elsewhere`);
f.open = true;
this.opens++;
return this.#handle(f);
};
return new Promise((resolve, reject) => {
const go = () => { try { resolve(run()); } catch (e) { reject(e); } };
if (this.holdOpens) this.pending.push(go);
else setTimeout(go, 0);
});
}
#handle(f: FakeFile): OpfsSyncFile {
let closed = false;
const live = () => { if (closed) throw named("InvalidStateError", "closed"); };
const used = () => { let n = 0; for (const x of this.files.values()) n += x.data.length; return n; };
return {
read: (buf, { at }) => {
live();
const n = Math.max(0, Math.min(buf.length, f.data.length - at));
buf.set(f.data.subarray(at, at + n));
return n;
},
write: (buf, { at }) => {
live();
const end = at + buf.length;
if (end > f.data.length) {
if (used() + end - f.data.length > this.quota) throw named("QuotaExceededError", "quota");
const d = new Uint8Array(end);
d.set(f.data);
f.data = d;
}
f.data.set(buf, at);
return buf.length;
},
getSize: () => { live(); return f.data.length; },
flush: () => {
live();
if (this.failFlush) throw new Error("disk gone");
f.durable = f.data.slice();
f.flushes++;
},
close: () => { if (!closed) { closed = true; f.open = false; } },
};
}
async remove(name: string): Promise<void> {
const f = this.files.get(name);
if (f?.open) throw new DiskInUseError(`${name}: open`);
this.files.delete(name);
}
async size(name: string): Promise<number> {
const f = this.files.get(name);
if (!f) throw named("NotFoundError", name);
return f.data.length;
}
release(): void { this.pending.shift()!(); }
releaseAll(): void { while (this.pending.length) this.release(); }
/** The page or browser died: every handle is gone, and each file is as at its last flush. */
crash(): void {
for (const f of this.files.values()) {
f.data = f.durable.slice();
f.open = false;
}
}
extents(): number[] {
return [...this.files.keys()].filter((n) => /^e\d+$/.test(n)).map((n) => Number(n.slice(1))).sort((a, b) => a - b);
}
}
const fill = (v: number, n = B) => new Uint8Array(n).fill(v);
const tick = () => new Promise((r) => setTimeout(r, 0));
const quiet = { log: () => {} };
async function rd(d: { read(off: number, v: Uint8Array[]): unknown }, off: number, len: number): Promise<Uint8Array> {
const v = new Uint8Array(len);
await d.read(off, [v]);
return v;
}
/** A formatted disk of `size` bytes in a fresh directory. */
async function fresh(size = 64 * MiB, opts: { maxOpen?: number; onError?: (e: unknown) => void } = {}) {
const dir = new FakeDir();
const d = await OpfsDisk.open(dir, { name: "kwdisk:test", ...quiet, ...opts });
await d.format({ identity: `test size=${size}`, size });
return { dir, d };
}
/** The small template the data disk tests seed from: blocks 0..3 and one in extent 2. */
function template(size = 64 * MiB) {
const blocks: Array<[number, Uint8Array]> = [[0, fill(0xa0)], [1, fill(0xa1)], [3, fill(0xa3)], [(2 * E) / B + 5, fill(0xa5)]];
return { size, bytes: encodeKwsparse({ size, blocks }), blocks };
}
test("format: a template's blocks land in their extents, one file per extent written; absent extents read as zeros", async () => {
const dir = new FakeDir();
const d = await OpfsDisk.open(dir, { name: "kwdisk:t", ...quiet });
assert.equal(d.complete, false);
assert.throws(() => d.read(0, [new Uint8Array(B)]), /not formatted/);
const t = template();
await d.format({ identity: "t size=1", size: t.size, image: decodeKwsparse(t.bytes) });
assert.equal(d.complete, true);
assert.deepEqual(dir.extents(), [0, 2]);
assert.equal(dir.files.get("e0")!.data.length, 4 * B, "never pre-sized: an extent is as long as its last write");
assert.deepEqual(await rd(d, 0, 4 * B), Uint8Array.from([...fill(0xa0), ...fill(0xa1), ...fill(0), ...fill(0xa3)]));
assert.deepEqual(await rd(d, E, 2 * B), fill(0, 2 * B), "a missing extent reads as zeros");
assert.deepEqual(await rd(d, 2 * E + 5 * B, B), fill(0xa5));
assert.deepEqual(await rd(d, 2 * E + 6 * B, B), fill(0), "past a short extent's end: zeros");
const uid = d.uid;
d.close();
const again = await OpfsDisk.open(dir, { name: "kwdisk:t", ...quiet });
assert.equal(again.complete, true);
assert.equal(again.uid, uid);
assert.equal(again.gen, 0);
assert.equal(again.size, t.size);
assert.equal(again.header?.origin, undefined);
again.close();
});
test("reads and writes across an extent boundary and over several views", async () => {
const { dir, d } = await fresh();
const a = fill(1, 3 * B), b = fill(2, 2 * B);
await d.write(E - 2 * B, [a, b]); // 5 blocks from 2 before the boundary
assert.deepEqual(dir.extents(), [0, 1]);
assert.equal(dir.files.get("e0")!.data.length, E);
assert.equal(dir.files.get("e1")!.data.length, 3 * B);
const x = new Uint8Array(B), y = new Uint8Array(4 * B);
await d.read(E - 2 * B, [x, y]);
assert.deepEqual(x, fill(1));
assert.deepEqual(y, Uint8Array.from([...fill(1, 2 * B), ...fill(2, 2 * B)]));
// 512-byte writes need no read-modify-write.
await d.write(E + 512, [fill(9, 512)]);
assert.deepEqual((await rd(d, E, B)).subarray(0, 1536), Uint8Array.from([...fill(1, 512), ...fill(9, 512), ...fill(1, 512)]));
});
test("handles open lazily: a miss returns a promise, and requests on one extent keep their order", async () => {
const { dir, d } = await fresh(64 * MiB, { maxOpen: 2 });
await d.write(0, [fill(1)]);
await d.write(E, [fill(2)]);
await d.write(2 * E, [fill(3)]); // a third handle: the first one is closed
assert.equal(d.stats.evictions, 1);
dir.holdOpens = true;
const data = fill(7);
const w = d.write(0, [data]);
assert.ok(w instanceof Promise, "extent 0's handle must be opened again");
data.fill(8); // the guest's page changes after the submission: the write took a copy
const w2 = d.write(B / 2, [fill(5, 512)]);
const r = d.read(0, [new Uint8Array(B)]);
assert.ok(w2 instanceof Promise && r instanceof Promise, "later requests on the extent wait for the first");
const out = new Uint8Array(B);
const r2 = d.read(0, [out]);
assert.equal(dir.pending.length, 1, "one open for all of them");
dir.releaseAll();
await Promise.all([w, w2, r, r2]);
const want = fill(7);
want.fill(5, 2048, 2560);
assert.deepEqual(out, want);
// Another extent's requests do not wait for extent 0's.
dir.holdOpens = false;
});
test("discard: a wholly covered extent is deleted, a partial one zeroed inside the file and never extended", async () => {
const { dir, d } = await fresh(32 * MiB);
await d.write(0, [fill(1, 4 * B)]);
await d.write(E, [fill(2, 4 * B)]);
await d.write(3 * E, [fill(3, B)]); // the last extent
await d.discard(E, E); // all of extent 1
assert.deepEqual(dir.extents(), [0, 3]);
assert.equal(d.stats.deletes, 1);
assert.deepEqual(await rd(d, E, B), fill(0));
await d.writeZeroes(B, 8 * B); // blocks 1..8 of extent 0, a file 4 blocks long
assert.equal(dir.files.get("e0")!.data.length, 4 * B, "zeros past the end are not written");
assert.deepEqual(await rd(d, 0, 2 * B), Uint8Array.from([...fill(1), ...fill(0)]));
await d.discard(2 * E, 2 * E); // extent 2 (missing) and 3 (the last)
assert.deepEqual(dir.extents(), [0]);
assert.deepEqual(await rd(d, 3 * E, B), fill(0));
await d.write(E + B, [fill(4)]); // a deleted extent comes back on a write
assert.deepEqual(await rd(d, E, 2 * B), Uint8Array.from([...fill(0), ...fill(4)]));
});
test("flush: only the extents written since the last flush; a crash keeps exactly what was flushed", async () => {
const { dir, d } = await fresh();
await d.write(0, [fill(1)]);
await d.write(2 * E, [fill(2)]);
await d.flush();
assert.equal(dir.files.get("e0")!.flushes, 1);
assert.equal(dir.files.get("e2")!.flushes, 1);
await d.write(B, [fill(3)]);
await d.flush();
assert.equal(dir.files.get("e0")!.flushes, 2);
assert.equal(dir.files.get("e2")!.flushes, 1, "an extent not written since is not flushed");
await d.write(2 * E, [fill(9)]); // not flushed
dir.crash();
const again = await OpfsDisk.open(dir, { name: "kwdisk:test", ...quiet });
assert.deepEqual(await rd(again, 0, 2 * B), Uint8Array.from([...fill(1), ...fill(3)]));
assert.deepEqual(await rd(again, 2 * E, B), fill(2), "the write after the last flush is gone");
});
test("a flush waits for the requests before it, and counts for requestSync", async () => {
const { dir, d } = await fresh(64 * MiB, { maxOpen: 1 });
await d.write(0, [fill(1)]);
dir.holdOpens = true;
const w = d.write(E, [fill(2)]); // a new extent: its file is being created
const mark = d.flushSeq;
const f = d.flush();
assert.ok(f instanceof Promise);
let flushed = false;
void d.whenFlushed(mark).then(() => { flushed = true; });
await tick();
assert.equal(flushed, false);
dir.releaseAll();
await Promise.all([w, f]);
await tick();
assert.equal(flushed, true);
assert.equal(dir.files.get("e1")!.durable.length, B, "the flush covered the write before it");
assert.equal(dir.files.get("e0")!.durable.length, B, "closing a written handle flushed it");
});
test("snapshots: the generation goes up before the first write after open and after each seal, durable before the data", async () => {
const { dir, d } = await fresh();
assert.equal(d.gen, 0);
const st0 = d.snapshotState();
assert.equal(st0.identity, `store kwdisk:test test size=${64 * MiB} uid=${d.uid}`);
await d.write(0, [fill(1)]);
assert.equal(d.gen, 1);
await d.write(B, [fill(1)]);
assert.equal(d.gen, 1, "one generation until the next seal");
const { state, done } = d.snapshotSeal();
await done;
assert.equal(state.gen, 1);
assert.equal(dir.files.get("e0")!.durable.length, 2 * B, "the seal flushed the data");
await d.write(0, [fill(2)]);
assert.equal(d.gen, 2);
// The header with generation 2 is durable although the data is not flushed: a crash
// now gives a disk that a restore of the generation-1 snapshot refuses.
dir.crash();
const again = await OpfsDisk.open(dir, { name: "kwdisk:test", ...quiet });
assert.equal(again.gen, 2);
assert.notEqual(again.snapshotState().gen, state.gen);
assert.equal(again.snapshotState().identity, state.identity, "same disk, other generation");
// A disk opened and only read keeps its generation; the first write bumps it.
assert.equal(again.gen, 2);
await again.write(0, [fill(3)]);
assert.equal(again.gen, 3);
});
test("snapshots: the identity is a CowDisk store's of the same name, so a copy with the uid and generation matches", async () => {
const { d } = await fresh(64 * MiB);
const identity = `test size=${64 * MiB}`;
const store: OverlayStore = {
name: "kwdisk:test",
async open(): Promise<StoreIndex> { return { keys: new Set(), initialized: true, gen: d.gen, uid: d.uid }; },
async getBlocks() { return new Map(); },
async save() {},
async clear() {},
};
const cow = new CowDisk(new ZeroBase(64 * MiB), { store, log: () => {} });
cow.adoptStore(await store.open(identity), identity);
assert.deepEqual(cow.snapshotState(), d.snapshotState());
});
test("seeding cut off by a crash: the disk is not complete, and openDataDisk wipes it and seeds it again", async () => {
const dir = new FakeDir();
const t = template();
// An earlier disk with an extent the template does not have.
const first = await OpfsDisk.open(dir, { name: "kwdisk:kwdata-v1", ...quiet });
await first.format({ identity: `kwdata-v1 size=${t.size} bs=4096`, size: t.size });
await first.write(5 * E, [fill(5)]);
first.close();
// A format that dies after a few blocks.
const d = await OpfsDisk.open(dir, { name: "kwdisk:kwdata-v1", ...quiet });
await d.beginFormat({ identity: `kwdata-v1 size=${t.size} bs=4096`, size: t.size, origin: "template" });
await d.putBlocks([[0, fill(0xa0)]]);
dir.crash();
const half = await OpfsDisk.open(dir, { name: "kwdisk:kwdata-v1", ...quiet });
assert.equal(half.complete, false);
assert.equal(half.header?.complete, false);
half.close();
const logs: string[] = [];
const disk = await openDataDisk({ backend: "opfs", dir, template: t.bytes, log: (m) => logs.push(m) });
assert.equal(disk.seeded, true);
assert.ok(logs.some((m) => /cut off/.test(m)), logs.join("\n"));
assert.deepEqual(dir.extents(), [0, 2], "the stale extent went with the wipe");
assert.deepEqual(await rd(disk, 3 * B, B), fill(0xa3));
assert.equal(disk.identity, `kwdata-v1 size=${t.size} bs=4096`);
disk.close();
// Complete now: a second open adopts it.
const again = await openDataDisk({ backend: "opfs", dir, template: t.bytes, ...quiet });
assert.equal(again.seeded, false);
again.close();
});
test("a torn header write leaves the older slot; a disk of another format is refused untouched", async () => {
const dir = new FakeDir();
const t = template();
const disk = await openDataDisk({ backend: "opfs", dir, template: t.bytes, ...quiet });
await disk.write(0, [fill(1)]); // generation 1: a header write
const seq = disk.header!.seq;
disk.close();
const meta = dir.files.get("meta")!;
// Tear the newest slot.
const at = (seq & 1) * 4096;
meta.data[at + 20]! ^= 0xff;
const h = decodeHeader(meta.data);
assert.equal(h?.seq, seq - 1);
assert.equal(h?.complete, true);
meta.durable = meta.data.slice();
// Another identity in the header: DataDiskFormatError, nothing changed.
const other: OpfsHeader = { ...h!, seq: seq + 5, identity: "kwdata-v1 size=1 bs=512" };
meta.data.set(encodeHeaderSlot(other), ((seq + 5) & 1) * 4096);
const before = [...dir.files.keys()];
await assert.rejects(openDataDisk({ backend: "opfs", dir, template: t.bytes, ...quiet }), { name: "DataDiskFormatError" });
assert.deepEqual([...dir.files.keys()], before);
assert.equal(dir.files.get("meta")!.open, false, "the refused disk's lock is let go");
});
test("grow: a larger size relabels the identity and the new space reads as zeros; never shrinks; no snapshot mode", async () => {
const dir = new FakeDir();
const t = template();
const d = await openDataDisk({ backend: "opfs", dir, template: t.bytes, ...quiet });
assert.equal(d.size, t.size);
d.close();
const big = await openDataDisk({ backend: "opfs", dir, template: t.bytes, size: 2 * t.size, ...quiet });
assert.equal(big.size, 2 * t.size);
assert.equal(big.identity, `kwdata-v1 size=${2 * t.size} bs=4096`);
assert.deepEqual(await rd(big, t.size + B, B), fill(0));
big.close();
const small = await openDataDisk({ backend: "opfs", dir, template: t.bytes, size: t.size, ...quiet });
assert.equal(small.size, 2 * t.size, "a disk never shrinks");
assert.throws(() => small.grow(t.size, "x"), /never shrinks/);
small.close();
await assert.rejects(openDataDisk({ backend: "opfs", dir, template: t.bytes, mode: "snapshot", ...quiet }), /no snapshot mode/);
});
test("the meta file is the lock: a second opener gets DiskInUseError, and gets it once the first lets go", async () => {
const dir = new FakeDir();
const t = template();
const a = await openDataDisk({ backend: "opfs", dir, template: t.bytes, ...quiet });
await assert.rejects(openDataDisk({ backend: "opfs", dir, template: t.bytes, waitMs: 150, ...quiet }), { name: "DiskInUseError" });
const late = openDataDisk({ backend: "opfs", dir, template: t.bytes, waitMs: 3000, ...quiet });
setTimeout(() => a.close(), 200); // a worker that ends a little later
const b = await late;
assert.equal(b.complete, true);
b.close();
});
test("export: kwsparse of the blocks that are not all zeros; import replaces the disk with a new uid", async () => {
const dir = new FakeDir();
const t = template();
const d = await openDataDisk({ backend: "opfs", dir, template: t.bytes, ...quiet });
await d.write(E + 2 * B, [fill(6)]);
await d.writeZeroes(B, B); // block 1 becomes zeros inside the file
const { parts, blocks, size } = await d.exportParts();
assert.equal(size, t.size);
const img = decodeKwsparse(new Uint8Array(await new Blob(parts).arrayBuffer()));
assert.deepEqual(img.indices, [0, 3, E / B + 2, (2 * E) / B + 5]);
assert.equal(blocks, 4);
assert.deepEqual(img.block(2), fill(6));
const uid = d.uid;
d.close();
const other = encodeKwsparse({ size: 2 * t.size, blocks: [[7, fill(7)]] });
const r = await importDataDisk(other, { backend: "opfs", dir, ...quiet });
assert.deepEqual(r, { size: 2 * t.size, blocks: 1 });
const back = await openDataDisk({ backend: "opfs", dir, template: t.bytes, ...quiet });
assert.equal(back.size, 2 * t.size);
assert.notEqual(back.uid, uid);
assert.equal(back.header?.origin, "imported");
assert.deepEqual(await rd(back, 0, B), fill(0));
assert.deepEqual(await rd(back, 7 * B, B), fill(7));
assert.deepEqual(dir.extents(), [0]);
back.close();
});
test("detach: the requests in flight finish, then every request fails and the files are let go", async () => {
const { dir, d } = await fresh();
dir.holdOpens = true;
const w = d.write(E, [fill(4)]);
const det = d.detach();
assert.throws(() => d.write(0, [fill(1)]), /detached/);
assert.equal(d.persistent, false);
assert.throws(() => d.snapshotState(), /detached/);
dir.releaseAll();
await w;
await det;
assert.equal(dir.files.get("e1")!.durable.length, B, "flushed before closing");
assert.ok([...dir.files.values()].every((f) => !f.open), "no handle left open");
dir.holdOpens = false;
const again = await OpfsDisk.open(dir, { name: "kwdisk:test", ...quiet });
assert.deepEqual(await rd(again, E, B), fill(4));
again.close();
});
test("a failed write or flush throws (EIO in the guest) and reports to onError; QuotaExceededError included", async () => {
const errors: unknown[] = [];
const { dir, d } = await fresh(64 * MiB, { onError: (e) => errors.push(e) });
await d.write(0, [fill(1)]);
dir.quota = dir.files.get("meta")!.data.length + B + 512;
await assert.rejects(Promise.resolve().then(() => d.write(E, [fill(2)])), { name: "QuotaExceededError" });
assert.equal(errors.length, 1);
assert.equal((errors[0] as Error).name, "QuotaExceededError");
assert.throws(() => d.write(B, [fill(2)]), { name: "QuotaExceededError" }, "the open extent fails synchronously");
assert.equal(errors.length, 2);
assert.equal(d.stats.errors, 2);
dir.quota = Infinity;
await d.write(B, [fill(2)]);
// A flush that fails: the extent stays dirty and the next flush retries it.
dir.failFlush = true;
assert.throws(() => d.flush(), /disk gone/);
assert.equal(errors.length, 3);
dir.failFlush = false;
await d.flush();
assert.equal(dir.files.get("e0")!.durable.length, 2 * B);
});
test("a request that waited leaves nothing behind once it settles: a seal right then works", async () => {
const { dir, d } = await fresh(64 * MiB, { maxOpen: 1 });
await d.write(0, [fill(1)]);
dir.holdOpens = true;
const w = d.write(E, [fill(2)]) as Promise<unknown>;
let sealed: unknown = null;
// As BlockHost does: completion handled in a reaction registered after the call returned.
const seen = w.then(() => { sealed = d.snapshotSeal().state; });
assert.throws(() => d.snapshotSeal(), /in flight/);
dir.releaseAll();
await seen;
assert.equal((sealed as { gen: number }).gen, d.gen);
assert.equal(d.saving, null);
});
test("the fence: a moved IndexedDB identity is one an older page's identity parser refuses", () => {
const id = `kwdata-v1 size=${4 * 1024 * MiB} bs=4096`;
const f = fencedIdentity(id);
assert.equal(f, id + DATA_DISK_FENCE);
assert.equal(fencedIdentity(f), f, "fencing twice changes nothing");
assert.ok(isFencedIdentity(f) && !isFencedIdentity(id));
// The SDK's identity match (web/disk.ts identitySize(), the same in older releases) does not take it.
assert.equal(/^(.*) size=(\d+) bs=(\d+)$/.test(f), false);
});