mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-06 14:50:42 +08:00
829 lines
29 KiB
TypeScript
829 lines
29 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// OpfsDisk: a read-write disk kept in a directory of extent files, written
|
|
// with synchronous file handles (the browser's origin private file system,
|
|
// js/web/opfs.ts, where FileSystemSyncAccessHandle exists only in a dedicated
|
|
// worker). This module holds the logic over a small directory interface
|
|
// (OpfsDiskDir, OpfsSyncFile), so that it can be tested without a browser.
|
|
//
|
|
// Like FileDisk (node/disk.ts) it has no write cache: a guest write is a
|
|
// synchronous write() into the extent file, and a guest flush is flush() on
|
|
// every extent file written since the last flush. Crash semantics are a
|
|
// file's: after a crash any write since the last completed flush may or may
|
|
// not have landed, and a flush completes only once everything before it is
|
|
// durable.
|
|
//
|
|
// Layout of the directory:
|
|
// meta the header: two 4 KiB slots, each "KWOPFSH1", u32 LE length,
|
|
// u32 LE CRC-32 of the JSON that follows. The JSON's `seq` picks
|
|
// the newer valid slot; a write goes to the other slot and is
|
|
// flushed, so a torn write leaves the older one. Its sync
|
|
// access handle stays open while the disk is, which is the
|
|
// one-opener lock (a second opener gets DiskInUseError).
|
|
// e<N> extent N: bytes [N*extent, (N+1)*extent) of the disk
|
|
// (extent: 8 MiB, recorded in the header). Created on the
|
|
// first write into it, never pre-sized: Chromium charges a file
|
|
// by its length, not its allocated blocks, and keeps the quota
|
|
// of a truncated file while its handle is open. A missing
|
|
// extent reads as zeros, and a short one reads zeros past its
|
|
// end.
|
|
// Anything else in the directory is ignored (and removed by a format).
|
|
//
|
|
// The header holds the identity (what the disk is: the data disk's
|
|
// "<name>-<version> size=<bytes> bs=4096"), the size, a random uid (new when
|
|
// the disk is formatted, unless the format copies another disk's), the
|
|
// write generation (snapshots, below), and `complete`: a disk is usable only
|
|
// once a format finished (its blocks durable, then the header). A disk
|
|
// without a complete header is wiped and formatted again by its owner.
|
|
//
|
|
// Snapshots (core/block.ts): the generation goes up before the first write
|
|
// after open and after each snapshotSeal(), and the header carrying it is
|
|
// written and flushed before that write, as FileDisk's sidecar. The
|
|
// snapshot identity is "store <name> <identity> uid=<uid>", the same as a
|
|
// CowDisk with a store of that name, so a disk copied between the two
|
|
// (migrateDataDisk(), web/disk.ts) with its uid and generation resumes the
|
|
// same machine snapshot.
|
|
//
|
|
// Handles open lazily (opening is asynchronous, so a read or write of an
|
|
// extent whose handle is not open returns a promise) and at most `maxOpen`
|
|
// stay open, the least recently used one closed first (flushed first if it
|
|
// was written). Operations on one extent run in submission order: one that
|
|
// has to wait chains on the extent's tail, and later ones wait for it.
|
|
|
|
import { F_DISCARD, F_FLUSH, F_WRITE_ZEROES, FlushTracker, type BlockDevice, type DiskSnapshotState, type MaybePromise } from "./block.ts";
|
|
import { isZeroBlock, kwsparseHeader } from "./kwsparse.ts";
|
|
|
|
const BLOCK = 4096;
|
|
/** The extent size of a new disk. */
|
|
export const OPFS_EXTENT = 8 * 1048576;
|
|
const SLOT = 4096;
|
|
const MAGIC = "KWOPFSH1";
|
|
const META = "meta";
|
|
const ZEROS = new Uint8Array(1048576);
|
|
const noop = () => {};
|
|
|
|
/** A file opened for synchronous I/O (the subset of FileSystemSyncAccessHandle the disk uses). */
|
|
export interface OpfsSyncFile {
|
|
/** Read into buf at byte `at`; returns the bytes read (fewer at the end of the file). */
|
|
read(buf: Uint8Array, opts: { at: number }): number;
|
|
/** Write buf at byte `at` (extending the file); returns the bytes written. */
|
|
write(buf: Uint8Array, opts: { at: number }): number;
|
|
getSize(): number;
|
|
flush(): void;
|
|
close(): void;
|
|
}
|
|
|
|
/** The disk's directory (FileSystemDirectoryHandle's operations the disk uses; js/web/opfs.ts opfsDiskDir()). */
|
|
export interface OpfsDiskDir {
|
|
/** The names of its entries. */
|
|
list(): Promise<string[]>;
|
|
/**
|
|
* Open file `name` for synchronous I/O, creating it with `create`. Rejects
|
|
* with an error named "NotFoundError" if it is missing (and not created),
|
|
* and with a DiskInUseError if another handle has it open.
|
|
*/
|
|
open(name: string, create: boolean): Promise<OpfsSyncFile>;
|
|
/** Remove file `name` (a missing one is not an error). */
|
|
remove(name: string): Promise<void>;
|
|
/** The length of file `name` without opening it for I/O, if this directory can tell (stats only). */
|
|
size?(name: string): Promise<number>;
|
|
}
|
|
|
|
/** The disk (its meta file) is open elsewhere: another tab or worker holds it. */
|
|
export class DiskInUseError extends Error {
|
|
override name = "DiskInUseError";
|
|
}
|
|
|
|
/** What the header says (the JSON of the newer valid slot). */
|
|
export interface OpfsHeader {
|
|
v: 1;
|
|
seq: number;
|
|
/** What the disk is (the data disk: "<name>-<version> size=<bytes> bs=4096"). */
|
|
identity: string;
|
|
size: number;
|
|
/** Bytes per extent file. */
|
|
extent: number;
|
|
uid: string;
|
|
/** The write generation (snapshots). */
|
|
gen: number;
|
|
/** A format finished: the disk may be used. */
|
|
complete: boolean;
|
|
/** How it was made: "template", "imported", "migrated", ... */
|
|
origin?: string;
|
|
/** Where its blocks came from (a migrated disk's source). */
|
|
from?: string;
|
|
/** Date.now() of the format, and of this header. */
|
|
created?: number;
|
|
updated?: number;
|
|
}
|
|
|
|
export interface OpfsDiskOptions {
|
|
/** For messages and the snapshot identity, e.g. "kwdisk:kwdata-v1". */
|
|
name: string;
|
|
log?: (msg: string) => void;
|
|
/** A write or flush failed (e.g. QuotaExceededError); the guest sees EIO for it. */
|
|
onError?: (err: unknown) => void;
|
|
/** How long open() retries a meta file another handle holds, in ms (default 5000; a closing worker lets go late). */
|
|
waitMs?: number;
|
|
/** Extent handles kept open at most (default 128). */
|
|
maxOpen?: number;
|
|
}
|
|
|
|
export interface OpfsFormat {
|
|
identity: string;
|
|
size: number;
|
|
/** Default: a new random one. */
|
|
uid?: string;
|
|
/** Default 0. */
|
|
gen?: number;
|
|
origin?: string;
|
|
from?: string;
|
|
/** Blocks to write (a kwsparse image: the template or an import), 4 KiB each. */
|
|
image?: { blockSize: number; indices: number[]; block(i: number): Uint8Array } | null;
|
|
}
|
|
|
|
export interface OpfsDiskStats {
|
|
reads: number;
|
|
writes: number;
|
|
flushes: number;
|
|
/** flush() calls on extent files (by guest flushes, seals and closes of written handles). */
|
|
extentFlushes: number;
|
|
/** Requests that had to wait (a handle to open, or an earlier request on the extent). */
|
|
waits: number;
|
|
/** Extent handles opened, files created, extents deleted (wholly discarded), handles closed to stay under maxOpen. */
|
|
opens: number;
|
|
creates: number;
|
|
deletes: number;
|
|
evictions: number;
|
|
/** Zero bytes written by discards and write-zeroes inside a file. */
|
|
zeroBytes: number;
|
|
/** Header writes (generations, grows, formats). */
|
|
headerWrites: number;
|
|
errors: number;
|
|
}
|
|
|
|
// Not crypto.randomUUID(): that needs a secure context.
|
|
const newUid = (): string => Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
|
|
let crcTable: Uint32Array | undefined;
|
|
function crc32(b: Uint8Array): number {
|
|
if (!crcTable) {
|
|
crcTable = new Uint32Array(256);
|
|
for (let n = 0; n < 256; n++) {
|
|
let c = n;
|
|
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
crcTable[n] = c >>> 0;
|
|
}
|
|
}
|
|
let c = 0xffffffff;
|
|
for (let i = 0; i < b.length; i++) c = crcTable[(c ^ b[i]!) & 0xff]! ^ (c >>> 8);
|
|
return (c ^ 0xffffffff) >>> 0;
|
|
}
|
|
|
|
/** One header slot (SLOT bytes). */
|
|
export function encodeHeaderSlot(h: OpfsHeader): Uint8Array {
|
|
const json = new TextEncoder().encode(JSON.stringify(h));
|
|
if (json.length > SLOT - 16) throw new Error("opfs disk: header too large");
|
|
const out = new Uint8Array(SLOT);
|
|
for (let i = 0; i < 8; i++) out[i] = MAGIC.charCodeAt(i);
|
|
const dv = new DataView(out.buffer);
|
|
dv.setUint32(8, json.length, true);
|
|
dv.setUint32(12, crc32(json), true);
|
|
out.set(json, 16);
|
|
return out;
|
|
}
|
|
|
|
function decodeSlot(s: Uint8Array): OpfsHeader | null {
|
|
if (s.length < 16) return null;
|
|
for (let i = 0; i < 8; i++) if (s[i] !== MAGIC.charCodeAt(i)) return null;
|
|
const dv = new DataView(s.buffer, s.byteOffset, s.length);
|
|
const len = dv.getUint32(8, true);
|
|
if (len > s.length - 16) return null;
|
|
const json = s.subarray(16, 16 + len);
|
|
if (crc32(json) !== dv.getUint32(12, true)) return null;
|
|
try {
|
|
const h = JSON.parse(new TextDecoder().decode(json)) as OpfsHeader;
|
|
if (h?.v !== 1 || !Number.isSafeInteger(h.seq) || typeof h.identity !== "string" || !Number.isSafeInteger(h.size) ||
|
|
!Number.isSafeInteger(h.extent) || h.extent <= 0 || h.extent % BLOCK || typeof h.uid !== "string" || !Number.isSafeInteger(h.gen)) return null;
|
|
return h;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** The newer valid header in the meta file's bytes (both slots), or null. */
|
|
export function decodeHeader(bytes: Uint8Array): OpfsHeader | null {
|
|
const a = decodeSlot(bytes.subarray(0, SLOT)), b = decodeSlot(bytes.subarray(SLOT, 2 * SLOT));
|
|
if (a && b) return a.seq >= b.seq ? a : b;
|
|
return a ?? b;
|
|
}
|
|
|
|
function readAll(f: OpfsSyncFile, buf: Uint8Array, at: number): number {
|
|
let n = 0;
|
|
while (n < buf.length) {
|
|
const k = f.read(buf.subarray(n), { at: at + n });
|
|
if (k <= 0) break;
|
|
n += k;
|
|
}
|
|
return n;
|
|
}
|
|
|
|
const extentName = (x: number) => `e${x}`;
|
|
const isInUse = (e: unknown) => (e as Error)?.name === "DiskInUseError";
|
|
|
|
/**
|
|
* A disk in an OpfsDiskDir; see the top of this file. Make one with
|
|
* OpfsDisk.open(), which takes the lock and reads the header; a disk that
|
|
* is not `complete` must be formatted (format()) before any I/O.
|
|
*/
|
|
export class OpfsDisk implements BlockDevice {
|
|
readonly name: string;
|
|
readonly dir: OpfsDiskDir;
|
|
size = 0;
|
|
flags = F_FLUSH | F_DISCARD | F_WRITE_ZEROES;
|
|
log: (msg: string) => void;
|
|
onError: ((err: unknown) => void) | null;
|
|
/** The header (null: none, a disk never formatted). */
|
|
header: OpfsHeader | null;
|
|
/** A finished format: the disk may be used. */
|
|
complete: boolean;
|
|
/** Bytes per extent file. */
|
|
extent: number;
|
|
maxOpen: number;
|
|
flushes: FlushTracker = new FlushTracker();
|
|
stats: OpfsDiskStats = { reads: 0, writes: 0, flushes: 0, extentFlushes: 0, waits: 0, opens: 0, creates: 0, deletes: 0, evictions: 0, zeroBytes: 0, headerWrites: 0, errors: 0 };
|
|
/** Set by openDataDisk: why this disk is not the persistent one (never set on an attached OpfsDisk; for DiskState). */
|
|
notice?: string;
|
|
/** Set by openDataDisk: formatted from the template in this session. */
|
|
seeded = false;
|
|
/** Detached or closed: every request fails. */
|
|
detached = false;
|
|
#meta: OpfsSyncFile | null;
|
|
/** Extents that exist as files. */
|
|
#present = new Set<number>();
|
|
/** Open extent handles, least recently used first. */
|
|
#open = new Map<number, OpfsSyncFile>();
|
|
/** Extent lengths, where known (an open handle, or the directory's size()). */
|
|
#sizes = new Map<number, number>();
|
|
/** Extents written since their last flush. */
|
|
#dirty = new Set<number>();
|
|
/** Extent -> the tail of the requests waiting on it (never rejects). */
|
|
#tails = new Map<number, Promise<void>>();
|
|
/** The next write starts a new generation. */
|
|
#sealed = true;
|
|
|
|
/** Use OpfsDisk.open(). */
|
|
constructor(dir: OpfsDiskDir, meta: OpfsSyncFile, header: OpfsHeader | null, names: string[], { name, log, onError, maxOpen = 128 }: OpfsDiskOptions) {
|
|
this.dir = dir;
|
|
this.name = name;
|
|
this.log = log ?? ((m) => console.warn(m));
|
|
this.onError = onError ?? null;
|
|
this.maxOpen = Math.max(1, maxOpen);
|
|
this.#meta = meta;
|
|
this.header = header;
|
|
this.complete = !!header?.complete;
|
|
this.extent = header?.extent ?? OPFS_EXTENT;
|
|
if (this.complete) this.size = header!.size;
|
|
for (const n of names) {
|
|
const m = /^e(\d+)$/.exec(n);
|
|
if (m) this.#present.add(Number(m[1]));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Open the disk in `dir`: take its meta file (the lock; another holder
|
|
* makes this retry for `waitMs`, then reject with DiskInUseError), read
|
|
* the header and list the extents.
|
|
*/
|
|
static async open(dir: OpfsDiskDir, opts: OpfsDiskOptions): Promise<OpfsDisk> {
|
|
const until = Date.now() + (opts.waitMs ?? 5000);
|
|
let meta: OpfsSyncFile;
|
|
for (;;) {
|
|
try {
|
|
meta = await dir.open(META, true);
|
|
break;
|
|
} catch (e) {
|
|
if (!isInUse(e) || Date.now() >= until) {
|
|
if (isInUse(e)) throw new DiskInUseError(`${opts.name} is in use (open in another tab or worker)`);
|
|
throw e;
|
|
}
|
|
await new Promise((r) => setTimeout(r, 100));
|
|
}
|
|
}
|
|
try {
|
|
const head = new Uint8Array(2 * SLOT);
|
|
const n = readAll(meta, head, 0);
|
|
const header = decodeHeader(head.subarray(0, n));
|
|
const disk = new OpfsDisk(dir, meta, header, await dir.list(), opts);
|
|
await disk.measure(); // the extents' lengths, so the first stats (the page's attach line) have them
|
|
return disk;
|
|
} catch (e) {
|
|
try { meta.close(); } catch {}
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
get identity(): string | undefined {
|
|
return this.complete ? this.header!.identity : undefined;
|
|
}
|
|
|
|
get uid(): string | undefined {
|
|
return this.complete ? this.header!.uid : undefined;
|
|
}
|
|
|
|
/** The write generation (snapshotState). */
|
|
get gen(): number {
|
|
return this.header?.gen ?? 0;
|
|
}
|
|
|
|
/** Flushes reach the files (Kernel.requestSync waits for them) while the disk is attached. */
|
|
get persistent(): boolean {
|
|
return !this.detached && this.complete;
|
|
}
|
|
|
|
get flushSeq(): number {
|
|
return this.flushes.flushSeq;
|
|
}
|
|
|
|
whenFlushed(after: number): Promise<void> {
|
|
return this.flushes.whenFlushed(after);
|
|
}
|
|
|
|
/** The requests waiting on extents, if any (settled()/requestSync() wait for them). */
|
|
get saving(): Promise<void> | null {
|
|
return this.#tails.size ? Promise.all(this.#tails.values()).then(noop) : null;
|
|
}
|
|
|
|
/** Extent files, and the bytes they hold as far as known (what the browser charges for). */
|
|
get extents(): number {
|
|
return this.#present.size;
|
|
}
|
|
|
|
get storedBytes(): number {
|
|
let n = 0;
|
|
for (const x of this.#present) n += this.#sizes.get(x) ?? 0;
|
|
return n;
|
|
}
|
|
|
|
/** The bytes the extent files hold, every length looked up (storedBytes may not know them all yet). */
|
|
async measure(): Promise<number> {
|
|
const size = this.dir.size?.bind(this.dir);
|
|
await Promise.all([...this.#present].filter((x) => !this.#open.has(x) && !this.#sizes.has(x)).map(async (x) => {
|
|
if (size) this.#sizes.set(x, await size(extentName(x)).catch(() => 0));
|
|
}));
|
|
return this.storedBytes;
|
|
}
|
|
|
|
// --- header --------------------------------------------------------------
|
|
|
|
#writeHeader(h: Omit<OpfsHeader, "v" | "seq">): void {
|
|
const meta = this.#meta;
|
|
if (!meta) throw new Error(`${this.name}: closed`);
|
|
const next: OpfsHeader = { v: 1, ...h, seq: (this.header?.seq ?? 0) + 1, updated: Date.now() };
|
|
meta.write(encodeHeaderSlot(next), { at: (next.seq & 1) * SLOT });
|
|
meta.flush();
|
|
this.stats.headerWrites++;
|
|
this.header = next;
|
|
}
|
|
|
|
#check(): void {
|
|
if (this.detached) throw new Error(`${this.name}: detached`);
|
|
if (!this.complete) throw new Error(`${this.name}: not formatted`);
|
|
}
|
|
|
|
#fail(e: unknown): void {
|
|
this.stats.errors++;
|
|
const err = e as Error;
|
|
this.log(`[host] ${this.name}: ${err?.name ?? "error"}: ${err?.message ?? e}`);
|
|
try { this.onError?.(e); } catch {}
|
|
}
|
|
|
|
/** A write is submitted: the first one after open or a seal starts a new generation, durable before the data. */
|
|
#touch(): void {
|
|
if (!this.#sealed) return;
|
|
const h = this.header!;
|
|
this.#writeHeader({ ...h, gen: h.gen + 1 });
|
|
this.#sealed = false;
|
|
}
|
|
|
|
// --- extents -------------------------------------------------------------
|
|
|
|
/** Run fn after the requests waiting on extent x; if it ends up waiting itself, later ones wait for it. */
|
|
#serial(x: number, fn: () => MaybePromise<void>): MaybePromise<void> {
|
|
const tail = this.#tails.get(x);
|
|
const r = tail ? tail.then(fn) : fn();
|
|
if (r instanceof Promise) {
|
|
// Gone in the reaction that settles it, registered before the caller's: once BlockHost
|
|
// completes the request, nothing is left waiting on the extent (snapshotSeal() checks).
|
|
const done = () => { if (this.#tails.get(x) === t) this.#tails.delete(x); };
|
|
const t: Promise<void> = r.then(done, done);
|
|
this.#tails.set(x, t);
|
|
}
|
|
return r;
|
|
}
|
|
|
|
/** Can a request on x run now (nothing waiting on it, its handle open or the extent absent)? */
|
|
#ready(x: number, create: boolean): boolean {
|
|
return !this.#tails.has(x) && (this.#open.has(x) || (!create && !this.#present.has(x)));
|
|
}
|
|
|
|
/** Extent x's handle: now, null for an absent extent (without create), or a promise when it must be opened. */
|
|
#file(x: number, create: boolean): OpfsSyncFile | null | Promise<OpfsSyncFile | null> {
|
|
const f = this.#open.get(x);
|
|
if (f) {
|
|
this.#open.delete(x); // most recently used last
|
|
this.#open.set(x, f);
|
|
return f;
|
|
}
|
|
if (!create && !this.#present.has(x)) return null;
|
|
return this.#openExtent(x, create);
|
|
}
|
|
|
|
async #openExtent(x: number, create: boolean): Promise<OpfsSyncFile | null> {
|
|
const had = this.#present.has(x);
|
|
let f: OpfsSyncFile;
|
|
try {
|
|
f = await this.dir.open(extentName(x), create);
|
|
} catch (e) {
|
|
if (!create && (e as Error)?.name === "NotFoundError") {
|
|
this.#present.delete(x);
|
|
this.#sizes.delete(x);
|
|
return null;
|
|
}
|
|
throw e;
|
|
}
|
|
if (!this.#meta) {
|
|
// Closed meanwhile: keep no handle open.
|
|
try { f.close(); } catch {}
|
|
throw new Error(`${this.name}: closed`);
|
|
}
|
|
this.stats.opens++;
|
|
if (!had) this.stats.creates++;
|
|
this.#evict();
|
|
this.#open.set(x, f);
|
|
this.#present.add(x);
|
|
this.#sizes.set(x, f.getSize());
|
|
return f;
|
|
}
|
|
|
|
/** Close the least recently used handles with nothing waiting on them, to stay under maxOpen. */
|
|
#evict(): void {
|
|
if (this.#open.size < this.maxOpen) return;
|
|
for (const [x, f] of this.#open) {
|
|
if (this.#open.size < this.maxOpen) break;
|
|
if (this.#tails.has(x)) continue;
|
|
if (this.#dirty.has(x)) {
|
|
f.flush();
|
|
this.stats.extentFlushes++;
|
|
this.#dirty.delete(x);
|
|
}
|
|
f.close();
|
|
this.#open.delete(x);
|
|
this.stats.evictions++;
|
|
}
|
|
}
|
|
|
|
/** [extent, byte in extent, start, end in the range] for the range [off, off + len). */
|
|
#pieces(off: number, len: number): Array<[number, number, number, number]> {
|
|
const out: Array<[number, number, number, number]> = [];
|
|
const E = this.extent;
|
|
for (let p = off; p < off + len;) {
|
|
const x = Math.floor(p / E), e = Math.min(off + len, (x + 1) * E);
|
|
out.push([x, p - x * E, p - off, e - off]);
|
|
p = e;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
#put(f: OpfsSyncFile, x: number, data: Uint8Array, at: number): void {
|
|
const n = f.write(data, { at });
|
|
if (n !== data.length) throw new Error(`${this.name}: short write to extent ${x} (${n} of ${data.length} bytes)`);
|
|
if (at + n > (this.#sizes.get(x) ?? 0)) this.#sizes.set(x, at + n);
|
|
this.#dirty.add(x);
|
|
}
|
|
|
|
/** Bytes [at, at + n) of extent x read as zeros: written as zeros up to the file's length (beyond it they are zeros already). */
|
|
#zeroIn(f: OpfsSyncFile, x: number, at: number, n: number): void {
|
|
const end = Math.min(at + n, f.getSize());
|
|
for (let p = at; p < end; p += ZEROS.length) {
|
|
const k = Math.min(ZEROS.length, end - p);
|
|
this.#put(f, x, ZEROS.subarray(0, k), p);
|
|
this.stats.zeroBytes += k;
|
|
}
|
|
}
|
|
|
|
/** Remove extent x's file (it reads as zeros then). */
|
|
async #drop(x: number): Promise<void> {
|
|
if (!this.#present.has(x)) return;
|
|
const f = this.#open.get(x);
|
|
if (f) {
|
|
this.#open.delete(x);
|
|
try { f.close(); } catch {}
|
|
}
|
|
this.#dirty.delete(x);
|
|
await this.dir.remove(extentName(x));
|
|
this.#present.delete(x);
|
|
this.#sizes.delete(x);
|
|
this.stats.deletes++;
|
|
}
|
|
|
|
/** Every request waiting on an extent has finished. */
|
|
async #idle(): Promise<void> {
|
|
while (this.#tails.size) await Promise.all(this.#tails.values());
|
|
}
|
|
|
|
#flushDirty(): void {
|
|
for (const x of [...this.#dirty]) {
|
|
this.#open.get(x)?.flush();
|
|
this.stats.extentFlushes++;
|
|
this.#dirty.delete(x);
|
|
}
|
|
}
|
|
|
|
#closeExtents(): void {
|
|
for (const f of this.#open.values()) {
|
|
try { f.close(); } catch {}
|
|
}
|
|
this.#open.clear();
|
|
}
|
|
|
|
// --- block device --------------------------------------------------------
|
|
|
|
read(off: number, views: Uint8Array[]): MaybePromise<void> {
|
|
this.#check();
|
|
this.stats.reads++;
|
|
let waits: Promise<void>[] | null = null;
|
|
let o = off;
|
|
for (const v of views) {
|
|
for (const [x, at, s, e] of this.#pieces(o, v.length)) {
|
|
const sub = v.subarray(s, e);
|
|
const run = (f: OpfsSyncFile | null) => {
|
|
const n = f ? readAll(f, sub, at) : 0;
|
|
if (n < sub.length) sub.fill(0, n);
|
|
};
|
|
const r = this.#serial(x, () => {
|
|
const f = this.#file(x, false);
|
|
return f instanceof Promise ? f.then(run) : run(f);
|
|
});
|
|
if (r instanceof Promise) (waits ??= []).push(r);
|
|
}
|
|
o += v.length;
|
|
}
|
|
if (!waits) return;
|
|
this.stats.waits++;
|
|
return Promise.all(waits).then(noop);
|
|
}
|
|
|
|
write(off: number, views: Uint8Array[]): MaybePromise<unknown> {
|
|
this.#check();
|
|
try {
|
|
this.#touch();
|
|
} catch (e) {
|
|
this.#fail(e);
|
|
throw e;
|
|
}
|
|
this.stats.writes++;
|
|
let waits: Promise<void>[] | null = null;
|
|
let o = off;
|
|
for (const v of views) {
|
|
for (const [x, at, s, e] of this.#pieces(o, v.length)) {
|
|
// A request that waits takes a copy: the guest's pages need not stay as they are.
|
|
const data = this.#ready(x, true) ? v.subarray(s, e) : v.slice(s, e);
|
|
const run = (f: OpfsSyncFile | null) => this.#put(f!, x, data, at);
|
|
let r: MaybePromise<void>;
|
|
try {
|
|
r = this.#serial(x, () => {
|
|
const f = this.#file(x, true);
|
|
return f instanceof Promise ? f.then(run) : run(f);
|
|
});
|
|
} catch (err) {
|
|
this.#fail(err);
|
|
throw err;
|
|
}
|
|
if (r instanceof Promise) (waits ??= []).push(r.catch((err: unknown) => { this.#fail(err); throw err; }));
|
|
}
|
|
o += v.length;
|
|
}
|
|
if (!waits) return;
|
|
this.stats.waits++;
|
|
return Promise.all(waits);
|
|
}
|
|
|
|
discard(off: number, len: number): MaybePromise<unknown> {
|
|
return this.writeZeroes(off, len);
|
|
}
|
|
|
|
/** The range reads as zeros: a wholly covered extent is deleted, the rest written as zeros within the files. */
|
|
writeZeroes(off: number, len: number): MaybePromise<unknown> {
|
|
this.#check();
|
|
try {
|
|
this.#touch();
|
|
} catch (e) {
|
|
this.#fail(e);
|
|
throw e;
|
|
}
|
|
let waits: Promise<void>[] | null = null;
|
|
for (const [x, at, s, e] of this.#pieces(off, len)) {
|
|
const span = Math.min(this.extent, this.size - x * this.extent);
|
|
const whole = at === 0 && e - s >= span;
|
|
let r: MaybePromise<void>;
|
|
try {
|
|
r = this.#serial(x, () => {
|
|
if (!this.#present.has(x)) return;
|
|
if (whole) return this.#drop(x);
|
|
const f = this.#file(x, false);
|
|
const run = (h: OpfsSyncFile | null) => { if (h) this.#zeroIn(h, x, at, e - s); };
|
|
return f instanceof Promise ? f.then(run) : run(f);
|
|
});
|
|
} catch (err) {
|
|
this.#fail(err);
|
|
throw err;
|
|
}
|
|
if (r instanceof Promise) (waits ??= []).push(r.catch((err: unknown) => { this.#fail(err); throw err; }));
|
|
}
|
|
if (!waits) return;
|
|
this.stats.waits++;
|
|
return Promise.all(waits);
|
|
}
|
|
|
|
/** flush() every extent written since the last flush, once the requests before this one have finished. */
|
|
flush(): MaybePromise<unknown> {
|
|
this.#check();
|
|
const seq = this.flushes.begin();
|
|
this.stats.flushes++;
|
|
const run = () => {
|
|
try {
|
|
this.#flushDirty();
|
|
} catch (e) {
|
|
this.#fail(e);
|
|
throw e;
|
|
}
|
|
this.flushes.done(seq);
|
|
};
|
|
if (!this.#tails.size) return run();
|
|
this.stats.waits++;
|
|
return Promise.all(this.#tails.values()).then(run);
|
|
}
|
|
|
|
// --- snapshots -----------------------------------------------------------
|
|
|
|
snapshotState(): DiskSnapshotState {
|
|
if (!this.persistent) throw new Error(`${this.name}: detached, so a snapshot could not be checked against it`);
|
|
return { name: this.name, identity: `store ${this.name} ${this.identity} uid=${this.uid}`, gen: this.gen };
|
|
}
|
|
|
|
/** At the consistent point (nothing in flight): flush every written extent now; the next write starts a new generation. */
|
|
snapshotSeal(): { state: DiskSnapshotState; done: Promise<void> } {
|
|
const state = this.snapshotState();
|
|
if (this.#tails.size) throw new Error(`${this.name}: a request is in flight`);
|
|
try {
|
|
this.#flushDirty();
|
|
} catch (e) {
|
|
this.#fail(e);
|
|
throw e;
|
|
}
|
|
this.#sealed = true;
|
|
return { state, done: Promise.resolve() };
|
|
}
|
|
|
|
// --- management ----------------------------------------------------------
|
|
|
|
/**
|
|
* Start a format: the header says incomplete (durable first), then every
|
|
* other file goes. Then putBlocks(), then completeFormat(); format() does
|
|
* all three. Until completeFormat() the disk refuses guest I/O, and a
|
|
* disk opened after a cut-off format is not complete.
|
|
*/
|
|
async beginFormat({ identity, size, uid = newUid(), gen = 0, origin, from }: Omit<OpfsFormat, "image">): Promise<void> {
|
|
if (!this.#meta) throw new Error(`${this.name}: closed`);
|
|
if (!(size > 0) || size % 512) throw new Error(`${this.name}: bad size ${size}`);
|
|
await this.#idle();
|
|
this.#closeExtents();
|
|
this.#dirty.clear();
|
|
this.complete = false;
|
|
this.extent = OPFS_EXTENT;
|
|
this.#writeHeader({ identity, size, extent: this.extent, uid, gen, complete: false, origin, from, created: Date.now() });
|
|
for (const n of await this.dir.list()) if (n !== META) await this.dir.remove(n);
|
|
this.#present.clear();
|
|
this.#sizes.clear();
|
|
this.size = size;
|
|
}
|
|
|
|
/** Write 4 KiB blocks (block number, data) during a format; all-zero blocks are left out (they read as zeros). */
|
|
async putBlocks(entries: Iterable<[number, Uint8Array]>): Promise<void> {
|
|
if (this.complete || !this.header) throw new Error(`${this.name}: putBlocks() outside a format`);
|
|
const waits: Promise<void>[] = [];
|
|
for (const [b, v] of entries) {
|
|
if (v.length !== BLOCK) throw new Error(`${this.name}: block ${b} is ${v.length} bytes`);
|
|
if ((b + 1) * BLOCK > this.size) throw new Error(`${this.name}: block ${b} is past the end`);
|
|
if (isZeroBlock(v)) continue;
|
|
const x = Math.floor(b * BLOCK / this.extent), at = b * BLOCK - x * this.extent;
|
|
const data = this.#ready(x, true) ? v : v.slice();
|
|
const run = (f: OpfsSyncFile | null) => this.#put(f!, x, data, at);
|
|
const r = this.#serial(x, () => {
|
|
const f = this.#file(x, true);
|
|
return f instanceof Promise ? f.then(run) : run(f);
|
|
});
|
|
if (r instanceof Promise) waits.push(r);
|
|
}
|
|
await Promise.all(waits);
|
|
}
|
|
|
|
/** Finish a format: every block durable, then the header says complete. */
|
|
async completeFormat(): Promise<void> {
|
|
if (this.complete || !this.header) throw new Error(`${this.name}: completeFormat() outside a format`);
|
|
await this.#idle();
|
|
this.#flushDirty();
|
|
this.#writeHeader({ ...this.header, complete: true });
|
|
this.complete = true;
|
|
this.#sealed = true;
|
|
}
|
|
|
|
/** Replace the content: beginFormat(), the image's blocks, completeFormat(). */
|
|
async format(f: OpfsFormat): Promise<void> {
|
|
await this.beginFormat(f);
|
|
const img = f.image;
|
|
if (img) {
|
|
if (img.blockSize !== BLOCK) throw new Error(`${this.name}: image block size ${img.blockSize}, need ${BLOCK}`);
|
|
const n = img.indices.length;
|
|
for (let i = 0; i < n; i += 256) {
|
|
const part: Array<[number, Uint8Array]> = [];
|
|
for (let j = i; j < Math.min(n, i + 256); j++) part.push([img.indices[j]!, img.block(j)]);
|
|
await this.putBlocks(part);
|
|
}
|
|
}
|
|
await this.completeFormat();
|
|
}
|
|
|
|
/** Grow to `size` bytes (never shrinks), with a new identity; the new space reads as zeros. */
|
|
grow(size: number, identity: string): void {
|
|
this.#check();
|
|
if (size < this.size) throw new Error(`${this.name}: a disk never shrinks (${this.size} to ${size} bytes)`);
|
|
if (size % 512) throw new Error(`${this.name}: bad size ${size}`);
|
|
this.#writeHeader({ ...this.header!, size, identity });
|
|
this.size = size;
|
|
}
|
|
|
|
/**
|
|
* The disk's content as a kwsparse image (uncompressed) in parts: a
|
|
* Blob per extent of its blocks that are not all zeros, so that a browser
|
|
* can keep a large export out of the JS heap (gzipBlob() compresses them).
|
|
*/
|
|
async exportParts(): Promise<{ size: number; blocks: number; parts: BlobPart[] }> {
|
|
this.#check();
|
|
await this.#idle();
|
|
const indices: number[] = [], parts: BlobPart[] = [];
|
|
for (const x of [...this.#present].sort((a, b) => a - b)) {
|
|
const span = Math.min(this.extent, this.size - x * this.extent);
|
|
if (span <= 0) continue;
|
|
await this.#serial(x, () => {
|
|
const run = (f: OpfsSyncFile | null) => {
|
|
if (!f) return;
|
|
const len = Math.min(span, f.getSize());
|
|
const buf = new Uint8Array(Math.ceil(len / BLOCK) * BLOCK);
|
|
readAll(f, buf.subarray(0, len), 0);
|
|
const list: Uint8Array<ArrayBuffer>[] = [];
|
|
for (let p = 0; p < buf.length; p += BLOCK) {
|
|
const blk = buf.subarray(p, p + BLOCK);
|
|
if (isZeroBlock(blk)) continue;
|
|
indices.push((x * this.extent + p) / BLOCK);
|
|
list.push(blk);
|
|
}
|
|
if (list.length) parts.push(new Blob(list));
|
|
};
|
|
const f = this.#file(x, false);
|
|
return f instanceof Promise ? f.then(run) : run(f);
|
|
});
|
|
}
|
|
const head = kwsparseHeader(this.size, BLOCK, indices) as Uint8Array<ArrayBuffer>;
|
|
return { size: this.size, blocks: indices.length, parts: [head, ...parts] };
|
|
}
|
|
|
|
/**
|
|
* Stop using the files (before another opener replaces or removes the
|
|
* disk): every later request fails (EIO in the guest); the requests in
|
|
* flight finish, written extents are flushed and every handle, the lock's
|
|
* too, is closed.
|
|
*/
|
|
async detach(): Promise<void> {
|
|
if (this.detached && !this.#meta) return;
|
|
this.detached = true;
|
|
await this.#idle();
|
|
this.close();
|
|
}
|
|
|
|
/** Flush what was written and close every handle (the lock is released). */
|
|
close(): void {
|
|
this.detached = true;
|
|
try {
|
|
this.#flushDirty();
|
|
} catch (e) {
|
|
this.#fail(e);
|
|
}
|
|
this.#closeExtents();
|
|
const meta = this.#meta;
|
|
this.#meta = null;
|
|
try { meta?.close(); } catch {}
|
|
}
|
|
}
|