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}/`;89101112131415export 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 26 27 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}454647export async function dropTarballs(bucket: Bucket, repo: string): Promise<void> {48 for (const key of await bucket.list(tarballsOf(repo))) await bucket.remove(key);49}