cache.ts

2.1 KB · raw

1import type { Database } from "bun:sqlite";2import { type Bucket, BucketWriteError, KEPR_PREFIX } from "../bucket/reader.ts";3import { filesAt, objectBytes, tarballGeneration } from "../mirror/queries.ts";4import { knownSave } from "../mirror/store.ts";5import { buildTarball } from "./tar.ts";67const tarballsOf = (repo: string) => `${KEPR_PREFIX}tarballs/${repo}/`;89/**10 * A save's tarball, kept in the bucket under Kepr's own folder (June, 2026-09-30) as11 * `.kepr/tarballs/<repo>/<generation>/<id>.tar.gz` once first requested (`tarballGeneration`).12 * Without a write key nothing is kept, and each request builds it again. Null when the save is13 * gone from the mirror, as it is for a moment while a rebuild runs.14 */15export async function cachedTarball(16	bucket: Bucket,17	db: Database,18	repo: string,19	saveId: string,20): Promise<Uint8Array | null> {21	for (;;) {22		const generation = tarballGeneration(db);23		const key = `${tarballsOf(repo)}${generation}/${saveId}.tar.gz`;24		const stored = await bucket.get(key);25		// A strip, a hidden-path change or a rebuild may have landed during any await: bytes are26		// served only for the generation still current, and the build below runs in one synchronous27		// go, so what it reads matches the key it files under.28		if (tarballGeneration(db) !== generation) continue;29		if (stored) return stored;30		if (!knownSave(db, saveId)) return null;31		const files = filesAt(db, saveId).map((file) => {32			const bytes = objectBytes(db, file.hash);33			if (!bytes) throw new Error(`${repo}: object ${file.hash} is missing from the mirror`);34			return { path: file.path, bytes, executable: file.executable };35		});36		const tarball = buildTarball(`${repo}-${saveId.slice(0, 8)}`, files);37		try {38			await bucket.put(key, tarball, "application/gzip");39		} catch (error) {40			if (!(error instanceof BucketWriteError)) throw error;41		}42		if (tarballGeneration(db) === generation) return tarball;43	}44}4546/** Deletes a repo's kept tarballs to free space; stale ones are never looked up anyway. */47export async function dropTarballs(bucket: Bucket, repo: string): Promise<void> {48	for (const key of await bucket.list(tarballsOf(repo))) await bucket.remove(key);49}