sync.ts

16.3 KB · raw

1import type { Database } from "bun:sqlite";2import {3	applyHidden,4	knownEventIds,5	knownObject,6	knownReleases,7	knownSave,8	land,9	mirrorState,10	openMirror,11	type StoredObject,12	storeObjects,13} from "../mirror/store.ts";14import { backupWhen } from "../server/backup.ts";15import type { BucketSource } from "../server/config.ts";16import {17	hiddenPaths,18	hiddenToHand,19	isRegistered,20	keepState,21	recordHiddenHanded,22	recordSync,23	registerRepo,24	renamedTo,25} from "../server/db.ts";26import { removal } from "../server/remove.ts";27import { RESERVED_NAMES } from "../server/reserved.ts";28import { dropTarballs } from "../tarball/cache.ts";29import { type Bucket, inTurn, KEPR_PREFIX, openBucket } from "./reader.ts";30import {31	type ArrivingSave,32	BucketError,33	checkFormat,34	checkHead,35	type EventRecord,36	escapePath,37	isSafePath,38	listEventIds,39	listReleaseVersions,40	listRepos,41	OversizedObject,42	objectSize,43	type ReleaseRecord,44	readEvent,45	readHead,46	readObject,47	readRelease,48	readReleasesLatest,49	readSave,50	type SaveRecord,51} from "./repo.ts";5253const INTERVAL_MS = 2 * 60 * 1000;54// Compressed bytes a sync holds before landing them; sized for a 2 GB host.55const LANDING_BYTES = 32 * 1024 * 1024;56const LANDING_SAVES = 100;57// Bucket reads in flight at once. Each waits about 170 ms on Tylee's round trip to the bucket58// (measured 2026-10-02), so reading one at a time left the line idle.59const READS_AT_ONCE = 16;60// Compressed object bytes being read at once; a larger object waits and is read alone.61const READ_BYTES = 32 * 1024 * 1024;62// Repos synced at once: every read waits on the bucket, so a serial pass left the line idle.63const REPOS_AT_ONCE = 4;64// Each repo of a pass gets this share of the pass's bytes, so a few in flight hold the same total.65const LANDING = LANDING_BYTES / REPOS_AT_ONCE;66const READS = READ_BYTES / REPOS_AT_ONCE;6768export type SyncTarget = {69	bucket: Bucket;70	kepr: Database;71	mirrorDir: string;72};7374let running: Promise<void> | null = null;7576/** Syncs every repo in the bucket. Never overlaps itself. */77export function syncAll(target: SyncTarget): Promise<void> {78	return running ?? holdSync(() => syncEach(target));79}8081/**82 * Runs `work` once any sync under way has finished, and keeps syncs waiting until it is done: a83 * rename moves a repo's keys, which a sync must never see half moved.84 */85export function holdSync(work: () => Promise<void>): Promise<void> {86	// Cleared before anyone awaiting `work` resumes, so a sync asked for next starts afresh.87	const mine = (running ?? Promise.resolve()).then(work).finally(() => {88		if (running === slot) running = null;89	});90	const slot = mine.catch(() => {});91	running = slot;92	return mine;93}9495/**96 * What the app asks of the sync: a pass and wait for it, a pass posted and answered at once,97 * syncs held off while work runs, hidden lists applied, bucket settings followed, a backup made98 * where it cannot stall a request. Mirrors have one writer; in this thread a posted pass has run.99 */100export type Syncer = {101	syncAll(): Promise<void>;102	syncSoon(): Promise<void>;103	hold(work: () => Promise<void>): Promise<void>;104	applyHidden(repos: string[]): Promise<void>;105	setBucket(source: BucketSource): void;106	backup(dataDir: string, when: "due" | "now"): Promise<void>;107};108109/** The sync in this thread, as the worker and the tests run it. */110export function localSyncer(target: SyncTarget): Syncer {111	return {112		syncAll: () => syncAll(target),113		syncSoon: () => syncAll(target),114		hold: holdSync,115		applyHidden: async (repos) => {116			for (const asked of repos) {117				// A rename may have moved the repo while this waited on its hold.118				const repo = renamedTo(target.kepr, asked) ?? asked;119				if (!isRegistered(target.kepr, repo)) continue;120				applyHidden(openMirror(target.mirrorDir, repo), hiddenPaths(target.kepr, repo));121			}122		},123		setBucket: (source) => Object.assign(target.bucket, openBucket(source)),124		backup: async (dataDir, when) => void backupWhen(target.kepr, dataDir, when),125	};126}127128/** A request to the sync's worker (`worker.ts`), and its reply. */129export type SyncRequest =130	| { kind: "start"; dataDir: string; source: BucketSource }131	| { kind: "sync" | "hold" | "release"; id: number }132	| { kind: "hidden"; id: number; repos: string[] }133	| { kind: "backup"; id: number; dataDir: string; when: "due" | "now" }134	| { kind: "bucket"; source: BucketSource };135export type SyncReply = { kind: "done"; id: number; error?: string };136137/**138 * The sync on its own thread (2026-10-02), so a landing, a recount or a migration never stalls a139 * request. A worker that dies takes Kepr down with140 * it, for the service manager to restart, rather than leaving requests waiting on it.141 */142export function startSyncWorker(dataDir: string, source: BucketSource): Syncer {143	const worker = new Worker(new URL("./worker.ts", import.meta.url));144	// The server keeps Kepr running; the worker alone never should.145	worker.unref();146	const waiting = new Map<number, { resolve: () => void; reject: (error: Error) => void }>();147	let next = 0;148	worker.addEventListener("error", (event) => {149		console.error(`kepr: the sync worker failed: ${event.message}`);150		process.exit(1);151	});152	worker.addEventListener("message", ({ data }: MessageEvent<SyncReply>) => {153		const reply = waiting.get(data.id);154		waiting.delete(data.id);155		if (data.error === undefined) reply?.resolve();156		else reply?.reject(new Error(data.error));157	});158	const send = (request: SyncRequest) => worker.postMessage(request);159	const ask = (request: (id: number) => SyncRequest) =>160		new Promise<number>((resolve, reject) => {161			const id = next++;162			waiting.set(id, { resolve: () => resolve(id), reject });163			send(request(id));164		});165	const once = async (request: (id: number) => SyncRequest) => void (await ask(request));166	send({ kind: "start", dataDir, source });167	return {168		syncAll: () => once((id) => ({ kind: "sync", id })),169		syncSoon: () => Promise.resolve(send({ kind: "sync", id: next++ })),170		async hold(work) {171			const id = await ask((id) => ({ kind: "hold", id }));172			try {173				await work();174			} finally {175				send({ kind: "release", id });176			}177		},178		applyHidden: (repos) => once((id) => ({ kind: "hidden", id, repos })),179		setBucket: (source) => send({ kind: "bucket", source }),180		backup: (dataDir, when) => once((id) => ({ kind: "backup", id, dataDir, when })),181	};182}183184export function startSyncLoop(target: SyncTarget): void {185	const tick = () => syncAll(target).catch((error) => console.error(`kepr: sync failed: ${error}`));186	tick();187	setInterval(tick, INTERVAL_MS);188}189190async function syncEach(target: SyncTarget): Promise<void> {191	const heads = new Map<string, string>();192	try {193		await listRepos(target.bucket, heads);194	} catch (error) {195		keepState(target.kepr, "bucket_error", String(error));196		throw error;197	}198	// What the console's status shows, so it never asks the bucket itself.199	keepState(target.kepr, "bucket_error", null);200	keepState(target.kepr, "bucket_read_at", String(Math.floor(Date.now() / 1000)));201	keepState(target.kepr, "bucket_repos", JSON.stringify([...heads.keys()]));202	// A few repos at a time, each from the head the listing read; a failure stays that repo's.203	await inTurn([...heads], REPOS_AT_ONCE, async ([repo, head]) => {204		// A repo being deleted is left alone: landing its records mid-delete would put its row back.205		if (repo === removal(target.kepr)?.repo) return;206		registerRepo(target.kepr, repo);207		let error: string | null = null;208		if (RESERVED_NAMES.has(repo)) {209			error = `not synced: the name "${repo}" clashes with Kepr's own /${repo} route; rename the repo`;210		} else {211			try {212				const mirror = openMirror(target.mirrorDir, repo);213				const paths = hiddenPaths(target.kepr, repo);214				const events = await syncRepo(target.bucket, mirror, repo, paths, LANDING, READS, head);215				if (events.some((event) => event.kind === "strip")) await dropTarballs(target.bucket, repo);216			} catch (cause) {217				error = cause instanceof Error ? cause.message : String(cause);218			}219		}220		recordSync(target.kepr, repo, Math.floor(Date.now() / 1000), error);221		await handHidden(target, repo);222	});223}224225/**226 * Hands a repo's hidden paths to Koh at `.kepr/hidden/<repo>`, one per line, for it to add to227 * `.kohignore`, unless they are known to be there already, then drops the tarballs kept under the228 * old list. The sync does it rather than the console, so a failed write or a restart is retried at229 * the next pass, and it never overlaps a rename.230 */231async function handHidden(target: SyncTarget, repo: string): Promise<void> {232	const list = hiddenToHand(target.kepr, repo);233	if (list === null) return;234	const paths = list.split("\n").filter(Boolean);235	const bytes = new TextEncoder().encode(paths.map((path) => `${path}\n`).join(""));236	// Unknown until the write is confirmed, so a restart or failure mid-write is written again237	// even if the list changes back to the one recorded before.238	recordHiddenHanded(target.kepr, repo, null);239	try {240		await target.bucket.put(`${KEPR_PREFIX}hidden/${repo}`, bytes, "text/plain");241	} catch (error) {242		console.error(`kepr: handing ${repo}'s hidden paths to Koh failed: ${error}`);243		return;244	}245	recordHiddenHanded(target.kepr, repo, list);246	// Only storage: a kept tarball is never served once its generation's hidden list has changed.247	await dropTarballs(target.bucket, repo).catch((error) =>248		console.error(`kepr: dropping ${repo}'s kept tarballs failed: ${error}`),249	);250}251252/**253 * Koh's steal flow (§9.4) against a mirror: walk back from the remote head to a save the mirror has,254 * fetch what is missing, and land it, in batches oldest first. Events are listed every time, since a255 * flag or a strip arrives without moving `head`; releases only when `head` or `releases/latest`256 * moved (§18), since publishing one moves both. A path §5.5 refuses, or one whose object inflates257 * past Koh's file limit, is quarantined: the save lands without it, as if stripped. `hidden` is258 * applied first, so a list changed since the last sync takes effect even with nothing new. Returns259 * the events it landed.260 */261export async function syncRepo(262	bucket: Bucket,263	mirror: Database,264	repo: string,265	hidden: string[] = [],266	landingBytes = LANDING_BYTES,267	readBytes = READ_BYTES,268	listed?: string,269): Promise<EventRecord[]> {270	applyHidden(mirror, hidden);271	// A listing read the head already; without one, the bucket is asked.272	const head = listed === undefined ? await readHead(bucket, repo) : checkHead(repo, listed);273	// The format is read once per head: koh writes `format` only when it offers, which moves the274	// head, so asking on every pass spent a request per repo per pass to hear nothing new.275	if (head === null || mirrorState(mirror, "head") !== head) await checkFormat(bucket, repo);276	if (head === null) return [];277	const unknown = new Set<string>();278	// What the walk back read, so the landing pass need not read it again: the walk goes down from279	// the head, so its last records are the landing's first; a landing batch's worth is kept and no280	// more, so a first sync of a huge repo still never holds its history in memory.281	const walked = new Map<string, ArrivingSave>();282	for (let cursor = head; cursor !== "" && !knownSave(mirror, cursor); ) {283		if (unknown.has(cursor)) throw new BucketError(`${repo}: save ${cursor} is its own ancestor`);284		unknown.add(cursor);285		const save = await readSave(bucket, repo, cursor);286		if (walked.size === LANDING_SAVES) walked.delete(walked.keys().next().value as string);287		walked.set(save.id, save);288		cursor = save.parent;289	}290	// Oldest first, landing whenever the batch passes `landingBytes` of objects or LANDING_SAVES291	// records: a first sync of a big repo never holds its whole history in memory, and one cut short292	// resumes from the last batch.293	let saves: SaveRecord[] = [];294	let objects = new Map<string, StoredObject>();295	let quarantined: string[] = [];296	let fetched = 0;297	const oversized = new Set<string>();298	const landBatch = (batchHead: string) => {299		land(mirror, {300			head: batchHead,301			releasesLatest: mirrorState(mirror, "releases_latest") ?? "",302			saves,303			objects,304			events: [],305			releases: [],306			quarantined,307		});308		saves = [];309		objects = new Map();310		quarantined = [];311		fetched = 0;312	};313	const gate = byteGate(readBytes);314	let failure: unknown = null;315	// Reads one object into `ahead`. A read the gate admits after the batch filled, or after another316	// read failed, puts its hash back for the next batch instead.317	const readInto = async (ahead: Map<string, StoredObject>, wanted: string[], hash: string) => {318		const size = await objectSize(bucket, repo, hash);319		await gate.enter(size);320		try {321			if (failure !== null || fetched >= landingBytes) {322				wanted.unshift(hash);323				return;324			}325			const object = await readObject(bucket, repo, hash);326			ahead.set(hash, object);327			fetched += object.compressed.length;328		} catch (cause) {329			if (!(cause instanceof OversizedObject)) throw cause;330			oversized.add(hash);331		} finally {332			gate.leave(size);333		}334	};335	const ids = [...unknown].reverse();336	for (let start = 0; start < ids.length; start += READS_AT_ONCE) {337		const records = await inTurn(ids.slice(start, start + READS_AT_ONCE), READS_AT_ONCE, (id) => {338			const read = walked.get(id);339			if (read === undefined) return readSave(bucket, repo, id);340			walked.delete(id);341			return Promise.resolve(read);342		});343		for (const save of records) {344			quarantined.push(...save.quarantined);345			// One save can hold more than a batch, as a first import does: its objects are stored346			// ahead of it, after the saves before it have landed, so no landing's cleanup sees them347			// unreferenced.348			const ahead = new Map<string, StoredObject>();349			const wanted = [...new Set(save.files.map((file) => file.hash))].filter(350				(hash) => !objects.has(hash) && !oversized.has(hash) && !knownObject(mirror, hash),351			);352			while (wanted.length > 0) {353				// No read starts once the batch is full, so a batch passes `landingBytes` by at most354				// the reads under way, which the gate holds to `readBytes` or one larger object.355				const reader = async () => {356					while (failure === null && fetched < landingBytes && wanted.length > 0) {357						await readInto(ahead, wanted, wanted.shift() as string).catch((cause) => {358							failure ??= cause;359						});360					}361				};362				// Every reader settles before a failure is reported, so none outlives this sync.363				await Promise.all(Array.from({ length: READS_AT_ONCE }, reader));364				if (failure !== null) throw failure;365				if (fetched >= landingBytes) {366					const last = saves.at(-1);367					if (last) landBatch(last.id);368					storeObjects(mirror, ahead);369					ahead.clear();370					fetched = 0;371				}372			}373			for (const [hash, object] of ahead) objects.set(hash, object);374			quarantined.push(375				...save.files.filter((f) => oversized.has(f.hash)).map((f) => escapePath(f.path)),376			);377			save.files = save.files.filter((file) => !oversized.has(file.hash));378			saves.push(save);379			if (saves.length >= LANDING_SAVES && save.id !== head) landBatch(save.id);380		}381	}382	const known = knownEventIds(mirror);383	const newEvents = (await listEventIds(bucket, repo)).filter((id) => !known.has(id));384	const events = (385		await inTurn(newEvents, READS_AT_ONCE, (id) => readEvent(bucket, repo, id))386	).filter(387		// Koh ignores it too: no save can hold an illegal path (§5.5).388		(event) => event.kind !== "strip" || isSafePath(event.path),389	);390	const releasesLatest = (await readReleasesLatest(bucket, repo)) ?? "";391	const moved =392		mirrorState(mirror, "head") !== head ||393		mirrorState(mirror, "releases_latest") !== releasesLatest;394	const releases = moved ? await newReleases(bucket, mirror, repo) : [];395	if (!moved && events.length === 0) return [];396	land(mirror, {397		head,398		releasesLatest,399		saves,400		objects,401		events,402		releases,403		quarantined,404	});405	return events;406}407408/** Admits reads while their bytes in flight stay within `limit`; a larger one waits to go alone. */409function byteGate(limit: number) {410	let inFlight = 0;411	let waiting: (() => void)[] = [];412	return {413		async enter(size: number): Promise<void> {414			while (inFlight > 0 && inFlight + size > limit) {415				await new Promise<void>((resolve) => waiting.push(resolve));416			}417			inFlight += size;418		},419		leave(size: number): void {420			inFlight -= size;421			const woken = waiting;422			waiting = [];423			for (const wake of woken) wake();424		},425	};426}427428async function newReleases(429	bucket: Bucket,430	mirror: Database,431	repo: string,432): Promise<ReleaseRecord[]> {433	const known = knownReleases(mirror);434	const versions = (await listReleaseVersions(bucket, repo)).filter((v) => !known.has(v));435	return inTurn(versions, READS_AT_ONCE, (version) => readRelease(bucket, repo, version));436}