npm run migrate: the single-library layout copied into a new library with fresh history, every node reference rewritten, the reviewer's verdicts re-keyed, verified node by node before anything is written; --check writes nothing; old files kept in backup-<time>/
Fixtures written by626dc19andc4d6856(tests/fixtures/migrate/make.ts builds them). 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
79aa85e883
commit
d5d0d7563c
16 files changed
+1182
-1
No files matched your search
+2
-1
@@ -12,7 +12,8 @@
|
|||||||
"e2e": "playwright test",
|
"e2e": "playwright test",
|
||||||
"check": "tsc --noEmit",
|
"check": "tsc --noEmit",
|
||||||
"verify": "tsx scripts/verify.ts",
|
"verify": "tsx scripts/verify.ts",
|
||||||
"fixtures": "tsx scripts/fixtures.ts"
|
"fixtures": "tsx scripts/fixtures.ts",
|
||||||
|
"migrate": "tsx server/migrateLibraries.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
|
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
|
||||||
|
|||||||
@@ -0,0 +1,427 @@
|
|||||||
|
/**
|
||||||
|
* From the single-library layout to the libraries layout (libraries.ts), once, when asked:
|
||||||
|
*
|
||||||
|
* npm run migrate migrate IE_DATA (or .data)
|
||||||
|
* npm run migrate -- --check a dry run: build, verify and report, writing nothing
|
||||||
|
* npm run migrate -- [--check] DIR another data directory
|
||||||
|
*
|
||||||
|
* The library's text is what must come across, not its history: the tree is copied, in this
|
||||||
|
* process, into a new library with a new id and a history of one commit ("Bring the library over"),
|
||||||
|
* with `Doc.graft`, which carries everything that is content: titles, bodies, kinds, notes with
|
||||||
|
* their anchors (a note on the root's own text too), who wrote each node, locks, forms and lenses,
|
||||||
|
* targets, declined phrases, the Wikipedia container and its articles' notes, the order of
|
||||||
|
* everything, and the hashes each node was last reconciled with (so nothing turns stale). Every
|
||||||
|
* reference to a node is then rewritten through the map of old ids to new: node targets (links,
|
||||||
|
* cards) get the new id and the titles down to it from the root, as the page would write them; a
|
||||||
|
* target that already named nothing keeps its hint, put in today's form (an old target's document
|
||||||
|
* slug becomes that top's title). Open conflicts come along with their ids rewritten. The link
|
||||||
|
* reviewer's verdicts, people's decisions and pending suggestions (links/pending.json) are
|
||||||
|
* re-keyed to the new ids; vectors are rebuilt when first needed.
|
||||||
|
*
|
||||||
|
* Before anything is written, the copy is checked against the original node by node: the same tree
|
||||||
|
* (each node's parent and children, in order), the same number of nodes, the same title, body,
|
||||||
|
* kind, author, lock, form, lens, flags, declined phrases, anchors (start, end, quoted and current
|
||||||
|
* words) and staleness for each, every target that found its node before finding the same node
|
||||||
|
* (by its new id) now, and the same number of open conflicts. It is checked again after being
|
||||||
|
* written out and read back, and again from the file on disk. Any difference stops the migration
|
||||||
|
* with a report, and the data directory is left as it was.
|
||||||
|
*
|
||||||
|
* Then: the libraries are written to libraries.tmp-<time>/ and renamed to libraries/ (the one step
|
||||||
|
* that commits), and the old files (library/, library.json, links/, vectors/) are moved, unchanged,
|
||||||
|
* into backup-<time>/. Nothing is deleted. wiki-cache/ and models/ stay where they are.
|
||||||
|
*
|
||||||
|
* Not carried: history (every commit before), branches other than main (they stay in the backup,
|
||||||
|
* and the report names them), resolved conflicts, the empty spans of notes already orphaned (the
|
||||||
|
* notes themselves come across), fields of a node no version of this program reads (named in the
|
||||||
|
* report; `slug`, from before documents went, is dropped silently), and vectors.
|
||||||
|
*
|
||||||
|
* Run again, it does nothing (the libraries layout is there and no old files are left). If a
|
||||||
|
* migration stopped after the commit step, a second run only moves the old files aside. It will
|
||||||
|
* not run while a server has the data directory open (lock.ts).
|
||||||
|
*/
|
||||||
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||||
|
import { join, resolve as resolvePath } from "node:path";
|
||||||
|
import { pathToFileURL } from "node:url";
|
||||||
|
import { nodeRef, resolveNode, targetKey } from "../src/core/links";
|
||||||
|
import { Doc, NOLINK, ancestors, isStale, label, notesOf, sections, staleness, topOf, type Conflict, type NodeId, type NodeSnap, type Ref, type Snap } from "../src/core/model";
|
||||||
|
import { canonRef } from "../src/core/ref";
|
||||||
|
import { digest } from "../src/core/text";
|
||||||
|
import { LIBRARIES, OLD_FILES, indexText, layout, stamp, type LibraryEntry } from "./libraries";
|
||||||
|
import { busy } from "./lock";
|
||||||
|
import { dataDir } from "./util";
|
||||||
|
|
||||||
|
export interface MigrateOptions {
|
||||||
|
/** Build, verify and report; write nothing. */
|
||||||
|
check?: boolean;
|
||||||
|
log?: (line: string) => void;
|
||||||
|
/** For the tests: change the new library after it is built, before it is verified. */
|
||||||
|
tamper?: (doc: Doc) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MigrateResult {
|
||||||
|
status: "migrated" | "checked" | "nothing" | "finished" | "refused" | "failed";
|
||||||
|
problems: string[];
|
||||||
|
/** The new library's id, and where the old files went. */
|
||||||
|
library?: string;
|
||||||
|
backup?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fields a node may hold that the copy carries (or that mean nothing without the old history). */
|
||||||
|
const KNOWN = new Set(["kind", "title", "body", "by", "pinned", "form", "lens", "ref", "wanchor", "articles", "up", "down", "anchors", "library"]);
|
||||||
|
/** Fields from older versions that are dropped on purpose. */
|
||||||
|
const DROPPED = new Set(["slug"]);
|
||||||
|
|
||||||
|
type NodeRef = Ref & { kind: "node" };
|
||||||
|
type Pending = Record<string, { at: number; suggestions: { id: string; node: string; range: [number, number]; target: Ref; review?: unknown; decided?: unknown; applied?: unknown }[] }>;
|
||||||
|
|
||||||
|
const MESSAGE = "Bring the library over";
|
||||||
|
|
||||||
|
export function migrateLibraries(dataIn: string, o: MigrateOptions = {}): MigrateResult {
|
||||||
|
const data = resolvePath(dataIn);
|
||||||
|
const log = o.log ?? console.log;
|
||||||
|
const l = layout(data);
|
||||||
|
const what = o.check ? "dry run" : "migration";
|
||||||
|
|
||||||
|
if (l.kind === "empty") {
|
||||||
|
log(`${data}: nothing to migrate (no library here); the server starts it fresh.`);
|
||||||
|
return { status: "nothing", problems: [] };
|
||||||
|
}
|
||||||
|
if (l.kind === "libraries") {
|
||||||
|
log(`${data}: already in the libraries layout; nothing to do.`);
|
||||||
|
return { status: "nothing", problems: [] };
|
||||||
|
}
|
||||||
|
if (l.kind === "older") {
|
||||||
|
const msg = `${data} holds data from before the single library (${l.found.join(", ")}). Open it once with a version from before libraries (commit c4d6856), which brings it into one library, then migrate.`;
|
||||||
|
log(msg);
|
||||||
|
return { status: "refused", problems: [msg] };
|
||||||
|
}
|
||||||
|
const why = busy(data);
|
||||||
|
if (why && !o.check) {
|
||||||
|
const msg = `Refusing to migrate: ${why}. Stop it first.`;
|
||||||
|
log(msg);
|
||||||
|
return { status: "refused", problems: [msg] };
|
||||||
|
}
|
||||||
|
if (why) log(`note: ${why}; a dry run only reads, but stop it before the real run.`);
|
||||||
|
const backupName = `backup-${stamp()}`;
|
||||||
|
if (l.kind === "unfinished" || !existsSync(join(data, "library", "main.loro"))) {
|
||||||
|
// The libraries were written but the old files were not moved; or old files without a library.
|
||||||
|
log(`${data}: ${l.kind === "unfinished" ? "an earlier migration wrote libraries/ but did not move the old files aside" : "no library/main.loro, only old files"}: ${l.found.join(", ")}.`);
|
||||||
|
if (o.check) {
|
||||||
|
log(`${what}: they would be moved into ${join(data, backupName)}/. Nothing was written.`);
|
||||||
|
return { status: "checked", problems: [] };
|
||||||
|
}
|
||||||
|
const backup = moveAside(data, backupName, l.found);
|
||||||
|
log(`Moved them into ${backup}/, unchanged.`);
|
||||||
|
return { status: "finished", problems: [], backup };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- read ----
|
||||||
|
const dir = join(data, "library");
|
||||||
|
const old = Doc.load(readFileSync(join(dir, "main.loro")), "migration");
|
||||||
|
const branches = readdirSync(dir).filter((f) => f.endsWith(".loro") && f !== "main.loro").map((f) => decodeURIComponent(f.slice(0, -5)));
|
||||||
|
let pendingRaw: Pending = {};
|
||||||
|
const pendingFile = join(data, "links", "pending.json");
|
||||||
|
const warnings: string[] = [];
|
||||||
|
if (existsSync(pendingFile)) {
|
||||||
|
try {
|
||||||
|
pendingRaw = JSON.parse(readFileSync(pendingFile, "utf8")) as Pending;
|
||||||
|
} catch (err) {
|
||||||
|
warnings.push(`links/pending.json could not be read (${(err as Error).message}); the reviewer's verdicts are not carried (it stays in the backup)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- build and verify, in memory ----
|
||||||
|
const built = build(old, pendingRaw);
|
||||||
|
warnings.push(...built.warnings);
|
||||||
|
o.tamper?.(built.doc);
|
||||||
|
let problems = verify(old, built.doc, built.ids);
|
||||||
|
if (!problems.length) problems = verify(old, Doc.load(built.doc.snapshotBytes(), "migration"), built.ids).map((p) => `after writing out and reading back: ${p}`);
|
||||||
|
|
||||||
|
const snap = old.snap();
|
||||||
|
log(`${what}: ${data}`);
|
||||||
|
log(` library “${snap.nodes[snap.root].title}”: ${Object.keys(snap.nodes).length} nodes, ${snap.nodes[snap.root].children.length} under the root, ${built.stats.links} node targets (${built.stats.broken} already naming nothing, kept with their hints)`);
|
||||||
|
log(` pending links: ${built.stats.pendingKept} entries carried (${built.stats.decisions} with a verdict or a decision)${built.stats.pendingDropped ? `, ${built.stats.pendingDropped} dropped (their node or target is gone)` : ""}`);
|
||||||
|
log(` conflicts: ${built.stats.openConflicts} open carried${built.stats.resolvedConflicts ? `, ${built.stats.resolvedConflicts} resolved left behind` : ""}`);
|
||||||
|
if (built.stats.orphanSpans) log(` ${built.stats.orphanSpans} empty spans of already orphaned notes not carried (the notes are)`);
|
||||||
|
if (branches.length) log(` branches other than main, not carried (they stay in the backup): ${branches.join(", ")}`);
|
||||||
|
for (const w of warnings) log(` note: ${w}`);
|
||||||
|
if (problems.length) {
|
||||||
|
log(`FAILED: the copy differs from the library in ${problems.length} place${problems.length > 1 ? "s" : ""}; nothing was written.`);
|
||||||
|
for (const p of problems.slice(0, 50)) log(` - ${p}`);
|
||||||
|
if (problems.length > 50) log(` … and ${problems.length - 50} more`);
|
||||||
|
return { status: "failed", problems };
|
||||||
|
}
|
||||||
|
const id = built.doc.libraryId!;
|
||||||
|
log(` verified: same tree, ${built.ids.size} nodes, identical titles, bodies, notes, flags and anchors, every target that resolved resolves to the same node`);
|
||||||
|
if (o.check) {
|
||||||
|
log(`${what}: it would become library ${id} (address /l/${id}); the old files would move into ${join(data, backupName)}/. Nothing was written.`);
|
||||||
|
return { status: "checked", problems: [], library: id };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- write, check what is on disk, commit, move the old files aside ----
|
||||||
|
for (const f of readdirSync(data)) if (f.startsWith(`${LIBRARIES}.tmp-`)) rmSync(join(data, f), { recursive: true, force: true });
|
||||||
|
const tmp = join(data, `${LIBRARIES}.tmp-${stamp()}`);
|
||||||
|
const lib = join(tmp, id);
|
||||||
|
mkdirSync(lib, { recursive: true });
|
||||||
|
writeFileSync(join(lib, "main.loro"), built.doc.snapshotBytes());
|
||||||
|
if (Object.keys(built.pending).length) {
|
||||||
|
mkdirSync(join(lib, "links"));
|
||||||
|
writeFileSync(join(lib, "links", "pending.json"), JSON.stringify(built.pending));
|
||||||
|
}
|
||||||
|
const entry: LibraryEntry = { id, title: built.doc.snap().nodes[built.doc.snap().root].title, created: new Date().toISOString() };
|
||||||
|
writeFileSync(join(tmp, "index.json"), indexText([entry]));
|
||||||
|
const onDisk = verify(old, Doc.load(readFileSync(join(lib, "main.loro")), "migration"), built.ids);
|
||||||
|
if (onDisk.length) {
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
log(`FAILED: the file written differs from the library; nothing was changed.`);
|
||||||
|
for (const p of onDisk.slice(0, 50)) log(` - ${p}`);
|
||||||
|
return { status: "failed", problems: onDisk };
|
||||||
|
}
|
||||||
|
renameSync(tmp, join(data, LIBRARIES));
|
||||||
|
const backup = moveAside(data, backupName, OLD_FILES.filter((f) => existsSync(join(data, f))));
|
||||||
|
log(`Migrated: ${join(data, LIBRARIES, id)} (address /l/${id}).`);
|
||||||
|
log(`The old files are in ${backup}/, unchanged. Pages open on the old library will say to reload.`);
|
||||||
|
return { status: "migrated", problems: [], library: id, backup };
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveAside(data: string, name: string, files: string[]): string {
|
||||||
|
let backup = join(data, name);
|
||||||
|
for (let i = 2; existsSync(backup); i++) backup = join(data, `${name}-${i}`);
|
||||||
|
mkdirSync(backup, { recursive: true });
|
||||||
|
for (const f of files) renameSync(join(data, f), join(backup, f));
|
||||||
|
return backup;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- building the copy ----
|
||||||
|
|
||||||
|
interface Built {
|
||||||
|
doc: Doc;
|
||||||
|
ids: Map<NodeId, NodeId>;
|
||||||
|
pending: Pending;
|
||||||
|
warnings: string[];
|
||||||
|
stats: { links: number; broken: number; pendingKept: number; pendingDropped: number; decisions: number; openConflicts: number; resolvedConflicts: number; orphanSpans: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
function build(old: Doc, pendingRaw: Pending): Built {
|
||||||
|
const src = old.snap();
|
||||||
|
const r = src.nodes[src.root];
|
||||||
|
const doc = Doc.library("server", undefined, r.title);
|
||||||
|
const root = doc.snap().root;
|
||||||
|
const ids = new Map<NodeId, NodeId>([[src.root, root]]);
|
||||||
|
const warnings: string[] = [];
|
||||||
|
const stats = { links: 0, broken: 0, pendingKept: 0, pendingDropped: 0, decisions: 0, openConflicts: 0, resolvedConflicts: 0, orphanSpans: 0 };
|
||||||
|
|
||||||
|
const roots = old.tree.roots().length;
|
||||||
|
if (roots > 1) warnings.push(`the old database has ${roots} roots; only the first (the library, the one every version shows) is carried`);
|
||||||
|
const unknown = new Map<string, number>();
|
||||||
|
for (const id of Object.keys(src.nodes) as NodeId[]) {
|
||||||
|
const n = old.tree.getNodeByID(id);
|
||||||
|
for (const k of Object.keys((n?.data.toJSON() ?? {}) as Record<string, unknown>)) {
|
||||||
|
if (KNOWN.has(k) || DROPPED.has(k) || k.startsWith(NOLINK)) continue;
|
||||||
|
unknown.set(k, (unknown.get(k) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
stats.orphanSpans += src.nodes[id].anchors.filter((a) => a.end <= a.start).length;
|
||||||
|
}
|
||||||
|
if (unknown.size) warnings.push(`fields no version of this program reads, not carried: ${[...unknown].map(([k, n]) => `${k} (${n})`).join(", ")}`);
|
||||||
|
|
||||||
|
doc.begin(MESSAGE, "human", "migrate");
|
||||||
|
const top = doc.tree.getNodeByID(root)!;
|
||||||
|
top.data.set("title", r.title);
|
||||||
|
(top.data.get("body") as { insert(i: number, s: string): void }).insert(0, r.body);
|
||||||
|
top.data.set("by", r.by);
|
||||||
|
top.data.set("pinned", r.pinned);
|
||||||
|
top.data.set("up", r.seenUp);
|
||||||
|
top.data.set("down", r.seenDown);
|
||||||
|
if (r.form) top.data.set("form", r.form);
|
||||||
|
if (r.lens) top.data.set("lens", r.lens);
|
||||||
|
for (const p of r.nolink ?? []) top.data.set(NOLINK + p, 1);
|
||||||
|
doc.mark(root);
|
||||||
|
// The root's children in order, the Wikipedia container among them; a note on the root's own text
|
||||||
|
// keeps its anchors, the new root's text being the same.
|
||||||
|
for (const c of r.children) doc.graft(src, c, root, { keepAnchors: true, ids });
|
||||||
|
doc.mark(root);
|
||||||
|
|
||||||
|
// Node targets, rewritten through the map; written straight into each node's data, as graft
|
||||||
|
// writes, so that no one becomes their author.
|
||||||
|
const now = doc.snap();
|
||||||
|
for (const [was, id] of ids) {
|
||||||
|
const ref = src.nodes[was].ref;
|
||||||
|
if (ref?.kind !== "node") continue;
|
||||||
|
stats.links++;
|
||||||
|
const to = resolveOld(old, src, ref, was);
|
||||||
|
const next = to ? nodeRef(now, ids.get(to)!) : hint(old, src, ref);
|
||||||
|
if (!to) stats.broken++;
|
||||||
|
doc.tree.getNodeByID(id)!.data.set("ref", next as never);
|
||||||
|
doc.mark(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open conflicts, their nodes renamed; a deleted node's id (an edit-delete) is kept, naming nothing in either.
|
||||||
|
for (const c of old.conflicts()) {
|
||||||
|
if (c.status !== "open") {
|
||||||
|
stats.resolvedConflicts++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const map = (x: string | undefined) => (x ? (ids.get(x as NodeId) ?? x) : x);
|
||||||
|
const next: Conflict = { ...c, node: map(c.node) as NodeId, ...(c.other ? { other: map(c.other) as NodeId } : {}), ...(c.parent ? { parent: map(c.parent) as NodeId } : {}) };
|
||||||
|
doc.conflictMap.set(c.id, JSON.stringify(next));
|
||||||
|
stats.openConflicts++;
|
||||||
|
}
|
||||||
|
doc.reread();
|
||||||
|
doc.commit(MESSAGE, "human", "migrate");
|
||||||
|
|
||||||
|
// The link reviewer's verdicts, people's decisions and what is pending, keyed by the new ids.
|
||||||
|
const after = doc.snap();
|
||||||
|
const pending: Pending = {};
|
||||||
|
for (const [node, entry] of Object.entries(pendingRaw)) {
|
||||||
|
const list = Array.isArray(entry?.suggestions) ? entry.suggestions : [];
|
||||||
|
const nn = ids.get(node as NodeId);
|
||||||
|
if (!nn) {
|
||||||
|
stats.pendingDropped += list.length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const out: Pending[string]["suggestions"] = [];
|
||||||
|
for (const s of list) {
|
||||||
|
let target = s.target;
|
||||||
|
if (target?.kind === "node") {
|
||||||
|
const to = resolveOld(old, src, target, node as NodeId);
|
||||||
|
if (!to) {
|
||||||
|
stats.pendingDropped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
target = nodeRef(after, ids.get(to)!);
|
||||||
|
}
|
||||||
|
out.push({ ...s, node: nn, target, id: digest(`${nn}\u0000${s.range[0]}\u0000${s.range[1]}\u0000${targetKey(target)}`) });
|
||||||
|
if (s.review || s.decided || s.applied) stats.decisions++;
|
||||||
|
}
|
||||||
|
stats.pendingKept += out.length;
|
||||||
|
if (out.length) pending[nn] = { at: entry.at, suggestions: out };
|
||||||
|
}
|
||||||
|
return { doc, ids, pending, warnings, stats };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A node's `slug` as older versions stored it (documents were the root's children). */
|
||||||
|
const slugOf = (old: Doc, id: NodeId) => old.tree.getNodeByID(id)?.data.get("slug") as string | undefined;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Walk section titles down from a node, as resolveNode does: exact title first, then ignoring case,
|
||||||
|
* and among sections sharing a title the one `here` is in.
|
||||||
|
*/
|
||||||
|
function walk(snap: Snap, from: NodeId, path: string[], quote: string | undefined, here: NodeId): NodeId | null {
|
||||||
|
const mine = new Set([here, ...ancestors(snap, here)]);
|
||||||
|
let at = from;
|
||||||
|
for (const title of path) {
|
||||||
|
const kids = sections(snap, at);
|
||||||
|
let same = kids.filter((c) => snap.nodes[c].title === title);
|
||||||
|
if (!same.length) same = kids.filter((c) => snap.nodes[c].title.toLowerCase() === title.toLowerCase());
|
||||||
|
if (!same.length) return null;
|
||||||
|
at = same.find((c) => mine.has(c)) ?? same[0];
|
||||||
|
}
|
||||||
|
if (quote === undefined) return at;
|
||||||
|
return notesOf(snap, at).find((c) => snap.nodes[c].anchors.some((a) => a.text === quote || a.quote === quote)) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The node an old target named, read as the version that wrote it would: by id while it exists;
|
||||||
|
* else, with a document slug (before step 1), from the top with that slug; else from the root (as
|
||||||
|
* today), then from the top of where it is written (as relative paths were read before).
|
||||||
|
*/
|
||||||
|
function resolveOld(old: Doc, snap: Snap, ref: NodeRef, here: NodeId): NodeId | null {
|
||||||
|
if (ref.id && snap.nodes[ref.id]) return ref.id;
|
||||||
|
const path = ref.path ?? [];
|
||||||
|
const slug = (ref as { doc?: unknown }).doc;
|
||||||
|
const top = topOf(snap, here);
|
||||||
|
if (typeof slug === "string") {
|
||||||
|
const doc = snap.nodes[snap.root].children.find((c) => slugOf(old, c) === slug);
|
||||||
|
return doc ? walk(snap, doc, path, ref.quote, here) : null;
|
||||||
|
}
|
||||||
|
if (!ref.path) return null;
|
||||||
|
if (ref.rel) return top ? walk(snap, top, path, ref.quote, here) : null;
|
||||||
|
return walk(snap, snap.root, path, ref.quote, here) ?? (top ? walk(snap, top, path, ref.quote, here) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A target that names nothing, in today's form: titles from the root (a slug made the top's title, if that top is still there), no id. */
|
||||||
|
function hint(old: Doc, snap: Snap, ref: NodeRef): NodeRef {
|
||||||
|
const out: NodeRef = { kind: "node", path: [...(ref.path ?? [])] };
|
||||||
|
const slug = (ref as { doc?: unknown }).doc;
|
||||||
|
if (typeof slug === "string") {
|
||||||
|
const doc = snap.nodes[snap.root].children.find((c) => slugOf(old, c) === slug);
|
||||||
|
if (doc) out.path = [snap.nodes[doc].title, ...out.path!];
|
||||||
|
else out.rel = true;
|
||||||
|
} else if (ref.rel) out.rel = true;
|
||||||
|
if (ref.quote !== undefined) out.quote = ref.quote;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- verifying the copy ----
|
||||||
|
|
||||||
|
/** Every difference between the library and its copy that matters, as lines naming the node. */
|
||||||
|
export function verify(old: Doc, neu: Doc, ids: Map<NodeId, NodeId>): string[] {
|
||||||
|
const a = old.snap();
|
||||||
|
const b = neu.snap();
|
||||||
|
const out: string[] = [];
|
||||||
|
const where = (id: NodeId) => {
|
||||||
|
const names: string[] = [];
|
||||||
|
for (let x: NodeId | null = id; x; x = a.nodes[x]?.parent ?? null) names.unshift(clipped(label(a, x)));
|
||||||
|
return `“${names.join(" › ")}”`;
|
||||||
|
};
|
||||||
|
if (!b.library) out.push("the copy is not a library");
|
||||||
|
if (!neu.libraryId || neu.libraryId === old.libraryId) out.push("the copy does not have a library id of its own");
|
||||||
|
const na = Object.keys(a.nodes).length;
|
||||||
|
const nb = Object.keys(b.nodes).length;
|
||||||
|
if (na !== nb) out.push(`node count: ${na} in the library, ${nb} in the copy`);
|
||||||
|
if (ids.get(a.root) !== b.root) out.push("the library's root did not become the copy's root");
|
||||||
|
const seen = new Set<NodeId>();
|
||||||
|
const visit = (id: NodeId) => {
|
||||||
|
const x = a.nodes[id];
|
||||||
|
const nid = ids.get(id);
|
||||||
|
const y = nid ? b.nodes[nid] : undefined;
|
||||||
|
if (!y) return void out.push(`${where(id)} is missing from the copy`);
|
||||||
|
seen.add(nid!);
|
||||||
|
const at = where(id);
|
||||||
|
const want = (x.parent ? ids.get(x.parent) : null) ?? null;
|
||||||
|
if (y.parent !== want) out.push(`${at}: under another parent`);
|
||||||
|
if (y.children.join() !== x.children.map((c) => ids.get(c) ?? "?").join()) out.push(`${at}: children differ (${x.children.length} in the library, ${y.children.length} in the copy, or another order)`);
|
||||||
|
const fields: (keyof NodeSnap)[] = ["kind", "title", "body", "by", "pinned", "form", "lens", "articles", "seenUp", "seenDown"];
|
||||||
|
for (const f of fields) if ((x[f] ?? null) !== (y[f] ?? null)) out.push(`${at}: ${f} differs`);
|
||||||
|
if (JSON.stringify(x.wanchor ?? null) !== JSON.stringify(y.wanchor ?? null)) out.push(`${at}: its place in the article differs`);
|
||||||
|
if ((x.nolink ?? []).join("\u0000") !== (y.nolink ?? []).join("\u0000")) out.push(`${at}: declined phrases differ`);
|
||||||
|
const anchors = (n: NodeSnap) => JSON.stringify(n.anchors.filter((q) => q.end > q.start).map((q) => [q.start, q.end, q.quote, q.text]));
|
||||||
|
if (anchors(x) !== anchors(y)) out.push(`${at}: anchors differ`);
|
||||||
|
const sa = staleness(a, id);
|
||||||
|
const sb = staleness(b, nid!);
|
||||||
|
const dropped = x.anchors.some((q) => q.end <= q.start);
|
||||||
|
if (sa.orphan !== sb.orphan || sa.up !== sb.up || (!dropped && sa.down !== sb.down) || isStale(a, id) !== isStale(b, nid!)) out.push(`${at}: staleness differs`);
|
||||||
|
if ((x.ref?.kind ?? null) !== (y.ref?.kind ?? null)) out.push(`${at}: target differs`);
|
||||||
|
else if (x.ref && y.ref && x.ref.kind !== "node" && JSON.stringify(canonRef(x.ref)) !== JSON.stringify(canonRef(y.ref))) out.push(`${at}: target differs`);
|
||||||
|
else if (x.ref?.kind === "node" && y.ref?.kind === "node") {
|
||||||
|
const to = resolveOld(old, a, x.ref, id);
|
||||||
|
const now = resolveNode(b, y.ref, nid!);
|
||||||
|
if (to && (y.ref.id !== ids.get(to) || now !== ids.get(to))) out.push(`${at}: its link to ${where(to)} does not find that node in the copy`);
|
||||||
|
if (!to && now) out.push(`${at}: a link that named nothing now names ${clipped(label(b, now))}`);
|
||||||
|
if (!to && y.ref.id) out.push(`${at}: a link that named nothing kept an old id`);
|
||||||
|
}
|
||||||
|
x.children.forEach(visit);
|
||||||
|
};
|
||||||
|
visit(a.root);
|
||||||
|
if (seen.size !== nb) out.push(`the copy has ${nb - seen.size} nodes the library does not`);
|
||||||
|
const open = (d: Doc) => d.conflicts().filter((c) => c.status === "open").length;
|
||||||
|
if (open(old) !== open(neu)) out.push(`open conflicts: ${open(old)} in the library, ${open(neu)} in the copy`);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const clipped = (s: string) => (s.length > 40 ? `${s.slice(0, 39)}…` : s);
|
||||||
|
|
||||||
|
// ---- the command ----
|
||||||
|
|
||||||
|
if (process.argv[1] && import.meta.url === pathToFileURL(resolvePath(process.argv[1])).href) {
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const check = args.includes("--check");
|
||||||
|
const unknown = args.filter((a) => a.startsWith("-") && a !== "--check");
|
||||||
|
const dirs = args.filter((a) => !a.startsWith("-"));
|
||||||
|
if (unknown.length || dirs.length > 1) {
|
||||||
|
console.error("usage: npm run migrate [-- [--check] [DATA_DIR]] (DATA_DIR defaults to IE_DATA, else .data)");
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
const r = migrateLibraries(dirs[0] ?? dataDir(), { check });
|
||||||
|
process.exit(r.status === "failed" ? 1 : r.status === "refused" ? 2 : 0);
|
||||||
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"commit": "c4d6856",
|
||||||
|
"first": {
|
||||||
|
"made": {
|
||||||
|
"rootNote": "55200@6511406945601655",
|
||||||
|
"top": "55246@6511406945601655",
|
||||||
|
"first": "55319@6511406945601655",
|
||||||
|
"second": "55462@6511406945601655",
|
||||||
|
"deep": "55614@6511406945601655",
|
||||||
|
"gloss": "55687@6511406945601655",
|
||||||
|
"passage": "55729@6511406945601655",
|
||||||
|
"inner": "55796@6511406945601655",
|
||||||
|
"underNote": "55825@6511406945601655",
|
||||||
|
"orphan": "55864@6511406945601655",
|
||||||
|
"toFixed": "55920@6511406945601655",
|
||||||
|
"toKepler": "55928@6511406945601655",
|
||||||
|
"toWeb": "55936@6511406945601655",
|
||||||
|
"toGloss": "55944@6511406945601655",
|
||||||
|
"noteLink": "55961@6511406945601655",
|
||||||
|
"card": "55995@6511406945601655",
|
||||||
|
"fromOcto": "56005@6511406945601655",
|
||||||
|
"doomed": "56016@6511406945601655",
|
||||||
|
"toDoomed": "56035@6511406945601655",
|
||||||
|
"locked": "3667@6511406945601655",
|
||||||
|
"articles": "56054@6511406945601655",
|
||||||
|
"article": "56061@6511406945601655",
|
||||||
|
"annotation": "56068@6511406945601655"
|
||||||
|
},
|
||||||
|
"scanned": {
|
||||||
|
"first": 1,
|
||||||
|
"approved": 1,
|
||||||
|
"top": 1,
|
||||||
|
"listed": 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"imported": [
|
||||||
|
"infinite-expand",
|
||||||
|
"fixed-points",
|
||||||
|
"octopus-minds"
|
||||||
|
]
|
||||||
|
}
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
|||||||
|
{"55462@6511406945601655":{"at":1794898907309,"suggestions":[{"id":"78b226f461a797bb","node":"55462@6511406945601655","range":[89,109],"quote":"triple-alpha process","key":"triple alpha process","target":{"kind":"wiki","title":"Triple-alpha process","lang":"en"},"score":1,"tier":"auto","why":"fits the text 1.00; a technical term","source":"wikipedia","title":"Triple-alpha process","description":"Nuclear fusion of helium into carbon in stars","kind":"term","review":{"link":true,"reason":"mock: a name or a term a reader may look up","at":1794898907311},"applied":1794898907311,"decided":{"link":true,"by":"reviewer","at":1794898907314}}]},"55246@6511406945601655":{"at":1794898907323,"suggestions":[{"id":"8d4bbd744746d404","node":"55246@6511406945601655","range":[22,29],"quote":"octopus","key":"octopus","target":{"kind":"wiki","title":"Octopus","lang":"en"},"score":0.939,"tier":"suggest","why":"fits the text 0.94; a fairly uncommon word","source":"wikipedia","title":"Octopus","description":"Soft-bodied eight-limbed order of molluscs","kind":"noun","decided":{"link":false,"by":"fixture","at":1794898907326}}]}}
|
||||||
Vendored
+246
@@ -0,0 +1,246 @@
|
|||||||
|
/**
|
||||||
|
* Builds the old-layout data directories that tests/migrateLibraries.test.ts migrates, by running
|
||||||
|
* the server of an older commit on an empty data directory and editing it over HTTP, as a page or
|
||||||
|
* an outside agent would. The result is committed beside this file, so the tests need no git and no
|
||||||
|
* server; run this again only to rebuild them.
|
||||||
|
*
|
||||||
|
* npx tsx tests/fixtures/migrate/make.ts <scratch dir>
|
||||||
|
*
|
||||||
|
* It makes, in <scratch dir>, a git worktree for each commit (node_modules linked to this
|
||||||
|
* checkout's), runs each server with IE_LLM=mock IE_WIKI=mock IE_EMBED=fake on ports 4800-4802, and
|
||||||
|
* writes into tests/fixtures/migrate/:
|
||||||
|
*
|
||||||
|
* pre/ written by 626dc19 (before step 1: documents with slugs, node targets with `doc`)
|
||||||
|
* main/ written by c4d6856 (no documents; node targets by titles from the root)
|
||||||
|
* mixed/ pre/, then opened and edited by c4d6856 (old and new targets side by side)
|
||||||
|
*
|
||||||
|
* Each holds library/main.loro, library.json and links/pending.json; edits.json beside them names
|
||||||
|
* what was made, for the tests to check by.
|
||||||
|
*/
|
||||||
|
import { spawn, execFileSync, type ChildProcess } from "node:child_process";
|
||||||
|
import { cpSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||||
|
import { join, resolve } from "node:path";
|
||||||
|
|
||||||
|
const here = resolve(new URL(".", import.meta.url).pathname);
|
||||||
|
const repo = resolve(here, "../../..");
|
||||||
|
const scratch = resolve(process.argv[2] ?? "");
|
||||||
|
if (!process.argv[2]) throw new Error("give a scratch directory");
|
||||||
|
mkdirSync(scratch, { recursive: true });
|
||||||
|
|
||||||
|
interface Node {
|
||||||
|
id: string;
|
||||||
|
parent: string | null;
|
||||||
|
kind: string;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
slug?: string;
|
||||||
|
children: string[];
|
||||||
|
anchors: { text: string }[];
|
||||||
|
ref?: unknown;
|
||||||
|
articles?: boolean;
|
||||||
|
}
|
||||||
|
interface Tree {
|
||||||
|
root: string;
|
||||||
|
nodes: Record<string, Node>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function worktree(commit: string): string {
|
||||||
|
const dir = join(scratch, `ie-${commit}`);
|
||||||
|
if (!existsSync(dir)) {
|
||||||
|
execFileSync("git", ["-C", repo, "worktree", "add", "--detach", dir, commit], { stdio: "inherit" });
|
||||||
|
symlinkSync(join(repo, "node_modules"), join(dir, "node_modules"));
|
||||||
|
}
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function serve(dir: string, data: string, port: number, library: string): Promise<ChildProcess> {
|
||||||
|
const child = spawn(process.execPath, ["--import", "tsx", "server/index.ts"], {
|
||||||
|
cwd: dir,
|
||||||
|
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: "fixture" },
|
||||||
|
stdio: ["ignore", "inherit", "inherit"],
|
||||||
|
});
|
||||||
|
for (let i = 0; i < 200; i++) {
|
||||||
|
try {
|
||||||
|
if ((await fetch(`http://127.0.0.1:${port}/api/state`)).ok) return child;
|
||||||
|
} catch {
|
||||||
|
/* not up yet */
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, 150));
|
||||||
|
}
|
||||||
|
child.kill("SIGTERM");
|
||||||
|
throw new Error(`the server in ${dir} did not start`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stop(child: ChildProcess) {
|
||||||
|
const done = new Promise((r) => child.once("exit", r));
|
||||||
|
child.kill("SIGTERM");
|
||||||
|
await done;
|
||||||
|
}
|
||||||
|
|
||||||
|
function client(port: number) {
|
||||||
|
const base = `http://127.0.0.1:${port}`;
|
||||||
|
const call = async (path: string, init?: RequestInit) => {
|
||||||
|
const res = await fetch(base + path, init);
|
||||||
|
const body = await res.json();
|
||||||
|
if (!res.ok) throw new Error(`${path}: ${res.status} ${JSON.stringify(body)}`);
|
||||||
|
return body;
|
||||||
|
};
|
||||||
|
const post = (path: string, body: unknown) => call(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||||
|
return {
|
||||||
|
tree: () => call("/api/tree") as Promise<Tree>,
|
||||||
|
ops: async (ops: unknown[], actor: "human" | "llm" = "human") => (await post("/api/ops", { ops, actor, author: "fixture", message: "fixture" })).created as string[],
|
||||||
|
post,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const byTitle = (t: Tree, parent: string, title: string) => {
|
||||||
|
const id = t.nodes[parent].children.find((c) => t.nodes[c].title === title);
|
||||||
|
if (!id) throw new Error(`no “${title}” under ${t.nodes[parent].title}`);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
const top = (t: Tree, title: string) => byTitle(t, t.root, title);
|
||||||
|
|
||||||
|
/** A node target as each version's page made it: with the document's slug and the titles below it, or the titles from the root. */
|
||||||
|
function refTo(t: Tree, id: string, old: boolean, quote?: string) {
|
||||||
|
const path: string[] = [];
|
||||||
|
let sec = id;
|
||||||
|
while (t.nodes[sec].kind === "note") sec = t.nodes[sec].parent!;
|
||||||
|
for (let x = t.nodes[sec]; x.parent; x = t.nodes[x.parent]) path.unshift(x.title);
|
||||||
|
const r: Record<string, unknown> = { kind: "node", id };
|
||||||
|
if (old) {
|
||||||
|
r.doc = t.nodes[top(t, path[0])].slug;
|
||||||
|
r.path = path.slice(1);
|
||||||
|
} else r.path = path;
|
||||||
|
if (quote !== undefined) r.quote = quote;
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The edits both versions get: a tree of every kind of node, link, flag and decision. */
|
||||||
|
async function edits(port: number, old: boolean) {
|
||||||
|
const c = client(port);
|
||||||
|
let t = await c.tree();
|
||||||
|
const seed = top(t, "Infinispand");
|
||||||
|
const octo = top(t, "Octopus minds");
|
||||||
|
const fixed = top(t, "Fixed points");
|
||||||
|
const made: Record<string, string> = {};
|
||||||
|
|
||||||
|
// The root's own text, and a note on it (anchored in the root's body).
|
||||||
|
await c.ops([{ op: "update", id: t.root, body: "Everything I keep. Root words worth a note sit here." }]);
|
||||||
|
[made.rootNote] = await c.ops([{ op: "create", parent: t.root, kind: "note", quote: "Root words", form: "note", lens: "why", body: "A note on the library root itself." }]);
|
||||||
|
|
||||||
|
// A new top with sections, notes on notes, a section under a note, a titled note.
|
||||||
|
[made.top, made.first, made.second, made.deep] = await c.ops(
|
||||||
|
[
|
||||||
|
{ op: "create", parent: t.root, index: 1, title: "Migration notes", body: "Alpha beta gamma. The octopus has three hearts. Delta epsilon zeta." },
|
||||||
|
{ op: "create", parent: "$0", title: "First part", body: "Kepler read about Fixed points. Some plain words here. Freddie Mercury sang while a eukaryote swam past bacteria near the planet Mercury." },
|
||||||
|
{ op: "create", parent: "$0", title: "Second part", body: "Haskell Curry and Fred Hoyle wrote about recursion and stars. The Hoyle state powers the triple-alpha process in stars, and the eukaryote watches." },
|
||||||
|
{ op: "create", parent: "$2", title: "Deep part", body: "Deep text that points elsewhere and at the doomed section." },
|
||||||
|
],
|
||||||
|
"llm",
|
||||||
|
);
|
||||||
|
[made.gloss, made.passage] = await c.ops(
|
||||||
|
[
|
||||||
|
{ op: "create", parent: made.top, kind: "note", quote: "three hearts", form: "gloss", lens: "define", body: "Two pump blood through the gills." },
|
||||||
|
{ op: "create", parent: made.top, kind: "note", quote: "Alpha beta gamma.", form: "passage", body: "A passage about the first letters. It has inner words." },
|
||||||
|
],
|
||||||
|
"llm",
|
||||||
|
);
|
||||||
|
[made.inner] = await c.ops([{ op: "create", parent: made.passage, kind: "note", quote: "inner words", form: "note", lens: "example", body: "A note on a note." }], "llm");
|
||||||
|
[made.underNote] = await c.ops([{ op: "create", parent: made.passage, kind: "section", title: "A section under a note", body: "It hangs from the passage." }], "llm");
|
||||||
|
await c.ops([{ op: "update", id: made.gloss, title: "Hearts, titled" }]);
|
||||||
|
|
||||||
|
// An orphan: a note whose words are then deleted.
|
||||||
|
[made.orphan] = await c.ops([{ op: "create", parent: made.top, kind: "note", quote: "Delta epsilon", form: "note", body: "Its words are about to go." }], "llm");
|
||||||
|
await c.ops([{ op: "update", id: made.top, body: "Alpha beta gamma. The octopus has three hearts. Zeta." }]);
|
||||||
|
|
||||||
|
t = await c.tree();
|
||||||
|
const octoFirst = t.nodes[octo].children.find((x) => t.nodes[x].kind === "section")!;
|
||||||
|
// Links of every kind: to another top, to Wikipedia, to the web, a note that also links, a card, to a note.
|
||||||
|
[made.toFixed, made.toKepler, made.toWeb, made.toGloss] = await c.ops([
|
||||||
|
{ op: "create", parent: made.first, kind: "note", quote: "Fixed points", ref: refTo(t, fixed, old) },
|
||||||
|
{ op: "create", parent: made.first, kind: "note", quote: "Kepler", ref: { kind: "wiki", title: "Johannes Kepler", lang: "en" } },
|
||||||
|
{ op: "create", parent: made.first, kind: "note", quote: "plain words", ref: { kind: "url", url: "https://example.org/page", title: "An example" } },
|
||||||
|
{ op: "create", parent: made.second, kind: "note", quote: "Haskell Curry", ref: refTo(t, made.gloss, old, "three hearts") },
|
||||||
|
]);
|
||||||
|
[made.noteLink] = await c.ops([{ op: "create", parent: made.second, kind: "note", quote: "Fred Hoyle", form: "note", body: "He named the Big Bang.", ref: { kind: "wiki", title: "Fred Hoyle", lang: "en" } }], "llm");
|
||||||
|
[made.card] = await c.ops([{ op: "create", parent: made.second, title: "A card", body: "", ref: refTo(t, octoFirst, old) }]);
|
||||||
|
[made.fromOcto] = await c.ops([{ op: "create", parent: octoFirst, kind: "note", quote: t.nodes[octoFirst].body.split(" ").slice(0, 2).join(" "), ref: refTo(t, made.deep, old) }]);
|
||||||
|
|
||||||
|
// A broken link: its target deleted, so only its hint is left.
|
||||||
|
[made.doomed] = await c.ops([{ op: "create", parent: made.second, title: "Doomed", body: "Soon gone." }]);
|
||||||
|
t = await c.tree();
|
||||||
|
[made.toDoomed] = await c.ops([{ op: "create", parent: made.deep, kind: "note", quote: "doomed section", ref: refTo(t, made.doomed, old) }]);
|
||||||
|
await c.ops([{ op: "delete", id: made.doomed }]);
|
||||||
|
|
||||||
|
// Locks: one set on a model's node, one taken off a person's.
|
||||||
|
const seedFirst = t.nodes[seed].children.find((x) => t.nodes[x].kind === "section")!;
|
||||||
|
made.locked = seedFirst;
|
||||||
|
await c.ops([{ op: "update", id: seedFirst, pinned: true }]);
|
||||||
|
await c.ops([{ op: "update", id: made.top, pinned: false }]);
|
||||||
|
|
||||||
|
// A declined phrase, by op.
|
||||||
|
await c.ops([{ op: "update", id: made.second, nolink: ["recursion"] }]);
|
||||||
|
|
||||||
|
// A Wikipedia article's node with an annotation on it.
|
||||||
|
[made.articles, made.article, made.annotation] = await c.ops([
|
||||||
|
{ op: "create", parent: t.root, kind: "section", title: "Wikipedia", body: "", articles: true },
|
||||||
|
{ op: "create", parent: "$0", kind: "section", title: "Octopus", body: "", ref: { kind: "wiki", title: "Octopus", lang: "en", pageId: 1200106 } },
|
||||||
|
{ op: "create", parent: "$1", kind: "note", body: "Two thirds of the neurons are in the arms.", form: "note", wanchor: { sec: ["Description", "Nervous system and senses"], q: "two thirds of their neurons", pre: "with roughly ", post: " in the arms", rev: 1 } },
|
||||||
|
]);
|
||||||
|
|
||||||
|
// The reviewer's verdicts (the mock links names and rejects single words), approved links made,
|
||||||
|
// a person's decline and decision, and plain pending suggestions.
|
||||||
|
const scan = await c.post("/api/links/scan", { node: made.second, review: "all" });
|
||||||
|
const approved = (scan.apply ?? []).map((s: { id: string }) => s.id);
|
||||||
|
if (approved.length) await c.post("/api/links/accept", { ids: approved, author: "reviewer" });
|
||||||
|
await c.post("/api/links/scan", { node: made.first });
|
||||||
|
const pending = await c.post("/api/links/scan", { node: made.top, save: true });
|
||||||
|
const listed = (await (await fetch(`http://127.0.0.1:${port}/api/links/pending?all=1`)).json()).suggestions as { id: string; quote: string; review?: unknown; decided?: unknown }[];
|
||||||
|
const open = listed.filter((s) => !s.review && !s.decided);
|
||||||
|
if (open[0]) await c.post("/api/links/reject", { ids: [open[0].id], author: "fixture" });
|
||||||
|
if (open[1]) await c.post("/api/links/decide", { ids: [open[1].id], link: false, by: "fixture" });
|
||||||
|
return { made, scanned: { first: scan.suggestions.length, approved: approved.length, top: pending.suggestions.length, listed: listed.length } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What c4d6856 adds to a library pre/ wrote: a new link by root titles, a rename, a new node. */
|
||||||
|
async function laterEdits(port: number) {
|
||||||
|
const c = client(port);
|
||||||
|
const t = await c.tree();
|
||||||
|
const mig = top(t, "Migration notes");
|
||||||
|
const second = byTitle(t, mig, "Second part");
|
||||||
|
const octo = top(t, "Octopus minds");
|
||||||
|
await c.ops([{ op: "update", id: octo, title: "Octopus minds, renamed" }]);
|
||||||
|
const t2 = await c.tree();
|
||||||
|
const [later] = await c.ops([{ op: "create", parent: second, title: "Added later", body: "Written by the newer code, linking stars." }]);
|
||||||
|
const [laterLink] = await c.ops([{ op: "create", parent: later, kind: "note", quote: "stars", ref: refTo(t2, octo, false) }]);
|
||||||
|
return { later, laterLink };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function build(name: string, commit: string, port: number, from?: string, then?: string) {
|
||||||
|
const data = mkdtempSync(join(scratch, `data-${name}-`));
|
||||||
|
if (from) cpSync(from, data, { recursive: true });
|
||||||
|
const lib = mkdtempSync(join(scratch, "lib-"));
|
||||||
|
const dir = worktree(commit);
|
||||||
|
for (const f of ["octopus-minds.md", "fixed-points.md"]) cpSync(join(dir, "library", f), join(lib, f));
|
||||||
|
const child = await serve(dir, data, port, lib);
|
||||||
|
let info: unknown;
|
||||||
|
try {
|
||||||
|
info = from ? await laterEdits(port) : await edits(port, commit === "626dc19");
|
||||||
|
} finally {
|
||||||
|
await stop(child);
|
||||||
|
}
|
||||||
|
const out = join(here, name);
|
||||||
|
rmSync(out, { recursive: true, force: true });
|
||||||
|
mkdirSync(out, { recursive: true });
|
||||||
|
for (const f of ["library", "library.json", "links"]) if (existsSync(join(data, f))) cpSync(join(data, f), join(out, f), { recursive: true });
|
||||||
|
const prior = then ? JSON.parse(execFileSync("cat", [join(here, then, "edits.json")]).toString()) : {};
|
||||||
|
writeFileSync(join(out, "edits.json"), JSON.stringify({ commit, ...prior, ...(from ? { later: info } : { first: info }) }, null, 2) + "\n");
|
||||||
|
rmSync(lib, { recursive: true, force: true });
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pre = await build("pre", "626dc19", 4800);
|
||||||
|
const main = await build("main", "c4d6856", 4801);
|
||||||
|
const mixed = await build("mixed", "c4d6856", 4802, pre, "pre");
|
||||||
|
for (const d of [pre, main, mixed]) rmSync(d, { recursive: true, force: true });
|
||||||
|
console.log("fixtures written to", here);
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"commit": "626dc19",
|
||||||
|
"first": {
|
||||||
|
"made": {
|
||||||
|
"rootNote": "55203@2342252495945464",
|
||||||
|
"top": "55249@2342252495945464",
|
||||||
|
"first": "55323@2342252495945464",
|
||||||
|
"second": "55466@2342252495945464",
|
||||||
|
"deep": "55618@2342252495945464",
|
||||||
|
"gloss": "55691@2342252495945464",
|
||||||
|
"passage": "55733@2342252495945464",
|
||||||
|
"inner": "55800@2342252495945464",
|
||||||
|
"underNote": "55829@2342252495945464",
|
||||||
|
"orphan": "55868@2342252495945464",
|
||||||
|
"toFixed": "55924@2342252495945464",
|
||||||
|
"toKepler": "55932@2342252495945464",
|
||||||
|
"toWeb": "55940@2342252495945464",
|
||||||
|
"toGloss": "55948@2342252495945464",
|
||||||
|
"noteLink": "55965@2342252495945464",
|
||||||
|
"card": "55999@2342252495945464",
|
||||||
|
"fromOcto": "56009@2342252495945464",
|
||||||
|
"doomed": "56020@2342252495945464",
|
||||||
|
"toDoomed": "56039@2342252495945464",
|
||||||
|
"locked": "3668@2342252495945464",
|
||||||
|
"articles": "56058@2342252495945464",
|
||||||
|
"article": "56065@2342252495945464",
|
||||||
|
"annotation": "56072@2342252495945464"
|
||||||
|
},
|
||||||
|
"scanned": {
|
||||||
|
"first": 1,
|
||||||
|
"approved": 1,
|
||||||
|
"top": 1,
|
||||||
|
"listed": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"later": {
|
||||||
|
"later": "4@705515326553021",
|
||||||
|
"laterLink": "54@705515326553021"
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"imported": [
|
||||||
|
"infinite-expand",
|
||||||
|
"fixed-points",
|
||||||
|
"octopus-minds"
|
||||||
|
]
|
||||||
|
}
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
|||||||
|
{"55466@2342252495945464":{"at":1794898906089,"suggestions":[{"id":"d4c0c680082b5ed5","node":"55466@2342252495945464","range":[89,109],"quote":"triple-alpha process","key":"triple alpha process","target":{"kind":"wiki","title":"Triple-alpha process","lang":"en"},"score":1,"tier":"auto","why":"fits the text 1.00; a technical term","source":"wikipedia","title":"Triple-alpha process","description":"Nuclear fusion of helium into carbon in stars","kind":"term","review":{"link":true,"reason":"mock: a name or a term a reader may look up","at":1794898906091},"applied":1794898906091,"decided":{"link":true,"by":"reviewer","at":1794898906094}}]},"55249@2342252495945464":{"at":1794898906103,"suggestions":[{"id":"f758ba6ad795fb36","node":"55249@2342252495945464","range":[22,29],"quote":"octopus","key":"octopus","target":{"kind":"wiki","title":"Octopus","lang":"en"},"score":0.939,"tier":"suggest","why":"fits the text 0.94; a fairly uncommon word","source":"wikipedia","title":"Octopus","description":"Soft-bodied eight-limbed order of molluscs","kind":"noun","decided":{"link":false,"by":"fixture","at":1794898906107}}]}}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"commit": "626dc19",
|
||||||
|
"first": {
|
||||||
|
"made": {
|
||||||
|
"rootNote": "55203@2342252495945464",
|
||||||
|
"top": "55249@2342252495945464",
|
||||||
|
"first": "55323@2342252495945464",
|
||||||
|
"second": "55466@2342252495945464",
|
||||||
|
"deep": "55618@2342252495945464",
|
||||||
|
"gloss": "55691@2342252495945464",
|
||||||
|
"passage": "55733@2342252495945464",
|
||||||
|
"inner": "55800@2342252495945464",
|
||||||
|
"underNote": "55829@2342252495945464",
|
||||||
|
"orphan": "55868@2342252495945464",
|
||||||
|
"toFixed": "55924@2342252495945464",
|
||||||
|
"toKepler": "55932@2342252495945464",
|
||||||
|
"toWeb": "55940@2342252495945464",
|
||||||
|
"toGloss": "55948@2342252495945464",
|
||||||
|
"noteLink": "55965@2342252495945464",
|
||||||
|
"card": "55999@2342252495945464",
|
||||||
|
"fromOcto": "56009@2342252495945464",
|
||||||
|
"doomed": "56020@2342252495945464",
|
||||||
|
"toDoomed": "56039@2342252495945464",
|
||||||
|
"locked": "3668@2342252495945464",
|
||||||
|
"articles": "56058@2342252495945464",
|
||||||
|
"article": "56065@2342252495945464",
|
||||||
|
"annotation": "56072@2342252495945464"
|
||||||
|
},
|
||||||
|
"scanned": {
|
||||||
|
"first": 1,
|
||||||
|
"approved": 1,
|
||||||
|
"top": 1,
|
||||||
|
"listed": 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"imported": [
|
||||||
|
"infinite-expand",
|
||||||
|
"fixed-points",
|
||||||
|
"octopus-minds"
|
||||||
|
]
|
||||||
|
}
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
|||||||
|
{"55466@2342252495945464":{"at":1794898906089,"suggestions":[{"id":"d4c0c680082b5ed5","node":"55466@2342252495945464","range":[89,109],"quote":"triple-alpha process","key":"triple alpha process","target":{"kind":"wiki","title":"Triple-alpha process","lang":"en"},"score":1,"tier":"auto","why":"fits the text 1.00; a technical term","source":"wikipedia","title":"Triple-alpha process","description":"Nuclear fusion of helium into carbon in stars","kind":"term","review":{"link":true,"reason":"mock: a name or a term a reader may look up","at":1794898906091},"applied":1794898906091,"decided":{"link":true,"by":"reviewer","at":1794898906094}}]},"55249@2342252495945464":{"at":1794898906103,"suggestions":[{"id":"f758ba6ad795fb36","node":"55249@2342252495945464","range":[22,29],"quote":"octopus","key":"octopus","target":{"kind":"wiki","title":"Octopus","lang":"en"},"score":0.939,"tier":"suggest","why":"fits the text 0.94; a fairly uncommon word","source":"wikipedia","title":"Octopus","description":"Soft-bodied eight-limbed order of molluscs","kind":"noun","decided":{"link":false,"by":"fixture","at":1794898906107}}]}}
|
||||||
@@ -0,0 +1,371 @@
|
|||||||
|
/**
|
||||||
|
* The migration from the single-library layout (server/migrateLibraries.ts), on data directories
|
||||||
|
* written by older commits (tests/fixtures/migrate, made by make.ts there): pre/ by the code before
|
||||||
|
* documents went, main/ by the code just before libraries, mixed/ by the first then the second.
|
||||||
|
* The text, the notes, the flags and every reference must come across exactly; a dry run writes
|
||||||
|
* nothing; a second run does nothing; a copy that differs leaves the data untouched; the server
|
||||||
|
* will not open the old layout.
|
||||||
|
*/
|
||||||
|
import { spawn, type ChildProcess } from "node:child_process";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join, relative } from "node:path";
|
||||||
|
import { afterAll, describe, expect, it } from "vitest";
|
||||||
|
import { Libraries, layout, readIndex } from "../server/libraries";
|
||||||
|
import { LOCK } from "../server/lock";
|
||||||
|
import { migrateLibraries, type MigrateResult } from "../server/migrateLibraries";
|
||||||
|
import { resolveNode, targetKey } from "../src/core/links";
|
||||||
|
import { Doc, descendants, isStale, type NodeId, type Snap } from "../src/core/model";
|
||||||
|
import { digest } from "../src/core/text";
|
||||||
|
|
||||||
|
const FIXTURES = new URL("./fixtures/migrate/", import.meta.url).pathname;
|
||||||
|
const temps: string[] = [];
|
||||||
|
const temp = () => {
|
||||||
|
const d = mkdtempSync(join(tmpdir(), "ie-migrate-"));
|
||||||
|
temps.push(d);
|
||||||
|
return d;
|
||||||
|
};
|
||||||
|
const children: ChildProcess[] = [];
|
||||||
|
afterAll(() => {
|
||||||
|
for (const c of children) c.kill("SIGKILL");
|
||||||
|
for (const d of temps) rmSync(d, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
interface Edits {
|
||||||
|
first: { made: Record<string, NodeId> };
|
||||||
|
later?: { later: NodeId; laterLink: NodeId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A copy of a fixture's data directory, and what was made in it. */
|
||||||
|
function fixture(name: string): { data: string; edits: Edits } {
|
||||||
|
const data = temp();
|
||||||
|
for (const f of ["library", "library.json", "links"]) cpSync(join(FIXTURES, name, f), join(data, f), { recursive: true });
|
||||||
|
return { data, edits: JSON.parse(readFileSync(join(FIXTURES, name, "edits.json"), "utf8")) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every file under a directory, with a hash of its bytes: to show that nothing was written. */
|
||||||
|
function files(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
const run = (data: string, o: Parameters<typeof migrateLibraries>[1] = {}) => {
|
||||||
|
const lines: string[] = [];
|
||||||
|
const r = migrateLibraries(data, { log: (l) => lines.push(l), ...o });
|
||||||
|
return { ...r, lines } as MigrateResult & { lines: string[] };
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Titles from the root down to a node, its own last: what identifies a node in both libraries. */
|
||||||
|
function pathOf(snap: Snap, id: NodeId): string {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (let x: NodeId | null = id; x; x = snap.nodes[x].parent) out.unshift(`${snap.nodes[x].kind}:${snap.nodes[x].title}#${snap.nodes[x].parent ? snap.nodes[snap.nodes[x].parent!].children.indexOf(x) : 0}`);
|
||||||
|
return out.join(" / ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The new library, read from its file on disk. */
|
||||||
|
const opened = (data: string, id: string) => Doc.load(readFileSync(join(data, "libraries", id, "main.loro")), "test");
|
||||||
|
|
||||||
|
describe.each(["pre", "main", "mixed"])("migrating data written by %s", (name) => {
|
||||||
|
const { data, edits } = fixture(name);
|
||||||
|
const before = files(data);
|
||||||
|
const old = Doc.load(readFileSync(join(data, "library", "main.loro")), "test");
|
||||||
|
const a = old.snap();
|
||||||
|
const made = edits.first.made;
|
||||||
|
|
||||||
|
// What the fixture's reviewer did not produce: a suggestion to a node, one rejected and one undecided.
|
||||||
|
const pending = JSON.parse(readFileSync(join(data, "links", "pending.json"), "utf8"));
|
||||||
|
const sugg = (quote: string, start: number, extra: object) => ({
|
||||||
|
id: `old-${quote}`,
|
||||||
|
node: made.second,
|
||||||
|
range: [start, start + quote.length],
|
||||||
|
quote,
|
||||||
|
key: quote.toLowerCase(),
|
||||||
|
target: { kind: "node", id: made.deep, path: ["Migration notes", "Second part", "Deep part"] },
|
||||||
|
score: 0.9,
|
||||||
|
tier: "suggest",
|
||||||
|
why: "test",
|
||||||
|
source: "library",
|
||||||
|
title: "Deep part",
|
||||||
|
description: null,
|
||||||
|
kind: "title",
|
||||||
|
...extra,
|
||||||
|
});
|
||||||
|
const body2 = a.nodes[made.second].body;
|
||||||
|
pending[made.second] = {
|
||||||
|
at: 1,
|
||||||
|
suggestions: [
|
||||||
|
...(pending[made.second]?.suggestions ?? []),
|
||||||
|
sugg("Haskell Curry", body2.indexOf("Haskell Curry"), { review: { link: false, reason: "test: no", at: 2 } }),
|
||||||
|
sugg("stars", body2.indexOf("stars"), {}),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
// A suggestion whose node is gone is dropped.
|
||||||
|
pending[made.doomed] = { at: 1, suggestions: [sugg("Soon", 0, { node: made.doomed })] };
|
||||||
|
writeFileSync(join(data, "links", "pending.json"), JSON.stringify(pending));
|
||||||
|
const withPending = files(data);
|
||||||
|
|
||||||
|
it("refuses to open in the server, and a dry run verifies and writes nothing", () => {
|
||||||
|
expect(layout(data).kind).toBe("old");
|
||||||
|
expect(() => new Libraries(data, () => {}).open(() => {})).toThrow(/npm run migrate/);
|
||||||
|
const r = run(data, { check: true });
|
||||||
|
expect(r.problems).toEqual([]);
|
||||||
|
expect(r.status).toBe("checked");
|
||||||
|
expect(r.lines.join("\n")).toMatch(/verified: same tree/);
|
||||||
|
expect(r.lines.join("\n")).toMatch(/Nothing was written/);
|
||||||
|
expect(files(data)).toEqual(withPending);
|
||||||
|
expect(before).not.toEqual(withPending); // (the test's own pending entries, above)
|
||||||
|
});
|
||||||
|
|
||||||
|
it("migrates: the same tree, text, notes, flags and anchors under new ids, in a new library", () => {
|
||||||
|
const r = run(data);
|
||||||
|
expect(r.problems).toEqual([]);
|
||||||
|
expect(r.status).toBe("migrated");
|
||||||
|
expect(layout(data).kind).toBe("libraries");
|
||||||
|
const index = readIndex(join(data, "libraries"));
|
||||||
|
expect(index).toEqual([{ id: r.library, title: "Library", created: expect.any(String) }]);
|
||||||
|
// The old files, moved aside unchanged.
|
||||||
|
const backup = files(r.backup!);
|
||||||
|
for (const [f, h] of Object.entries(withPending)) expect(backup[f], f).toBe(h);
|
||||||
|
expect(existsSync(join(data, "library"))).toBe(false);
|
||||||
|
|
||||||
|
const neu = opened(data, r.library!);
|
||||||
|
const b = neu.snap();
|
||||||
|
expect(neu.libraryId).toBe(r.library);
|
||||||
|
expect(neu.libraryId).not.toBe(old.libraryId);
|
||||||
|
expect(b.library).toBe(true);
|
||||||
|
// Node for node, by place: the same titles, bodies, kinds, authors, locks, notes and anchors.
|
||||||
|
const rows = (s: Snap) =>
|
||||||
|
Object.keys(s.nodes)
|
||||||
|
.map((id) => {
|
||||||
|
const n = s.nodes[id as NodeId];
|
||||||
|
return [pathOf(s, id as NodeId), n.kind, n.title, n.body, n.by, n.pinned, n.form ?? null, n.lens ?? null, n.articles ?? false, JSON.stringify(n.wanchor ?? null), (n.nolink ?? []).join("|"), n.anchors.filter((x) => x.end > x.start).map((x) => `${x.start}-${x.end}:${x.quote}:${x.text}`).join("|"), isStale(s, id as NodeId)].join("\u0000");
|
||||||
|
})
|
||||||
|
.sort();
|
||||||
|
expect(rows(b)).toEqual(rows(a));
|
||||||
|
// No old id is left anywhere in the new library's nodes.
|
||||||
|
const oldIds = new Set(Object.keys(a.nodes));
|
||||||
|
for (const n of Object.values(b.nodes)) {
|
||||||
|
expect(oldIds.has(n.id)).toBe(false);
|
||||||
|
if (n.ref?.kind === "node" && n.ref.id) expect(b.nodes[n.ref.id], `${n.title}'s target`).toBeTruthy();
|
||||||
|
}
|
||||||
|
// A history of its own: nothing from before.
|
||||||
|
expect(neu.loro.getAllChanges().size).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("carries what the tests made: the root's note, locks, the article and its note, the orphan, declines", () => {
|
||||||
|
const r = migrateLibraries(data, { log: () => {} }); // a second run: nothing to do
|
||||||
|
expect(r.status).toBe("nothing");
|
||||||
|
const id = readIndex(join(data, "libraries"))[0].id;
|
||||||
|
const b = opened(data, id).snap();
|
||||||
|
const find = (title: string, kind = "section") => Object.values(b.nodes).find((n) => n.title === title && n.kind === kind)!;
|
||||||
|
const root = b.nodes[b.root];
|
||||||
|
expect(root.body).toBe("Everything I keep. Root words worth a note sit here.");
|
||||||
|
const rootNote = root.children.map((c) => b.nodes[c]).find((n) => n.kind === "note")!;
|
||||||
|
expect(rootNote.anchors.map((x) => x.text)).toEqual(["Root words"]);
|
||||||
|
expect(rootNote.body).toBe("A note on the library root itself.");
|
||||||
|
expect(b.nodes[root.children[0]].title).toBe("Infinispand");
|
||||||
|
expect(b.nodes[root.children[1]].title).toBe("Migration notes");
|
||||||
|
// Locks: set on a model's node, taken off a person's.
|
||||||
|
const seed = find("Infinispand");
|
||||||
|
expect(b.nodes[seed.children.find((c) => b.nodes[c].kind === "section")!].pinned).toBe(true);
|
||||||
|
expect(find("Migration notes").pinned).toBe(false);
|
||||||
|
// The Wikipedia container, its article and the note on the article.
|
||||||
|
const box = root.children.map((c) => b.nodes[c]).find((n) => n.articles)!;
|
||||||
|
expect(box.title).toBe("Wikipedia");
|
||||||
|
const art = b.nodes[box.children[0]];
|
||||||
|
expect(art.ref).toEqual({ kind: "wiki", title: "Octopus", lang: "en", pageId: 1200106 });
|
||||||
|
expect(b.nodes[art.children[0]].wanchor?.q).toBe("two thirds of their neurons");
|
||||||
|
// The orphan keeps its text; the titled note its title; the section under a note its place.
|
||||||
|
const top = find("Migration notes");
|
||||||
|
const notes = top.children.map((c) => b.nodes[c]).filter((n) => n.kind === "note");
|
||||||
|
expect(notes.map((n) => n.body)).toContain("Its words are about to go.");
|
||||||
|
expect(find("Hearts, titled", "note").anchors[0].text).toBe("three hearts");
|
||||||
|
expect(b.nodes[find("A section under a note").parent!].form).toBe("passage");
|
||||||
|
expect(find("Second part").nolink).toContain("recursion");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rewrites every node target to the new ids, and keeps a broken one's hint", () => {
|
||||||
|
const id = readIndex(join(data, "libraries"))[0].id;
|
||||||
|
const b = opened(data, id).snap();
|
||||||
|
const find = (title: string) => Object.values(b.nodes).find((n) => n.title === title)!;
|
||||||
|
// The links the tests made, in the top they made.
|
||||||
|
const mine = new Set(descendants(b, find("Migration notes").id));
|
||||||
|
const linkOn = (quote: string) => Object.values(b.nodes).find((n) => mine.has(n.id) && n.kind === "note" && n.anchors.some((x) => x.text === quote) && n.ref)!;
|
||||||
|
const target = (quote: string) => {
|
||||||
|
const n = linkOn(quote);
|
||||||
|
expect(n.ref?.kind).toBe("node");
|
||||||
|
return resolveNode(b, n.ref as never, n.id);
|
||||||
|
};
|
||||||
|
expect(target("Fixed points")).toBe(Object.values(b.nodes).find((n) => n.parent === b.root && n.title === "Fixed points")!.id);
|
||||||
|
expect(b.nodes[target("Haskell Curry")!].title).toBe("Hearts, titled");
|
||||||
|
expect(linkOn("Haskell Curry").ref).toMatchObject({ quote: "three hearts", path: ["Migration notes"] });
|
||||||
|
expect(linkOn("Fred Hoyle").ref).toEqual({ kind: "wiki", title: "Fred Hoyle", lang: "en" });
|
||||||
|
expect(linkOn("plain words").ref).toEqual({ kind: "url", url: "https://example.org/page", title: "An example" });
|
||||||
|
const card = find("A card");
|
||||||
|
expect(b.nodes[resolveNode(b, card.ref as never, card.id)!].parent).toBe(Object.values(b.nodes).find((n) => n.parent === b.root && n.title.startsWith("Octopus minds"))!.id);
|
||||||
|
// From a starter tree into the new top.
|
||||||
|
const octo = Object.values(b.nodes).find((n) => n.parent === b.root && n.title.startsWith("Octopus minds"))!;
|
||||||
|
const octoFirst = b.nodes[octo.children.find((c) => b.nodes[c].kind === "section")!];
|
||||||
|
const fromOcto = octoFirst.children.map((c) => b.nodes[c]).find((n) => n.ref?.kind === "node")!;
|
||||||
|
expect(b.nodes[resolveNode(b, fromOcto.ref as never, fromOcto.id)!].title).toBe("Deep part");
|
||||||
|
// The link to the deleted section: still naming nothing, with its titles from the root and no id.
|
||||||
|
const broken = linkOn("doomed section");
|
||||||
|
expect(broken.ref).toEqual({ kind: "node", path: ["Migration notes", "Second part", "Doomed"] });
|
||||||
|
expect(resolveNode(b, broken.ref as never, broken.id)).toBeNull();
|
||||||
|
if (name === "mixed") {
|
||||||
|
// The link the newer code made, to a top renamed since.
|
||||||
|
expect(b.nodes[target("stars")!].title).toBe("Octopus minds, renamed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("re-keys the reviewer's verdicts, people's decisions and pending suggestions to the new ids", () => {
|
||||||
|
const id = readIndex(join(data, "libraries"))[0].id;
|
||||||
|
const b = opened(data, id).snap();
|
||||||
|
const carried = JSON.parse(readFileSync(join(data, "libraries", id, "links", "pending.json"), "utf8")) as Record<string, { suggestions: { id: string; node: NodeId; range: [number, number]; quote: string; target: { kind: string; id?: NodeId }; review?: { link: boolean }; decided?: { link: boolean } }[] }>;
|
||||||
|
const all = Object.entries(carried).flatMap(([k, e]) => e.suggestions.map((s) => ({ k, ...s })));
|
||||||
|
// Every entry under its new node, its words where they were, its id made from the new ids.
|
||||||
|
for (const s of all) {
|
||||||
|
expect(s.k).toBe(s.node);
|
||||||
|
expect(b.nodes[s.node].body.slice(s.range[0], s.range[1])).toBe(s.quote);
|
||||||
|
expect(s.id).toBe(digest(`${s.node}\u0000${s.range[0]}\u0000${s.range[1]}\u0000${targetKey(s.target as never)}`));
|
||||||
|
}
|
||||||
|
const by = (quote: string) => all.find((s) => s.quote === quote)!;
|
||||||
|
expect(by("triple-alpha process").review?.link).toBe(true);
|
||||||
|
expect(by("triple-alpha process").decided?.link).toBe(true);
|
||||||
|
expect(by("octopus").decided?.link).toBe(false);
|
||||||
|
expect(by("Haskell Curry").review?.link).toBe(false);
|
||||||
|
expect(b.nodes[by("Haskell Curry").target.id!].title).toBe("Deep part");
|
||||||
|
expect(b.nodes[by("stars").target.id!].title).toBe("Deep part");
|
||||||
|
expect(by("stars").review).toBeUndefined();
|
||||||
|
expect(all.some((s) => s.quote === "Soon")).toBe(false); // its node was deleted
|
||||||
|
// And the server opens the result as it is.
|
||||||
|
const libs = new Libraries(data, () => {}).open(() => {
|
||||||
|
throw new Error("must not seed a migrated library");
|
||||||
|
});
|
||||||
|
expect(libs.first().id).toBe(id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the migration's guards", () => {
|
||||||
|
it("leaves the data untouched when the copy differs, and says where", () => {
|
||||||
|
const { data } = fixture("pre");
|
||||||
|
const before = files(data);
|
||||||
|
const r = run(data, {
|
||||||
|
tamper: (doc) => {
|
||||||
|
const snap = doc.snap();
|
||||||
|
const id = Object.values(snap.nodes).find((n) => n.title === "Deep part")!.id;
|
||||||
|
doc.apply([{ op: "update", id, body: "Changed." }], "tamper");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(r.status).toBe("failed");
|
||||||
|
expect(r.problems.some((p) => /“Library › Migration notes › Second part › Deep part”: body differs/.test(p))).toBe(true);
|
||||||
|
expect(r.lines.join("\n")).toMatch(/FAILED: .*nothing was written/);
|
||||||
|
expect(files(data)).toEqual(before);
|
||||||
|
expect(readdirSync(data).sort()).toEqual(["library", "library.json", "links"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("finishes a migration that stopped before moving the old files, and cleans a leftover temporary directory", () => {
|
||||||
|
const { data } = fixture("main");
|
||||||
|
mkdirSync(join(data, "libraries.tmp-20200101-000000", "x"), { recursive: true });
|
||||||
|
const first = run(data);
|
||||||
|
expect(first.status).toBe("migrated");
|
||||||
|
expect(readdirSync(data).some((f) => f.startsWith("libraries.tmp-"))).toBe(false);
|
||||||
|
// As if the run had stopped after the commit step: the old files back in place.
|
||||||
|
cpSync(join(first.backup!, "library"), join(data, "library"), { recursive: true });
|
||||||
|
cpSync(join(first.backup!, "links"), join(data, "links"), { recursive: true });
|
||||||
|
expect(layout(data).kind).toBe("unfinished");
|
||||||
|
expect(() => new Libraries(data, () => {}).open(() => {})).toThrow(/did not finish/);
|
||||||
|
const check = files(data);
|
||||||
|
expect(run(data, { check: true }).status).toBe("checked");
|
||||||
|
expect(files(data)).toEqual(check);
|
||||||
|
const again = run(data);
|
||||||
|
expect(again.status).toBe("finished");
|
||||||
|
expect(layout(data).kind).toBe("libraries");
|
||||||
|
expect(existsSync(join(again.backup!, "library", "main.loro"))).toBe(true);
|
||||||
|
expect(run(data).status).toBe("nothing");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("carries open conflicts with their nodes renamed, reports other branches and unknown fields, drops slugs", () => {
|
||||||
|
const data = temp();
|
||||||
|
const old = Doc.library("old");
|
||||||
|
const [top, sec] = old.apply(
|
||||||
|
[
|
||||||
|
{ op: "create", parent: old.snap().root, title: "Top", body: "Text." },
|
||||||
|
{ op: "create", parent: "$0" as NodeId, title: "Section", body: "More." },
|
||||||
|
],
|
||||||
|
"make",
|
||||||
|
).created;
|
||||||
|
old.begin("raw", "human");
|
||||||
|
old.tree.getNodeByID(top)!.data.set("slug", "top");
|
||||||
|
old.tree.getNodeByID(sec)!.data.set("color", "red");
|
||||||
|
old.conflictMap.set("c1", JSON.stringify({ id: "c1", type: "edit-edit", node: sec, field: "body", title: "Section", base: "b", a: "x", b: "y", merged: "xy", status: "open" }));
|
||||||
|
old.conflictMap.set("c2", JSON.stringify({ id: "c2", type: "edit-edit", node: sec, field: "title", title: "Section", base: "b", a: "x", b: "y", merged: "xy", status: "resolved" }));
|
||||||
|
old.commit("raw", "human");
|
||||||
|
mkdirSync(join(data, "library"));
|
||||||
|
writeFileSync(join(data, "library", "main.loro"), old.snapshotBytes());
|
||||||
|
writeFileSync(join(data, "library", "draft.loro"), old.snapshotBytes());
|
||||||
|
const r = run(data);
|
||||||
|
expect(r.problems).toEqual([]);
|
||||||
|
const text = r.lines.join("\n");
|
||||||
|
expect(text).toMatch(/branches other than main, not carried .*: draft/);
|
||||||
|
expect(text).toMatch(/fields no version of this program reads, not carried: color \(1\)/);
|
||||||
|
expect(text).not.toMatch(/slug/);
|
||||||
|
expect(text).toMatch(/1 open carried, 1 resolved left behind/);
|
||||||
|
const neu = opened(data, r.library!);
|
||||||
|
const s = neu.snap();
|
||||||
|
const newSec = Object.values(s.nodes).find((n) => n.title === "Section")!.id;
|
||||||
|
expect(neu.conflicts()).toEqual([expect.objectContaining({ id: "c1", node: newSec, status: "open" })]);
|
||||||
|
expect(existsSync(join(r.backup!, "library", "draft.loro"))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does nothing on an empty directory, and refuses the layout from before the single library", () => {
|
||||||
|
const empty = temp();
|
||||||
|
expect(run(empty).status).toBe("nothing");
|
||||||
|
expect(readdirSync(empty)).toEqual([]);
|
||||||
|
const older = temp();
|
||||||
|
mkdirSync(join(older, "docs", "tides"), { recursive: true });
|
||||||
|
const r = run(older);
|
||||||
|
expect(r.status).toBe("refused");
|
||||||
|
expect(r.problems[0]).toMatch(/c4d6856/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses to run while a server has the data open: by its lock, or, for a server from before locks, by its checkout", async () => {
|
||||||
|
// A stand-in server: a process whose command line names server/index.ts.
|
||||||
|
const checkout = temp();
|
||||||
|
const data = join(checkout, ".data");
|
||||||
|
cpSync(join(FIXTURES, "pre", "library"), join(data, "library"), { recursive: true });
|
||||||
|
const sleeper = (cwd: string) => {
|
||||||
|
const c = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)", "server/index.ts"], { cwd, stdio: "ignore" });
|
||||||
|
children.push(c);
|
||||||
|
return c;
|
||||||
|
};
|
||||||
|
const old = sleeper(checkout);
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
const r = run(data);
|
||||||
|
expect(r.status).toBe("refused");
|
||||||
|
expect(r.problems[0]).toMatch(new RegExp(`pid ${old.pid}`));
|
||||||
|
// A dry run is allowed: it writes nothing.
|
||||||
|
expect(run(data, { check: true }).status).toBe("checked");
|
||||||
|
old.kill("SIGKILL");
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
// A server with a lock, running from elsewhere.
|
||||||
|
const elsewhere = temp();
|
||||||
|
const locked = sleeper(elsewhere);
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
writeFileSync(join(data, LOCK), JSON.stringify({ pid: locked.pid, port: 4999 }));
|
||||||
|
expect(run(data).problems[0]).toMatch(new RegExp(`pid ${locked.pid}, port 4999`));
|
||||||
|
locked.kill("SIGKILL");
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
// A stale lock is no obstacle.
|
||||||
|
expect(run(data).status).toBe("migrated");
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user