Files
unkernel/js/node/distro-fetch.ts

340 lines
15 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// fetchDistro(name) for Node: a named distro image (distros.json) as a
// local file path that createKernel({ distro }) takes. In a source
// checkout it is the build's vendor/build/distro/<name>.erofs and nothing
// is downloaded; in an installed package it is downloaded once from the
// GitHub release of the package's version into a cache directory, checked
// against that release's distros.json (size and SHA-256) on the way in.
//
// A versioned release (tag v<version>) never changes, so once its
// distros.json and the image are cached, later calls use them without the
// network. A release given by releaseUrl or $UNKERNEL_RELEASE_URL can
// change (an image rebuilt in place), so its distros.json is read again on
// each call, the cached copy only when that fails. Either way a cached
// image is hashed in full once: a sidecar file (<image>.verified) records
// the size, mtime and SHA-256 it was checked with, and the image is trusted
// while its size and mtime still match and the recorded hash is the index
// entry's; otherwise it is hashed again, and downloaded again if that
// fails. Files are written under a unique name and renamed into place, so
// that calls fetching at the same time never see a partial file.
//
// Nothing here runs unless called: the SDK itself never goes to the network
// for a distro.
//
// The package root (for package.json's version and the checkout's
// vendor/build/distro) is passed in by the entry (node.ts, cli.ts), so that
// `new URL(..., import.meta.url)` stays in the entry module.
import { createHash, randomBytes } from "node:crypto";
import { type BigIntStats, accessSync, constants, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { DistroIndex, DistroIndexEntry } from "../core/distro.ts";
/** The GitHub repository whose releases carry the distro images. */
export const RELEASE_REPO = "pithings/unkernel";
/** What fetchDistro() is doing, for a progress display. */
export interface FetchDistroProgress {
/**
* "index": reading distros.json (`path` set when it is the cached copy of
* a versioned release, read without the network); "download": bytes
* arriving (loaded of total); "verify": checking a cached file; "done".
*/
stage: "index" | "download" | "verify" | "done";
name: string;
/** The image's file name (once the index is read). */
file?: string;
/** Where it comes from (the release directory URL). */
url?: string;
/** Where it goes (the local file). */
path?: string;
loaded?: number;
total?: number;
/** "done": whether it came from the cache (true) or was downloaded now. */
cached?: boolean;
}
export interface FetchDistroOptions {
/**
* The release directory holding distros.json and the images, as a URL
* (ending in "/" or not). Default: $UNKERNEL_RELEASE_URL, else
* https://github.com/pithings/unkernel/releases/download/v<version>/ for
* the package's version. Its distros.json is read on every call (falling
* back to the cached copy), since such a location can change; the
* versioned release's is read once.
*/
releaseUrl?: string;
/**
* Where downloads are kept: a directory per release under it. Default:
* defaultCacheDir().
*/
cacheDir?: string;
/**
* In a source checkout, use its build (vendor/build/distro/) and never
* download (default true). false: download even there.
*/
local?: boolean;
onProgress?: (p: FetchDistroProgress) => void;
signal?: AbortSignal;
}
/** fetchDistro() could not produce the image: `offline` when the network failed and nothing usable was cached. */
export class DistroFetchError extends Error {
readonly offline: boolean;
constructor(message: string, { offline = false, cause }: { offline?: boolean; cause?: unknown } = {}) {
super(message, { cause });
this.name = "DistroFetchError";
this.offline = offline;
}
}
/** Is `root` a source checkout (as opposed to an installed package)? */
export function isCheckout(root: string): boolean {
return existsSync(path.join(root, "kernel/build.sh"));
}
/**
* The default cache directory: $UNKERNEL_CACHE_DIR, else
* $XDG_CACHE_HOME/unkernel or ~/.cache/unkernel when it can be created and
* written, else <os.tmpdir()>/unkernel-cache-<uid>. Throws a
* DistroFetchError when none of them can be used.
*/
export function defaultCacheDir(): string {
if (process.env.UNKERNEL_CACHE_DIR) return path.resolve(process.env.UNKERNEL_CACHE_DIR);
let home: string | undefined;
if (process.env.XDG_CACHE_HOME && path.isAbsolute(process.env.XDG_CACHE_HOME)) home = path.join(process.env.XDG_CACHE_HOME, "unkernel");
else {
try {
const h = homedir();
if (h) home = path.join(h, ".cache", "unkernel");
} catch {}
}
if (home && writable(home)) return home;
// Shared with other users: only a directory of our own (or none yet).
const uid = process.getuid?.();
const tmp = path.join(tmpdir(), uid === undefined ? "unkernel-cache" : `unkernel-cache-${uid}`);
if (writable(tmp) && (uid === undefined || !existsSync(tmp) || statSync(tmp).uid === uid)) return tmp;
throw new DistroFetchError(`no writable cache directory for distro images (tried ${[home, tmp].filter(Boolean).join(" and ")}); ` +
"set UNKERNEL_CACHE_DIR or pass cacheDir");
}
/** Can `dir` be written, or created (its nearest existing ancestor a writable directory)? */
function writable(dir: string): boolean {
for (let d = dir; ; d = path.dirname(d)) {
try {
if (!statSync(d).isDirectory()) return false;
accessSync(d, constants.W_OK | constants.X_OK);
return true;
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "ENOENT" || path.dirname(d) === d) return false;
}
}
}
/** The package's version (package.json next to the package root). */
function packageVersion(root: string): string {
const v = (JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) as { version?: unknown }).version;
if (typeof v !== "string") throw new DistroFetchError(`no version in ${path.join(root, "package.json")}`);
return v;
}
const sha256File = (file: string) => createHash("sha256").update(readFileSync(file)).digest("hex");
const mib = (n: number) => `${(n / 1048576).toFixed(1)} MiB`;
/** A name next to `file` that no other call, in this process or another, uses. */
const unique = (file: string) => `${file}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
/** Write `file` whole or not at all: under a unique name, then renamed into place. */
function writeAtomic(file: string, data: string): void {
const tmp = unique(file);
try {
writeFileSync(tmp, data);
renameSync(tmp, file);
} finally {
rmSync(tmp, { force: true });
}
}
/** mkdir -p `dir` and check it can be written, failing with a DistroFetchError that says what to do. */
function makeDir(dir: string): void {
try {
mkdirSync(dir, { recursive: true });
accessSync(dir, constants.W_OK | constants.X_OK);
} catch (e) {
throw new DistroFetchError(`cannot write the cache directory ${dir}: ${(e as Error).message}; ` +
"set UNKERNEL_CACHE_DIR or pass cacheDir to use another", { cause: e });
}
}
/** What <image>.verified holds: the image's size and mtime when its SHA-256 was found to be `sha256`. */
interface VerifiedRecord { size: number; mtimeNs: string; sha256: string }
/** Record that the file with stats `st` has SHA-256 `sha256` (best effort: without it the next call hashes again). */
function recordVerified(file: string, st: BigIntStats, sha256: string): void {
const rec: VerifiedRecord = { size: Number(st.size), mtimeNs: String(st.mtimeNs), sha256 };
try { writeAtomic(`${file}.verified`, JSON.stringify(rec)); } catch {}
}
/**
* A cached file that matches the entry: its size, then the record of an
* earlier check (same size and mtime, the entry's SHA-256), else its
* SHA-256, which is then recorded.
*/
function verified(file: string, e: DistroIndexEntry): boolean {
try {
// Stats from before the hash: a file replaced meanwhile fails the record next time.
const st = statSync(file, { bigint: true });
if (st.size !== BigInt(e.size)) return false;
let rec: Partial<VerifiedRecord> | undefined;
try { rec = JSON.parse(readFileSync(`${file}.verified`, "utf8")) as Partial<VerifiedRecord>; } catch {}
if (rec?.size === e.size && rec.mtimeNs === String(st.mtimeNs) && rec.sha256 === e.sha256) return true;
if (sha256File(file) !== e.sha256) return false;
recordVerified(file, st, e.sha256);
return true;
} catch {
return false;
}
}
/** The index as it must look; throws on anything else. */
function checkIndex(j: unknown, where: string): DistroIndex {
const ix = j as DistroIndex;
const ok = ix && Array.isArray(ix.distros) && ix.distros.every((d) =>
d && typeof d.name === "string" && /^[a-z0-9]+$/.test(d.name) && typeof d.file === "string" && /^[a-z0-9]+\.(erofs|ext4)$/.test(d.file) &&
Number.isSafeInteger(d.size) && typeof d.sha256 === "string" && /^[0-9a-f]{64}$/.test(d.sha256));
if (!ok) throw new DistroFetchError(`${where} is not a distros.json index`);
return ix;
}
/** The cached index at `file`, or undefined when it is missing or not an index. */
function cachedIndex(file: string): DistroIndex | undefined {
try {
return checkIndex(JSON.parse(readFileSync(file, "utf8")), file);
} catch {
return undefined;
}
}
/**
* The distro `name` as a local image file (see the top). `root` is the
* package root (the directory with package.json).
*/
export async function fetchDistroFrom(root: string, name: string, opts: FetchDistroOptions = {}): Promise<string> {
if (!/^[a-z0-9]+$/.test(name)) throw new DistroFetchError(`not a distro name: ${JSON.stringify(name)} (a name is [a-z0-9]+)`);
const progress = opts.onProgress ?? (() => {});
if ((opts.local ?? true) && isCheckout(root)) {
const dir = path.join(root, "vendor/build/distro");
const found = [`${name}.erofs`, `${name}.ext4`].map((f) => path.join(dir, f)).find((f) => existsSync(f));
if (!found) throw new DistroFetchError(`no ${path.join(dir, `${name}.erofs`)} in this source checkout: build it with kernel/build.sh distro ${name}`);
progress({ stage: "done", name, path: found, cached: true });
return found;
}
const custom = opts.releaseUrl ?? process.env.UNKERNEL_RELEASE_URL;
let base = custom, tag: string;
if (base) {
tag = `url-${createHash("sha256").update(base.replace(/\/*$/, "/")).digest("hex").slice(0, 12)}`;
} else {
tag = `v${packageVersion(root)}`;
base = `https://github.com/${RELEASE_REPO}/releases/download/${tag}/`;
}
base = base.replace(/\/*$/, "/");
const dir = path.join(opts.cacheDir ? path.resolve(opts.cacheDir) : defaultCacheDir(), tag);
const offlineHelp = `unkernel downloads distro images on first use from ${base} and keeps them in ${dir}; ` +
"connect to the network and try again, or use an image file you have";
// The index: a versioned release's cached copy as it is (the release
// never changes); else from the release, else the copy kept from an
// earlier download.
const indexFile = path.join(dir, "distros.json");
let index = custom ? undefined : cachedIndex(indexFile);
if (index?.distros.some((d) => d.name === name)) progress({ stage: "index", name, url: base, path: indexFile });
else {
progress({ stage: "index", name, url: base });
let text: string | undefined;
try {
const r = await fetch(new URL("distros.json", base), { signal: opts.signal });
if (!r.ok) throw new DistroFetchError(`GET ${new URL("distros.json", base)}: ${r.status} ${r.statusText}`.trim());
text = await r.text();
index = checkIndex(JSON.parse(text), `${new URL("distros.json", base)}`);
} catch (e) {
if (opts.signal?.aborted) throw e;
if (!existsSync(indexFile)) {
const http = e instanceof DistroFetchError;
throw new DistroFetchError(http ? `${(e as Error).message}: no distro images for this release at ${base}`
: `cannot read ${new URL("distros.json", base)}: ${(e as Error).message}; ${offlineHelp}`, { offline: !http, cause: e });
}
text = undefined;
index = checkIndex(JSON.parse(readFileSync(indexFile, "utf8")), indexFile);
}
// Kept for later calls; a cache that cannot be written still serves the images it has.
if (text !== undefined) {
try {
mkdirSync(dir, { recursive: true });
writeAtomic(indexFile, text);
} catch {}
}
}
const entry = index.distros.find((d) => d.name === name);
if (!entry) throw new DistroFetchError(`no distro "${name}" in ${new URL("distros.json", base)} (it has: ${index.distros.map((d) => d.name).join(", ") || "none"})`);
const file = path.join(dir, entry.file), url = new URL(entry.file, base).href;
if (existsSync(file)) {
progress({ stage: "verify", name, file: entry.file, url, path: file });
if (verified(file, entry)) {
progress({ stage: "done", name, file: entry.file, url, path: file, cached: true });
return file;
}
// Left until the download renames over it: another call may have just put a good one there.
}
// Download into a part file, hashing on the way, then check, rename and record the check.
makeDir(dir);
const part = unique(file);
try {
let r: Response;
try {
r = await fetch(url, { signal: opts.signal });
} catch (e) {
if (opts.signal?.aborted) throw e;
throw new DistroFetchError(`cannot download ${url}: ${(e as Error).message}; ${offlineHelp}`, { offline: true, cause: e });
}
if (!r.ok || !r.body) throw new DistroFetchError(`GET ${url}: ${r.status} ${r.statusText}`.trim());
const hash = createHash("sha256"), out = createWriteStream(part);
let loaded = 0;
progress({ stage: "download", name, file: entry.file, url, path: file, loaded, total: entry.size });
try {
for await (const chunk of r.body as unknown as AsyncIterable<Uint8Array>) {
hash.update(chunk);
loaded += chunk.length;
if (!out.write(chunk)) await new Promise<void>((res) => out.once("drain", () => res()));
progress({ stage: "download", name, file: entry.file, url, path: file, loaded, total: entry.size });
}
} catch (e) {
if (opts.signal?.aborted) throw e;
throw new DistroFetchError(`download of ${url} broke off after ${mib(loaded)}: ${(e as Error).message}; ${offlineHelp}`, { offline: true, cause: e });
} finally {
await new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())));
}
const sum = hash.digest("hex");
if (loaded !== entry.size || sum !== entry.sha256)
throw new DistroFetchError(`${url}: got ${loaded} bytes with SHA-256 ${sum}, distros.json says ${entry.size} bytes, ${entry.sha256}`);
// The part file's stats (a rename keeps them), not the renamed file's: another call may replace that first.
const st = statSync(part, { bigint: true });
renameSync(part, file);
recordVerified(file, st, sum);
} finally {
rmSync(part, { force: true });
}
progress({ stage: "done", name, file: entry.file, url, path: file, cached: false });
return file;
}
/** fetchDistroFrom() for the package at the `root` URL (an entry's `new URL("..", String(import.meta.url))`). */
export function distroFetcher(root: URL): (name: string, opts?: FetchDistroOptions) => Promise<string> {
const dir = fileURLToPath(root);
return (name, opts) => fetchDistroFrom(dir, name, opts);
}