Several libraries on the server: one directory, store, notice stream, link index, pending links, reviewer and jobs each; /api/libraries and /api/l/<id>/…; the page holds one library, named by its address, and switches by a page load
The old single-library layout is not opened (the server says to run the migration, which comes next); the per-document migration, /recover and the old replicas check are gone. A server lock keeps two servers off one data directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
1 parent
045a8459da
commit
79aa85e883
22 files changed
+1468
-759
No files matched your search
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Several libraries: the registry on disk (server/libraries.ts), and the server's routes for them,
|
||||
* driven over HTTP as a page or an outside agent would (a real server, on a temporary data
|
||||
* directory). Nothing of one library may reach another: not an op, a sync, a link suggestion, a
|
||||
* nearby or Related list, a pending entry or a vector.
|
||||
*/
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { Libraries, readIndex } from "../server/libraries";
|
||||
import { LOCK } from "../server/lock";
|
||||
import { Doc } from "../src/core/model";
|
||||
|
||||
const ROOT = new URL("..", import.meta.url).pathname;
|
||||
const temps: string[] = [];
|
||||
const temp = () => {
|
||||
const d = mkdtempSync(join(tmpdir(), "ie-libs-"));
|
||||
temps.push(d);
|
||||
return d;
|
||||
};
|
||||
const servers: ChildProcess[] = [];
|
||||
afterAll(() => {
|
||||
for (const s of servers) s.kill("SIGKILL");
|
||||
for (const d of temps) rmSync(d, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("the libraries on disk", () => {
|
||||
it("makes, lists, renames and deletes libraries, each in its own directory; the last one stays", () => {
|
||||
const data = temp();
|
||||
const libs = new Libraries(data, () => {}).open((doc) => doc.apply([{ op: "create", parent: doc.snap().root, title: "Seeded", body: "Text." }], "seed"));
|
||||
const first = libs.first();
|
||||
const work = libs.create(" Work notes ");
|
||||
expect(work.title).toBe("Work notes");
|
||||
expect(work.titles()).toEqual([]);
|
||||
expect(work.id).not.toBe(first.id);
|
||||
expect(libs.list().map((l) => [l.title, l.nodes])).toEqual([
|
||||
["Library", 2],
|
||||
["Work notes", 1],
|
||||
]);
|
||||
// An op on one never touches the other: separate databases, separate files.
|
||||
const hash = first.main.stateHash();
|
||||
work.main.apply([{ op: "create", parent: work.main.snap().root, title: "Only here", body: "" }], "add");
|
||||
work.save("main");
|
||||
expect(first.main.stateHash()).toBe(hash);
|
||||
expect(existsSync(join(data, "libraries", work.id, "main.loro"))).toBe(true);
|
||||
// Renamed: a commit on its root's title, which the list reads.
|
||||
libs.rename(work.id, "Work");
|
||||
expect(work.main.snap().nodes[work.main.snap().root].title).toBe("Work");
|
||||
expect(libs.list()[1].title).toBe("Work");
|
||||
// A rename made in a replica (the root's title edited) shows in the list and the index.
|
||||
first.main.apply([{ op: "update", id: first.main.snap().root, title: "Mine" }], "rename");
|
||||
first.save("main");
|
||||
expect(libs.list()[0].title).toBe("Mine");
|
||||
expect(readIndex(join(data, "libraries"))[0].title).toBe("Mine");
|
||||
// Deleted: moved aside whole, still listed in the index as deleted, gone from the list.
|
||||
const moved = libs.remove(work.id);
|
||||
expect(moved).toContain(join("libraries", ".deleted", `${work.id}-`));
|
||||
expect(existsSync(join(moved, "main.loro"))).toBe(true);
|
||||
expect(existsSync(join(data, "libraries", work.id))).toBe(false);
|
||||
expect(libs.list().map((l) => l.id)).toEqual([first.id]);
|
||||
expect(readIndex(join(data, "libraries"))[1]).toMatchObject({ id: work.id, deleted: expect.any(String), movedTo: expect.stringContaining(".deleted") });
|
||||
expect(() => libs.remove(first.id)).toThrow(/last library/);
|
||||
// Opened again: the same libraries, the deleted one left out, nothing seeded.
|
||||
first.flush();
|
||||
const again = new Libraries(data, () => {}).open(() => {
|
||||
throw new Error("must not seed again");
|
||||
});
|
||||
expect(again.list().map((l) => [l.id, l.title])).toEqual([[first.id, "Mine"]]);
|
||||
});
|
||||
|
||||
it("refuses a title that is empty or too long", () => {
|
||||
const libs = new Libraries(temp(), () => {}).open(() => {});
|
||||
expect(() => libs.create(" ")).toThrow(/title/);
|
||||
expect(() => libs.create("x".repeat(201))).toThrow(/200/);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- the server ----
|
||||
|
||||
const PORT = 4804;
|
||||
const base = `http://127.0.0.1:${PORT}`;
|
||||
|
||||
function serve(data: string, library: string, port = PORT): { child: ChildProcess; out: string[]; exited: Promise<number | null> } {
|
||||
const out: string[] = [];
|
||||
const child = spawn(process.execPath, ["--import", "tsx", "server/index.ts"], {
|
||||
cwd: ROOT,
|
||||
env: { ...process.env, IE_PROD: "1", IE_LLM: "mock", IE_MOCK_DELAY: "0", IE_WIKI: "mock", IE_EMBED: "fake", IE_DATA: data, IE_LIBRARY: library, PORT: String(port), IE_USER: "tester" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
servers.push(child);
|
||||
child.stdout!.on("data", (d) => out.push(String(d)));
|
||||
child.stderr!.on("data", (d) => out.push(String(d)));
|
||||
const exited = new Promise<number | null>((r) => child.once("exit", (code) => r(code)));
|
||||
return { child, out, exited };
|
||||
}
|
||||
|
||||
async function up() {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
try {
|
||||
if ((await fetch(`${base}/api/libraries`)).ok) return;
|
||||
} catch {
|
||||
/* not yet */
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
throw new Error("the server did not start");
|
||||
}
|
||||
|
||||
const get = async (path: string) => (await fetch(base + path)).json();
|
||||
const send = (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) => fetch(base + path, { method, headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
const ops = async (lib: string, list: unknown[]) => {
|
||||
const res = await send("POST", `/api/l/${lib}/ops`, { ops: list, author: "test", actor: "human" });
|
||||
expect(res.status).toBe(200);
|
||||
return (await res.json()).created as string[];
|
||||
};
|
||||
|
||||
describe("the server with several libraries", () => {
|
||||
it("will not open a data directory in the old layout: one line saying to run the migration, and nothing written", async () => {
|
||||
const data = temp();
|
||||
cpSync(new URL("./fixtures/migrate/main/library", import.meta.url).pathname, join(data, "library"), { recursive: true });
|
||||
const before = readdirSync(data).sort();
|
||||
const s = serve(data, temp());
|
||||
expect(await s.exited).toBe(1);
|
||||
const text = s.out.join("").trim();
|
||||
expect(text.split("\n")).toHaveLength(1);
|
||||
expect(text).toMatch(/old single-library layout.*npm run migrate/);
|
||||
expect(readdirSync(data).sort()).toEqual(before);
|
||||
}, 30_000);
|
||||
|
||||
it("keeps libraries apart: ops, syncs, link suggestions, nearby, Related, pending entries and vectors", async () => {
|
||||
const data = temp();
|
||||
const starters = temp();
|
||||
writeFileSync(join(starters, "tides.md"), "# Tides\n\nThe sea rises and falls twice a day, pulled by the Moon.\n\n## Tidal locking\n\nA body that always shows the same face to what it orbits.\n");
|
||||
const s = serve(data, starters);
|
||||
await up();
|
||||
// An empty data directory: one library, with the seed and the starter trees.
|
||||
const [a] = (await get("/api/libraries")).libraries;
|
||||
expect(a.title).toBe("Library");
|
||||
const treeA = await get(`/api/l/${a.id}/tree`);
|
||||
const topsA = treeA.nodes[treeA.root].children.map((c: string) => treeA.nodes[c].title);
|
||||
expect(topsA).toEqual(["Infinispand", "Tides"]);
|
||||
// The unprefixed routes are the first library's.
|
||||
expect((await get("/api/tree")).library).toBe(a.id);
|
||||
expect((await get("/api/state")).library).toBe(a.id);
|
||||
expect(existsSync(join(data, LOCK))).toBe(true);
|
||||
|
||||
// A new library: its root alone, under the given title.
|
||||
const made = await send("POST", "/api/libraries", { title: "Second" });
|
||||
expect(made.status).toBe(201);
|
||||
const b = (await made.json()).library;
|
||||
expect(b).toMatchObject({ title: "Second", nodes: 1 });
|
||||
const state = await get(`/api/l/${b.id}/state`);
|
||||
expect(state).toMatchObject({ library: b.id, title: "Second" });
|
||||
expect(state.libraries.map((l: { id: string }) => l.id)).toEqual([a.id, b.id]);
|
||||
// The same titles as the first library's, and text that names them.
|
||||
const rootB = (await get(`/api/l/${b.id}/tree`)).root;
|
||||
const [tidesB, lockingB, moon] = await ops(b.id, [
|
||||
{ op: "create", parent: rootB, title: "Tides", body: "Water moving under the pull of the Moon and the Sun." },
|
||||
{ op: "create", parent: "$0", title: "Tidal locking", body: "A body that always shows the same face to what it orbits, as the Moon does to Earth." },
|
||||
{ op: "create", parent: rootB, title: "Moon", body: "The Moon shows one face to Earth because of tidal locking, which slowed its spin." },
|
||||
]);
|
||||
const after = await get(`/api/l/${a.id}/tree`);
|
||||
expect(Object.keys(after.nodes).length).toBe(Object.keys(treeA.nodes).length);
|
||||
expect(after.history[0].message).toBe(treeA.history[0].message);
|
||||
const treeB = await get(`/api/l/${b.id}/tree`);
|
||||
expect(Object.keys(treeB.nodes)).toHaveLength(4);
|
||||
for (const id of Object.keys(treeB.nodes)) expect(after.nodes[id]).toBeUndefined();
|
||||
|
||||
// A replica of one library cannot sync into the other.
|
||||
const bytes = Doc.library("x").snapshotBytes();
|
||||
const foreign = await fetch(`${base}/api/l/${b.id}/sync/main`, { method: "POST", headers: { "x-library": a.id, "x-vv": "[]" }, body: bytes as BodyInit });
|
||||
expect(foreign.status).toBe(409);
|
||||
// A node of one library is not found under the other's prefix.
|
||||
expect((await send("GET", `/api/l/${b.id}/nodes/${encodeURIComponent(treeA.root)}/tree`)).status).toBe(404);
|
||||
expect((await send("GET", "/api/l/nosuchlibrary/tree")).status).toBe(404);
|
||||
|
||||
// Link discovery in the second library proposes its own nodes only.
|
||||
const scan = await (await send("POST", `/api/l/${b.id}/links/scan`, { node: moon })).json();
|
||||
const nodeTargets = scan.suggestions.filter((x: { target: { kind: string } }) => x.target.kind === "node");
|
||||
expect(nodeTargets.length).toBeGreaterThan(0);
|
||||
for (const x of nodeTargets) expect(treeB.nodes[x.target.id]).toBeTruthy();
|
||||
expect(nodeTargets.map((x: { target: { id: string } }) => x.target.id)).toEqual([lockingB]);
|
||||
expect(treeB.nodes[tidesB].title).toBe("Tides");
|
||||
const related = await get(`/api/l/${b.id}/links/related?node=${encodeURIComponent(moon)}`);
|
||||
for (const r of related.related) expect(treeB.nodes[r.node]).toBeTruthy();
|
||||
const nearby = await get(`/api/l/${b.id}/links/nearby?node=${encodeURIComponent(moon)}&k=10`);
|
||||
expect(nearby.nearby.length).toBeGreaterThan(0);
|
||||
for (const n of nearby.nearby) expect(treeB.nodes[n.handle]).toBeTruthy();
|
||||
// And the first library's lists never name the second's nodes.
|
||||
const tidesA = treeA.nodes[treeA.root].children.find((c: string) => treeA.nodes[c].title === "Tides");
|
||||
const nearA = await get(`/api/l/${a.id}/links/nearby?node=${encodeURIComponent(tidesA)}&k=10`);
|
||||
for (const n of nearA.nearby) expect(treeA.nodes[n.handle]).toBeTruthy();
|
||||
// Pending entries and vectors are kept in each library's own directory.
|
||||
await new Promise((r) => setTimeout(r, 900));
|
||||
const pendingB = JSON.parse(readFileSync(join(data, "libraries", b.id, "links", "pending.json"), "utf8"));
|
||||
expect(Object.keys(pendingB)).toEqual([moon]);
|
||||
expect(existsSync(join(data, "libraries", a.id, "links", "pending.json"))).toBe(false);
|
||||
const vecB = JSON.parse(readFileSync(join(data, "libraries", b.id, "vectors", "nodes.json"), "utf8"));
|
||||
const vecA = JSON.parse(readFileSync(join(data, "libraries", a.id, "vectors", "nodes.json"), "utf8"));
|
||||
const ids = (v: unknown) => JSON.stringify(v);
|
||||
for (const id of Object.keys(treeB.nodes)) expect(ids(vecA)).not.toContain(id);
|
||||
for (const id of Object.keys(treeA.nodes)) expect(ids(vecB)).not.toContain(id);
|
||||
expect(existsSync(join(data, "links"))).toBe(false);
|
||||
expect(existsSync(join(data, "vectors"))).toBe(false);
|
||||
|
||||
// Renamed, then deleted: moved aside, its routes gone; the last library stays.
|
||||
expect((await send("PATCH", `/api/libraries/${b.id}`, { title: "Second, renamed" })).status).toBe(200);
|
||||
expect((await get(`/api/l/${b.id}/tree`)).nodes[rootB].title).toBe("Second, renamed");
|
||||
const del = await send("DELETE", `/api/libraries/${b.id}`);
|
||||
expect(del.status).toBe(200);
|
||||
const { movedTo } = await del.json();
|
||||
expect(existsSync(join(movedTo, "main.loro"))).toBe(true);
|
||||
expect(existsSync(join(movedTo, "links", "pending.json"))).toBe(true);
|
||||
expect((await send("GET", `/api/l/${b.id}/state`)).status).toBe(404);
|
||||
expect((await get("/api/libraries")).libraries.map((l: { id: string }) => l.id)).toEqual([a.id]);
|
||||
expect((await send("DELETE", `/api/libraries/${a.id}`)).status).toBe(409);
|
||||
|
||||
// A second server on the same data is refused while the first runs.
|
||||
const second = serve(data, starters, PORT + 1);
|
||||
expect(await second.exited).toBe(1);
|
||||
expect(second.out.join("")).toMatch(/Another server \(pid \d+, port 4804\)/);
|
||||
// Stopped, the first lets go of its lock; started again, the same library, nothing seeded twice.
|
||||
s.child.kill("SIGTERM");
|
||||
await s.exited;
|
||||
expect(existsSync(join(data, LOCK))).toBe(false);
|
||||
const again = serve(data, starters);
|
||||
await up();
|
||||
const listed = (await get("/api/libraries")).libraries;
|
||||
expect(listed.map((l: { id: string; nodes: number }) => [l.id, l.nodes])).toEqual([[a.id, Object.keys(treeA.nodes).length]]);
|
||||
again.child.kill("SIGTERM");
|
||||
await again.exited;
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* Migration from one database per document (and from the single-document layout before that) to
|
||||
* one library: every document's content equal, histories kept, conflicts still open, the old files
|
||||
* untouched, and a second start that does nothing.
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, relative } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LibraryStore } from "../server/library";
|
||||
import { Doc, descendants, isStale, tops, type NodeId } from "../src/core/model";
|
||||
import { at, history, mergeBranch, revertSubtreeTo, revertTo, verifyHistory } from "../src/core/repo";
|
||||
|
||||
const temp = () => mkdtempSync(join(tmpdir(), "ie-migrate-"));
|
||||
|
||||
/** A document as the per-document version made them: a single tree, with notes, a pin and a form. */
|
||||
function oldDoc(title: string) {
|
||||
const doc = Doc.create("alice", title, "Alpha is first. Beta is second. Gamma is third.");
|
||||
const root = doc.snap().root;
|
||||
doc.apply(
|
||||
[
|
||||
{ op: "create", parent: root, title: "One", body: "The first child, with a phrase worth a note." },
|
||||
{ op: "create", parent: root, title: "Two", body: "The second child." },
|
||||
{ op: "create", parent: root, kind: "note", quote: "Beta", form: "gloss", lens: "define", body: "the second letter" },
|
||||
{ op: "create", parent: "$0" as NodeId, kind: "note", quote: "a phrase worth a note", form: "passage", body: "A passage." },
|
||||
{ op: "bless", id: root },
|
||||
],
|
||||
"Pre-generate",
|
||||
{ actor: "llm" },
|
||||
);
|
||||
return doc;
|
||||
}
|
||||
|
||||
/** Every file under a directory, with a hash of its bytes. */
|
||||
function sums(dir: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
const walk = (d: string) => {
|
||||
for (const f of readdirSync(d)) {
|
||||
const p = join(d, f);
|
||||
if (statSync(p).isDirectory()) walk(p);
|
||||
else out[relative(dir, p)] = createHash("sha256").update(readFileSync(p)).digest("hex");
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
return out;
|
||||
}
|
||||
|
||||
function write(data: string, id: string, branches: Record<string, Doc>, mtime: number) {
|
||||
const dir = join(data, "docs", id);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const [name, doc] of Object.entries(branches)) {
|
||||
writeFileSync(join(dir, `${encodeURIComponent(name)}.loro`), doc.snapshotBytes());
|
||||
utimesSync(join(dir, `${encodeURIComponent(name)}.loro`), mtime, mtime);
|
||||
}
|
||||
writeFileSync(join(dir, "meta.json"), JSON.stringify({ uid: createHash("md5").update(id).digest("hex").slice(0, 12), created: "2026-11-01T00:00:00Z" }));
|
||||
}
|
||||
|
||||
describe("migration from the per-document layout", () => {
|
||||
it("builds one library from every document's main branch, keeping content, histories and open conflicts, and touches nothing old", () => {
|
||||
const data = temp();
|
||||
// The first document, with work on it: a human edit (a pin), and an open conflict from a merge.
|
||||
const first = oldDoc("Infinite Expand");
|
||||
const one = first.snap().nodes[first.snap().root].children[0];
|
||||
first.apply([{ op: "update", id: one, body: "A person rewrote this, keeping a phrase worth a note." }], "Human edit");
|
||||
const bob = first.fork("bob");
|
||||
first.apply([{ op: "update", id: one, title: "One, says main" }], "Main retitles");
|
||||
bob.apply([{ op: "update", id: one, title: "One, says bob" }], "Bob retitles");
|
||||
mergeBranch(first, bob, "bob");
|
||||
expect(first.conflicts().filter((c) => c.status === "open")).toHaveLength(1);
|
||||
const alt = first.fork();
|
||||
alt.apply([{ op: "update", id: alt.snap().root, title: "On alt" }], "alt edit");
|
||||
const tides = oldDoc("The tides");
|
||||
// A duplicate began as a byte copy of another document, so it shares that document's history.
|
||||
const copy = Doc.load(tides.snapshotBytes(), "x");
|
||||
copy.apply([{ op: "update", id: copy.snap().root, title: "The tides (copy)" }], "Duplicate");
|
||||
write(data, "infinite-expand", { main: first, alt }, 1_700_000_000);
|
||||
write(data, "tides", { main: tides }, 1_700_000_300);
|
||||
write(data, "tides-copy", { main: copy }, 1_700_000_200);
|
||||
writeFileSync(join(data, "library.json"), JSON.stringify({ imported: ["infinite-expand", "tides"] }));
|
||||
const before = sums(data);
|
||||
const oldCommits = history(first).length;
|
||||
|
||||
const logs: string[] = [];
|
||||
const store = new LibraryStore(data, (m) => logs.push(m)).open();
|
||||
const lib = store.main;
|
||||
const snap = lib.snap();
|
||||
|
||||
// One library: the first document first, then most recently changed first.
|
||||
expect(snap.library).toBe(true);
|
||||
expect(store.titles()).toEqual(["Infinite Expand", "The tides", "The tides (copy)"]);
|
||||
const [nFirst, nTides, nCopy] = tops(snap);
|
||||
for (const [node, old] of [[nFirst, first], [nTides, tides], [nCopy, copy]] as const) {
|
||||
expect(lib.shape(snap, node)).toBe(old.shape());
|
||||
// Exactly what was stale before is stale now (the first document's edits left its root out of date).
|
||||
const was = old.snap();
|
||||
expect([node, ...descendants(snap, node)].filter((n) => isStale(snap, n)).length).toBe(Object.keys(was.nodes).filter((n) => isStale(was, n as NodeId)).length);
|
||||
}
|
||||
expect(isStale(snap, snap.root)).toBe(false);
|
||||
// Kept documents keep their node ids, so anchors and conflict records still point at them.
|
||||
expect(nFirst).toBe(first.snap().root);
|
||||
expect(nTides).toBe(tides.snap().root);
|
||||
expect(nCopy).not.toBe(copy.snap().root);
|
||||
expect(lib.conflicts().filter((c) => c.status === "open").map((c) => c.node)).toEqual([one]);
|
||||
expect(snap.nodes[one].pinned).toBe(true);
|
||||
|
||||
// The first document's history is the library's history from before it existed, and verifies.
|
||||
const h = history(lib);
|
||||
expect(h[0]).toMatchObject({ tag: "migrate", message: "Gather 3 documents into the library" });
|
||||
expect(h.filter((c) => ["Human edit", "Main retitles", "Bob retitles"].includes(c.message) || c.message.startsWith("Merge bob"))).toHaveLength(4);
|
||||
expect(h.length).toBe(oldCommits + history(tides).length + 1); // the copy's history is not carried
|
||||
expect(verifyHistory(lib)).toMatchObject({ unhashed: 0, mismatches: [] });
|
||||
const then = at(lib, h.find((c) => c.message === "Human edit")!).snap();
|
||||
expect(then.library).toBe(false);
|
||||
expect(then.nodes[then.root].title).toBe("Infinite Expand");
|
||||
expect(then.nodes[one].body).toBe("A person rewrote this, keeping a phrase worth a note.");
|
||||
// Reverting the whole library to before it existed is refused; reverting the document to then works.
|
||||
const humanEdit = h.find((c) => c.message === "Human edit")!;
|
||||
expect(() => revertTo(lib, humanEdit)).toThrow(/before the library existed/);
|
||||
revertSubtreeTo(lib, humanEdit, first.snap().root);
|
||||
expect(lib.snap().nodes[one].title).toBe("One");
|
||||
expect(lib.shape(lib.snap(), nTides)).toBe(tides.shape());
|
||||
expect(verifyHistory(lib).mismatches).toEqual([]);
|
||||
|
||||
// The old directory is renamed, every byte as it was; the record says what was and was not carried.
|
||||
const moved = readdirSync(data).find((f) => f.startsWith("docs.migrated-"))!;
|
||||
expect(existsSync(join(data, "docs"))).toBe(false);
|
||||
const after = sums(data);
|
||||
for (const [file, hash] of Object.entries(before)) expect(after[file.replace(/^docs\//, `${moved}/`)]).toBe(hash);
|
||||
const record = JSON.parse(readFileSync(join(data, "library", "migrated.json"), "utf8"));
|
||||
expect(record.docs.map((d: { slug: string; history: string }) => [d.slug, d.history])).toEqual([["infinite-expand", "kept"], ["tides", "kept"], ["tides-copy", "copied"]]);
|
||||
expect(record.branchesNotCarried).toEqual([{ doc: "infinite-expand", branch: "alt" }]);
|
||||
expect(Object.keys(record.docs[0].versions).sort()).toEqual(["alt", "main"]);
|
||||
expect(logs.join("\n")).toMatch(/infinite-expand: alt/);
|
||||
expect(logs.join("\n")).toMatch(/tides-copy .*copied as content/);
|
||||
|
||||
// A second start is a no-op.
|
||||
store.save("main");
|
||||
const settled = sums(data);
|
||||
const again: string[] = [];
|
||||
const store2 = new LibraryStore(data, (m) => again.push(m)).open();
|
||||
expect(again).toEqual([]);
|
||||
expect(sums(data)).toEqual(settled);
|
||||
expect(store2.main.stateHash()).toBe(lib.stateHash());
|
||||
});
|
||||
|
||||
it("migrates the single-document layout's flat files the same way", () => {
|
||||
const data = temp();
|
||||
const main = oldDoc("Infinite Expand");
|
||||
const alt = main.fork();
|
||||
alt.apply([{ op: "update", id: alt.snap().root, title: "On alt" }], "alt edit");
|
||||
writeFileSync(join(data, "main.loro"), main.snapshotBytes());
|
||||
writeFileSync(join(data, "my%20branch.loro"), alt.snapshotBytes());
|
||||
writeFileSync(join(data, "notes.txt"), "not a branch");
|
||||
const logs: string[] = [];
|
||||
const store = new LibraryStore(data, (m) => logs.push(m)).open();
|
||||
const snap = store.main.snap();
|
||||
expect(store.titles()).toEqual(["Infinite Expand"]);
|
||||
expect(store.main.shape(snap, tops(snap)[0])).toBe(main.shape());
|
||||
expect(readdirSync(data).filter((f) => f.endsWith(".loro"))).toEqual([]);
|
||||
expect(existsSync(join(data, "notes.txt"))).toBe(true); // anything else is left alone
|
||||
const flat = readdirSync(data).find((f) => f.startsWith("flat.migrated-"))!;
|
||||
expect(readdirSync(join(data, flat)).sort()).toEqual(["main.loro", "my%20branch.loro"]);
|
||||
expect(readFileSync(join(data, flat, "main.loro")).equals(Buffer.from(main.snapshotBytes()))).toBe(true);
|
||||
expect(logs.join("\n")).toMatch(/infinite-expand: my branch/);
|
||||
});
|
||||
|
||||
it("starts a fresh library when there is nothing to migrate", () => {
|
||||
const data = temp();
|
||||
const store = new LibraryStore(data, () => {}).open();
|
||||
expect(store.main.snap().library).toBe(true);
|
||||
expect(store.titles()).toEqual([]);
|
||||
expect(readdirSync(data)).toEqual(["library"]);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -85,7 +85,7 @@ describe("a large library", () => {
|
||||
mkdirSync(join(data, "library"));
|
||||
writeFileSync(join(data, "library", "main.loro"), bytes);
|
||||
t = performance.now();
|
||||
const store = new LibraryStore(data, () => {}).open();
|
||||
const store = new LibraryStore(join(data, "library")).open();
|
||||
expect(store.titles()).toHaveLength(100);
|
||||
const serverStart = performance.now() - t;
|
||||
|
||||
|
||||
+70
-27
@@ -1,11 +1,11 @@
|
||||
/** The library on disk (seeding and starter files), and a node with everything under it: imported, exported, copied, moved and addressed wherever it is. */
|
||||
/** The libraries on disk (seeding and starter files), and a node with everything under it: imported, exported, copied, moved and addressed wherever it is. */
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LibraryStore } from "../server/library";
|
||||
import { Libraries, importStarters, readIndex } from "../server/libraries";
|
||||
import { FormatError, serializeDoc } from "../src/core/format";
|
||||
import { address, resolve } from "../src/core/address";
|
||||
import { LIBRARY_ID, address, inLibrary, resolve, splitLibrary } from "../src/core/address";
|
||||
import { resolveNode } from "../src/core/links";
|
||||
import { Doc, descendants, isStale, sections, staleness, tops } from "../src/core/model";
|
||||
import { SEED_TITLE, importTree, writeSeed } from "../src/core/seed";
|
||||
@@ -16,46 +16,39 @@ const temp = () => mkdtempSync(join(tmpdir(), "ie-lib-"));
|
||||
const quiet = () => {};
|
||||
const MD = (title: string) => `# ${title}\n\nA root body with a phrase.\n\n## One\n\nSection text.\n\n^ "Section" gloss: a note\n`;
|
||||
|
||||
describe("the library on disk", () => {
|
||||
describe("the libraries on disk", () => {
|
||||
it("starts an empty data directory as one library with the first tree, written once", () => {
|
||||
const data = temp();
|
||||
const store = new LibraryStore(data, quiet).open();
|
||||
store.seedFirst((doc) => writeSeed(doc, prompt, seed));
|
||||
let seeded = 0;
|
||||
const libs = new Libraries(data, quiet).open((doc) => (seeded++, writeSeed(doc, prompt, seed)));
|
||||
const store = libs.first();
|
||||
expect(seeded).toBe(1);
|
||||
expect(store.titles()).toEqual([SEED_TITLE]);
|
||||
expect(store.main.snap().library).toBe(true);
|
||||
expect(JSON.parse(readFileSync(join(data, "library.json"), "utf8")).imported).toEqual(["infinite-expand"]);
|
||||
expect(readIndex(join(data, "libraries")).map((e) => e.id)).toEqual([store.id]);
|
||||
store.flush();
|
||||
// A second start loads the same library (same id) and writes nothing new.
|
||||
const again = new LibraryStore(data, quiet).open();
|
||||
again.seedFirst(() => {
|
||||
// A second start loads the same library (same id) and seeds nothing.
|
||||
const again = new Libraries(data, quiet).open(() => {
|
||||
throw new Error("should not seed twice");
|
||||
});
|
||||
expect(again.id).toBe(store.id);
|
||||
expect(again.main.stateHash()).toBe(store.main.stateHash());
|
||||
expect(again.first().id).toBe(store.id);
|
||||
expect(again.first().main.stateHash()).toBe(store.main.stateHash());
|
||||
});
|
||||
|
||||
it("imports each starter file once, as a child of the root; a deleted one stays deleted and a broken one is skipped", () => {
|
||||
it("writes the starter files, in file name order, into the first library only; a broken one is skipped", () => {
|
||||
const data = temp();
|
||||
const lib = temp();
|
||||
writeFileSync(join(lib, "good-one.md"), MD("Good one"));
|
||||
writeFileSync(join(lib, "Second File.md"), MD("Second"));
|
||||
writeFileSync(join(lib, "broken.md"), MD("Broken").replace('"Section"', '"Missing"'));
|
||||
const logs: string[] = [];
|
||||
const store = new LibraryStore(data, (m) => logs.push(m)).open();
|
||||
store.importLibrary(lib);
|
||||
expect(store.titles()).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
|
||||
const libs = new Libraries(data, quiet).open((doc) => importStarters(doc, lib, (m) => logs.push(m)));
|
||||
expect(libs.first().titles()).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
|
||||
expect(logs.join("\n")).toMatch(/skipped broken\.md:\n {2}library\/broken\.md:9: in “One”: quote not found: "Missing"/);
|
||||
|
||||
const good = tops(store.main.snap()).find((id) => store.main.snap().nodes[id].title === "Good one")!;
|
||||
store.main.apply([{ op: "delete", id: good }], "Delete “Good one”");
|
||||
store.save("main");
|
||||
const again = new LibraryStore(data, quiet).open();
|
||||
again.importLibrary(lib);
|
||||
expect(again.titles()).toEqual(["Second"]);
|
||||
// Once fixed, the broken file is picked up.
|
||||
writeFileSync(join(lib, "broken.md"), MD("Broken"));
|
||||
again.importLibrary(lib);
|
||||
expect(again.titles()).toEqual(["Second", "Broken"]);
|
||||
// A new library starts with its root alone, whatever the starter directory holds.
|
||||
const work = libs.create("Work");
|
||||
expect(work.titles()).toEqual([]);
|
||||
expect(work.title).toBe("Work");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -136,4 +129,54 @@ describe("a node and everything under it, wherever it is", () => {
|
||||
expect(resolve(lib.snap(), "/doc/tides")).toEqual({ missing: "no page /doc/tides" });
|
||||
expect(resolve(lib.snap(), "/n/%E0%A4%A")).toMatchObject({ missing: expect.any(String) });
|
||||
});
|
||||
|
||||
it("is addressed under its library: /l/<library>/n/<id>; an address without a library is read in the one last used", () => {
|
||||
expect(inLibrary("abc", "/")).toBe("/l/abc");
|
||||
expect(inLibrary("abc", "/n/1%402")).toBe("/l/abc/n/1%402");
|
||||
expect(splitLibrary("/l/abc")).toEqual({ library: "abc", part: "/" });
|
||||
expect(splitLibrary("/l/abc/n/1%402")).toEqual({ library: "abc", part: "/n/1%402" });
|
||||
expect(splitLibrary("/l/abc/w/en/Octopus")).toEqual({ library: "abc", part: "/w/en/Octopus" });
|
||||
expect(splitLibrary("/")).toEqual({ library: null, part: "/" });
|
||||
expect(splitLibrary("/n/1%402")).toEqual({ library: null, part: "/n/1%402" });
|
||||
expect(splitLibrary("/doc/tides")).toEqual({ library: null, part: "/doc/tides" });
|
||||
const lib = Doc.library("alice");
|
||||
expect(LIBRARY_ID.test(lib.libraryId!)).toBe(true);
|
||||
});
|
||||
|
||||
it("is copied into another library whole by graft: flags, notes on the root's text, and a map of old ids to new", () => {
|
||||
const from = Doc.library("alice");
|
||||
const root = from.snap().root;
|
||||
const [top, , box] = from.apply(
|
||||
[
|
||||
{ op: "update", id: root, body: "Root text with words." },
|
||||
{ op: "create", parent: root, title: "Top", body: "Some text." },
|
||||
{ op: "create", parent: root, kind: "note", quote: "words", body: "On the root." },
|
||||
{ op: "create", parent: root, kind: "section", title: "Wikipedia", body: "", articles: true },
|
||||
],
|
||||
"make",
|
||||
).created;
|
||||
from.apply([{ op: "update", id: top, pinned: false, nolink: ["text"] }], "flags");
|
||||
const src = from.snap();
|
||||
const into = Doc.library("bob");
|
||||
const to = into.snap().root;
|
||||
into.begin("copy", "human");
|
||||
(into.tree.getNodeByID(to)!.data.get("body") as { insert(i: number, t: string): void }).insert(0, src.nodes[root].body);
|
||||
const ids = new Map();
|
||||
for (const c of src.nodes[root].children) into.graft(src, c, to, { keepAnchors: true, ids });
|
||||
into.commit("copy", "human");
|
||||
const got = into.snap();
|
||||
expect(ids.size).toBe(3);
|
||||
const note = got.nodes[ids.get(src.nodes[root].children[1])];
|
||||
expect(note.anchors.map((a) => a.text)).toEqual(["words"]);
|
||||
expect(got.nodes[ids.get(box)].articles).toBe(true);
|
||||
expect(got.nodes[ids.get(top)]).toMatchObject({ title: "Top", pinned: false, nolink: ["text"] });
|
||||
// Without keepAnchors, a note at the top of a graft into another text loses its anchors, as before.
|
||||
into.begin("again", "human");
|
||||
const lone = into.graft(src, src.nodes[root].children[1], to);
|
||||
into.commit("again", "human");
|
||||
expect(into.snap().nodes[lone].anchors).toEqual([]);
|
||||
// The Wikipedia flag goes only where create allows it: under a library root.
|
||||
const nested = from.apply([{ op: "copy", id: box, parent: top }], "copy box").created[0];
|
||||
expect(from.snap().nodes[nested].articles).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user