Files
unkernel/js/web/disk.ts

913 lines
43 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Browser disks: an image served over HTTP (read lazily with Range
// requests) under a copy-on-write overlay that is saved in IndexedDB, and
// the persistent data disk (an ext4 file system kept in IndexedDB, or in
// OPFS extent files: core/opfs-disk.ts, web/opfs.ts).
import { BaseDisk, CowDisk, HttpBase, SparseBase, ZeroBase, type OverlayStore, type StoreIndex } from "../core/block.ts";
import { DistroDisk } from "../core/distro.ts";
import { decodeKwsparse, gunzipIfNeeded, isZeroBlock, type KwsparseImage } from "../core/kwsparse.ts";
import { OPFS_EXTENT, OpfsDisk, type OpfsDiskDir } from "../core/opfs-disk.ts";
import { OpfsUnavailableError, opfsDiskBlocker, opfsDiskDir, readOpfsHeader, removeOpfsDisk } from "./opfs.ts";
const BLOCK = 4096;
// ---------------------------------------------------------------------------
// Overlay persistence in IndexedDB (one database per disk name).
//
// Object stores: "blocks" (block number -> Uint8Array(4096), or an empty
// Uint8Array for a block of zeros over a non-zero base) and "meta"
// ("identity": what the blocks belong to; "initialized": a seeded data disk;
// "uid": a random id, new whenever the store is created, seeded or cleared;
// "gen": the disk's write generation, saved in the same transaction as the
// blocks, which machine snapshots check, see core/block.ts).
//
// Every save is one readwrite transaction, so the stored state is always
// the state after some complete flush. Transactions use durability
// "strict": the kernel issues a flush where it needs data to be durable
// (fsync, sync, an ext4 journal commit every 5 s), and a strict commit is
// flushed to the device before it completes, so it also survives an OS crash
// or power loss, not only a closed tab or a browser crash. The cost is one
// device flush per guest flush; "relaxed" would still keep each flush atomic
// and in order, but could lose the newest ones.
const reqP = <T>(r: IDBRequest<T>): Promise<T> =>
new Promise((res, rej) => { r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); });
const EMPTY = new Uint8Array(0);
// Not crypto.randomUUID(): that needs a secure context, and the page also runs on plain http.
const newUid = (): string => Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
export interface IdbStoreOptions {
log?: ((msg: string) => void) | null;
durability?: IDBTransactionDurability;
}
/** Overlay persistence in IndexedDB: database "kwdisk:<name>". */
export class IdbStore implements OverlayStore {
readonly name: string;
log: (msg: string) => void;
durability: IDBTransactionDurability;
dbp: Promise<IDBDatabase> | null = null;
constructor(name: string, { log = null, durability = "strict" }: IdbStoreOptions = {}) {
this.name = `kwdisk:${name}`;
this.log = log ?? ((m) => console.warn(m));
this.durability = durability;
}
/** The open connection, reopened if the browser closed it or another version needs it. */
#open(): Promise<IDBDatabase> {
if (this.dbp) return this.dbp;
const p: Promise<IDBDatabase> = new Promise((resolve, reject) => {
const r = indexedDB.open(this.name, 1);
r.onupgradeneeded = () => {
r.result.createObjectStore("blocks");
r.result.createObjectStore("meta");
};
r.onsuccess = () => {
const db = r.result;
db.onversionchange = () => {
// Another tab deletes or upgrades the database: let it.
this.log(`[host] ${this.name}: closing the IndexedDB connection (version change requested elsewhere)`);
db.close();
if (this.dbp === p) this.dbp = null;
};
// The browser closed it (storage cleared, disk error): reopen on next use.
db.onclose = () => { if (this.dbp === p) this.dbp = null; };
resolve(db);
};
r.onerror = () => reject(r.error);
r.onblocked = () => this.log(`[host] ${this.name}: waiting for another tab to release IndexedDB`);
});
this.dbp = p;
p.catch(() => { if (this.dbp === p) this.dbp = null; });
return p;
}
static #done(tx: IDBTransaction): Promise<void> {
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = tx.onabort = () => reject(tx.error ?? new DOMException("IndexedDB transaction aborted", "AbortError"));
});
}
/**
* Run fn(tx) in a transaction and wait for it to commit; returns what fn
* returned (awaited). A failure other than a full quota is retried once
* on a fresh connection (fn must be idempotent).
*/
async #run<T>(stores: string | string[], mode: IDBTransactionMode, fn: (tx: IDBTransaction) => T | Promise<T>, retry = true): Promise<T> {
try {
const db = await this.#open();
const tx = db.transaction(stores, mode, mode === "readwrite" ? { durability: this.durability } : undefined);
const done = IdbStore.#done(tx);
let r: Promise<T>;
try {
r = Promise.resolve(fn(tx));
} catch (e) {
done.catch(() => {});
tx.abort();
throw e;
}
r.catch(() => {});
await done;
return await r;
} catch (e) {
const err = e as Error;
if (!retry || err?.name === "QuotaExceededError") throw e;
this.log(`[host] ${this.name}: ${err?.name ?? "error"}: ${err?.message ?? e}; reopening and retrying once`);
if (this.dbp) {
try { (await this.dbp).close(); } catch {}
this.dbp = null;
}
return this.#run(stores, mode, fn, false);
}
}
/**
* Read the index: the numbers of all stored blocks (not their data).
* If the database belongs to another identity: onMismatch "clear" drops
* the blocks (logged loudly), "refuse" leaves everything alone and
* returns {mismatch: storedIdentity}. With write: false nothing is
* written (a read-only transaction; a fresh database stays unmarked).
*/
async open(identity: string, { onMismatch = "refuse", write = true }: { onMismatch?: "clear" | "refuse"; write?: boolean } = {}): Promise<StoreIndex> {
const res = await this.#run<StoreIndex>(["blocks", "meta"], write ? "readwrite" : "readonly", async (tx) => {
const blocks = tx.objectStore("blocks"), meta = tx.objectStore("meta");
let [id, init, gen, uid0] = await Promise.all([reqP(meta.get("identity")), reqP(meta.get("initialized")),
reqP(meta.get("gen")), reqP(meta.get("uid"))]);
// A reset that was cut off before its blocks were deleted (clear()):
// the disk is empty, and a writer finishes the job here.
if (await reqP(meta.get("reset"))) {
if (!write) return { keys: new Set(), initialized: false, gen: 0 };
blocks.clear();
meta.clear();
id = init = gen = uid0 = undefined;
}
if (id !== undefined && id !== identity) {
if (onMismatch !== "clear" || !write) return { keys: new Set(), initialized: !!init, mismatch: String(id) };
blocks.clear();
meta.delete("initialized");
meta.delete("gen");
const uid = newUid();
meta.put(uid, "uid");
meta.put(identity, "identity");
return { keys: new Set(), initialized: false, cleared: String(id), gen: 0, uid };
}
if (id === undefined && write) meta.put(identity, "identity");
let uid = typeof uid0 === "string" ? uid0 : undefined;
if (uid === undefined && write) meta.put(uid = newUid(), "uid");
const keys = await reqP(blocks.getAllKeys());
return { keys: new Set(keys as number[]), initialized: !!init, gen: typeof gen === "number" ? gen : 0, uid };
});
if (res.cleared !== undefined) {
this.log(`[host] ${this.name}: THE SAVED CHANGES WERE DROPPED: they belong to another image ` +
`("${res.cleared}", now "${identity}")`);
}
return res;
}
/** Records for the given block numbers: Map block -> Uint8Array (missing blocks are absent). */
async getBlocks(blocks: number[]): Promise<Map<number, Uint8Array>> {
if (!blocks.length) return new Map();
let lo = Infinity, hi = -Infinity;
for (const b of blocks) { if (b < lo) lo = b; if (b > hi) hi = b; }
const want = new Set(blocks);
return this.#run("blocks", "readonly", async (tx) => {
const s = tx.objectStore("blocks");
const out = new Map<number, Uint8Array>();
if (want.size === 1) {
const v = await reqP(s.get(lo));
if (v !== undefined) out.set(lo, v as Uint8Array);
return out;
}
const range = IDBKeyRange.bound(lo, hi);
const [keys, vals] = await Promise.all([reqP(s.getAllKeys(range)), reqP(s.getAll(range))]);
for (let i = 0; i < keys.length; i++) {
const k = keys[i] as number;
if (want.has(k)) out.set(k, vals[i] as Uint8Array);
}
return out;
});
}
/** One transaction: put [block, data] pairs, delete block numbers, and record the write generation if given. */
async save(puts: Array<[number, Uint8Array]>, dels: number[] = [], meta?: { gen: number }): Promise<void> {
await this.#run(meta ? ["blocks", "meta"] : "blocks", "readwrite", (tx) => {
const s = tx.objectStore("blocks");
for (const [b, v] of puts) s.put(v, b); // structured clone happens here
for (const b of dels) s.delete(b);
if (meta) tx.objectStore("meta").put(meta.gen, "gen");
});
}
/** One transaction: replace everything with these blocks and mark the store initialized (a new uid, generation 0). Returns the uid. */
async seed(entries: Iterable<[number, Uint8Array]>, identity: string): Promise<string> {
const uid = newUid();
await this.#run(["blocks", "meta"], "readwrite", (tx) => {
const s = tx.objectStore("blocks"), meta = tx.objectStore("meta");
s.clear();
for (const [b, v] of entries) s.put(v, b);
meta.put(identity, "identity");
meta.put(true, "initialized");
meta.put(uid, "uid");
meta.delete("gen");
meta.delete("reset");
});
return uid;
}
/** All records, read in one transaction (a consistent snapshot). */
async readAll(): Promise<Map<number, Uint8Array>> {
return this.#run("blocks", "readonly", async (tx) => {
const s = tx.objectStore("blocks");
const [keys, vals] = await Promise.all([reqP(s.getAllKeys()), reqP(s.getAll())]);
return new Map(keys.map((k, i) => [k as number, vals[i] as Uint8Array]));
});
}
async count(): Promise<number> {
return this.#run("blocks", "readonly", (tx) => reqP(tx.objectStore("blocks").count()));
}
/**
* Forget everything. Deleting a large disk's blocks takes a while, and a
* page that reloads meanwhile aborts the transaction, so a marker is
* committed first (a small transaction): open() treats a marked store
* as empty and finishes the deletion.
*/
async clear(): Promise<void> {
await this.#run("meta", "readwrite", (tx) => { tx.objectStore("meta").put(true, "reset"); });
await this.#run(["blocks", "meta"], "readwrite", (tx) => {
tx.objectStore("blocks").clear();
tx.objectStore("meta").clear();
});
}
/** The stored identity, without reading the index (undefined: none, or a reset that was cut off). */
async identity(): Promise<string | undefined> {
return this.#run("meta", "readonly", async (tx) => {
const meta = tx.objectStore("meta");
const [id, reset] = await Promise.all([reqP(meta.get("identity")), reqP(meta.get("reset"))]);
return reset || id === undefined ? undefined : String(id);
});
}
/** The meta record, read-only (nothing created but the empty database). */
async meta(): Promise<{ identity?: string; initialized: boolean; uid?: string; gen: number; reset: boolean; fenced?: string }> {
return this.#run("meta", "readonly", async (tx) => {
const meta = tx.objectStore("meta");
const [id, init, uid, gen, reset, fenced] = await Promise.all(["identity", "initialized", "uid", "gen", "reset", "fenced"].map((k) => reqP(meta.get(k))));
return {
identity: id === undefined ? undefined : String(id), initialized: !!init, uid: typeof uid === "string" ? uid : undefined,
gen: typeof gen === "number" ? gen : 0, reset: !!reset, fenced: typeof fenced === "string" ? fenced : undefined,
};
});
}
/**
* Up to `count` records from block `from` on, in block order (one
* read-only transaction): [block, data] pairs, or with keysOnly the block
* numbers alone (data is then empty). For reading a large store in
* batches.
*/
async range(from: number, count: number, { keysOnly = false }: { keysOnly?: boolean } = {}): Promise<Array<[number, Uint8Array]>> {
return this.#run("blocks", "readonly", async (tx) => {
const s = tx.objectStore("blocks"), r = IDBKeyRange.lowerBound(from);
const [keys, vals] = await Promise.all([reqP(s.getAllKeys(r, count)), keysOnly ? Promise.resolve([]) : reqP(s.getAll(r, count))]);
return keys.map((k, i) => [k as number, (vals[i] as Uint8Array | undefined) ?? EMPTY]);
});
}
/** Replace the identity `from` with `to`, with `extra` meta records (one transaction; false if the stored identity is not `from`). The blocks stay. */
async relabel(from: string, to: string, extra: Record<string, unknown> = {}): Promise<boolean> {
return this.#run("meta", "readwrite", async (tx) => {
const meta = tx.objectStore("meta");
if (await reqP(meta.get("reset")) || await reqP(meta.get("identity")) !== from) return false;
meta.put(to, "identity");
// More meta in the same transaction (undefined deletes the key).
for (const [k, v] of Object.entries(extra)) if (v === undefined) meta.delete(k); else meta.put(v, k);
return true;
});
}
/** Put meta records (one transaction; undefined deletes the key). */
async putMeta(entries: Record<string, unknown>): Promise<void> {
await this.#run("meta", "readwrite", (tx) => {
const meta = tx.objectStore("meta");
for (const [k, v] of Object.entries(entries)) if (v === undefined) meta.delete(k); else meta.put(v, k);
});
}
/**
* Delete up to `count` blocks, the lowest first (one transaction, whose
* key range is exactly those blocks), only while the stored identity
* passes `guard` (checked in the same transaction; nothing is deleted
* otherwise, and this resolves -1). The meta stays. Resolves the number
* deleted (0: none left).
*/
async removeBlocks(count: number, guard: (identity: string | undefined) => boolean): Promise<number> {
return this.#run(["blocks", "meta"], "readwrite", async (tx) => {
const meta = tx.objectStore("meta"), blocks = tx.objectStore("blocks");
const [id, reset] = await Promise.all([reqP(meta.get("identity")), reqP(meta.get("reset"))]);
if (reset || !guard(id === undefined ? undefined : String(id))) return -1;
const keys = await reqP(blocks.getAllKeys(null, count)) as number[];
if (keys.length) blocks.delete(IDBKeyRange.bound(keys[0]!, keys.at(-1)!));
return keys.length;
});
}
async close(): Promise<void> {
const p = this.dbp;
this.dbp = null;
if (p) try { (await p).close(); } catch {}
}
}
// ---------------------------------------------------------------------------
// HTTP disks.
export interface HttpDiskOptions {
/** Name of the saved overlay (default: the URL). */
name?: string;
/** Save the overlay in IndexedDB on each flush (default true, if IndexedDB exists). */
persist?: boolean;
chunkSize?: number;
log?: (msg: string) => void;
/** A save failed (e.g. QuotaExceededError). */
onError?: (err: unknown) => void;
}
/**
* A disk image served over HTTP, read lazily with Range requests, written to
* a copy-on-write overlay, optionally persisted in IndexedDB under `name`.
* A saved overlay that belongs to another version of the image (size, ETag)
* is dropped, loudly (it would corrupt the file system).
*/
export async function openHttpDisk(url: string, { name = url, persist = true, chunkSize, log, onError }: HttpDiskOptions = {}): Promise<CowDisk> {
const base = await HttpBase.open(url, { chunkSize });
const store = persist && typeof indexedDB !== "undefined" ? new IdbStore(name, { log }) : null;
return new CowDisk(base, { store, log, onError }).open({ onMismatch: "clear" });
}
/** Drop the persisted overlay of a disk opened with openHttpDisk(…, {name}). */
export async function resetHttpDisk(name: string): Promise<void> {
if (typeof indexedDB === "undefined") return;
const s = new IdbStore(name);
try {
await s.clear();
} finally {
await s.close();
}
}
/**
* A distro image served over HTTP (relative to the page) as the read-only
* disk createKernel({ distro }) takes: read lazily with Range requests,
* after the prefetch its distro header asks for (`prefetch` overrides it,
* false turns it off; HttpBaseOptions.prefetch), which starts here;
* nothing kept in IndexedDB, every range checked against the image first
* seen (HttpBase strict). For a caller that needs the disk before
* booting (snapshotDiskMismatch(); the distro is the snapshot's first disk);
* createKernel({ distro: url }) opens it the same way. The disk's `stats`
* say what was fetched.
*/
export async function openDistroDisk(url: string, { chunkSize, prefetch, log }: { chunkSize?: number; prefetch?: number | false; log?: (msg: string) => void } = {}): Promise<DistroDisk> {
const abs = typeof location === "object" && location?.href ? new URL(url, location.href).href : url;
return DistroDisk.open(new BaseDisk(await HttpBase.open(abs, { chunkSize, prefetch, log, strict: true })), { name: abs, log });
}
// ---------------------------------------------------------------------------
// The data disk: an ext4 file system (label kwdata) that persists across
// page loads. Its template (kernel/build.sh datadisk, a kwsparse image,
// bundled as the custom section "unkernel.datadisk") is copied into the
// store on first use; after that the store alone holds the disk (over a
// ZeroBase), and is never reset implicitly: it is keyed by the format
// version, not by the template.
//
// Two backends keep it (`backend`): "idb" (the default), IndexedDB database
// "kwdisk:<name>-<version>" under a CowDisk; and "opfs", an OpfsDisk
// (core/opfs-disk.ts) in the OPFS directory kwdisk/<name>-<version>/, only
// in a dedicated worker (synchronous file handles). Both have the same
// identity ("<name>-<version> size=<bytes> bs=4096"), uid and generation
// rules, and the same name in a snapshot's identity ("kwdisk:<name>-<version>"),
// so migrateDataDisk() can copy a disk from IndexedDB to OPFS with its uid and
// generation and a suspended machine still resumes on the copy. The move
// is one way: the IndexedDB copy is fenced (its identity gets
// DATA_DISK_FENCE appended, which openDataDisk(), and an older SDK as a
// format mismatch, refuses, so nothing boots the stale copy), and then
// clearMovedDataDisk() removes its blocks in batches, keeping the fenced
// meta as a tombstone: a page on IndexedDB still refuses it rather than
// seeding a second persistent disk there.
//
// Its size is in the store's identity. The template is 4 GiB; a larger
// disk (openDataDisk's `size`) is the template's blocks on a larger zero
// base, and the guest's /init grows the file system to the device at boot
// (`kwbox growfs`). A saved disk grows to a larger `size` (its identity is
// relabelled; the new space reads as zeros) and never shrinks.
export const DATA_DISK_NAME = "kwdata";
export const DATA_DISK_VERSION = "v1";
/** Where a data disk is kept: "idb" (IndexedDB, the default) or "opfs" (OPFS extent files, in a dedicated worker only). */
export type DataDiskBackend = "idb" | "opfs";
export interface DataDiskNameOptions {
/** Default "kwdata". */
name?: string;
/** Format version, default DATA_DISK_VERSION. */
version?: string;
log?: (msg: string) => void;
/** Default "idb". */
backend?: DataDiskBackend;
/** OPFS: this directory instead of OPFS's kwdisk/<name>-<version> (another file system, a test's in-memory one; no worker needed then). */
dir?: OpfsDiskDir;
}
/** The store of a data disk: database "kwdisk:<name>-<version>" and its identity. */
export function dataDiskStore(size: number, { name = DATA_DISK_NAME, version = DATA_DISK_VERSION, log }: DataDiskNameOptions = {}): { store: IdbStore; identity: string } {
const id = `${name}-${version}`;
return { store: new IdbStore(id, { log }), identity: `${id} size=${size} bs=${BLOCK}` };
}
/** Appended to the IndexedDB identity of a data disk moved to OPFS or set aside for a new one (its blocks go with clearMovedDataDisk(); the meta stays). */
export const DATA_DISK_FENCE = " moved=opfs";
/** An identity fenced by a move to OPFS? */
export const isFencedIdentity = (id: string): boolean => id.endsWith(DATA_DISK_FENCE);
export const fencedIdentity = (id: string): string => (isFencedIdentity(id) ? id : id + DATA_DISK_FENCE);
const unfencedIdentity = (id: string): string => (isFencedIdentity(id) ? id.slice(0, -DATA_DISK_FENCE.length) : id);
/** The size in a data disk identity of this name and version (dataDiskStore()), else undefined. */
function identitySize(identity: string | undefined, name: string, version: string): number | undefined {
const m = identity?.match(/^(.*) size=(\d+) bs=(\d+)$/);
return m && m[1] === `${name}-${version}` && Number(m[3]) === BLOCK ? Number(m[2]) : undefined;
}
function formatError(message: string): Error {
const e = new Error(message);
e.name = "DataDiskFormatError";
return e;
}
/** Does IndexedDB have this database? undefined where it cannot tell (no indexedDB.databases()). */
async function idbHas(dbName: string): Promise<boolean | undefined> {
if (typeof indexedDB === "undefined") return false;
if (typeof indexedDB.databases !== "function") return undefined;
try {
return (await indexedDB.databases()).some((d) => d.name === dbName);
} catch {
return undefined;
}
}
export interface OpenDataDiskOptions extends DataDiskNameOptions {
/** The template: a kwsparse image (gzipped or not), or a decoded one. */
template: Uint8Array | ArrayBuffer | KwsparseImage;
/**
* "persistent" (default): the IndexedDB store, seeded from the template
* on first use. "snapshot": memory only, starting from a consistent copy
* of the saved disk if it is at most snapshotLimit bytes, else from the
* template (e.g. another tab owns the disk). The OPFS backend has no
* snapshot mode.
*/
mode?: "persistent" | "snapshot";
/** Default 64 MiB; below 0 the saved disk is not read at all (the template). */
snapshotLimit?: number;
/**
* The disk's size in bytes (rounded down to 4 KiB, at least the
* template's): a new disk is made this large, a saved disk smaller than
* this grows to it, a larger one keeps its size (a disk never shrinks).
* The guest's /init grows the file system to the device. Default: the
* saved disk's size, or the template's for a new one. Snapshot mode never
* grows a saved disk.
*/
size?: number;
onError?: (err: unknown) => void;
/** OPFS: how long to wait for a disk another worker still holds (a closing one), in ms (default 5000; then DiskInUseError). */
waitMs?: number;
}
/**
* Open the data disk. The result has .persistent, and .notice when it is
* not the persistent disk. Throws a DataDiskFormatError if the saved disk
* has another identity (format), or was moved to OPFS (an IndexedDB copy
* fenced by migrateDataDisk()); nothing is cleared, the caller decides (the
* page runs a snapshot of the template and says why).
*
* With backend "opfs" the disk is an OpfsDisk, which runs only in a
* dedicated worker: elsewhere, or where OPFS is refused (no secure context,
* a private window), this rejects with an OpfsUnavailableError; while
* another tab or worker has the disk open, with a DiskInUseError. A disk
* whose making was cut off is made again from the template.
*/
export function openDataDisk(o: OpenDataDiskOptions & { backend: "opfs" }): Promise<OpfsDisk>;
export function openDataDisk(o: OpenDataDiskOptions & { backend?: "idb" }): Promise<CowDisk>;
export function openDataDisk(o: OpenDataDiskOptions): Promise<CowDisk | OpfsDisk>;
export function openDataDisk(o: OpenDataDiskOptions): Promise<CowDisk | OpfsDisk> {
return o.backend === "opfs" ? openOpfsDataDisk(o) : openIdbDataDisk(o);
}
async function decodeTemplate(template: OpenDataDiskOptions["template"]): Promise<KwsparseImage> {
const tpl = "indices" in template ? template : decodeKwsparse(await gunzipIfNeeded(template));
if (tpl.blockSize !== BLOCK) throw new Error(`data disk template: block size ${tpl.blockSize}, need ${BLOCK}`);
return tpl;
}
const wantSize = (tpl: KwsparseImage, size: number | undefined) =>
size !== undefined && size > 0 ? Math.max(tpl.size, Math.floor(size / BLOCK) * BLOCK) : undefined;
async function openIdbDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_VERSION, template, mode = "persistent",
snapshotLimit = 64 * 1048576, size, log = (m) => console.warn(m), onError }: OpenDataDiskOptions): Promise<CowDisk> {
const tpl = await decodeTemplate(template);
const haveIdb = typeof indexedDB !== "undefined";
const want = wantSize(tpl, size);
const { store } = dataDiskStore(0, { name, version, log });
const idOf = (n: number) => dataDiskStore(n, { name, version }).identity;
if (mode !== "persistent" || !haveIdb) {
let base = new SparseBase(want ?? tpl.size, tpl.map()), from = "the template";
if (haveIdb && snapshotLimit >= 0) {
try {
const saved = identitySize(await store.identity(), name, version);
const st = saved === undefined ? null : await store.open(idOf(saved), { onMismatch: "refuse", write: false });
if (saved !== undefined && st?.initialized && st.mismatch === undefined) {
if (snapshotLimit > 0 && st.keys.size * BLOCK <= snapshotLimit) {
base = new SparseBase(saved, await store.readAll());
from = "a copy of the saved disk";
} else {
from = `the template (the saved disk, ${(st.keys.size * BLOCK / 1048576).toFixed(0)} MiB, is too large to copy)`;
}
}
} catch (e) {
log(`[host] data disk: cannot read the saved disk for a snapshot: ${(e as Error)?.message ?? e}`);
} finally {
await store.close();
}
}
const d = new CowDisk(base, { log });
d.notice = `in memory only, started from ${from}`;
return d;
}
await warnOtherVersions(name, version, log);
// The saved size (another format's identity: none, and the open below refuses it), grown to `want`.
const savedId = await store.identity();
if (savedId !== undefined && isFencedIdentity(savedId)) {
await store.close();
throw formatError(`the data disk now lives in OPFS (this browser's origin private file system, where the page keeps it in worker mode); ` +
`IndexedDB ${store.name} only marks the move (its blocks are removed after it), and this page leaves it as it is`);
}
let eff = identitySize(savedId, name, version) ?? want ?? tpl.size;
if (savedId !== undefined && want !== undefined && want > eff && await store.relabel(savedId, idOf(want))) {
log(`[host] data disk: grew from ${eff / 1073741824} GiB to ${want / 1073741824} GiB (the guest grows its file system at boot)`);
eff = want;
}
const identity = idOf(eff);
const st = await store.open(identity, { onMismatch: "refuse" });
if (st.mismatch !== undefined) {
await store.close();
throw formatError(`the saved data disk is "${st.mismatch}", this page expects "${identity}"; it was left untouched`);
}
const d = new CowDisk(new ZeroBase(eff), { store, log, onError });
if (!st.initialized) {
const uid = await store.seed(tpl.indices.map((b, i) => [b, tpl.block(i).slice()]), identity);
d.adoptStore({ keys: new Set(tpl.indices), initialized: true, gen: 0, uid }, identity);
d.seeded = true;
log(`[host] data disk: created from the template (${tpl.indices.length} blocks) in IndexedDB ${store.name}`);
} else {
d.adoptStore(st, identity);
}
d.identity = identity;
return d;
}
/** The OpfsDisk of a data disk (its meta file taken: the lock), in a dedicated worker. */
async function openOpfsDisk(name: string, version: string, { dir, log, onError, waitMs }: { dir?: OpfsDiskDir; log?: (m: string) => void; onError?: (e: unknown) => void; waitMs?: number }): Promise<OpfsDisk> {
const id = `${name}-${version}`;
return OpfsDisk.open(dir ?? await opfsDiskDir(id), { name: `kwdisk:${id}`, log, onError, waitMs });
}
async function openOpfsDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_VERSION, template, mode = "persistent", size,
log = (m) => console.warn(m), onError, waitMs, dir }: OpenDataDiskOptions): Promise<OpfsDisk> {
if (mode !== "persistent") throw new Error("the OPFS data disk has no snapshot mode (use the IndexedDB backend for an in-memory copy)");
const tpl = await decodeTemplate(template);
const want = wantSize(tpl, size);
const idOf = (n: number) => dataDiskStore(n, { name, version }).identity;
const disk = await openOpfsDisk(name, version, { dir, log, onError, waitMs });
try {
if (!disk.complete) {
if (disk.header) log(`[host] data disk: OPFS kwdisk/${name}-${version} was cut off while it was being made (${disk.header.origin ?? "a format"}): made again from the template`);
const eff = want ?? tpl.size;
await disk.format({ identity: idOf(eff), size: eff, image: tpl, origin: "template" });
disk.seeded = true;
log(`[host] data disk: created from the template (${tpl.indices.length} blocks) in OPFS kwdisk/${name}-${version}`);
} else {
const saved = identitySize(disk.identity, name, version);
if (saved === undefined || saved !== disk.size)
throw formatError(`the saved data disk is "${disk.identity}", this page expects "${idOf(want ?? disk.size)}"; it was left untouched`);
if (want !== undefined && want > saved) {
disk.grow(want, idOf(want));
log(`[host] data disk: grew from ${saved / 1073741824} GiB to ${want / 1073741824} GiB (the guest grows its file system at boot)`);
}
}
return disk;
} catch (e) {
disk.close();
throw e;
}
}
/** Log saved data disks of other format versions (kept, never attached). */
async function warnOtherVersions(name: string, version: string, log: (msg: string) => void): Promise<void> {
if (typeof indexedDB?.databases !== "function") return;
try {
for (const db of await indexedDB.databases()) {
if (db.name?.startsWith(`kwdisk:${name}-`) && db.name !== `kwdisk:${name}-${version}`)
log(`[host] data disk: IndexedDB also has ${db.name}, saved by another format version; it is kept but not attached`);
}
} catch {}
}
/**
* Replace the persisted data disk with a kwsparse image (gzipped or not).
* The disk must not be attached (or be detached, followed by a reload).
* With backend "opfs" this runs only in a dedicated worker (OpenDataDiskOptions).
*/
export async function importDataDisk(bytes: Uint8Array | ArrayBuffer, { name = DATA_DISK_NAME, version = DATA_DISK_VERSION, size, log, backend = "idb", waitMs, dir }: DataDiskNameOptions & { size?: number; waitMs?: number } = {}): Promise<{ size: number; blocks: number }> {
const img = decodeKwsparse(await gunzipIfNeeded(bytes));
if (img.blockSize !== BLOCK) throw new Error(`block size ${img.blockSize}, need ${BLOCK}`);
if (size !== undefined && img.size !== size)
throw new Error(`the image is ${img.size} bytes, the data disk is ${size}`);
const { store, identity } = dataDiskStore(img.size, { name, version, log });
if (backend === "opfs") {
const disk = await openOpfsDisk(name, version, { dir, log, waitMs });
try {
await disk.format({ identity, size: img.size, image: img, origin: "imported" });
} finally {
disk.close();
}
return { size: img.size, blocks: img.indices.length };
}
try {
await store.seed(img.indices.map((b, i) => [b, img.block(i).slice()]), identity);
} finally {
await store.close();
}
return { size: img.size, blocks: img.indices.length };
}
/**
* Forget the persisted data disk; the next boot starts again from the
* template. With backend "opfs" this removes its directory (anywhere OPFS
* works; a DiskInUseError while a worker has it open).
*/
export async function resetDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_VERSION, backend = "idb" }: DataDiskNameOptions = {}): Promise<void> {
if (backend === "opfs") {
await removeOpfsDisk(`${name}-${version}`);
return;
}
if (typeof indexedDB === "undefined") return;
const { store } = dataDiskStore(0, { name, version });
try {
await store.clear();
} finally {
await store.close();
}
}
/** What is saved of a data disk in one backend (dataDiskInfo()). */
export interface DataDiskInfo {
backend: DataDiskBackend;
/** Something is saved (a disk, maybe incomplete). */
exists: boolean;
/** It is usable: seeded (IndexedDB), or a finished format (OPFS). */
complete: boolean;
/** Its identity (IndexedDB: as stored, fenced or not). */
identity?: string;
/** The size in its identity, if it is a data disk of this name and format. */
size?: number;
uid?: string;
gen?: number;
/** IndexedDB: moved to OPFS (the identity is fenced; its blocks are removed after the move, the meta kept as a tombstone). */
fenced?: boolean;
/**
* IndexedDB, fenced: why. "fresh": set aside for a new disk; "migrating":
* fenced by a copy to OPFS that had not confirmed its end (it did when
* the OPFS disk is complete with this uid); "migrated": the copy ended.
* Absent: unknown (treat as "migrating").
*/
fencedFor?: "fresh" | "migrating" | "migrated";
/** IndexedDB: stored blocks; OPFS: extent files. */
blocks?: number;
files?: number;
/** The bytes it keeps in the browser's storage: IndexedDB blocks × 4096; OPFS (asked for with `bytes`) the extent files' lengths. */
bytes?: number;
/** OPFS: how it was made ("template", "imported", "migrated"). */
origin?: string;
/** OPFS: another worker holds it, so its header could not be read. */
inUse?: boolean;
}
/**
* What a backend holds of the data disk, read without opening it for use
* (anywhere: no worker needed, nothing written; for IndexedDB nothing is
* created where indexedDB.databases() says the database is missing).
*/
export async function dataDiskInfo({ name = DATA_DISK_NAME, version = DATA_DISK_VERSION, backend = "idb", bytes = false }: DataDiskNameOptions & {
/** OPFS: also sum the extent files' lengths (one lookup per file). */
bytes?: boolean;
} = {}): Promise<DataDiskInfo> {
const id = `${name}-${version}`;
if (backend === "opfs") {
const r = await readOpfsHeader(id, { bytes });
if (r === null) return { backend, exists: false, complete: false };
if (r === "in use") return { backend, exists: true, complete: false, inUse: true };
const h = r.header;
const b = r.bytes === undefined ? {} : { bytes: r.bytes };
if (!h) return { backend, exists: r.files > 0, complete: false, files: r.files, ...b };
return { backend, exists: true, complete: h.complete, identity: h.identity, size: identitySize(h.identity, name, version), uid: h.uid, gen: h.gen, files: r.files, origin: h.origin, ...b };
}
const { store } = dataDiskStore(0, { name, version });
if (await idbHas(store.name) === false) return { backend, exists: false, complete: false };
try {
const m = await store.meta();
if (m.reset || m.identity === undefined) return { backend, exists: false, complete: false };
const fenced = isFencedIdentity(m.identity);
const blocks = await store.count();
return {
backend, exists: true, complete: m.initialized, identity: m.identity, size: identitySize(unfencedIdentity(m.identity), name, version),
uid: m.uid, gen: m.gen, fenced, blocks, bytes: blocks * 4096,
...(fenced && (m.fenced === "fresh" || m.fenced === "migrating" || m.fenced === "migrated") ? { fencedFor: m.fenced } : {}),
};
} finally {
await store.close();
}
}
/**
* Fence the IndexedDB data disk, set aside for a new OPFS disk (meta
* `fenced`: "fresh"; migrateDataDisk() fences its own copy): true if it was
* fenced now. The blocks stay until clearMovedDataDisk().
* Nothing in the SDK takes a fence off again (only a migration whose last
* step failed, for the disk it fenced itself).
*/
export async function fenceDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_VERSION, log }: DataDiskNameOptions = {}): Promise<boolean> {
const { store } = dataDiskStore(0, { name, version, log });
if (await idbHas(store.name) === false) return false;
try {
const id = await store.identity();
if (id === undefined || isFencedIdentity(id)) return false;
return await store.relabel(id, fencedIdentity(id), { fenced: "fresh" });
} finally {
await store.close();
}
}
export interface ClearMovedDataDiskOptions extends DataDiskNameOptions {
/** Blocks per transaction (default 1024). */
batch?: number;
/** Pause between transactions, in ms (default 20), so that the removal stays in the background. */
pauseMs?: number;
/** After each transaction: blocks removed so far by this call. */
onProgress?: (removed: number) => void;
signal?: AbortSignal;
}
/**
* Remove the blocks of a fenced IndexedDB data disk (one moved to OPFS, or
* set aside for a new one), in batches of one transaction each, so that a
* page that ends meanwhile keeps what was done and a later call goes on.
* The meta stays, with the fenced identity: a tombstone that openDataDisk()
* (and an older SDK) refuses with a DataDiskFormatError, instead of seeding a
* new disk in IndexedDB. Every transaction checks the fence first, so the
* blocks of an unfenced disk are never removed: it rejects then. Resolves the
* number of blocks removed.
*/
export async function clearMovedDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_VERSION, log, batch = 1024, pauseMs = 20, onProgress, signal }: ClearMovedDataDiskOptions = {}): Promise<number> {
const { store } = dataDiskStore(0, { name, version, log });
if (await idbHas(store.name) === false) return 0;
let removed = 0;
try {
for (;;) {
signal?.throwIfAborted();
const n = await store.removeBlocks(batch, (id) => id !== undefined && isFencedIdentity(id));
if (n < 0) throw new Error(`IndexedDB ${store.name} is not fenced (not moved to OPFS): its blocks stay`);
if (n === 0) return removed;
removed += n;
onProgress?.(removed);
if (pauseMs > 0) await new Promise((r) => setTimeout(r, pauseMs));
}
} finally {
await store.close();
}
}
/** The copy would not fit in the browser's storage quota (migrateDataDisk()). */
export class DataDiskSpaceError extends Error {
override name = "DataDiskSpaceError";
/** Bytes the copy needs, and bytes free (quota - usage), as navigator.storage.estimate() tells. */
need: number;
free: number;
constructor(need: number, free: number) {
super(`the copy needs ${(need / 1048576).toFixed(0)} MiB and the browser lets this site keep ${(Math.max(0, free) / 1048576).toFixed(0)} MiB more`);
this.need = need;
this.free = free;
}
}
export interface MigrateDataDiskOptions extends DataDiskNameOptions {
/** Progress: IndexedDB records copied of `total`. */
onProgress?: (p: { done: number; total: number }) => void;
/** Refuse with a DataDiskSpaceError a copy that does not fit in the quota (navigator.storage.estimate()); default true. */
checkSpace?: boolean;
/** Records per IndexedDB read (default 1024: 4 MiB). */
batch?: number;
waitMs?: number;
}
/**
* Copy the IndexedDB data disk to OPFS, one way (in a dedicated worker; the
* disk attached in neither place, the caller holding the one-tab lock),
* replacing the OPFS disk. The records are read in batches by key range,
* never all at once, after a check that the copy fits beside the IndexedDB
* disk (both exist until clearMovedDataDisk()). The copy keeps the uid and
* write generation, so a machine snapshot made on the IndexedDB disk resumes
* on the OPFS one. Then the IndexedDB disk is fenced (its identity
* relabelled, the blocks kept), and only then is the OPFS disk's header
* made complete; if that last step fails, the fence comes off again, so
* the IndexedDB disk stays usable, and the OPFS disk is not complete (its
* next opener makes it again). A fenced disk (moved already) is refused:
* the move is one way. After it resolves, clearMovedDataDisk() may remove
* the IndexedDB blocks.
*/
export async function migrateDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_VERSION, log, onProgress, checkSpace = true,
batch = 1024, waitMs, dir }: MigrateDataDiskOptions = {}): Promise<{ identity: string; blocks: number; bytes: number; uid: string; gen: number; kept: boolean }> {
const why = dir ? null : opfsDiskBlocker();
if (why) throw new OpfsUnavailableError(why);
const { store } = dataDiskStore(0, { name, version, log });
let disk: OpfsDisk | null = null, fencedNow: [string, string] | null = null;
try {
const m = await store.meta();
if (m.reset || !m.initialized || m.identity === undefined) throw new Error(`IndexedDB ${store.name} holds no data disk`);
if (isFencedIdentity(m.identity)) throw new Error(`IndexedDB ${store.name} was moved to OPFS already (the move is one way)`);
const identity = m.identity;
const size = identitySize(identity, name, version);
if (size === undefined) throw formatError(`IndexedDB ${store.name} holds "${identity}", not a data disk of this format`);
// The block numbers first, for the space it needs: a browser charges an extent file by its
// length, so each extent costs up to its last block.
const ends = new Map<number, number>();
let total = 0;
for (let from = 0; ;) {
const keys = await store.range(from, 8192, { keysOnly: true });
if (!keys.length) break;
for (const [b] of keys) {
const x = Math.floor(b * BLOCK / OPFS_EXTENT), end = (b + 1) * BLOCK - x * OPFS_EXTENT;
if (end > (ends.get(x) ?? 0)) ends.set(x, end);
}
total += keys.length;
from = keys.at(-1)![0] + 1;
}
let need = 0;
for (const n of ends.values()) need += n;
disk = await openOpfsDisk(name, version, { dir, log, waitMs });
if (checkSpace) {
// Room for both copies (the IndexedDB one is in the usage); the OPFS disk this replaces gives its space back.
const est = await navigator.storage?.estimate?.().catch(() => undefined);
const free = est?.quota !== undefined && est.usage !== undefined ? est.quota - est.usage + await disk.measure() : Infinity;
if (need > free) throw new DataDiskSpaceError(need, free);
}
const keep = m.uid !== undefined;
await disk.beginFormat({ identity, size, uid: m.uid, gen: keep ? m.gen : 0, origin: "migrated", from: `IndexedDB ${store.name}` });
let done = 0;
onProgress?.({ done, total });
for (let from = 0; ;) {
const recs = await store.range(from, batch);
if (!recs.length) break;
// An empty record reads as zeros (the data disk has none: zeros are no record).
await disk.putBlocks(recs.filter(([, v]) => v.length === BLOCK && !isZeroBlock(v)));
done += recs.length;
from = recs.at(-1)![0] + 1;
onProgress?.({ done, total });
}
if (!await store.relabel(identity, fencedIdentity(identity), { fenced: "migrating" })) throw new Error(`IndexedDB ${store.name} changed during the copy`);
fencedNow = [fencedIdentity(identity), identity];
await disk.completeFormat();
fencedNow = null;
// The copy is complete (if this is lost, the complete OPFS disk with this uid says so).
await store.putMeta({ fenced: "migrated" }).catch(() => {});
log?.(`[host] data disk: copied ${done} blocks from IndexedDB ${store.name} to OPFS kwdisk/${name}-${version}` +
(keep ? " (same uid and generation: a suspended session resumes on it)" : " (a new uid)") + "; the IndexedDB copy is fenced");
return { identity, blocks: done, bytes: need, uid: disk.uid!, gen: disk.gen, kept: keep };
} catch (e) {
// The last step failed after the fence: the IndexedDB disk must stay usable (the load stays on it).
if (fencedNow) await store.relabel(fencedNow[0], fencedNow[1], { fenced: undefined }).catch(() => false);
throw e;
} finally {
disk?.close();
await store.close();
}
}