cache.ts

3.3 KB · raw

1import type { Database } from "bun:sqlite";2import { type Bucket, BucketWriteError, KEPR_PREFIX } from "../bucket/reader.ts";3import {4	filesAt,5	headId,6	objectBytes,7	releaseRecords,8	tarballGeneration,9} from "../mirror/queries.ts";10import { knownSave } from "../mirror/store.ts";11import { buildTarball } from "./tar.ts";1213const tarballsOf = (repo: string) => `${KEPR_PREFIX}tarballs/${repo}/`;1415/** A tarball the bucket already holds, or one built here for this request. */16export type Tarball = { url: string } | { bytes: Uint8Array };1718/**19 * A save's tarball, kept in the bucket under Kepr's own folder (June, 2026-09-30) as20 * `.kepr/tarballs/<repo>/<generation>/<id>.tar.gz` once first requested (`tarballGeneration`).21 * Only a save the repo's HEAD names or a release names is kept: a crawler walking the history22 * asks for every save, and storing each one would add a copy of the repo per save. Any other23 * save's tarball is built and served without being stored. If the bucket refuses the write24 * nothing is kept, and each request builds it again. Null when the save is gone from the mirror,25 * as it is for a moment while a rebuild runs.26 */27export async function cachedTarball(28	bucket: Bucket,29	db: Database,30	repo: string,31	saveId: string,32	filename: string,33): Promise<Tarball | null> {34	for (;;) {35		const generation = tarballGeneration(db);36		const key = `${tarballsOf(repo)}${generation}/${saveId}.tar.gz`;37		const stored = await bucket.tag(key);38		// A strip, a hidden-path change or a rebuild may land during any await, and the sync's thread39		// can land one between any two statements: the generation and the files are read in one40		// snapshot, so what is built matches the key it files under, and bytes are served only for41		// the generation still current.42		const read = db.transaction(() => {43			if (tarballGeneration(db) !== generation) return "moved";44			if (stored !== null) return "stored";45			if (!knownSave(db, saveId)) return "unknown";46			// A migrated save's six-character ID can be the prefix of the full one here.47			const released = releaseRecords(db).some(48				(it) => it.save !== "" && saveId.startsWith(it.save),49			);50			const keep = headId(db) === saveId || released;51			const files = filesAt(db, saveId).map((file) => {52				const bytes = objectBytes(db, file.hash);53				if (!bytes) throw new Error(`${repo}: object ${file.hash} is missing from the mirror`);54				return { path: file.path, bytes, executable: file.executable };55			});56			return { files, keep };57		})();58		if (read === "moved") continue;59		if (read === "unknown") return null;60		// The bucket serves what it already holds, as a release file does: no download and copy here.61		if (read === "stored") return { url: bucket.downloadUrl(key, filename, "application/gzip") };62		const tarball = buildTarball(`${repo}-${saveId.slice(0, 8)}`, read.files);63		if (read.keep) {64			try {65				await bucket.put(key, tarball, "application/gzip");66			} catch (error) {67				if (!(error instanceof BucketWriteError)) throw error;68			}69		}70		if (tarballGeneration(db) === generation) return { bytes: tarball };71	}72}7374/** Deletes a repo's kept tarballs to free space; stale ones are never looked up anyway. */75export async function dropTarballs(bucket: Bucket, repo: string): Promise<void> {76	for (const key of await bucket.list(tarballsOf(repo))) await bucket.remove(key);77}