Files
unkernel/js/web/opfs.ts

171 lines
6.5 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The origin private file system (navigator.storage.getDirectory()) for
// OpfsDisk (core/opfs-disk.ts): one directory per disk, kwdisk/<name> (the
// data disk's is kwdisk/kwdata-v1). An OpfsDisk needs
// FileSystemSyncAccessHandle, which browsers give only to dedicated
// workers; reading a header (getFile()) and removing a disk work anywhere
// OPFS does.
import { DiskInUseError, decodeHeader, type OpfsDiskDir, type OpfsHeader, type OpfsSyncFile } from "../core/opfs-disk.ts";
/** OPFS cannot be used here: no navigator.storage.getDirectory(), not a secure context, the browser refused it, or (for an OpfsDisk) not a dedicated worker. */
export class OpfsUnavailableError extends Error {
override name = "OpfsUnavailableError";
}
// The subset of the File System API used here (lib.dom lacks the worker-only parts).
interface FileHandle {
kind: "file";
getFile(): Promise<File>;
createSyncAccessHandle?(): Promise<OpfsSyncFile>;
}
interface DirHandle {
kind: "directory";
getDirectoryHandle(name: string, o?: { create?: boolean }): Promise<DirHandle>;
getFileHandle(name: string, o?: { create?: boolean }): Promise<FileHandle>;
removeEntry(name: string, o?: { recursive?: boolean }): Promise<void>;
keys(): AsyncIterable<string>;
}
/** The directory that holds the disks. */
const ROOT = "kwdisk";
/** Why OPFS is not available here for reading and removing disks (null: try navigator.storage.getDirectory()). */
export function opfsBlocker(): string | null {
if (typeof navigator === "undefined" || typeof navigator.storage?.getDirectory !== "function") return "this browser has no OPFS (navigator.storage.getDirectory)";
if (globalThis.isSecureContext === false) return "OPFS needs a secure context (https or localhost)";
return null;
}
/** Why an OpfsDisk cannot run here (it needs a dedicated worker's synchronous file handles), or null. */
export function opfsDiskBlocker(): string | null {
const b = opfsBlocker();
if (b) return b;
const D = (globalThis as { DedicatedWorkerGlobalScope?: new () => unknown }).DedicatedWorkerGlobalScope;
if (typeof D !== "function" || !(globalThis instanceof D)) return "an OPFS disk runs only in a dedicated worker (FileSystemSyncAccessHandle)";
return null;
}
async function root(): Promise<DirHandle> {
const why = opfsBlocker();
if (why) throw new OpfsUnavailableError(why);
try {
return await navigator.storage.getDirectory() as unknown as DirHandle;
} catch (e) {
const err = e as Error;
throw new OpfsUnavailableError(`the browser refused OPFS (${err?.name ?? "Error"}: ${err?.message ?? e})`, { cause: e });
}
}
/** Resolves true where navigator.storage.getDirectory() answers (a private window may refuse it). */
export async function opfsAvailable(): Promise<boolean> {
try {
await root();
return true;
} catch {
return false;
}
}
const isNotFound = (e: unknown) => (e as Error)?.name === "NotFoundError";
const inUse = (e: unknown) => (e as Error)?.name === "NoModificationAllowedError";
/** The handle of kwdisk/<id> (created with `create`), or null if missing. */
async function diskHandle(id: string, create: boolean): Promise<DirHandle | null> {
try {
return await (await (await root()).getDirectoryHandle(ROOT, { create })).getDirectoryHandle(id, { create });
} catch (e) {
if (!create && isNotFound(e)) return null;
throw e;
}
}
/** An OpfsDiskDir over a directory handle (files opened with createSyncAccessHandle()). */
export function opfsDir(h: DirHandle): OpfsDiskDir {
return {
async list() {
const out: string[] = [];
for await (const n of h.keys()) out.push(n);
return out;
},
async open(name, create) {
const f = await h.getFileHandle(name, { create });
if (typeof f.createSyncAccessHandle !== "function") throw new OpfsUnavailableError("no FileSystemSyncAccessHandle here (it exists only in dedicated workers)");
try {
return await f.createSyncAccessHandle();
} catch (e) {
if (inUse(e)) throw new DiskInUseError(`${name}: open elsewhere`, { cause: e });
throw e;
}
},
async remove(name) {
try {
await h.removeEntry(name);
} catch (e) {
if (isNotFound(e)) return;
if (inUse(e)) throw new DiskInUseError(`${name}: open elsewhere`, { cause: e });
throw e;
}
},
async size(name) {
return (await (await h.getFileHandle(name)).getFile()).size;
},
};
}
/** The OpfsDiskDir of disk `id` (kwdisk/<id>, created). Needs a dedicated worker. */
export async function opfsDiskDir(id: string): Promise<OpfsDiskDir> {
const why = opfsDiskBlocker();
if (why) throw new OpfsUnavailableError(why);
return opfsDir((await diskHandle(id, true))!);
}
/**
* What a disk's header says, without opening the disk (anywhere OPFS works):
* null if there is no disk; "in use" if its holder keeps it from being read.
* With `bytes`, also the extent files' lengths summed (what the quota charges).
*/
export async function readOpfsHeader(id: string, { bytes = false }: { bytes?: boolean } = {}): Promise<{ header: OpfsHeader | null; files: number; bytes?: number } | null | "in use"> {
const h = await diskHandle(id, false);
if (!h) return null;
let files = 0, total = 0;
for await (const n of h.keys()) {
if (n === "meta") continue;
files++;
if (bytes) total += await h.getFileHandle(n).then((f) => f.getFile()).then((f) => f.size, () => 0);
}
let meta: Uint8Array;
try {
meta = new Uint8Array(await (await (await h.getFileHandle("meta")).getFile()).arrayBuffer());
} catch (e) {
if (isNotFound(e)) return { header: null, files, ...(bytes ? { bytes: total } : {}) };
if (inUse(e) || (e as Error)?.name === "NotReadableError") return "in use";
throw e;
}
return { header: decodeHeader(meta), files, ...(bytes ? { bytes: total } : {}) };
}
/**
* Remove disk `id` (kwdisk/<id>): its meta file first, so that a removal cut
* off half way leaves a disk without a header, which its next opener formats
* again. Rejects with DiskInUseError while a handle has a file of it open.
*/
export async function removeOpfsDisk(id: string): Promise<boolean> {
const h = await diskHandle(id, false);
if (!h) return false;
try {
await h.removeEntry("meta");
} catch (e) {
if (inUse(e)) throw new DiskInUseError(`OPFS ${ROOT}/${id} is in use (open in another tab or worker)`, { cause: e });
if (!isNotFound(e)) throw e;
}
try {
await (await (await root()).getDirectoryHandle(ROOT)).removeEntry(id, { recursive: true });
} catch (e) {
if (inUse(e)) throw new DiskInUseError(`OPFS ${ROOT}/${id} is in use (open in another tab or worker)`, { cause: e });
if (!isNotFound(e)) throw e;
}
return true;
}