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}/`;141516export type Tarball = { url: string } | { bytes: Uint8Array };1718192021222324252627export 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 39 40 41 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 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 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}737475export async function dropTarballs(bucket: Bucket, repo: string): Promise<void> {76 for (const key of await bucket.list(tarballsOf(repo))) await bucket.remove(key);77}