sync.ts

18.5 KB · raw

1import type { Database } from "bun:sqlite";2import { flattenTree, manifestBody, parseManifest } from "../mirror/manifest.ts";3import {4	applyHidden,5	knownEventIds,6	knownManifest,7	knownObject,8	knownReleases,9	knownSave,10	land,11	mirrorState,12	openMirror,13	type StoredObject,14	storeObjects,15} from "../mirror/store.ts";16import { backupWhen } from "../server/backup.ts";17import type { BucketSource } from "../server/config.ts";18import {19	hiddenPaths,20	hiddenToHand,21	isRegistered,22	keepState,23	recordHiddenHanded,24	recordSync,25	registerRepo,26	renamedTo,27} from "../server/db.ts";28import { removal } from "../server/remove.ts";29import { RESERVED_NAMES } from "../server/reserved.ts";30import { dropTarballs } from "../tarball/cache.ts";31import { type Bucket, inTurn, KEPR_PREFIX, openBucket } from "./reader.ts";32import {33	type ArrivingSave,34	BucketError,35	checkFormat,36	checkHead,37	type EventRecord,38	escapePath,39	isSafePath,40	listEventIds,41	listReleaseVersions,42	listRepos,43	OversizedObject,44	objectSize,45	type ReleaseRecord,46	readEvent,47	readHead,48	readManifest,49	readObject,50	readRelease,51	readReleasesLatest,52	readSave,53	type SaveFile,54	type SaveRecord,55} from "./repo.ts";5657const INTERVAL_MS = 2 * 60 * 1000;58// Compressed bytes a sync holds before landing them; sized for a 2 GB host.59const LANDING_BYTES = 32 * 1024 * 1024;60const LANDING_SAVES = 100;61// Bucket reads in flight at once. Each waits about 170 ms on Tylee's round trip to the bucket62// (measured 2026-10-02), so reading one at a time left the line idle.63const READS_AT_ONCE = 16;64// Compressed object bytes being read at once; a larger object waits and is read alone.65const READ_BYTES = 32 * 1024 * 1024;66// Repos synced at once: every read waits on the bucket, so a serial pass left the line idle.67const REPOS_AT_ONCE = 4;68// Each repo of a pass gets this share of the pass's bytes, so a few in flight hold the same total.69const LANDING = LANDING_BYTES / REPOS_AT_ONCE;70const READS = READ_BYTES / REPOS_AT_ONCE;7172export type SyncTarget = {73	bucket: Bucket;74	kepr: Database;75	mirrorDir: string;76};7778let running: Promise<void> | null = null;7980/** Syncs every repo in the bucket. Never overlaps itself. */81export function syncAll(target: SyncTarget): Promise<void> {82	return running ?? holdSync(() => syncEach(target));83}8485/**86 * Runs `work` once any sync under way has finished, and keeps syncs waiting until it is done: a87 * rename moves a repo's keys, which a sync must never see half moved.88 */89export function holdSync(work: () => Promise<void>): Promise<void> {90	// Cleared before anyone awaiting `work` resumes, so a sync asked for next starts afresh.91	const mine = (running ?? Promise.resolve()).then(work).finally(() => {92		if (running === slot) running = null;93	});94	const slot = mine.catch(() => {});95	running = slot;96	return mine;97}9899/**100 * What the app asks of the sync: a pass and wait for it, a pass posted and answered at once,101 * syncs held off while work runs, hidden lists applied, bucket settings followed, a backup made102 * where it cannot stall a request. Mirrors have one writer; in this thread a posted pass has run.103 */104export type Syncer = {105	syncAll(): Promise<void>;106	syncSoon(): Promise<void>;107	hold(work: () => Promise<void>): Promise<void>;108	applyHidden(repos: string[]): Promise<void>;109	setBucket(source: BucketSource): void;110	backup(dataDir: string, when: "due" | "now"): Promise<void>;111};112113/** The sync in this thread, as the worker and the tests run it. */114export function localSyncer(target: SyncTarget): Syncer {115	return {116		syncAll: () => syncAll(target),117		syncSoon: () => syncAll(target),118		hold: holdSync,119		applyHidden: async (repos) => {120			for (const asked of repos) {121				// A rename may have moved the repo while this waited on its hold.122				const repo = renamedTo(target.kepr, asked) ?? asked;123				if (!isRegistered(target.kepr, repo)) continue;124				applyHidden(openMirror(target.mirrorDir, repo), hiddenPaths(target.kepr, repo));125			}126		},127		setBucket: (source) => Object.assign(target.bucket, openBucket(source)),128		backup: async (dataDir, when) => void backupWhen(target.kepr, dataDir, when),129	};130}131132/** A request to the sync's worker (`worker.ts`), and its reply. */133export type SyncRequest =134	| { kind: "start"; dataDir: string; source: BucketSource }135	| { kind: "sync" | "hold" | "release"; id: number }136	| { kind: "hidden"; id: number; repos: string[] }137	| { kind: "backup"; id: number; dataDir: string; when: "due" | "now" }138	| { kind: "bucket"; source: BucketSource };139export type SyncReply = { kind: "done"; id: number; error?: string };140141/**142 * The sync on its own thread (2026-10-02), so a landing, a recount or a migration never stalls a143 * request. A worker that dies takes Kepr down with144 * it, for the service manager to restart, rather than leaving requests waiting on it.145 */146export function startSyncWorker(dataDir: string, source: BucketSource): Syncer {147	const worker = new Worker(new URL("./worker.ts", import.meta.url));148	// The server keeps Kepr running; the worker alone never should.149	worker.unref();150	const waiting = new Map<number, { resolve: () => void; reject: (error: Error) => void }>();151	let next = 0;152	worker.addEventListener("error", (event) => {153		console.error(`kepr: the sync worker failed: ${event.message}`);154		process.exit(1);155	});156	worker.addEventListener("message", ({ data }: MessageEvent<SyncReply>) => {157		const reply = waiting.get(data.id);158		waiting.delete(data.id);159		if (data.error === undefined) reply?.resolve();160		else reply?.reject(new Error(data.error));161	});162	const send = (request: SyncRequest) => worker.postMessage(request);163	const ask = (request: (id: number) => SyncRequest) =>164		new Promise<number>((resolve, reject) => {165			const id = next++;166			waiting.set(id, { resolve: () => resolve(id), reject });167			send(request(id));168		});169	const once = async (request: (id: number) => SyncRequest) => void (await ask(request));170	send({ kind: "start", dataDir, source });171	return {172		syncAll: () => once((id) => ({ kind: "sync", id })),173		syncSoon: () => Promise.resolve(send({ kind: "sync", id: next++ })),174		async hold(work) {175			const id = await ask((id) => ({ kind: "hold", id }));176			try {177				await work();178			} finally {179				send({ kind: "release", id });180			}181		},182		applyHidden: (repos) => once((id) => ({ kind: "hidden", id, repos })),183		setBucket: (source) => send({ kind: "bucket", source }),184		backup: (dataDir, when) => once((id) => ({ kind: "backup", id, dataDir, when })),185	};186}187188export function startSyncLoop(target: SyncTarget): void {189	const tick = () => syncAll(target).catch((error) => console.error(`kepr: sync failed: ${error}`));190	tick();191	setInterval(tick, INTERVAL_MS);192}193194async function syncEach(target: SyncTarget): Promise<void> {195	const heads = new Map<string, string>();196	try {197		await listRepos(target.bucket, heads);198	} catch (error) {199		keepState(target.kepr, "bucket_error", String(error));200		throw error;201	}202	// What the console's status shows, so it never asks the bucket itself.203	keepState(target.kepr, "bucket_error", null);204	keepState(target.kepr, "bucket_read_at", String(Math.floor(Date.now() / 1000)));205	keepState(target.kepr, "bucket_repos", JSON.stringify([...heads.keys()]));206	// A few repos at a time, each from the head the listing read; a failure stays that repo's.207	await inTurn([...heads], REPOS_AT_ONCE, async ([repo, head]) => {208		// A repo being deleted is left alone: landing its records mid-delete would put its row back.209		if (repo === removal(target.kepr)?.repo) return;210		registerRepo(target.kepr, repo);211		let error: string | null = null;212		if (RESERVED_NAMES.has(repo)) {213			error = `not synced: the name "${repo}" clashes with Kepr's own /${repo} route; rename the repo`;214		} else {215			try {216				const mirror = openMirror(target.mirrorDir, repo);217				const paths = hiddenPaths(target.kepr, repo);218				const events = await syncRepo(target.bucket, mirror, repo, paths, LANDING, READS, head);219				if (events.some((event) => event.kind === "strip")) await dropTarballs(target.bucket, repo);220			} catch (cause) {221				error = cause instanceof Error ? cause.message : String(cause);222			}223		}224		recordSync(target.kepr, repo, Math.floor(Date.now() / 1000), error);225		await handHidden(target, repo);226	});227}228229/**230 * Hands a repo's hidden paths to Koh at `.kepr/hidden/<repo>`, one per line, for it to add to231 * `.kohignore`, unless they are known to be there already, then drops the tarballs kept under the232 * old list. The sync does it rather than the console, so a failed write or a restart is retried at233 * the next pass, and it never overlaps a rename.234 */235async function handHidden(target: SyncTarget, repo: string): Promise<void> {236	const list = hiddenToHand(target.kepr, repo);237	if (list === null) return;238	const paths = list.split("\n").filter(Boolean);239	const bytes = new TextEncoder().encode(paths.map((path) => `${path}\n`).join(""));240	// Unknown until the write is confirmed, so a restart or failure mid-write is written again241	// even if the list changes back to the one recorded before.242	recordHiddenHanded(target.kepr, repo, null);243	try {244		await target.bucket.put(`${KEPR_PREFIX}hidden/${repo}`, bytes, "text/plain");245	} catch (error) {246		console.error(`kepr: handing ${repo}'s hidden paths to Koh failed: ${error}`);247		return;248	}249	recordHiddenHanded(target.kepr, repo, list);250	// Only storage: a kept tarball is never served once its generation's hidden list has changed.251	await dropTarballs(target.bucket, repo).catch((error) =>252		console.error(`kepr: dropping ${repo}'s kept tarballs failed: ${error}`),253	);254}255256/**257 * Koh's steal flow (§9.4) against a mirror: walk back from the remote head to a save the mirror has,258 * fetch what is missing, and land it, in batches oldest first. Events are listed every time, since a259 * flag or a strip arrives without moving `head`; releases only when `head` or `releases/latest`260 * moved (§18), since publishing one moves both. A path §5.5 refuses, or one whose object inflates261 * past Koh's file limit, is quarantined: the save lands without it, as if stripped. `hidden` is262 * applied first, so a list changed since the last sync takes effect even with nothing new. Returns263 * the events it landed.264 */265export async function syncRepo(266	bucket: Bucket,267	mirror: Database,268	repo: string,269	hidden: string[] = [],270	landingBytes = LANDING_BYTES,271	readBytes = READ_BYTES,272	listed?: string,273): Promise<EventRecord[]> {274	applyHidden(mirror, hidden);275	// A listing read the head already; without one, the bucket is asked.276	const head = listed === undefined ? await readHead(bucket, repo) : checkHead(repo, listed);277	// The format is read once per head: koh writes `format` only when it offers, which moves the278	// head, so asking on every pass spent a request per repo per pass to hear nothing new.279	if (head === null || mirrorState(mirror, "head") !== head) await checkFormat(bucket, repo);280	if (head === null) return [];281	const unknown = new Set<string>();282	// What the walk back read, so the landing pass need not read it again: the walk goes down from283	// the head, so its last records are the landing's first; a landing batch's worth is kept and no284	// more, so a first sync of a huge repo still never holds its history in memory.285	const walked = new Map<string, ArrivingSave>();286	for (let cursor = head; cursor !== "" && !knownSave(mirror, cursor); ) {287		if (unknown.has(cursor)) throw new BucketError(`${repo}: save ${cursor} is its own ancestor`);288		unknown.add(cursor);289		const save = await readSave(bucket, repo, cursor);290		if (walked.size === LANDING_SAVES) walked.delete(walked.keys().next().value as string);291		walked.set(save.id, save);292		cursor = save.parent;293	}294	// Oldest first, landing whenever the batch passes `landingBytes` of objects or LANDING_SAVES295	// records: a first sync of a big repo never holds its whole history in memory, and one cut short296	// resumes from the last batch.297	let saves: SaveRecord[] = [];298	let objects = new Map<string, StoredObject>();299	let manifests = new Map<string, string>();300	let quarantined: string[] = [];301	let fetched = 0;302	const oversized = new Set<string>();303	const landBatch = (batchHead: string) => {304		land(mirror, {305			head: batchHead,306			releasesLatest: mirrorState(mirror, "releases_latest") ?? "",307			saves,308			manifests,309			objects,310			events: [],311			releases: [],312			quarantined,313		});314		saves = [];315		objects = new Map();316		manifests = new Map();317		quarantined = [];318		fetched = 0;319	};320	const gate = byteGate(readBytes);321	let failure: unknown = null;322	// Reads one object into `ahead`. A read the gate admits after the batch filled, or after another323	// read failed, puts its hash back for the next batch instead.324	const readInto = async (ahead: Map<string, StoredObject>, wanted: string[], hash: string) => {325		const size = await objectSize(bucket, repo, hash);326		await gate.enter(size);327		try {328			if (failure !== null || fetched >= landingBytes) {329				wanted.unshift(hash);330				return;331			}332			const object = await readObject(bucket, repo, hash);333			ahead.set(hash, object);334			fetched += object.compressed.length;335		} catch (cause) {336			if (!(cause instanceof OversizedObject)) throw cause;337			oversized.add(hash);338		} finally {339			gate.leave(size);340		}341	};342	const ids = [...unknown].reverse();343	// A format-2 save names its root manifest instead of a file list: fetch the folders the mirror344	// lacks, checking every body against its key (§9.4), and flatten the tree to the files the345	// landing stores and counts. A manifest the mirror holds means its whole tree is held too.346	const treeOf = async (save: SaveRecord): Promise<SaveFile[]> => {347		if (save.manifest === undefined) return save.files;348		const bodies = new Map<string, string>();349		let pending = [save.manifest];350		while (pending.length > 0) {351			const wanted = pending.filter(352				(hash) => !bodies.has(hash) && !manifests.has(hash) && !knownManifest(mirror, hash),353			);354			pending = [];355			if (wanted.length === 0) break;356			const read = await inTurn(wanted, READS_AT_ONCE, async (hash) => {357				try {358					const body = await readManifest(bucket, repo, hash);359					return { hash, body, entries: parseManifest(body) };360				} catch (cause) {361					const reason = cause instanceof Error ? cause.message : String(cause);362					throw new BucketError(363						`${repo}: save ${save.id} names manifest ${hash}, which cannot be read: ${reason}`,364					);365				}366			});367			for (const { hash, body, entries } of read) {368				bodies.set(hash, body);369				for (const entry of entries) if (entry.kind === "folder") pending.push(entry.manifest);370			}371		}372		const files = flattenTree((hash) => {373			const body = bodies.get(hash) ?? manifests.get(hash) ?? manifestBody(mirror, hash);374			if (body === null) {375				throw new BucketError(`${repo}: save ${save.id} names manifest ${hash}, which is missing`);376			}377			return body;378		}, save.manifest);379		for (const [hash, body] of bodies) {380			manifests.set(hash, body);381			fetched += body.length;382		}383		return files;384	};385	for (let start = 0; start < ids.length; start += READS_AT_ONCE) {386		const records = await inTurn(ids.slice(start, start + READS_AT_ONCE), READS_AT_ONCE, (id) => {387			const read = walked.get(id);388			if (read === undefined) return readSave(bucket, repo, id);389			walked.delete(id);390			return Promise.resolve(read);391		});392		for (const save of records) {393			quarantined.push(...save.quarantined);394			if (save.manifest !== undefined) {395				const files = await treeOf(save);396				quarantined.push(397					...files.filter((file) => !isSafePath(file.path)).map((file) => escapePath(file.path)),398				);399				save.files = files.filter((file) => isSafePath(file.path));400			}401			// One save can hold more than a batch, as a first import does: its objects are stored402			// ahead of it, after the saves before it have landed, so no landing's cleanup sees them403			// unreferenced.404			const ahead = new Map<string, StoredObject>();405			const wanted = [...new Set(save.files.map((file) => file.hash))].filter(406				(hash) => !objects.has(hash) && !oversized.has(hash) && !knownObject(mirror, hash),407			);408			while (wanted.length > 0) {409				// No read starts once the batch is full, so a batch passes `landingBytes` by at most410				// the reads under way, which the gate holds to `readBytes` or one larger object.411				const reader = async () => {412					while (failure === null && fetched < landingBytes && wanted.length > 0) {413						await readInto(ahead, wanted, wanted.shift() as string).catch((cause) => {414							failure ??= cause;415						});416					}417				};418				// Every reader settles before a failure is reported, so none outlives this sync.419				await Promise.all(Array.from({ length: READS_AT_ONCE }, reader));420				if (failure !== null) throw failure;421				if (fetched >= landingBytes) {422					const last = saves.at(-1);423					if (last) landBatch(last.id);424					storeObjects(mirror, ahead);425					ahead.clear();426					fetched = 0;427				}428			}429			for (const [hash, object] of ahead) objects.set(hash, object);430			quarantined.push(431				...save.files.filter((f) => oversized.has(f.hash)).map((f) => escapePath(f.path)),432			);433			save.files = save.files.filter((file) => !oversized.has(file.hash));434			saves.push(save);435			if (saves.length >= LANDING_SAVES && save.id !== head) landBatch(save.id);436		}437	}438	const known = knownEventIds(mirror);439	const newEvents = (await listEventIds(bucket, repo)).filter((id) => !known.has(id));440	const events = (441		await inTurn(newEvents, READS_AT_ONCE, (id) => readEvent(bucket, repo, id))442	).filter(443		// Koh ignores it too: no save can hold an illegal path (§5.5).444		(event) => event.kind !== "strip" || isSafePath(event.path),445	);446	const releasesLatest = (await readReleasesLatest(bucket, repo)) ?? "";447	const moved =448		mirrorState(mirror, "head") !== head ||449		mirrorState(mirror, "releases_latest") !== releasesLatest;450	const releases = moved ? await newReleases(bucket, mirror, repo) : [];451	if (!moved && events.length === 0) return [];452	land(mirror, {453		head,454		releasesLatest,455		saves,456		manifests,457		objects,458		events,459		releases,460		quarantined,461	});462	return events;463}464465/** Admits reads while their bytes in flight stay within `limit`; a larger one waits to go alone. */466function byteGate(limit: number) {467	let inFlight = 0;468	let waiting: (() => void)[] = [];469	return {470		async enter(size: number): Promise<void> {471			while (inFlight > 0 && inFlight + size > limit) {472				await new Promise<void>((resolve) => waiting.push(resolve));473			}474			inFlight += size;475		},476		leave(size: number): void {477			inFlight -= size;478			const woken = waiting;479			waiting = [];480			for (const wake of woken) wake();481		},482	};483}484485async function newReleases(486	bucket: Bucket,487	mirror: Database,488	repo: string,489): Promise<ReleaseRecord[]> {490	const known = knownReleases(mirror);491	const versions = (await listReleaseVersions(bucket, repo)).filter((v) => !known.has(v));492	return inTurn(versions, READS_AT_ONCE, (version) => readRelease(bucket, repo, version));493}