sync.test.ts

5.7 KB · raw

1import { Database } from "bun:sqlite";2import { beforeAll, describe, expect, test } from "bun:test";3import { mkdtemp, writeFile } from "node:fs/promises";4import { tmpdir } from "node:os";5import { join } from "node:path";6import { openBucket } from "../src/bucket/reader.ts";7import { syncAll } from "../src/bucket/sync.ts";8import {9	fileAt,10	filesAt,11	headId,12	history,13	objectBytes,14	repoStats,15	saveByPrefix,16	timeline,17} from "../src/mirror/queries.ts";18import { openMirror } from "../src/mirror/store.ts";19import { openKeprDb } from "../src/server/db.ts";20import { type Fixture, makeKohBucket } from "./fixture.ts";2122const text = (bytes: Uint8Array | null) => new TextDecoder().decode(bytes ?? new Uint8Array());2324async function syncTarget(fx: Fixture) {25	const dataDir = await mkdtemp(join(tmpdir(), "kepr-data-"));26	const target = {27		bucket: openBucket({ kind: "folder", path: fx.bucketDir }),28		kepr: openKeprDb(dataDir),29		mirrorDir: join(dataDir, "mirror"),30	};31	return { ...target, mirror: () => openMirror(target.mirrorDir, fx.repo) };32}3334describe("a first sync of a koh3 bucket", () => {35	let fx: Fixture;36	let t: Awaited<ReturnType<typeof syncTarget>>;37	beforeAll(async () => {38		fx = await makeKohBucket();39		t = await syncTarget(fx);40		await syncAll(t);41	});42	const [head, checkpoint, second, first] = [0, 1, 2, 3].map((i) => () => fx.saveIds[i] as string);4344	test("registers the repo private, with a clean last sync", () => {45		const row = t.kepr.query("SELECT public, last_sync_at, last_sync_error FROM repos").get() as {46			public: number;47			last_sync_at: number;48			last_sync_error: string | null;49		};50		expect(row.public).toBe(0);51		expect(row.last_sync_error).toBeNull();52		expect(row.last_sync_at).toBeGreaterThan(0);53	});5455	test("history is newest first and leaves out the checkpoint", () => {56		expect(headId(t.mirror())).toBe(head());57		expect(history(t.mirror(), 10, 0).map((s) => s.id)).toEqual([head(), second(), first()]);58		expect(history(t.mirror(), 1, 1).map((s) => s.message)).toEqual(["add readme and entry point"]);59		expect(timeline(t.mirror()).map((s) => s.id)).toEqual([first(), second(), head()]);60		expect(saveByPrefix(t.mirror(), checkpoint())?.is_checkpoint).toBe(true);61	});6263	test("finds a save by a unique prefix of six or more characters", () => {64		const save = saveByPrefix(t.mirror(), second().slice(0, 6));65		expect([save?.id, save?.agent, save?.session]).toEqual([second(), "test-agent", "fixture"]);66		expect(saveByPrefix(t.mirror(), second().slice(0, 5))).toBeNull();67		expect(saveByPrefix(t.mirror(), "zzzzzz")).toBeNull();68	});6970	test("reads files and their bytes at any save", () => {71		const paths = filesAt(t.mirror(), head()).map((f) => f.path);72		expect(paths).toContain("src/lib/deep/util.ts");73		const now = fileAt(t.mirror(), head(), "src/main.ts");74		const then = fileAt(t.mirror(), second(), "src/main.ts");75		expect(text(objectBytes(t.mirror(), now?.hash as string))).toContain("hello");76		expect(text(objectBytes(t.mirror(), then?.hash as string))).toContain("'hi'");77		expect(fileAt(t.mirror(), first(), "src/main.ts")).toBeNull();78		expect(fileAt(t.mirror(), head(), "docs/logo.png")?.size).toBe(70);79	});8081	test("counts saves without checkpoints, and lines and language at head", () => {82		const stats = repoStats(t.mirror());83		expect(stats.saves).toBe(3);84		expect(stats.language).toBe("TypeScript");85		// README 9 + guide 3 + secret 1 + util 1 + main 2 + .kohignore86		expect(stats.lines).toBeGreaterThan(16);87		// vendor/big.c's 100 lines of C count toward neither.88		expect(stats.lines).toBeLessThan(100);89		expect(stats.updated).toBe(saveByPrefix(t.mirror(), head())?.created_at ?? -1);90	});9192	test("stores the flag event", () => {93		const flag = t.mirror().query("SELECT kind, save_id, reason FROM events").get();94		expect(flag).toEqual({ kind: "flag", save_id: first(), reason: "holds a secret" });95	});9697	test("a strip reaches the mirror and drops the object", async () => {98		const secret = fileAt(t.mirror(), head(), "secret.txt")?.hash as string;99		expect(objectBytes(t.mirror(), secret)).not.toBeNull();100		await fx.strip("secret.txt");101		await syncAll(t);102		for (const id of fx.saveIds) expect(fileAt(t.mirror(), id, "secret.txt")).toBeNull();103		expect(objectBytes(t.mirror(), secret)).toBeNull();104		expect(fileAt(t.mirror(), head(), "src/main.ts")).not.toBeNull();105	});106});107108test("a new save syncs incrementally and a bad format is recorded as the last sync error", async () => {109	const fx = await makeKohBucket("growing");110	const t = await syncTarget(fx);111	await syncAll(t);112	await writeFile(join(fx.repoDir, "new.txt"), "new\n");113	Bun.spawnSync(["koh3", "save", "add new"], {114		cwd: fx.repoDir,115		env: { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" },116	});117	await syncAll(t);118	expect(history(t.mirror(), 1, 0)[0]?.message).toBe("add new");119120	await writeFile(join(fx.bucketDir, fx.repo, "format"), "koh-remote 2");121	await syncAll(t);122	const row = t.kepr.query("SELECT last_sync_error FROM repos").get() as {123		last_sync_error: string;124	};125	expect(row.last_sync_error).toContain('remote format "koh-remote 2"');126});127128describe("the mirror's schema version", () => {129	test("a version 1 mirror reopens and any other version is refused as disposable", async () => {130		const dir = await mkdtemp(join(tmpdir(), "kepr-mirror-"));131		const created = openMirror(dir, "one");132		created.run("PRAGMA wal_checkpoint(TRUNCATE)");133		await Bun.write(join(dir, "copy.db"), Bun.file(join(dir, "one.db")));134		expect(openMirror(dir, "copy").query("PRAGMA user_version").get()).toEqual({135			user_version: 1,136		});137138		const future = new Database(join(dir, "future.db"));139		future.run("PRAGMA user_version = 2");140		future.close();141		expect(() => openMirror(dir, "future")).toThrow("disposable");142	});143});