Something went wrong. Try again.
An experimental port of NetBSD, FreeBSD, OpenBSD, and XNU to unkernel unkernel.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227// SPDX-License-Identifier: MIT// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>// The page's persistent data disk: an ext4 file system labelled kwdata (the// guest mounts it at /data) kept in IndexedDB (the SDK's openDataDisk) or,// in worker mode, in OPFS (built by the kernel worker from a spec; boot.ts// dataSpec()). This module owns the browser side: the template, the// one-tab-at-a-time lock, storage persistence and quota, export, import and// reset, and the jobs on the OPFS disk that need a worker of their own// (runDataJob(): data-worker.ts). boot.ts calls attachDataDisk() inline and// wires the rest to KW.*.import { DATA_DISK_NAME, dataDiskInfo, gzipBlob, importDataDisk, openDataDisk, resetDataDisk, type CowDisk, type DataDiskBackend, type DataDiskInfo } from "./sdk.ts";import type { DataJob, DataJobMessage } from "./data-worker.ts";
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export interface DiskLock { held: boolean; how: string; why?: unknown; /** Web Locks, held: let go of it (otherwise held for the page's lifetime). */ release?: () => void;}
/** * Hold the disk for this page's lifetime, if no other tab does: * navigator.locks (secure contexts), else a BroadcastChannel probe (plain * http LAN pages are not a secure context; two tabs opened in the same * instant may both win there). */export function acquireDiskLock(name = DATA_DISK_NAME): Promise<DiskLock> { const key = `kwdisk:${name}`; if (navigator.locks?.request) { return new Promise((resolve) => { navigator.locks.request(key, { ifAvailable: true }, (lock) => { if (!lock) { resolve({ held: false, how: "Web Locks" }); return undefined; } // Held until release(), or until the page goes away. return new Promise<void>((release) => resolve({ held: true, how: "Web Locks", release })); }).catch((e: unknown) => resolve(probeLock(key, e))); }); } return probeLock(key);}
/** * Resolves once the disk lock was free while this tab is shown (the tab that * held it closed): a request without `ifAvailable`, let go as soon as it is * granted, then a second so a tab that reloads takes it back first (a * hidden tab waits until it is shown: the reload is the shown tab's). It * does not hold the lock: take it with acquireDiskLock(), which may still * fail. Never resolves where Web Locks are missing (the BroadcastChannel * probe has nothing to wait on); `signal` withdraws the request. */export async function diskLockFreed(signal: AbortSignal, name = DATA_DISK_NAME): Promise<void> { if (!navigator.locks?.request) return new Promise<void>(() => {}); try { await navigator.locks.request(`kwdisk:${name}`, { signal }, () => undefined); } catch { return new Promise<void>(() => {}); // withdrawn, or refused } while (document.visibilityState !== "visible" && !signal.aborted) await new Promise((r) => document.addEventListener("visibilitychange", r, { once: true })); await sleep(1000); if (signal.aborted) return new Promise<void>(() => {});}
async function probeLock(key: string, why?: unknown): Promise<DiskLock> { if (typeof BroadcastChannel !== "function") return { held: true, how: "none (no Web Locks or BroadcastChannel)", why }; const ch = new BroadcastChannel(key); let held = false, taken = false; ch.onmessage = (e: MessageEvent) => { if (e.data?.type === "held") taken = true; else if (e.data?.type === "probe" && held) ch.postMessage({ type: "held" }); }; ch.postMessage({ type: "probe" }); await sleep(300); if (taken) { ch.close(); return { held: false, how: "BroadcastChannel" }; } held = true; // the channel stays open and answers probes for the page's lifetime return { held: true, how: "BroadcastChannel" };}
/** The template: the kernel bundle's custom section unkernel.datadisk (kernel/build.sh datadisk, bundle). */export function loadTemplate(bundled: Uint8Array | undefined): { bytes: Uint8Array | null; from: string } { return bundled ? { bytes: bundled, from: "bundled in the kernel" } : { bytes: null, from: "the kernel has no unkernel.datadisk section" };}
export interface StorageState { persisted?: boolean; usage?: number; quota?: number;}
/** navigator.storage: persistence (asked for with `ask`), usage and quota; fields undefined where unsupported. */export async function storageState({ ask = false }: { ask?: boolean } = {}): Promise<StorageState> { const s = navigator.storage; const out: StorageState = {}; try { if (ask && s?.persist) out.persisted = await s.persist(); else if (s?.persisted) out.persisted = await s.persisted(); } catch {} try { if (s?.estimate) { const e = await s.estimate(); out.usage = e.usage; out.quota = e.quota; } } catch {} return out;}
export interface DataAttach { /** null: no data disk (reason says why); in worker mode always null (the disk is the worker's). */ disk: CowDisk | null; lock: DiskLock | null; /** Where it is kept: IndexedDB, or (worker mode only) OPFS. */ backend: DataDiskBackend; /** Worker mode: a disk spec went to the worker. */ spec?: boolean; /** Attached, but not persistently: why. */ notice?: string; reason?: string; /** Where the template came from. */ from?: string;}
/** Why a tab without the lock has no data disk (Settings' status line: "No data disk: …"). */export const OTHER_TAB = "open in another tab";
/** * Open the data disk for this page, under `lock` (boot.ts takes it before * anything touches the disk; not held: no data disk); `size` (bytes) grows * a smaller saved disk (openDataDisk()). */export async function attachDataDisk({ enabled, bundled, size, lock, log, onError }: { enabled: boolean; bundled: Uint8Array | undefined; size?: number; lock: DiskLock | null; log: (m: string) => void; onError: (e: unknown) => void;}): Promise<DataAttach> { const backend = "idb"; if (!enabled) return { disk: null, lock: null, backend, reason: "off (?data=0)" }; if (typeof indexedDB === "undefined") return { disk: null, lock: null, backend, reason: "no IndexedDB in this browser" }; lock ??= await acquireDiskLock(); if (!lock.held) return { disk: null, lock, backend, reason: OTHER_TAB }; const tpl = loadTemplate(bundled); if (!tpl.bytes) return { disk: null, lock, backend, reason: `no template (${tpl.from})` }; try { const disk = await openDataDisk({ template: tpl.bytes, size, log, onError }); return { disk, lock, backend, from: tpl.from }; } catch (e) { // A saved disk of another format, one moved to OPFS (a fenced copy), or // IndexedDB refusing (private browsing, disabled storage): run on a copy // of the template. const err = e as Error; log(`[host] data disk: not attached persistently: ${err.name}: ${err.message}`); const disk = await openDataDisk({ template: tpl.bytes, mode: "snapshot", size, log, snapshotLimit: 0 }); const why = err.name === "DataDiskFormatError" ? err.message : `IndexedDB failed (${err.name}: ${err.message})`; return { disk, lock, backend, from: tpl.from, notice: `${why}; this tab's /data is a fresh disk in memory (changes are not saved)` }; }}
/** What IndexedDB and OPFS hold of the data disk (dataDiskInfo(): nothing opened, nothing written). */export async function dataStores(): Promise<{ idb: DataDiskInfo; opfs: DataDiskInfo }> { const [idb, opfs] = await Promise.all([dataDiskInfo({ backend: "idb" }), dataDiskInfo({ backend: "opfs" })]); return { idb, opfs };}
/** * Run a data disk job in a worker of its own (data-worker.ts): migrate the * IndexedDB disk to OPFS or import a .kwsparse image into OPFS (the kernel * worker must not have the OPFS disk open), or remove the blocks of the * fenced IndexedDB copy (in the background; progress counts the blocks * removed, total 0). Rejects with an error of the job's name * (DataDiskSpaceError, DiskInUseError, ...). */export function runDataJob<T>(job: DataJob, { onProgress, log }: { onProgress?: (done: number, total: number) => void; log?: (m: string) => void } = {}): Promise<T> { const w = new Worker(new URL("./data-worker.ts", import.meta.url), { type: "module", name: "unkernel-data" }); return new Promise<T>((resolve, reject) => { w.onmessage = (e: MessageEvent<DataJobMessage>) => { const m = e.data; if (m.t === "progress") onProgress?.(m.done, m.total); else if (m.t === "log") log?.(m.msg); else if (m.t === "done") resolve(m.value as T); else reject(Object.assign(new Error(m.message), { name: m.name })); }; w.onerror = (e) => reject(new Error(`the data disk worker failed: ${e.message || "it did not start"}`)); w.postMessage(job, job.op === "import" ? [job.bytes.buffer as ArrayBuffer] : []); }).finally(() => w.terminate());}
/** Remove the OPFS data disk (its directory; DiskInUseError while a worker has it open). */export const resetOpfsDataDisk = (): Promise<void> => resetDataDisk({ backend: "opfs" });
/** Download the disk's current content as a .kwsparse.gz file. */export async function exportDataDisk(disk: CowDisk): Promise<{ name: string; blocks: number; bytes: number }> { const { parts, blocks } = await disk.exportParts(); return downloadKwsparse(parts, blocks);}
/** Download kwsparse parts (CowDisk.exportParts(), here or from the kernel worker) as a .kwsparse.gz file. */export async function downloadKwsparse(parts: BlobPart[], blocks: number): Promise<{ name: string; blocks: number; bytes: number }> { const blob = await gzipBlob(parts); const name = `kwdata-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-")}.kwsparse.gz`; const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = name; document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 60000); return { name, blocks, bytes: blob.size };}
/** Stop a running disk's saves (and wait for one in flight) before its store is replaced. */export async function detachDataDisk(disk: CowDisk | null | undefined): Promise<void> { if (!disk) return; disk.detach(); await disk.saving?.catch(() => {}); await disk.store?.close?.();}
export { importDataDisk, resetDataDisk };