releases.ts

13.0 KB · raw

1import type { Database } from "bun:sqlite";2import type { Context } from "hono";3import type { Bucket } from "../bucket/reader.ts";4import {5	checkRelease,6	listReleaseVersions,7	type ReleaseFile,8	readReleasesLatest,9} from "../bucket/repo.ts";10import { releaseRecords } from "../mirror/queries.ts";11import { forgetRelease, replaceRelease } from "../mirror/store.ts";12import { clientIp } from "../server/client.ts";1314/** A release as the public sees it: its notes are the operator's override when one is set (§24). */15export type Release = {16	version: string;17	save: string;18	publishedAt: number;19	notes: string;20	files: ReleaseFile[];21};2223type ReleaseSetting = { version: string; hidden: number; notes: string | null };2425/**26 * A repo's releases without the hidden ones, newest first by numeric dot-separated comparison (the27 * rule `koh update` uses, §12). Files are ordered by platform name, as Kepr 2 listed them.28 */29export function visibleReleases(kepr: Database, mirror: Database, repo: string): Release[] {30	const settings = new Map(31		kepr32			.query<ReleaseSetting, [string]>(33				"SELECT version, hidden, notes FROM release_settings WHERE repo = ?",34			)35			.all(repo)36			.map((row) => [row.version, row]),37	);38	return releaseRecords(mirror)39		.filter((record) => settings.get(record.version)?.hidden !== 1)40		.map((record) => ({41			version: record.version,42			save: record.save,43			publishedAt: record.published_at,44			notes: settings.get(record.version)?.notes ?? record.notes,45			files: record.files.toSorted((a, b) => (a.platform < b.platform ? -1 : 1)),46		}))47		.sort((a, b) => compareVersions(b.version, a.version));48}4950export function compareVersions(a: string, b: string): number {51	const left = a.split(".").map(digits);52	const right = b.split(".").map(digits);53	for (let i = 0; i < Math.max(left.length, right.length); i++) {54		const [x, y] = [left[i] ?? "0", right[i] ?? "0"];55		// Compared as digit strings, never as floats, so long components keep their precision.56		if (x.length !== y.length) return x.length - y.length;57		if (x !== y) return x < y ? -1 : 1;58	}59	// Numerically equal (`1.0` and `1.0.0`): compare the text, so the order is still total.60	return a < b ? -1 : a > b ? 1 : 0;61}6263// A component's leading digits without leading zeros ("0" when it has none), as parseInt reads it.64function digits(part: string): string {65	return (/^\d+/.exec(part)?.[0] ?? "0").replace(/^0+(?=\d)/, "");66}6768/** §22.2's content types for a release file. */69export function releaseContentType(name: string): string {70	const lower = name.toLowerCase();71	if (lower.endsWith(".apk")) return "application/vnd.android.package-archive";72	if (lower.endsWith(".zip")) return "application/zip";73	return "application/octet-stream";74}7576const DAYS_KEPT = 400;77const DAY_MS = 24 * 60 * 60 * 1000;78const HOUR_MS = 60 * 60 * 1000;7980/** A UTC day as `download_days` keys it. */81export const utcDay = (ms: number): string => new Date(ms).toISOString().slice(0, 10);8283/**84 * User agents that fetch a release link to describe it, never to install it (2026-11-16): the link85 * previews in Slack, Discord, Telegram, WhatsApp, iMessage/Facebook and Twitter, and the search86 * crawlers. A bare `curl` is not here: `install.sh` downloads with it, and that is a person.87 */88const PREVIEW_AGENT =89	/bot|crawler|spider|scraper|slack|discord|telegram|whatsapp|facebookexternalhit|imessage|preview/i;9091// When each client last counted for one file, by `<client>|<repo>|<version>|<platform>`. In memory92// on purpose: a restart at worst counts an hour's reloads again, and no backup carries it.93const lastCounted = new Map<string, number>();9495/** Whether this client's ask for a file counts now: one per client per file per hour. */96function firstAsk(key: string, now: number): boolean {97	const at = lastCounted.get(key);98	// A timestamp ahead of now means the clock stepped back, and it blocks nothing: a fake clock99	// in a test must not hold a count off for as long as it stays behind the entry.100	if (at !== undefined && at <= now && at > now - HOUR_MS) return false;101	lastCounted.set(key, now);102	// Bounded: past a few thousand clients an hour, the stale entries of other files are swept.103	if (lastCounted.size > 4096) {104		for (const [other, when] of lastCounted) {105			if (when <= now - HOUR_MS) lastCounted.delete(other);106		}107	}108	return true;109}110111/**112 * Counts one download (§22.2), unless the request isn't a person asking for the file: a HEAD113 * fetches nothing, a preview fetch only describes the link (2026-11-16), and the same client114 * asking again within the hour is a reload. What is served never changes, only the count.115 */116export function countDownload(117	c: Context,118	kepr: Database,119	repo: string,120	version: string,121	platform: string,122): void {123	const now = Date.now();124	if (c.req.method === "HEAD" || PREVIEW_AGENT.test(c.req.header("User-Agent") ?? "")) return;125	const client = clientIp(c);126	// An address no runtime gave (a bare test request) can't tell clients apart, so it counts127	// every time rather than collapsing every client into one.128	if (client && !firstAsk(`${client}|${repo}|${version}|${platform}`, now)) return;129	kepr.transaction(() => {130		kepr131			.query(132				`INSERT INTO downloads (repo, version, platform, count) VALUES (?, ?, ?, 1)133				ON CONFLICT DO UPDATE SET count = count + 1`,134			)135			.run(repo, version, platform);136		kepr137			.query(138				`INSERT INTO download_days (repo, day, count) VALUES (?, ?, 1)139				ON CONFLICT DO UPDATE SET count = count + 1`,140			)141			.run(repo, utcDay(now));142		kepr.query("DELETE FROM download_days WHERE day < ?").run(utcDay(now - DAYS_KEPT * DAY_MS));143	})();144}145146/** Downloads per UTC day from `since` on, for one repo or all of them (§24). */147export function downloadsByDay(kepr: Database, since: string, repo: string): Map<string, number> {148	const rows = kepr149		.query<{ day: string; n: number }, [string, string, string]>(150			`SELECT day, SUM(count) AS n151			FROM download_days152			WHERE day >= ? AND (? = '' OR repo = ?)153			GROUP BY day`,154		)155		.all(since, repo, repo);156	return new Map(rows.map((row) => [row.day, row.n]));157}158159/** Each repo's downloads ever and since a day, most downloaded first. */160export function repoDownloads(kepr: Database, since: string) {161	return kepr162		.query<{ repo: string; total: number; recent: number }, [string]>(163			`SELECT d.repo,164				SUM(d.count) AS total,165				COALESCE((SELECT SUM(count) FROM download_days WHERE repo = d.repo AND day >= ?), 0)166					AS recent167			FROM downloads d168			GROUP BY d.repo169			ORDER BY total DESC, d.repo`,170		)171		.all(since);172}173174/** The most downloaded files across every repo. */175export function topFiles(kepr: Database, limit: number) {176	return kepr177		.query<{ repo: string; version: string; platform: string; count: number }, [number]>(178			`SELECT repo, version, platform, count179			FROM downloads180			ORDER BY count DESC, repo, version, platform181			LIMIT ?`,182		)183		.all(limit);184}185186/** A Nix tarball fetch (§22.2). */187export function countInstall(kepr: Database, repo: string): void {188	kepr189		.query(190			"INSERT INTO installs (repo, count) VALUES (?, 1) ON CONFLICT DO UPDATE SET count = count + 1",191		)192		.run(repo);193}194195/** Download counts of a repo's files, keyed `<version>/<platform>`. */196export function downloadCounts(kepr: Database, repo: string): Map<string, number> {197	const rows = kepr198		.query<{ version: string; platform: string; count: number }, [string]>(199			"SELECT version, platform, count FROM downloads WHERE repo = ?",200		)201		.all(repo);202	return new Map(rows.map((row) => [`${row.version}/${row.platform}`, row.count]));203}204205/** Downloads of every visible release of every public repo: the profile's count (§21.2). */206export function publicDownloadCount(kepr: Database): number {207	return (208		kepr209			.query<{ n: number }, []>(210				`SELECT COALESCE(SUM(d.count), 0) AS n FROM downloads d211				JOIN repos r ON r.name = d.repo AND r.public = 1212				LEFT JOIN release_settings s ON s.repo = d.repo AND s.version = d.version213				WHERE COALESCE(s.hidden, 0) = 0`,214			)215			.get()?.n ?? 0216	);217}218219/** A release as the operator sees it (§24): hidden ones too, and the record's own notes. */220export type OperatorRelease = {221	version: string;222	recordNotes: string;223	notes: string;224	hidden: boolean;225	downloads: [platform: string, count: number][];226};227228export function operatorReleases(229	kepr: Database,230	mirror: Database,231	repo: string,232): OperatorRelease[] {233	const counts = downloadCounts(kepr, repo);234	const settings = kepr235		.query<ReleaseSetting, [string]>(236			"SELECT version, hidden, notes FROM release_settings WHERE repo = ?",237		)238		.all(repo);239	return releaseRecords(mirror)240		.map((record) => {241			const setting = settings.find((row) => row.version === record.version);242			return {243				version: record.version,244				recordNotes: record.notes,245				notes: setting?.notes ?? record.notes,246				hidden: setting?.hidden === 1,247				downloads: record.files.map((file): [string, number] => [248					file.platform,249					counts.get(`${record.version}/${file.platform}`) ?? 0,250				]),251			};252		})253		.sort((a, b) => compareVersions(b.version, a.version));254}255256/** Hides or shows a version and sets its displayed notes; null notes fall back to the record's. */257export function setRelease(258	kepr: Database,259	repo: string,260	version: string,261	hidden: boolean,262	notes: string | null,263): void {264	kepr265		.query(266			`INSERT INTO release_settings (repo, version, hidden, notes) VALUES (?, ?, ?, ?)267			ON CONFLICT DO UPDATE SET hidden = excluded.hidden, notes = excluded.notes`,268		)269		.run(repo, version, hidden ? 1 : 0, notes);270}271272// Deletes run one at a time, so two can't each move `latest` from a reading the other outdated.273let deleting: Promise<unknown> = Promise.resolve();274275/**276 * Deletes a build from the bucket (June, 2026-09-30), since Koh has no way to. `releases/latest`277 * moves first, to the newest other version with a record (or goes with the last), then the files,278 * then the record: until the record goes the version still exists (§11.2), so a failure part-way279 * leaves it whole and deleting it again finishes the job. Kepr's settings and counts for it go too.280 */281export function deleteRelease(282	bucket: Bucket,283	kepr: Database,284	mirror: Database,285	repo: string,286	version: string,287): Promise<void> {288	const run = deleting.then(() => removeRelease(bucket, kepr, mirror, repo, version));289	deleting = run.catch(() => {});290	return run;291}292293async function removeRelease(294	bucket: Bucket,295	kepr: Database,296	mirror: Database,297	repo: string,298	version: string,299): Promise<void> {300	if ((await readReleasesLatest(bucket, repo)) === version) {301		const newest = (await listReleaseVersions(bucket, repo))302			.filter((other) => other !== version)303			.sort((a, b) => compareVersions(b, a))[0];304		const latest = `${repo}/releases/latest`;305		// ponytail: an unconditional write, as the reader has no put_if_match; a Koh publish landing306		// between the read above and this write loses `latest` until it offers again.307		if (newest) await bucket.put(latest, new TextEncoder().encode(newest), "text/plain");308		else await bucket.remove(latest);309	}310	const prefix = `${repo}/releases/${version}/`;311	const record = `${prefix}release.json`;312	for (const key of await bucket.list(prefix)) {313		if (key !== record) await bucket.remove(key);314	}315	await bucket.remove(record);316	forgetRelease(mirror, version);317	kepr.transaction(() => {318		for (const table of ["release_settings", "downloads"]) {319			// `table` is one of the two names above, never input.320			kepr.query(`DELETE FROM ${table} WHERE repo = ? AND version = ?`).run(repo, version);321		}322	})();323}324325/** Why a single file can't be deleted: the last one goes with its version, never alone. */326export class LastReleaseFile extends Error {}327328/**329 * Deletes one file of a build (2026-09-30). The record is rewritten without it first, so a failure330 * part-way leaves at most a file nothing lists; its count goes too. Runs in the same queue as whole331 * deletes, so neither reads a record the other is rewriting.332 */333export function deleteReleaseFile(334	bucket: Bucket,335	kepr: Database,336	mirror: Database,337	repo: string,338	version: string,339	platform: string,340): Promise<void> {341	const run = deleting.then(() => removeReleaseFile(bucket, kepr, mirror, repo, version, platform));342	deleting = run.catch(() => {});343	return run;344}345346async function removeReleaseFile(347	bucket: Bucket,348	kepr: Database,349	mirror: Database,350	repo: string,351	version: string,352	platform: string,353): Promise<void> {354	const key = `${repo}/releases/${version}/release.json`;355	const bytes = await bucket.get(key);356	if (bytes === null) throw new Error(`${key} is missing`);357	// Rewritten from the raw JSON, so fields Kepr doesn't read survive the edit.358	const raw = JSON.parse(new TextDecoder().decode(bytes)) as { files: ReleaseFile[] };359	const file = raw.files.find((f) => f.platform === platform);360	if (file) {361		if (raw.files.length === 1) throw new LastReleaseFile("delete the version instead");362		raw.files = raw.files.filter((f) => f !== file);363		const json = `${JSON.stringify(raw, null, 2)}\n`;364		await bucket.put(key, new TextEncoder().encode(json), "application/json");365		replaceRelease(mirror, checkRelease(repo, version, raw));366		await bucket.remove(`${repo}/releases/${version}/${platform}/${file.name}`);367	}368	kepr369		.query("DELETE FROM downloads WHERE repo = ? AND version = ? AND platform = ?")370		.run(repo, version, platform);371}