reader.ts

14.2 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			// Signed for HEAD, so a plain fetch's GET would be refused with 403.187			const response = await fetch(client.presign(key, { method: "HEAD", expiresIn: 60 }), {188				method: "HEAD",189			});190			if (response.status === 404) return null;191			if (!response.ok) throw new Error(`S3 HEAD ${key} failed: HTTP ${response.status}`);192			const tag = response.headers.get("etag");193			if (tag === null) throw new Error(`S3 HEAD ${key} named no version`);194			return tag;195		},196		async list(prefix) {197			const keys: string[] = [];198			let continuationToken: string | undefined;199			do {200				const page = await client.list({ prefix, continuationToken });201				for (const object of page.contents ?? []) keys.push(object.key);202				continuationToken = page.isTruncated ? page.nextContinuationToken : undefined;203			} while (continuationToken);204			return keys;205		},206		size: (key) => client.size(key),207		async folders() {208			const names: string[] = [];209			let continuationToken: string | undefined;210			do {211				const page = await client.list({ delimiter: "/", continuationToken });212				for (const { prefix } of page.commonPrefixes ?? []) names.push(prefix.slice(0, -1));213				continuationToken = page.isTruncated ? page.nextContinuationToken : undefined;214			} while (continuationToken);215			return names;216		},217		async sizes(prefix) {218			const sizes = new Map<string, number>();219			let continuationToken: string | undefined;220			do {221				const page = await client.list({ prefix, continuationToken });222				for (const object of page.contents ?? []) sizes.set(object.key, object.size ?? 0);223				continuationToken = page.isTruncated ? page.nextContinuationToken : undefined;224			} while (continuationToken);225			return sizes;226		},227		downloadUrl(key, filename, type) {228			// Bun signs these as response-content-disposition and response-content-type (verified, v1.3.14).229			return client.presign(key, {230				method: "GET",231				expiresIn: DOWNLOAD_SECONDS,232				contentDisposition: `attachment; filename="${filename}"`,233				type,234			});235		},236		viewUrl(key, type) {237			return client.presign(key, { method: "GET", expiresIn: DOWNLOAD_SECONDS, type });238		},239		async put(key, bytes, type) {240			requireWritable(key, RELEASE_WRITE);241			await write(key, (file) => file.write(bytes, { type }));242		},243		async putIfTag(key, bytes, type, tag) {244			requireWritable(key, RELEASE_WRITE);245			// A presigned PUT signs the host alone, so `If-Match` is the bucket's own condition: 412 is246			// another writer's value standing, and an S3 that can't do conditional writes refuses loudly.247			const url = client.presign(key, { method: "PUT", expiresIn: 60 });248			const response = await fetch(url, {249				method: "PUT",250				headers: { "If-Match": tag, "Content-Type": type },251				body: bytes,252			}).catch((error: unknown) => {253				throw new BucketWriteError(`The bucket refused ${key}: ${error}`);254			});255			if (response.status === 412) return false;256			if (!response.ok)257				throw new BucketWriteError(`The bucket refused ${key}: HTTP ${response.status}`);258			return true;259		},260		async remove(key) {261			requireWritable(key, RELEASE_FILE);262			await write(key, (file) => file.delete());263		},264		async copy(from, to) {265			requireRepoKey(from);266			requireRepoKey(to);267			const bytes = await this.get(from);268			if (bytes === null) throw new Error(`${from} is missing`);269			await write(to, (file) => file.write(bytes));270		},271		async removeRenamed(key) {272			requireRepoKey(key);273			await write(key, (file) => file.delete());274		},275		async repoKeys(repo) {276			return listRepoKeys((prefix) => this.list(prefix), repo);277		},278		async removeRepoKey(repo, key) {279			if (!isRepoKey(repo, key)) {280				throw new BucketWriteError(`Kepr deletes only ${repo}'s own keys, not "${key}"`);281			}282			await write(key, (file) => file.delete());283		},284	};285}286287function folderReader(root: string): Bucket {288	const list = async (prefix: string) => {289		const entries = await readdir(root, { recursive: true, withFileTypes: true });290		return entries291			.filter((entry) => entry.isFile())292			.map((entry) => relative(root, join(entry.parentPath, entry.name)))293			.filter((key) => key.startsWith(prefix))294			.sort();295	};296	return {297		async get(key) {298			if (key.split("/").includes("..")) throw new Error(`bucket key escapes the folder: ${key}`);299			const file = Bun.file(join(root, key));300			return (await file.exists()) ? await file.bytes() : null;301		},302		async tag(key) {303			const bytes = await this.get(key);304			// A folder has no ETag: the hash of the content names the version it holds.305			return bytes === null ? null : String(Bun.hash(bytes));306		},307		list,308		async size(key) {309			if (key.split("/").includes("..")) throw new Error(`bucket key escapes the folder: ${key}`);310			return Bun.file(join(root, key)).size;311		},312		async folders() {313			const entries = await readdir(root, { withFileTypes: true });314			return entries315				.filter((entry) => entry.isDirectory())316				.map((entry) => entry.name)317				.sort();318		},319		async sizes(prefix) {320			return new Map((await list(prefix)).map((key) => [key, Bun.file(join(root, key)).size]));321		},322		// Development and tests only: a file:// URL can't carry a filename, a type or an expiry.323		downloadUrl(key) {324			if (key.split("/").includes("..")) throw new Error(`bucket key escapes the folder: ${key}`);325			return pathToFileURL(join(root, key)).href;326		},327		viewUrl: () => null,328		async put(key, bytes) {329			requireWritable(key, RELEASE_WRITE);330			await Bun.write(join(root, key), bytes);331		},332		async putIfTag(key, bytes, _type, tag) {333			requireWritable(key, RELEASE_WRITE);334			// ponytail: a folder has no atomic compare-and-write, so a local Koh can still land in the335			// gap; the S3 reader is the one the race is about, and tests here are single-writer.336			if ((await this.tag(key)) !== tag) return false;337			await Bun.write(join(root, key), bytes);338			return true;339		},340		async remove(key) {341			requireWritable(key, RELEASE_FILE);342			await unlink(join(root, key)).catch((error: NodeJS.ErrnoException) => {343				if (error.code !== "ENOENT") throw error;344			});345		},346		async copy(from, to) {347			requireRepoKey(from);348			requireRepoKey(to);349			await Bun.write(join(root, to), Bun.file(join(root, from)));350		},351		async removeRenamed(key) {352			requireRepoKey(key);353			await unlink(join(root, key));354		},355		async repoKeys(repo) {356			return listRepoKeys(list, repo);357		},358		async removeRepoKey(repo, key) {359			if (!isRepoKey(repo, key)) {360				throw new BucketWriteError(`Kepr deletes only ${repo}'s own keys, not "${key}"`);361			}362			await unlink(join(root, key)).catch((error: NodeJS.ErrnoException) => {363				if (error.code !== "ENOENT") throw error;364			});365		},366	};367}