archive.ts

1.9 KB · raw

1import type { Hono } from "hono";2import { headId, saveByPrefix } from "../mirror/queries.ts";3import { notFound, openPublicRepo, type PageContext } from "../pages/layout.ts";4import { countInstall } from "../releases/releases.ts";5import { cachedTarball } from "./cache.ts";67// Long-lived but never `immutable` (§18): a strip can change what a save's tarball holds.8const TARBALL_CACHE = "public, max-age=31536000";910export function registerTarballRoutes(app: Hono, ctx: PageContext, tarballDir: string): void {11	app.get("/:repo/archive/HEAD.tar.gz", (c) => {12		const repo = openPublicRepo(ctx, c.req.param("repo"));13		const head = repo && headId(repo.mirror);14		if (!repo || !head) return notFound(c, ctx);15		const path = `/${repo.settings.name}/archive/${head}.tar.gz`;16		// Nix pins the immutable link in its lock file, so it must be absolute.17		c.header("Link", `<https://${ctx.domain}${path}>; rel="immutable"`);18		c.header("Cache-Control", "no-cache");19		return c.redirect(path, 302);20	});2122	app.get("/:repo/archive/:id{[0-9a-f]+\\.tar\\.gz}", (c) => {23		const repo = openPublicRepo(ctx, c.req.param("repo"));24		const id = c.req.param("id").replace(/\.tar\.gz$/, "");25		const save = repo && saveByPrefix(repo.mirror, id);26		if (!repo || !save) return notFound(c, ctx);27		const name = repo.settings.name;28		if (save.id !== id) {29			c.header("Cache-Control", "public, max-age=60");30			return c.redirect(`/${name}/archive/${save.id}.tar.gz`, 302);31		}32		const bytes = cachedTarball(tarballDir, repo.mirror, name, save.id);33		// §22.2: a Nix fetch is an install. Only the tarball itself counts, not the redirects to it.34		if (c.req.header("User-Agent")?.includes("nix/")) countInstall(ctx.kepr, name);35		c.header("Content-Type", "application/gzip");36		c.header("Content-Disposition", `attachment; filename="${name}-${save.id.slice(0, 8)}.tar.gz"`);37		c.header("Cache-Control", TARBALL_CACHE);38		return c.body(bytes);39	});40}