reader.ts

14.1 KB · raw

1import { readdir, unlink } from "node:fs/promises";2import { join, relative } from "node:path";3import { pathToFileURL } from "node:url";4import type { BucketSource } from "../server/config.ts";56/**7 * A Koh 3 remote as Kepr uses it (§9.1): read-only on Koh's data, which needs two of its five8 * operations, plus a short-lived download URL so Kepr never streams release files itself (§22.2).9 * Kepr's own files (uploads) live under `KEPR_PREFIX` (June, 2026-09-29); no Koh repo can have10 * that name, since Kepr and Koh both need a `head` for one. Beyond it Kepr touches only builds,11 * which Koh has no way to delete (June, 2026-09-30): it deletes a version's files, rewrites its12 * record without a deleted one, and moves `releases/latest`.13 */14export type Bucket = {15	get(key: string): Promise<Uint8Array | null>;16	/** The tag naming the version of `key` stored now, as `If-Match` wants it; null when absent. */17	tag(key: string): Promise<string | null>;18	list(prefix: string): Promise<string[]>;19	/** The top-level folders' names: one listing, however many keys they hold. */20	folders(): Promise<string[]>;21	/** A key's size in bytes, asked without reading it. */22	size(key: string): Promise<number>;23	/** Every key under `prefix` with its size in bytes, for the console's storage view. */24	sizes(prefix: string): Promise<Map<string, number>>;25	/** A URL that serves `key` for five minutes, as an attachment with this filename and content type. */26	downloadUrl(key: string, filename: string, type: string): string;27	/** A five-minute URL that shows `key` in the page, or null when Kepr must serve the bytes itself. */28	viewUrl(key: string, type: string): string | null;29	/**30	 * Writes one of Kepr's own files, a repo's `releases/latest`, or a version's `release.json` when31	 * one of its files is deleted; any other key is refused.32	 */33	put(key: string, bytes: Uint8Array, type: string): Promise<void>;34	/**35	 * Writes one of the keys `put` writes only while it still holds the version `tag` names, since a36	 * Koh publish can land at any moment (2026-11-16). False means another writer got there first and37	 * its value stands.38	 */39	putIfTag(key: string, bytes: Uint8Array, type: string, tag: string): Promise<boolean>;40	/** Deletes one of Kepr's own files, a release's file or `releases/latest`; nothing else. */41	remove(key: string): Promise<void>;42	/** Copies a key of one repo to another repo: a rename (June, 2026-10-01), and nothing else. */43	copy(from: string, to: string): Promise<void>;44	/** Deletes a key of a repo that a rename has copied to its new name. */45	removeRenamed(key: string): Promise<void>;46	/**47	 * Every key that belongs to one repo (§24): its own, and Kepr's files for it under `.kepr/`.48	 * What deleting a repo has to remove, and nothing of any other repo's.49	 */50	repoKeys(repo: string): Promise<string[]>;51	/** Deletes one of those keys; anything not of that repo is refused. */52	removeRepoKey(repo: string, key: string): Promise<void>;53};5455export const KEPR_PREFIX = ".kepr/";5657/** `each` over `items`, `atOnce` of them in flight at a time; the results in order. */58export async function inTurn<T, R>(59	items: T[],60	atOnce: number,61	each: (item: T) => Promise<R>,62): Promise<R[]> {63	const results: R[] = [];64	for (let i = 0; i < items.length; i += atOnce) {65		results.push(...(await Promise.all(items.slice(i, i + atOnce).map(each))));66	}67	return results;68}6970/** A write Kepr can't make: outside its folder, or refused by the bucket. */71export class BucketWriteError extends Error {}7273const DOWNLOAD_SECONDS = 5 * 60;7475const RELEASE_WRITE = /^[^/]+\/releases\/(latest|[^/]+\/release\.json)$/;76const RELEASE_FILE = /^[^/]+\/releases\/(latest|[^/]+\/.+)$/;7778// A key inside a repo, as a rename moves them: never Kepr's own folder, never `..` or empty parts.79function requireRepoKey(key: string): void {80	if (81		key.startsWith(KEPR_PREFIX) ||82		!key.includes("/") ||83		key.split("/").some((p) => p === ".." || p === "")84	) {85		throw new BucketWriteError(`a rename moves only a repo's keys, not "${key}"`);86	}87}8889function requireWritable(key: string, releaseKey: RegExp): void {90	const allowed = key.startsWith(KEPR_PREFIX) || releaseKey.test(key);91	if (!allowed || key.split("/").some((part) => part === ".." || part === "")) {92		throw new BucketWriteError(`Kepr writes only under ${KEPR_PREFIX} and builds, not "${key}"`);93	}94}9596// Kepr's own files for one repo: uploaded media, kept tarballs, the hidden list, the rename record.97const keprRepoFolders = (repo: string) => [98	`${KEPR_PREFIX}media/${repo}/`,99	`${KEPR_PREFIX}tarballs/${repo}/`,100];101const keprRepoFiles = (repo: string) => [102	`${KEPR_PREFIX}hidden/${repo}`,103	`${KEPR_PREFIX}renamed/${repo}`,104];105106/**107 * Whether `key` belongs to `repo` alone: inside it, or one of the files Kepr keeps for it. An empty108 * name is nothing, and no key may escape through `..` or an empty part.109 */110export function isRepoKey(repo: string, key: string): boolean {111	if (repo === "" || key.split("/").some((part) => part === ".." || part === "")) return false;112	if (key.startsWith(`${repo}/`)) return true;113	if (keprRepoFolders(repo).some((folder) => key.startsWith(folder))) return true;114	return keprRepoFiles(repo).includes(key);115}116117/** Every key of one repo: what a bucket lists under it, plus the files Kepr keeps for it. */118async function listRepoKeys(119	list: (prefix: string) => Promise<string[]>,120	repo: string,121): Promise<string[]> {122	if (repo === "") return [];123	const keys = await list(`${repo}/`);124	for (const folder of keprRepoFolders(repo)) keys.push(...(await list(folder)));125	return [...keys, ...keprRepoFiles(repo)].filter((key) => isRepoKey(repo, key));126}127128export function openBucket(source: BucketSource): Bucket {129	return source.kind === "s3" ? s3Reader(source) : folderReader(source.path);130}131132type S3Source = Extract<BucketSource, { kind: "s3" }>;133134/**135 * The console's connection test (§24), made before settings are saved: the key must list the136 * bucket and write Kepr's own test file. Returns what failed, or null.137 */138export async function checkS3Access(source: S3Source): Promise<string | null> {139	const reason = (error: unknown) => (error instanceof Error ? error.message : String(error));140	try {141		// One key is proof enough; listing the whole bucket could take minutes.142		await s3Client(source).list({ maxKeys: 1 });143	} catch (error) {144		return `The key cannot list the bucket: ${reason(error)}`;145	}146	try {147		const stamp = new TextEncoder().encode(new Date().toISOString());148		await s3Reader(source).put(`${KEPR_PREFIX}connection-test`, stamp, "text/plain");149	} catch (error) {150		return `The key cannot write ${KEPR_PREFIX}connection-test: ${reason(error)}`;151	}152	return null;153}154155function s3Client(source: S3Source): Bun.S3Client {156	return new Bun.S3Client({157		endpoint: source.endpoint,158		bucket: source.name,159		region: source.region,160		accessKeyId: source.accessKeyId,161		secretAccessKey: source.secretAccessKey,162	});163}164165function s3Reader(source: S3Source): Bucket {166	const client = s3Client(source);167	// A refused write is a BucketWriteError, which the console shows and a tarball cache skips.168	const write = async (key: string, run: (file: Bun.S3File) => Promise<unknown>) => {169		try {170			await run(client.file(key));171		} catch (error) {172			throw new BucketWriteError(`The bucket refused ${key}: ${error}`);173		}174	};175	return {176		async get(key) {177			// Through a presigned URL: Bun 1.3.14's S3File reads keep about one copy of every body178			// read, which a first sync of a big repo turns into hundreds of MB; fetch frees its own.179			const response = await fetch(client.presign(key, { method: "GET", expiresIn: 60 }));180			if (response.status === 404) return null;181			if (!response.ok) throw new Error(`S3 GET ${key} failed: HTTP ${response.status}`);182			return new Uint8Array(await response.arrayBuffer());183		},184		async tag(key) {185			// HEAD, not stat: a missing key is a 404 to check for, not an error Bun's reader types.186			const response = await fetch(client.presign(key, { method: "HEAD", expiresIn: 60 }));187			if (response.status === 404) return null;188			if (!response.ok) throw new Error(`S3 HEAD ${key} failed: HTTP ${response.status}`);189			const tag = response.headers.get("etag");190			if (tag === null) throw new Error(`S3 HEAD ${key} named no version`);191			return tag;192		},193		async list(prefix) {194			const keys: string[] = [];195			let continuationToken: string | undefined;196			do {197				const page = await client.list({ prefix, continuationToken });198				for (const object of page.contents ?? []) keys.push(object.key);199				continuationToken = page.isTruncated ? page.nextContinuationToken : undefined;200			} while (continuationToken);201			return keys;202		},203		size: (key) => client.size(key),204		async folders() {205			const names: string[] = [];206			let continuationToken: string | undefined;207			do {208				const page = await client.list({ delimiter: "/", continuationToken });209				for (const { prefix } of page.commonPrefixes ?? []) names.push(prefix.slice(0, -1));210				continuationToken = page.isTruncated ? page.nextContinuationToken : undefined;211			} while (continuationToken);212			return names;213		},214		async sizes(prefix) {215			const sizes = new Map<string, number>();216			let continuationToken: string | undefined;217			do {218				const page = await client.list({ prefix, continuationToken });219				for (const object of page.contents ?? []) sizes.set(object.key, object.size ?? 0);220				continuationToken = page.isTruncated ? page.nextContinuationToken : undefined;221			} while (continuationToken);222			return sizes;223		},224		downloadUrl(key, filename, type) {225			// Bun signs these as response-content-disposition and response-content-type (verified, v1.3.14).226			return client.presign(key, {227				method: "GET",228				expiresIn: DOWNLOAD_SECONDS,229				contentDisposition: `attachment; filename="${filename}"`,230				type,231			});232		},233		viewUrl(key, type) {234			return client.presign(key, { method: "GET", expiresIn: DOWNLOAD_SECONDS, type });235		},236		async put(key, bytes, type) {237			requireWritable(key, RELEASE_WRITE);238			await write(key, (file) => file.write(bytes, { type }));239		},240		async putIfTag(key, bytes, type, tag) {241			requireWritable(key, RELEASE_WRITE);242			// A presigned PUT signs the host alone, so `If-Match` is the bucket's own condition: 412 is243			// another writer's value standing, and an S3 that can't do conditional writes refuses loudly.244			const url = client.presign(key, { method: "PUT", expiresIn: 60 });245			const response = await fetch(url, {246				method: "PUT",247				headers: { "If-Match": tag, "Content-Type": type },248				body: bytes,249			}).catch((error: unknown) => {250				throw new BucketWriteError(`The bucket refused ${key}: ${error}`);251			});252			if (response.status === 412) return false;253			if (!response.ok)254				throw new BucketWriteError(`The bucket refused ${key}: HTTP ${response.status}`);255			return true;256		},257		async remove(key) {258			requireWritable(key, RELEASE_FILE);259			await write(key, (file) => file.delete());260		},261		async copy(from, to) {262			requireRepoKey(from);263			requireRepoKey(to);264			const bytes = await this.get(from);265			if (bytes === null) throw new Error(`${from} is missing`);266			await write(to, (file) => file.write(bytes));267		},268		async removeRenamed(key) {269			requireRepoKey(key);270			await write(key, (file) => file.delete());271		},272		async repoKeys(repo) {273			return listRepoKeys((prefix) => this.list(prefix), repo);274		},275		async removeRepoKey(repo, key) {276			if (!isRepoKey(repo, key)) {277				throw new BucketWriteError(`Kepr deletes only ${repo}'s own keys, not "${key}"`);278			}279			await write(key, (file) => file.delete());280		},281	};282}283284function folderReader(root: string): Bucket {285	const list = async (prefix: string) => {286		const entries = await readdir(root, { recursive: true, withFileTypes: true });287		return entries288			.filter((entry) => entry.isFile())289			.map((entry) => relative(root, join(entry.parentPath, entry.name)))290			.filter((key) => key.startsWith(prefix))291			.sort();292	};293	return {294		async get(key) {295			if (key.split("/").includes("..")) throw new Error(`bucket key escapes the folder: ${key}`);296			const file = Bun.file(join(root, key));297			return (await file.exists()) ? await file.bytes() : null;298		},299		async tag(key) {300			const bytes = await this.get(key);301			// A folder has no ETag: the hash of the content names the version it holds.302			return bytes === null ? null : String(Bun.hash(bytes));303		},304		list,305		async size(key) {306			if (key.split("/").includes("..")) throw new Error(`bucket key escapes the folder: ${key}`);307			return Bun.file(join(root, key)).size;308		},309		async folders() {310			const entries = await readdir(root, { withFileTypes: true });311			return entries312				.filter((entry) => entry.isDirectory())313				.map((entry) => entry.name)314				.sort();315		},316		async sizes(prefix) {317			return new Map((await list(prefix)).map((key) => [key, Bun.file(join(root, key)).size]));318		},319		// Development and tests only: a file:// URL can't carry a filename, a type or an expiry.320		downloadUrl(key) {321			if (key.split("/").includes("..")) throw new Error(`bucket key escapes the folder: ${key}`);322			return pathToFileURL(join(root, key)).href;323		},324		viewUrl: () => null,325		async put(key, bytes) {326			requireWritable(key, RELEASE_WRITE);327			await Bun.write(join(root, key), bytes);328		},329		async putIfTag(key, bytes, _type, tag) {330			requireWritable(key, RELEASE_WRITE);331			// ponytail: a folder has no atomic compare-and-write, so a local Koh can still land in the332			// gap; the S3 reader is the one the race is about, and tests here are single-writer.333			if ((await this.tag(key)) !== tag) return false;334			await Bun.write(join(root, key), bytes);335			return true;336		},337		async remove(key) {338			requireWritable(key, RELEASE_FILE);339			await unlink(join(root, key)).catch((error: NodeJS.ErrnoException) => {340				if (error.code !== "ENOENT") throw error;341			});342		},343		async copy(from, to) {344			requireRepoKey(from);345			requireRepoKey(to);346			await Bun.write(join(root, to), Bun.file(join(root, from)));347		},348		async removeRenamed(key) {349			requireRepoKey(key);350			await unlink(join(root, key));351		},352		async repoKeys(repo) {353			return listRepoKeys(list, repo);354		},355		async removeRepoKey(repo, key) {356			if (!isRepoKey(repo, key)) {357				throw new BucketWriteError(`Kepr deletes only ${repo}'s own keys, not "${key}"`);358			}359			await unlink(join(root, key)).catch((error: NodeJS.ErrnoException) => {360				if (error.code !== "ENOENT") throw error;361			});362		},363	};364}