sync.ts

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