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,284 @@
|
||||
/**
|
||||
* Everything the server keeps for one library, and the routes that act on it. Each library has its
|
||||
* own store, notice stream, node index (vectors), pending links, link reviewer and background jobs,
|
||||
* all bound to that library's database alone, so nothing one library holds can reach a request
|
||||
* about another: a route finds its library first and is handed only that library's bundle.
|
||||
*
|
||||
* What is shared holds no library's content: the model, Wikipedia (and its cache) and the embedding
|
||||
* model.
|
||||
*
|
||||
* Routes, after /api/l/<id>/ (or after /api/ for the first library):
|
||||
*
|
||||
* GET state what the page needs to start
|
||||
* GET events the library's notice stream (server-sent events)
|
||||
* GET branch/<b>, POST sync/<b> what replicas use
|
||||
* GET tree[/<b>], POST ops[/<b>] the op API
|
||||
* GET nodes/<id>/tree|export[/<b>], POST nodes/<id>/import
|
||||
* … links/* link discovery (links/routes.ts)
|
||||
*/
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { join } from "node:path";
|
||||
import { VersionVector } from "loro-crdt";
|
||||
import { FormatError, serializeDoc } from "../src/core/format";
|
||||
import { Doc, OpError, descendants, type NodeId, type Op } from "../src/core/model";
|
||||
import { encodeVV, history } from "../src/core/repo";
|
||||
import { IMPORT_MAX, importTree } from "../src/core/seed";
|
||||
import { slugify } from "../src/core/text";
|
||||
import type { LLM } from "../src/llm/types";
|
||||
import type { Embedder } from "./embed";
|
||||
import { LibraryStore, validBranch } from "./library";
|
||||
import { Jobs } from "./links/jobs";
|
||||
import { NodeIndex } from "./links/nodeIndex";
|
||||
import { PendingStore } from "./links/pending";
|
||||
import { Reviewer } from "./links/review";
|
||||
import { linkRoutes } from "./links/routes";
|
||||
import { Linker } from "./links/scan";
|
||||
import { HttpError, readBody, readJson, sendJson as json } from "./util";
|
||||
import type { WikiClient } from "./wiki";
|
||||
|
||||
/** What every library's bundle is given: shared, and holding no library's content. */
|
||||
export interface Shared {
|
||||
llm: () => LLM | null;
|
||||
wiki: () => WikiClient | null;
|
||||
embed: Embedder | null;
|
||||
reviewCalls: number;
|
||||
user: string;
|
||||
/** What /state says besides the library's own part. */
|
||||
state: () => Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Largest replica update a sync accepts. */
|
||||
const SYNC_MAX = 256 * 1024 * 1024;
|
||||
|
||||
const vvHeader = (doc: Doc) => encodeVV(doc.loro.version().toJSON());
|
||||
|
||||
export class Bundle {
|
||||
readonly listeners = new Set<ServerResponse>();
|
||||
readonly nodeIndex: NodeIndex;
|
||||
readonly pending: PendingStore;
|
||||
readonly reviewer: Reviewer;
|
||||
readonly jobs: Jobs;
|
||||
private linker: Linker | null = null;
|
||||
private handleLinks: ReturnType<typeof linkRoutes>;
|
||||
|
||||
constructor(
|
||||
readonly store: LibraryStore,
|
||||
private shared: Shared,
|
||||
) {
|
||||
const main = () => store.main;
|
||||
// The embedding model is loaded on first use, in a worker thread shared by every library; each
|
||||
// library's vectors are its own. Pending suggestions are derived data, kept beside the library.
|
||||
this.nodeIndex = new NodeIndex(main, { file: join(store.dir, "vectors", "nodes"), embedder: shared.embed });
|
||||
this.nodeIndex.watch(store.main);
|
||||
const getLinker = () => (this.linker ??= new Linker({ doc: main, wiki: shared.wiki, embedder: shared.embed, index: this.nodeIndex }));
|
||||
this.pending = new PendingStore(join(store.dir, "links", "pending.json"));
|
||||
// The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls.
|
||||
this.reviewer = new Reviewer({ llm: shared.llm, wiki: shared.wiki, pending: this.pending, snap: () => store.main.snap() });
|
||||
this.jobs = new Jobs({
|
||||
snap: () => store.main.snap(),
|
||||
linker: getLinker,
|
||||
wiki: shared.wiki,
|
||||
index: this.nodeIndex,
|
||||
pending: this.pending,
|
||||
announce: (state) => this.announce({ linkJob: state }),
|
||||
reviewer: this.reviewer,
|
||||
reviewCalls: shared.reviewCalls,
|
||||
});
|
||||
this.handleLinks = linkRoutes({ main, linker: getLinker, index: this.nodeIndex, pending: this.pending, jobs: this.jobs, embedder: shared.embed, reviewer: this.reviewer, wrote: () => this.wrote("main") });
|
||||
}
|
||||
|
||||
get id() {
|
||||
return this.store.id;
|
||||
}
|
||||
|
||||
/** A notice to every page open on this library. */
|
||||
announce(message: Record<string, unknown>) {
|
||||
const line = `data: ${JSON.stringify(message)}\n\n`;
|
||||
for (const res of this.listeners) res.write(line);
|
||||
}
|
||||
|
||||
/** A server-side write to a branch: saved shortly and announced to every replica. */
|
||||
wrote(branch: string) {
|
||||
this.store.saveSoon(branch);
|
||||
this.announce({ branch, from: "api" });
|
||||
}
|
||||
|
||||
/** Write what is waiting, on the way out. */
|
||||
flush() {
|
||||
this.store.flush();
|
||||
this.pending.flush();
|
||||
}
|
||||
|
||||
/** The library is being moved aside: stop its job, write what is waiting, tell its pages, and write nothing more. */
|
||||
close() {
|
||||
this.jobs.cancel();
|
||||
this.nodeIndex.close();
|
||||
this.pending.close();
|
||||
this.store.close();
|
||||
this.announce({ library: "deleted" });
|
||||
for (const res of this.listeners) res.end();
|
||||
this.listeners.clear();
|
||||
}
|
||||
|
||||
/** A request about this library; `parts` is the path after its prefix, `url` rewritten to /api/<parts>. */
|
||||
async handle(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<boolean> {
|
||||
const [a, b] = parts;
|
||||
const method = req.method ?? "GET";
|
||||
if (a === "state" && method === "GET") {
|
||||
const store = this.store;
|
||||
json(res, 200, {
|
||||
...this.shared.state(),
|
||||
library: store.id,
|
||||
title: store.title,
|
||||
branches: [...store.branches].map(([name, doc]) => ({ name, vv: vvHeader(doc) })),
|
||||
linkJob: this.jobs.current,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (a === "nodes") return (await this.nodeApi(req, res, url, parts.slice(1)), true);
|
||||
if (a && ["events", "branch", "sync", "tree", "ops"].includes(a)) return (await this.libraryApi(req, res, url, a, b), true);
|
||||
if (a === "links") {
|
||||
this.nodeIndex.activate();
|
||||
return this.handleLinks(req, res, url);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The library as a whole: what replicas use, and the op API. */
|
||||
private async libraryApi(req: IncomingMessage, res: ServerResponse, url: URL, action: string, b: string | undefined) {
|
||||
const method = req.method ?? "GET";
|
||||
const store = this.store;
|
||||
const name = b || "main";
|
||||
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
|
||||
|
||||
if (action === "events" && method === "GET") {
|
||||
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
|
||||
res.write(": connected\n\n");
|
||||
this.listeners.add(res);
|
||||
req.on("close", () => this.listeners.delete(res));
|
||||
return;
|
||||
}
|
||||
|
||||
// A replica fetches a branch whole.
|
||||
if (action === "branch" && method === "GET") {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc), "x-library": store.id });
|
||||
return res.end(doc.snapshotBytes());
|
||||
}
|
||||
|
||||
// A replica pushes what it has and gets back what it lacks. Request header x-vv is the
|
||||
// replica's version; the response carries the server's. A replica must name the library it
|
||||
// belongs to: bytes from another library (an old tab, a browser that outlived its data
|
||||
// directory, a page of another library) would add a second root to this one. A beacon cannot
|
||||
// send headers, so it names the library in the query.
|
||||
if (action === "sync" && method === "POST") {
|
||||
if ((req.headers["x-library"] ?? url.searchParams.get("library")) !== store.id) {
|
||||
return json(res, 409, { error: "This page belongs to a different library than the server has here. Reload the page.", library: store.id });
|
||||
}
|
||||
const bytes = await readBody(req, SYNC_MAX);
|
||||
let doc = store.branches.get(name);
|
||||
const before = doc ? vvHeader(doc) : "";
|
||||
if (!doc) {
|
||||
if (!bytes.length) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
doc = Doc.load(bytes, "server");
|
||||
if (doc.libraryId !== store.id) return json(res, 409, { error: "that branch is not of this library" });
|
||||
store.addBranch(name, doc);
|
||||
} else if (bytes.length) {
|
||||
doc.loro.import(bytes);
|
||||
doc.touch();
|
||||
}
|
||||
if (vvHeader(doc) !== before) {
|
||||
store.saveSoon(name);
|
||||
this.announce({ branch: name, from: String(req.headers["x-client"] ?? "") });
|
||||
}
|
||||
const theirs = req.headers["x-vv"] ? new Map(JSON.parse(String(req.headers["x-vv"]))) : new Map();
|
||||
const update = doc.loro.export({ mode: "update", from: new VersionVector(theirs as never) });
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc) });
|
||||
return res.end(update);
|
||||
}
|
||||
|
||||
// For outside agents: read the library as JSON…
|
||||
if (action === "tree" && method === "GET") {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
return json(res, 200, { ...doc.snap(), library: store.id, conflicts: doc.conflicts(), history: history(doc).slice(0, 50) });
|
||||
}
|
||||
|
||||
// …and write to it with the same ops everyone else uses. Node ids are the library's, so one
|
||||
// batch can work anywhere in it (moving a node from one place to another is a move).
|
||||
if (action === "ops" && method === "POST") return this.opsApi(req, res, name);
|
||||
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
|
||||
private async opsApi(req: IncomingMessage, res: ServerResponse, name: string) {
|
||||
const doc = this.store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
const input = await readJson<{ ops: Op[]; message?: string; author?: string; actor?: "human" | "llm" }>(req);
|
||||
if (!Array.isArray(input.ops)) return json(res, 400, { error: "expected { ops: [...] }" });
|
||||
const author = typeof input.author === "string" ? input.author.slice(0, 100) : "api";
|
||||
try {
|
||||
return json(res, 200, doc.as(author, () => doc.apply(input.ops, input.message ?? "Edit over HTTP", { actor: input.actor ?? "llm", tag: "api" })));
|
||||
} catch (err) {
|
||||
if (err instanceof OpError) return json(res, 422, { error: err.message });
|
||||
throw err;
|
||||
} finally {
|
||||
this.wrote(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One node and everything under it, by its id: the subtree as JSON with its conflicts, the text
|
||||
* format as a download, or a file in the text format imported under it. An import is an ordinary
|
||||
* commit on main; the browser makes the same commits in its own replica.
|
||||
*/
|
||||
private async nodeApi(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]) {
|
||||
const method = req.method ?? "GET";
|
||||
const [id, action, branch] = parts as [NodeId, string | undefined, string | undefined];
|
||||
const name = branch || "main";
|
||||
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
|
||||
const doc = this.store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
const snap = doc.snap();
|
||||
if (!id || !snap.nodes[id]) return json(res, 404, { error: `no such node: ${id ?? ""}` });
|
||||
|
||||
// GET nodes/<id>/tree[/<branch>]: the subtree, as tree returns the library.
|
||||
if (action === "tree" && method === "GET") {
|
||||
const ids = new Set([id, ...descendants(snap, id)]);
|
||||
return json(res, 200, { root: id, nodes: Object.fromEntries([...ids].map((x) => [x, snap.nodes[x]])), conflicts: doc.conflicts().filter((c) => [c.node, c.parent].some((x) => x && ids.has(x))) });
|
||||
}
|
||||
// GET nodes/<id>/export[/<branch>]: the text format, as a download.
|
||||
if (action === "export" && method === "GET") {
|
||||
const { text, skipped } = serializeDoc(snap, id);
|
||||
res.writeHead(200, {
|
||||
"content-type": "text/markdown; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="${slugify(snap.nodes[id].title) || "untitled"}${name === "main" ? "" : `-${encodeURIComponent(name)}`}.md"`,
|
||||
"x-skipped": JSON.stringify(skipped),
|
||||
});
|
||||
return res.end(text);
|
||||
}
|
||||
// POST nodes/<id>/import?name=file.md, with the file as the body: a new last child of the node (on main).
|
||||
if (action === "import" && !branch && method === "POST") {
|
||||
const file = (url.searchParams.get("name") ?? "").replace(/^.*[\\/]/, "").slice(0, 200) || "import.md";
|
||||
let text: string;
|
||||
try {
|
||||
text = (await readBody(req, IMPORT_MAX)).toString("utf8");
|
||||
} catch (err) {
|
||||
if (err instanceof HttpError && err.status === 413) return json(res, 413, { error: `the file is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB)` });
|
||||
throw err;
|
||||
}
|
||||
const main = this.store.main;
|
||||
if (!main.snap().nodes[id]) return json(res, 404, { error: `no such node on main: ${id}` });
|
||||
try {
|
||||
const top = importTree(main, text, file, { creator: this.shared.user, parent: id });
|
||||
this.wrote("main");
|
||||
return json(res, 201, { node: top, title: main.snap().nodes[top].title });
|
||||
} catch (err) {
|
||||
if (err instanceof FormatError) return json(res, 422, { error: err.message, problems: err.problems });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
}
|
||||
@@ -394,6 +394,11 @@ export class VectorIndex {
|
||||
|
||||
// -- persistence --
|
||||
|
||||
/** Write nothing more (its directory is being moved aside). */
|
||||
detach() {
|
||||
this.file = null;
|
||||
}
|
||||
|
||||
save() {
|
||||
if (!this.file) return;
|
||||
const model = this.embedder?.spec.id ?? null;
|
||||
|
||||
+110
-214
@@ -1,42 +1,35 @@
|
||||
/**
|
||||
* The local server. It does three small things:
|
||||
* - relays library updates between replicas (tabs, people, agents) and keeps a copy on disk
|
||||
* - relays each library's updates between replicas (tabs, people, agents) and keeps a copy on disk
|
||||
* - holds the API key and proxies model calls
|
||||
* - exposes the op API over HTTP, so an outside agent can read and edit the tree
|
||||
* - exposes the op API over HTTP, so an outside agent can read and edit a library
|
||||
* In development it also hosts Vite; in production it serves the built files.
|
||||
*
|
||||
* The whole library is one database: /api/tree, /api/ops, /api/sync… act on all of it, and
|
||||
* /api/nodes/<id>/… on one node and what is under it. See README.md for the list.
|
||||
* There are several libraries, each a database of its own (libraries.ts): /api/libraries lists,
|
||||
* makes, renames and deletes them, and /api/l/<id>/… acts on one of them (bundle.ts), the same
|
||||
* routes without the prefix on the first. See README.md for the list.
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import { userInfo } from "node:os";
|
||||
import { extname, join, resolve } from "node:path";
|
||||
import { VersionVector } from "loro-crdt";
|
||||
import { Doc, OpError, descendants, type NodeId, type Op } from "../src/core/model";
|
||||
import { encodeVV, history } from "../src/core/repo";
|
||||
import { FormatError, serializeDoc } from "../src/core/format";
|
||||
import { IMPORT_MAX, importTree, writeSeed } from "../src/core/seed";
|
||||
import { slugify } from "../src/core/text";
|
||||
import { writeSeed } from "../src/core/seed";
|
||||
import { mockLLM } from "../src/llm/mock";
|
||||
import { LLMUnavailable, type JsonReq, type LLM, type Req, type TurnReq } from "../src/llm/types";
|
||||
import { seed } from "../src/seed/tree";
|
||||
import { Bundle, type Shared } from "./bundle";
|
||||
import { claudeLLM, describeError } from "./claude";
|
||||
import { LibraryStore, validBranch } from "./library";
|
||||
import { Libraries, NeedsMigration, importStarters } from "./libraries";
|
||||
import { lockHolder, takeLock } from "./lock";
|
||||
import { SubscriptionError, queryPlanUsage, subscriptionLLM } from "./subscription";
|
||||
import { usage, withMockUsage } from "./usage";
|
||||
import { HttpError, ROOT as root, abortOnClose, dataDir, readBody, readJson, sendJson as json } from "./util";
|
||||
import { HttpError, ROOT as root, abortOnClose, dataDir, readJson, sendJson as json } from "./util";
|
||||
import { applyWebPolicy, webConfig } from "./web";
|
||||
import { WikiClient, validContact, wiki, wikiLang } from "./wiki";
|
||||
import { makeMockWikiFetch } from "./wikiMock";
|
||||
import { wikiOff, wikiRoutes } from "./wikiRoutes";
|
||||
import { embedder } from "./embed";
|
||||
import { Jobs } from "./links/jobs";
|
||||
import { NodeIndex } from "./links/nodeIndex";
|
||||
import { PendingStore } from "./links/pending";
|
||||
import { JOB_CALLS, Reviewer } from "./links/review";
|
||||
import { linkRoutes } from "./links/routes";
|
||||
import { Linker } from "./links/scan";
|
||||
import { JOB_CALLS } from "./links/review";
|
||||
|
||||
const PORT = Number(process.env.PORT ?? 4747);
|
||||
// Host names the dev server answers to besides localhost. Tailscale names are allowed so that
|
||||
@@ -103,89 +96,84 @@ const wikiState = { mode: wikiMode, lang: wikiLang(process.env.IE_WIKI_LANG), co
|
||||
/** A short reason for a failed model call, whichever provider made it. */
|
||||
const explain = (err: unknown) => (err instanceof SubscriptionError ? { status: err.status, message: err.message } : describeError(err));
|
||||
|
||||
// ---- the library on disk ----
|
||||
// ---- the libraries on disk ----
|
||||
|
||||
mkdirSync(DATA, { recursive: true });
|
||||
const started = performance.now();
|
||||
const store = new LibraryStore(DATA).open();
|
||||
store.seedFirst((doc) => writeSeed(doc, readFileSync(join(root, "src/seed/prompt.txt"), "utf8"), seed));
|
||||
store.importLibrary(LIBRARY);
|
||||
const startMs = Math.round(performance.now() - started);
|
||||
// Writes are gathered before they go to disk; whatever is waiting goes on the way out.
|
||||
process.on("exit", () => store.flush());
|
||||
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => process.exit(0));
|
||||
|
||||
const vvHeader = (doc: Doc) => encodeVV(doc.loro.version().toJSON());
|
||||
|
||||
// ---- link discovery (server/links) ----
|
||||
|
||||
// The embedding model is loaded on first use, in a worker thread; IE_EMBED=off turns it off, and
|
||||
// scanning then matches by text alone. Pending suggestions are derived data, kept beside the library.
|
||||
const embed = process.env.IE_EMBED === "off" ? null : embedder();
|
||||
const nodeIndex = new NodeIndex(() => store.main, { file: join(DATA, "vectors", "nodes"), embedder: embed });
|
||||
nodeIndex.watch(store.main);
|
||||
let linker: Linker | null = null;
|
||||
const getLinker = () => (linker ??= new Linker({ doc: () => store.main, wiki: wikiClient, embedder: embed, index: nodeIndex }));
|
||||
const pending = new PendingStore(join(DATA, "links", "pending.json"));
|
||||
process.on("exit", () => pending.flush());
|
||||
// The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls.
|
||||
const reviewer = new Reviewer({ llm: () => llm, wiki: wikiClient, pending, snap: () => store.main.snap() });
|
||||
const reviewCalls = Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS);
|
||||
const jobs = new Jobs({
|
||||
snap: () => store.main.snap(),
|
||||
linker: getLinker,
|
||||
wiki: wikiClient,
|
||||
index: nodeIndex,
|
||||
pending,
|
||||
announce: (state) => announce({ linkJob: state }),
|
||||
reviewer,
|
||||
reviewCalls,
|
||||
});
|
||||
const handleLinks = linkRoutes({ main: () => store.main, linker: getLinker, index: nodeIndex, pending, jobs, embedder: embed, reviewer, wrote: () => wrote("main") });
|
||||
|
||||
// ---- live notifications ----
|
||||
|
||||
const listeners = new Set<ServerResponse>();
|
||||
function announce(message: Record<string, unknown>) {
|
||||
const line = `data: ${JSON.stringify(message)}\n\n`;
|
||||
for (const res of listeners) res.write(line);
|
||||
// A data directory in an older layout is never opened, nor migrated without being asked: the
|
||||
// migration (npm run migrate) has a dry run and verifies what it writes.
|
||||
const held = lockHolder(DATA);
|
||||
if (held) {
|
||||
console.error(`Another server (pid ${held.pid}${held.port ? `, port ${held.port}` : ""}) has ${DATA} open; stop it first, or set IE_DATA to another directory.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const libraries = new Libraries(DATA);
|
||||
try {
|
||||
libraries.open((doc) => {
|
||||
writeSeed(doc, readFileSync(join(root, "src/seed/prompt.txt"), "utf8"), seed);
|
||||
console.log("seeded the first tree from src/seed");
|
||||
importStarters(doc, LIBRARY);
|
||||
});
|
||||
} catch (err) {
|
||||
if (!(err instanceof NeedsMigration)) throw err;
|
||||
console.error(err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
takeLock(DATA, PORT);
|
||||
const startMs = Math.round(performance.now() - started);
|
||||
|
||||
// ---- each library's link discovery, notices and routes (server/bundle.ts) ----
|
||||
|
||||
// The embedding model is loaded on first use, in a worker thread shared by every library;
|
||||
// IE_EMBED=off turns it off, and scanning then matches by text alone.
|
||||
const embed = process.env.IE_EMBED === "off" ? null : embedder();
|
||||
const shared: Shared = {
|
||||
llm: () => llm,
|
||||
wiki: wikiClient,
|
||||
embed,
|
||||
reviewCalls: Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS),
|
||||
user: USER,
|
||||
state: () => ({
|
||||
user: USER,
|
||||
llm: llm?.kind ?? "off",
|
||||
model: llm?.model ?? null,
|
||||
wiki: wikiState,
|
||||
embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off",
|
||||
web: { on: web.on, searches: web.searches, fetches: web.fetches },
|
||||
libraries: libraries.list(),
|
||||
}),
|
||||
};
|
||||
const bundles = new Map<string, Bundle>();
|
||||
for (const [id, store] of libraries.stores) bundles.set(id, new Bundle(store, shared));
|
||||
// Writes are gathered before they go to disk; whatever is waiting goes on the way out.
|
||||
process.on("exit", () => {
|
||||
for (const b of bundles.values()) b.flush();
|
||||
});
|
||||
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => process.exit(0));
|
||||
|
||||
// ---- http plumbing ----
|
||||
|
||||
/** Largest replica update a sync accepts. */
|
||||
const SYNC_MAX = 256 * 1024 * 1024;
|
||||
function needLLM(): LLM {
|
||||
if (!llm) throw new LLMUnavailable();
|
||||
return llm;
|
||||
}
|
||||
|
||||
/** A server-side write to a branch: saved shortly and announced to every replica. */
|
||||
function wrote(branch: string) {
|
||||
store.saveSoon(branch);
|
||||
announce({ branch, from: "api" });
|
||||
}
|
||||
|
||||
async function api(req: IncomingMessage, res: ServerResponse, url: URL) {
|
||||
const parts = url.pathname.split("/").slice(2).map(decodeURIComponent); // after /api/
|
||||
const [a, b] = parts;
|
||||
const method = req.method ?? "GET";
|
||||
|
||||
if (a === "state" && method === "GET") {
|
||||
return json(res, 200, {
|
||||
user: USER,
|
||||
llm: llm?.kind ?? "off",
|
||||
model: llm?.model ?? null,
|
||||
library: store.id,
|
||||
branches: [...store.branches].map(([name, doc]) => ({ name, vv: vvHeader(doc) })),
|
||||
migrated: store.migrated(),
|
||||
wiki: wikiState,
|
||||
embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off",
|
||||
web: { on: web.on, searches: web.searches, fetches: web.fetches },
|
||||
linkJob: jobs.current,
|
||||
});
|
||||
// One library: /api/l/<id>/…, everything that reads or writes a library's content.
|
||||
if (a === "l") {
|
||||
const bundle = b ? bundles.get(b) : undefined;
|
||||
if (!bundle) return json(res, 404, { error: `no library ${b ?? ""}` });
|
||||
const rest = parts.slice(2);
|
||||
if (await bundle.handle(req, res, rebased(url, rest), rest)) return;
|
||||
return json(res, 404, { error: "not found" });
|
||||
}
|
||||
|
||||
if (a === "libraries") return librariesApi(req, res, parts.slice(1));
|
||||
|
||||
if (a === "usage" && method === "GET") return json(res, 200, usage.summary());
|
||||
|
||||
if (a === "llm" && method === "POST") {
|
||||
@@ -227,148 +215,56 @@ async function api(req: IncomingMessage, res: ServerResponse, url: URL) {
|
||||
}
|
||||
}
|
||||
|
||||
if (a === "nodes") return nodeApi(req, res, url, parts.slice(1));
|
||||
if (["events", "branch", "sync", "tree", "ops"].includes(a)) return libraryApi(req, res, url, a, b);
|
||||
if (await handleWiki(req, res, url)) return;
|
||||
if (url.pathname.startsWith("/api/links/")) nodeIndex.activate();
|
||||
if (await handleLinks(req, res, url)) return;
|
||||
|
||||
// Without a library named, the first one: so `curl /api/tree` still reads a library.
|
||||
const first = bundles.get(libraries.first().id)!;
|
||||
if (await first.handle(req, res, url, parts)) return;
|
||||
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
|
||||
/** The library as a whole: what replicas use, and the op API. */
|
||||
async function libraryApi(req: IncomingMessage, res: ServerResponse, url: URL, action: string, b: string | undefined) {
|
||||
const method = req.method ?? "GET";
|
||||
const name = b || "main";
|
||||
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
|
||||
|
||||
if (action === "events" && method === "GET") {
|
||||
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
|
||||
res.write(": connected\n\n");
|
||||
listeners.add(res);
|
||||
req.on("close", () => listeners.delete(res));
|
||||
return;
|
||||
}
|
||||
|
||||
// A replica fetches a branch whole.
|
||||
if (action === "branch" && method === "GET") {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc), "x-library": store.id });
|
||||
return res.end(doc.snapshotBytes());
|
||||
}
|
||||
|
||||
// A replica pushes what it has and gets back what it lacks. Request header x-vv is the
|
||||
// replica's version; the response carries the server's. A replica must name the library it
|
||||
// belongs to: bytes from another library (an old tab, a browser that outlived its data
|
||||
// directory) would add a second root to this one. A beacon cannot send headers, so it names
|
||||
// the library in the query.
|
||||
if (action === "sync" && method === "POST") {
|
||||
if ((req.headers["x-library"] ?? url.searchParams.get("library")) !== store.id) {
|
||||
return json(res, 409, { error: "This page belongs to a different library than the server has now. Reload the page.", library: store.id });
|
||||
}
|
||||
const bytes = await readBody(req, SYNC_MAX);
|
||||
let doc = store.branches.get(name);
|
||||
const before = doc ? vvHeader(doc) : "";
|
||||
if (!doc) {
|
||||
if (!bytes.length) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
doc = Doc.load(bytes, "server");
|
||||
if (doc.libraryId !== store.id) return json(res, 409, { error: "that branch is not of this library" });
|
||||
store.addBranch(name, doc);
|
||||
} else if (bytes.length) {
|
||||
doc.loro.import(bytes);
|
||||
doc.touch();
|
||||
}
|
||||
if (vvHeader(doc) !== before) {
|
||||
store.saveSoon(name);
|
||||
announce({ branch: name, from: String(req.headers["x-client"] ?? "") });
|
||||
}
|
||||
const theirs = req.headers["x-vv"] ? new Map(JSON.parse(String(req.headers["x-vv"]))) : new Map();
|
||||
const update = doc.loro.export({ mode: "update", from: new VersionVector(theirs as never) });
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc) });
|
||||
return res.end(update);
|
||||
}
|
||||
|
||||
// For outside agents: read the library as JSON…
|
||||
if (action === "tree" && method === "GET") {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
return json(res, 200, { ...doc.snap(), conflicts: doc.conflicts(), history: history(doc).slice(0, 50) });
|
||||
}
|
||||
|
||||
// …and write to it with the same ops everyone else uses. Node ids are the library's, so one
|
||||
// batch can work anywhere in it (moving a node from one place to another is a move).
|
||||
if (action === "ops" && method === "POST") return opsApi(req, res, name);
|
||||
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
|
||||
async function opsApi(req: IncomingMessage, res: ServerResponse, name: string) {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
const input = await readJson<{ ops: Op[]; message?: string; author?: string; actor?: "human" | "llm" }>(req);
|
||||
if (!Array.isArray(input.ops)) return json(res, 400, { error: "expected { ops: [...] }" });
|
||||
const author = typeof input.author === "string" ? input.author.slice(0, 100) : "api";
|
||||
try {
|
||||
return json(res, 200, doc.as(author, () => doc.apply(input.ops, input.message ?? "Edit over HTTP", { actor: input.actor ?? "llm", tag: "api" })));
|
||||
} catch (err) {
|
||||
if (err instanceof OpError) return json(res, 422, { error: err.message });
|
||||
throw err;
|
||||
} finally {
|
||||
wrote(name);
|
||||
}
|
||||
/** The URL a library's routes see: /api/<rest>, its query kept. */
|
||||
function rebased(url: URL, rest: string[]): URL {
|
||||
const out = new URL(url);
|
||||
out.pathname = `/api/${rest.map(encodeURIComponent).join("/")}`;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* One node and everything under it, by its id: the subtree as JSON with its conflicts, the text
|
||||
* format as a download, or a file in the text format imported under it. An import is an ordinary
|
||||
* commit on main; the browser makes the same commits in its own replica.
|
||||
* The libraries:
|
||||
* GET /api/libraries → { libraries: [{ id, title, created, nodes, branches }] }, in order
|
||||
* POST /api/libraries { title } → 201 { library }: a new library, its root alone, at the end
|
||||
* PATCH /api/libraries/<id> { title } → { library }: renamed (a commit on its root's title)
|
||||
* DELETE /api/libraries/<id> → { deleted, movedTo }: moved aside whole; never the last one
|
||||
*/
|
||||
async function nodeApi(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]) {
|
||||
async function librariesApi(req: IncomingMessage, res: ServerResponse, parts: string[]) {
|
||||
const method = req.method ?? "GET";
|
||||
const [id, action, branch] = parts as [NodeId, string | undefined, string | undefined];
|
||||
const name = branch || "main";
|
||||
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
const snap = doc.snap();
|
||||
if (!id || !snap.nodes[id]) return json(res, 404, { error: `no such node: ${id ?? ""}` });
|
||||
|
||||
// GET /api/nodes/<id>/tree[/<branch>]: the subtree, as /api/tree returns the library.
|
||||
if (action === "tree" && method === "GET") {
|
||||
const ids = new Set([id, ...descendants(snap, id)]);
|
||||
return json(res, 200, { root: id, nodes: Object.fromEntries([...ids].map((x) => [x, snap.nodes[x]])), conflicts: doc.conflicts().filter((c) => [c.node, c.parent].some((x) => x && ids.has(x))) });
|
||||
const [id] = parts;
|
||||
const info = (lib: string) => libraries.list().find((l) => l.id === lib);
|
||||
if (!id && method === "GET") return json(res, 200, { libraries: libraries.list() });
|
||||
if (!id && method === "POST") {
|
||||
const input = await readJson<{ title?: unknown }>(req);
|
||||
const store = libraries.create(input.title as string);
|
||||
bundles.set(store.id, new Bundle(store, shared));
|
||||
console.log(`libraries: made “${store.title}” (${store.id})`);
|
||||
return json(res, 201, { library: info(store.id) });
|
||||
}
|
||||
// GET /api/nodes/<id>/export[/<branch>]: the text format, as a download.
|
||||
if (action === "export" && method === "GET") {
|
||||
const { text, skipped } = serializeDoc(snap, id);
|
||||
res.writeHead(200, {
|
||||
"content-type": "text/markdown; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="${slugify(snap.nodes[id].title) || "untitled"}${name === "main" ? "" : `-${encodeURIComponent(name)}`}.md"`,
|
||||
"x-skipped": JSON.stringify(skipped),
|
||||
});
|
||||
return res.end(text);
|
||||
if (id && parts.length === 1 && (method === "PATCH" || method === "POST")) {
|
||||
const input = await readJson<{ title?: unknown }>(req);
|
||||
const store = libraries.rename(id, input.title as string);
|
||||
bundles.get(id)?.announce({ branch: "main", from: "api" });
|
||||
return json(res, 200, { library: info(store.id) });
|
||||
}
|
||||
// POST /api/nodes/<id>/import?name=file.md, with the file as the body: a new last child of the node (on main).
|
||||
if (action === "import" && !branch && method === "POST") {
|
||||
const file = (url.searchParams.get("name") ?? "").replace(/^.*[\\/]/, "").slice(0, 200) || "import.md";
|
||||
let text: string;
|
||||
try {
|
||||
text = (await readBody(req, IMPORT_MAX)).toString("utf8");
|
||||
} catch (err) {
|
||||
if (err instanceof HttpError && err.status === 413) return json(res, 413, { error: `the file is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB)` });
|
||||
throw err;
|
||||
}
|
||||
const main = store.main;
|
||||
if (!main.snap().nodes[id]) return json(res, 404, { error: `no such node on main: ${id}` });
|
||||
try {
|
||||
const top = importTree(main, text, file, { creator: USER, parent: id });
|
||||
wrote("main");
|
||||
return json(res, 201, { node: top, title: main.snap().nodes[top].title });
|
||||
} catch (err) {
|
||||
if (err instanceof FormatError) return json(res, 422, { error: err.message, problems: err.problems });
|
||||
throw err;
|
||||
}
|
||||
if (id && parts.length === 1 && method === "DELETE") {
|
||||
const bundle = bundles.get(id);
|
||||
if (!bundle) return json(res, 404, { error: `no library ${id}` });
|
||||
if (libraries.stores.size <= 1) return json(res, 409, { error: "the last library cannot be deleted" });
|
||||
bundle.close();
|
||||
const movedTo = libraries.remove(id);
|
||||
bundles.delete(id);
|
||||
console.log(`libraries: deleted ${id}; its files are in ${movedTo}`);
|
||||
return json(res, 200, { deleted: id, movedTo });
|
||||
}
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
@@ -438,9 +334,9 @@ createServer(async (req, res) => {
|
||||
serveStatic(res, path);
|
||||
}
|
||||
}).listen(PORT, "127.0.0.1", () => {
|
||||
const nodes = Object.keys(store.main.snap().nodes).length;
|
||||
console.log(`Infinispand http://localhost:${PORT} model: ${llm ? `${llm.kind}${llm.model ? `: ${llm.model}` : ""}` : "off (set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to generate)"} data: ${DATA}`);
|
||||
console.log(`library: ${store.titles().length} top-level sections, ${nodes} nodes, opened in ${startMs} ms`);
|
||||
for (const l of libraries.list()) console.log(`library “${l.title}” (/l/${l.id}): ${libraries.get(l.id)!.titles().length} top-level sections, ${l.nodes} nodes`);
|
||||
console.log(`${libraries.stores.size} librar${libraries.stores.size === 1 ? "y" : "ies"} opened in ${startMs} ms`);
|
||||
console.log(`web research: ${web.on ? `on (at most ${web.searches} searches and ${web.fetches} pages read per request)` : `off${web.why ? ` (${web.why})` : ""}`}`);
|
||||
console.log(
|
||||
`wikipedia: ${wikiMode === "live" ? `live (${wikiState.lang}.wikipedia.org, ${wikiState.contact ? "with" : "without"} a contact)` : wikiMode === "mock" ? "mock (fixtures, no network)" : "off"}`,
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* The libraries on disk. Each is a tree of its own, with its own history, and nothing in one refers
|
||||
* to anything in another: a library is its own Loro database, with its own id, and what is derived
|
||||
* from it (link suggestions, the reviewer's verdicts, vectors) is kept in its own directory.
|
||||
*
|
||||
* <data>/libraries/index.json the libraries, in order: id, title, when made, whether deleted
|
||||
* <data>/libraries/<id>/<branch>.loro the library (library.ts)
|
||||
* <data>/libraries/<id>/links/pending.json link suggestions and the decisions about them (derived)
|
||||
* <data>/libraries/<id>/vectors/nodes.* its sections as vectors (derived)
|
||||
* <data>/libraries/.deleted/<id>-<time>/ a deleted library, moved aside whole
|
||||
*
|
||||
* What holds no library's content is shared: <data>/wiki-cache/ and <data>/models/.
|
||||
*
|
||||
* A library's id is its database's id (`meta.library`, base 36), also its directory's name and the
|
||||
* `/l/<id>` of its addresses. Its name is its root's title; the index keeps a copy so it can be read
|
||||
* without opening the database.
|
||||
*
|
||||
* An empty data directory starts with one library, the first, which gets the seed and the starter
|
||||
* trees; a library made later starts with its root alone. A data directory in the single-library
|
||||
* layout from before (`<data>/library/main.loro`) is not opened: `npm run migrate` brings it over
|
||||
* (migrateLibraries.ts).
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { LIBRARY_ID } from "../src/core/address";
|
||||
import { FormatError } from "../src/core/format";
|
||||
import { Doc, retitleOps } from "../src/core/model";
|
||||
import { writeText } from "../src/core/seed";
|
||||
import { LibraryStore } from "./library";
|
||||
import { HttpError, writeAtomic } from "./util";
|
||||
|
||||
export const LIBRARIES = "libraries";
|
||||
/** What the single-library layout kept at the top of the data directory, all of it moved aside by the migration. */
|
||||
export const OLD_FILES = ["library", "library.json", "links", "vectors"];
|
||||
|
||||
export interface LibraryEntry {
|
||||
id: string;
|
||||
title: string;
|
||||
/** When it was made (ISO). */
|
||||
created: string;
|
||||
/** When it was deleted (ISO), and where it was moved to, relative to the libraries directory. */
|
||||
deleted?: string;
|
||||
movedTo?: string;
|
||||
}
|
||||
|
||||
/** A library as the API lists it. */
|
||||
export interface LibraryInfo {
|
||||
id: string;
|
||||
title: string;
|
||||
created: string;
|
||||
nodes: number;
|
||||
branches: string[];
|
||||
}
|
||||
|
||||
export type Layout =
|
||||
| { kind: "empty" }
|
||||
| { kind: "libraries" }
|
||||
/** The single-library layout: <data>/library/main.loro and what goes with it. */
|
||||
| { kind: "old"; found: string[] }
|
||||
/** A migration that wrote the libraries but did not move the old files aside. */
|
||||
| { kind: "unfinished"; found: string[] }
|
||||
/** Older still: one database per document (<data>/docs/) or a single document (<data>/*.loro). */
|
||||
| { kind: "older"; found: string[] };
|
||||
|
||||
/** What a data directory holds. */
|
||||
export function layout(data: string): Layout {
|
||||
const have = (f: string) => existsSync(join(data, f));
|
||||
const old = OLD_FILES.filter(have);
|
||||
if (have(join(LIBRARIES, "index.json"))) return old.length ? { kind: "unfinished", found: old } : { kind: "libraries" };
|
||||
if (have(join("library", "main.loro"))) return { kind: "old", found: old };
|
||||
const older = [...(have("docs") ? ["docs"] : []), ...(existsSync(data) ? readdirSync(data).filter((f) => f.endsWith(".loro")) : [])];
|
||||
if (older.length) return { kind: "older", found: older };
|
||||
if (old.length) return { kind: "old", found: old };
|
||||
return { kind: "empty" };
|
||||
}
|
||||
|
||||
/** The data directory is not in the libraries layout: the server will not open it. */
|
||||
export class NeedsMigration extends Error {}
|
||||
|
||||
/** One line saying what to do about a data directory the server cannot open. */
|
||||
export function migrationNeeded(data: string, l: Layout): string | null {
|
||||
switch (l.kind) {
|
||||
case "empty":
|
||||
case "libraries":
|
||||
return null;
|
||||
case "old":
|
||||
return `${data} holds a library in the old single-library layout (${l.found.join(", ")}): stop any server using it and run \`npm run migrate\` (\`npm run migrate -- --check\` first for a dry run that writes nothing).`;
|
||||
case "unfinished":
|
||||
return `${data} holds both libraries/ and old files (${l.found.join(", ")}) from a migration that did not finish: run \`npm run migrate\` to move the old files aside.`;
|
||||
case "older":
|
||||
return `${data} holds data from before the single library (${l.found.join(", ")}): open it once with a version from before libraries (commit c4d6856) to bring it into one library, then run \`npm run migrate\`.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** A time stamp for directory names: 20261117-013500. */
|
||||
export const stamp = (d = new Date()) => d.toISOString().replace(/[-:]/g, "").replace(/\..*/, "").replace("T", "-");
|
||||
|
||||
export function readIndex(dir: string): LibraryEntry[] {
|
||||
const raw = JSON.parse(readFileSync(join(dir, "index.json"), "utf8")) as { libraries?: LibraryEntry[] };
|
||||
if (!Array.isArray(raw.libraries)) throw new Error(`${join(dir, "index.json")} lists no libraries`);
|
||||
return raw.libraries.filter((e) => e && typeof e.id === "string" && LIBRARY_ID.test(e.id));
|
||||
}
|
||||
|
||||
export const indexText = (entries: LibraryEntry[]) => JSON.stringify({ version: 1, libraries: entries }, null, 2) + "\n";
|
||||
|
||||
/**
|
||||
* Write each starter file (the text format) as a top of the library, in file name order. A file that
|
||||
* does not parse is logged and skipped; it never stops the server.
|
||||
*/
|
||||
export function importStarters(doc: Doc, dir: string, log: (msg: string) => void = console.log) {
|
||||
if (!existsSync(dir)) return;
|
||||
for (const f of readdirSync(dir).filter((f) => f.endsWith(".md")).sort()) {
|
||||
try {
|
||||
const id = writeText(doc, readFileSync(join(dir, f), "utf8"), `library/${f}`);
|
||||
log(`library: imported ${f} as “${doc.snap().nodes[id].title}”`);
|
||||
} catch (err) {
|
||||
log(`library: skipped ${f}:\n ${err instanceof FormatError ? err.problems.join("\n ") : String(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class Libraries {
|
||||
readonly dir: string;
|
||||
entries: LibraryEntry[] = [];
|
||||
readonly stores = new Map<string, LibraryStore>();
|
||||
|
||||
constructor(
|
||||
readonly data: string,
|
||||
private log: (msg: string) => void = console.log,
|
||||
) {
|
||||
this.dir = join(data, LIBRARIES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open every library. On an empty data directory, make the first library and hand it to `seed`
|
||||
* (the seed and the starter trees). Throws NeedsMigration on any other layout.
|
||||
*/
|
||||
open(seed: (doc: Doc) => void): this {
|
||||
const l = layout(this.data);
|
||||
const why = migrationNeeded(this.data, l);
|
||||
if (why) throw new NeedsMigration(why);
|
||||
if (l.kind === "empty") {
|
||||
mkdirSync(this.dir, { recursive: true });
|
||||
const doc = Doc.library("server");
|
||||
seed(doc);
|
||||
this.add(doc);
|
||||
return this;
|
||||
}
|
||||
this.entries = readIndex(this.dir);
|
||||
for (const e of this.entries) {
|
||||
if (e.deleted) continue;
|
||||
const dir = join(this.dir, e.id);
|
||||
if (!existsSync(join(dir, "main.loro"))) {
|
||||
this.log(`libraries: “${e.title}” (${e.id}) is listed but ${dir} holds no main.loro; left out`);
|
||||
continue;
|
||||
}
|
||||
const store = new LibraryStore(dir).open();
|
||||
if (store.id !== e.id) this.log(`libraries: ${dir} holds library ${store.id}, not ${e.id}; opened as ${e.id}`);
|
||||
this.stores.set(e.id, store);
|
||||
}
|
||||
// Every library deleted by hand: start again with an empty one rather than with none.
|
||||
if (!this.stores.size) this.add(Doc.library("server"));
|
||||
return this;
|
||||
}
|
||||
|
||||
/** A library's store, if it exists and is not deleted. */
|
||||
get(id: string): LibraryStore | undefined {
|
||||
return this.stores.get(id);
|
||||
}
|
||||
|
||||
/** The first library in the index that is open. */
|
||||
first(): LibraryStore {
|
||||
for (const e of this.entries) {
|
||||
const s = this.stores.get(e.id);
|
||||
if (s) return s;
|
||||
}
|
||||
throw new Error("no library is open");
|
||||
}
|
||||
|
||||
/** The open libraries, in order, with their names read from their roots. */
|
||||
list(): LibraryInfo[] {
|
||||
const out: LibraryInfo[] = [];
|
||||
let renamed = false;
|
||||
for (const e of this.entries) {
|
||||
const s = this.stores.get(e.id);
|
||||
if (!s) continue;
|
||||
const title = s.title;
|
||||
if (title !== e.title) {
|
||||
e.title = title;
|
||||
renamed = true;
|
||||
}
|
||||
out.push({ id: e.id, title, created: e.created, nodes: Object.keys(s.main.snap().nodes).length, branches: [...s.branches.keys()] });
|
||||
}
|
||||
if (renamed) this.saveIndex();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A new library, with its root alone, at the end of the list. */
|
||||
create(title: string): LibraryStore {
|
||||
const name = cleanTitle(title);
|
||||
return this.add(Doc.library("server", undefined, name));
|
||||
}
|
||||
|
||||
private add(doc: Doc): LibraryStore {
|
||||
const id = doc.libraryId!;
|
||||
if (this.entries.some((e) => e.id === id) || existsSync(join(this.dir, id))) throw new Error(`a library ${id} exists already`);
|
||||
const store = LibraryStore.create(join(this.dir, id), doc);
|
||||
this.stores.set(id, store);
|
||||
this.entries.push({ id, title: store.title, created: new Date().toISOString() });
|
||||
this.saveIndex();
|
||||
return store;
|
||||
}
|
||||
|
||||
/** Rename a library: an ordinary commit on its root's title (on main), so it syncs and versions like any rename. */
|
||||
rename(id: string, title: string): LibraryStore {
|
||||
const store = this.need(id);
|
||||
const name = cleanTitle(title);
|
||||
const doc = store.main;
|
||||
const snap = doc.snap();
|
||||
if (snap.nodes[snap.root].title !== name) {
|
||||
doc.as("server", () => doc.apply(retitleOps(snap, snap.root, name), `Rename the library to “${name}”`, { actor: "human" }));
|
||||
store.save("main");
|
||||
}
|
||||
const e = this.entries.find((x) => x.id === id)!;
|
||||
e.title = name;
|
||||
this.saveIndex();
|
||||
return store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a library: its directory is moved, whole and unchanged, to libraries/.deleted/<id>-<time>,
|
||||
* and the index keeps its entry, marked deleted. The last library cannot be deleted.
|
||||
*/
|
||||
remove(id: string): string {
|
||||
const store = this.need(id);
|
||||
if (this.stores.size <= 1) throw new HttpError(409, "the last library cannot be deleted");
|
||||
store.close();
|
||||
const rel = join(".deleted", `${id}-${stamp()}`);
|
||||
mkdirSync(join(this.dir, ".deleted"), { recursive: true });
|
||||
renameSync(store.dir, join(this.dir, rel));
|
||||
this.stores.delete(id);
|
||||
const e = this.entries.find((x) => x.id === id)!;
|
||||
e.deleted = new Date().toISOString();
|
||||
e.movedTo = rel;
|
||||
this.saveIndex();
|
||||
return join(this.dir, rel);
|
||||
}
|
||||
|
||||
private need(id: string): LibraryStore {
|
||||
const store = this.stores.get(id);
|
||||
if (!store) throw new HttpError(404, `no library ${id}`);
|
||||
return store;
|
||||
}
|
||||
|
||||
saveIndex() {
|
||||
writeAtomic(join(this.dir, "index.json"), indexText(this.entries));
|
||||
}
|
||||
|
||||
/** Write every library's waiting changes. */
|
||||
flush() {
|
||||
for (const s of this.stores.values()) s.flush();
|
||||
}
|
||||
}
|
||||
|
||||
function cleanTitle(title: unknown): string {
|
||||
if (typeof title !== "string") throw new HttpError(400, "give the library a title");
|
||||
const t = title.replace(/\s+/g, " ").trim();
|
||||
if (!t) throw new HttpError(400, "give the library a title");
|
||||
if (t.length > 200) throw new HttpError(400, "a library's title is at most 200 characters");
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Whether a path is a directory (for the migration's checks). */
|
||||
export const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
|
||||
+34
-82
@@ -1,22 +1,18 @@
|
||||
/**
|
||||
* The library on disk: one Loro database, a snapshot per branch.
|
||||
* One library on disk: one Loro database, a snapshot per branch, in the library's own directory.
|
||||
*
|
||||
* <data>/library/<branch>.loro the library on that branch
|
||||
* <data>/library/migrated.json what was brought over from the per-document layout, if anything was
|
||||
* <data>/library.json starter files already imported (by file name), so a deleted one stays deleted
|
||||
* <data>/libraries/<id>/<branch>.loro the library on that branch
|
||||
*
|
||||
* Branch names are percent-encoded into file names, so no request can name a file outside it.
|
||||
* Writes are gathered for a moment before they go to disk: with the whole library in one file, a
|
||||
* save per keystroke would rewrite the whole library each time. Replicas keep what has not been
|
||||
* saved and send it again, so a crash loses nothing that a browser still holds.
|
||||
*
|
||||
* The libraries themselves, their index and what is derived from each, are in libraries.ts.
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { FormatError } from "../src/core/format";
|
||||
import { Doc, tops } from "../src/core/model";
|
||||
import { writeText } from "../src/core/seed";
|
||||
import { slugify } from "../src/core/text";
|
||||
import { SEED_KEY, migrate } from "./migrate";
|
||||
import { writeAtomic } from "./util";
|
||||
|
||||
export const validBranch = (b: string) => b.length > 0 && b.length <= 100 && !/[\u0000-\u001f]/.test(b);
|
||||
@@ -26,27 +22,31 @@ const SAVE_DELAY = 250;
|
||||
|
||||
export class LibraryStore {
|
||||
readonly branches = new Map<string, Doc>();
|
||||
readonly dir: string;
|
||||
private timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
/** Set once the library has been moved aside: nothing more is written. */
|
||||
closed = false;
|
||||
|
||||
constructor(readonly data: string, private log: (msg: string) => void = console.log) {
|
||||
this.dir = join(data, "library");
|
||||
}
|
||||
constructor(readonly dir: string) {}
|
||||
|
||||
/** Migrate an older layout if there is one and no library yet, then load every branch. */
|
||||
/** Load every branch. A directory without main is not a library. */
|
||||
open(): this {
|
||||
if (!existsSync(this.dir)) migrate(this.data, this.log);
|
||||
mkdirSync(this.dir, { recursive: true });
|
||||
for (const f of readdirSync(this.dir)) {
|
||||
if (f.endsWith(".loro")) this.branches.set(decodeURIComponent(f.slice(0, -5)), Doc.load(readFileSync(join(this.dir, f)), "server"));
|
||||
}
|
||||
if (!this.branches.has("main")) {
|
||||
this.branches.set("main", Doc.library("server"));
|
||||
this.save("main");
|
||||
}
|
||||
if (!this.branches.has("main")) throw new Error(`${this.dir} has no main.loro`);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** A new library in a new directory, written at once. */
|
||||
static create(dir: string, doc: Doc): LibraryStore {
|
||||
if (existsSync(join(dir, "main.loro"))) throw new Error(`${dir} already holds a library`);
|
||||
const store = new LibraryStore(dir);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
store.branches.set("main", doc);
|
||||
store.save("main");
|
||||
return store;
|
||||
}
|
||||
|
||||
get main(): Doc {
|
||||
return this.branches.get("main")!;
|
||||
}
|
||||
@@ -55,21 +55,18 @@ export class LibraryStore {
|
||||
return this.main.libraryId ?? "";
|
||||
}
|
||||
|
||||
/** The library's name: its root's title. */
|
||||
get title(): string {
|
||||
const snap = this.main.snap();
|
||||
return snap.nodes[snap.root].title;
|
||||
}
|
||||
|
||||
/** The titles of the root's children on main, in order. */
|
||||
titles(): string[] {
|
||||
const snap = this.main.snap();
|
||||
return tops(snap).map((id) => snap.nodes[id].title);
|
||||
}
|
||||
|
||||
/** What the migration recorded, for browsers that still hold replicas of the old documents. */
|
||||
migrated(): unknown {
|
||||
try {
|
||||
return JSON.parse(readFileSync(join(this.dir, "migrated.json"), "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- writing ----
|
||||
|
||||
/** Write a branch to disk now. */
|
||||
@@ -77,13 +74,13 @@ export class LibraryStore {
|
||||
clearTimeout(this.timers.get(name));
|
||||
this.timers.delete(name);
|
||||
const doc = this.branches.get(name);
|
||||
if (!doc) return;
|
||||
if (!doc || this.closed) return;
|
||||
writeAtomic(join(this.dir, `${encodeURIComponent(name)}.loro`), doc.snapshotBytes());
|
||||
}
|
||||
|
||||
/** Write a branch to disk shortly, with whatever else arrives meanwhile. */
|
||||
saveSoon(name: string) {
|
||||
if (this.timers.has(name)) return;
|
||||
if (this.timers.has(name) || this.closed) return;
|
||||
this.timers.set(name, setTimeout(() => this.save(name), SAVE_DELAY));
|
||||
}
|
||||
|
||||
@@ -92,60 +89,15 @@ export class LibraryStore {
|
||||
for (const name of [...this.timers.keys()]) this.save(name);
|
||||
}
|
||||
|
||||
/** Write what is waiting, then write nothing more (the directory is about to be moved aside). */
|
||||
close() {
|
||||
this.flush();
|
||||
this.closed = true;
|
||||
}
|
||||
|
||||
/** A branch pushed by a replica that the server has not seen yet. */
|
||||
addBranch(name: string, doc: Doc) {
|
||||
this.branches.set(name, doc);
|
||||
this.save(name);
|
||||
}
|
||||
|
||||
// ---- starter files ----
|
||||
|
||||
private libraryFile() {
|
||||
return join(this.data, "library.json");
|
||||
}
|
||||
imported(): string[] {
|
||||
try {
|
||||
return JSON.parse(readFileSync(this.libraryFile(), "utf8")).imported ?? [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
markImported(id: string) {
|
||||
const ids = this.imported();
|
||||
if (!ids.includes(id)) writeFileSync(this.libraryFile(), JSON.stringify({ imported: [...ids, id] }, null, 2) + "\n");
|
||||
}
|
||||
|
||||
/** The first tree, written once. Like a starter file, it is not written again after being deleted. */
|
||||
seedFirst(write: (doc: Doc) => void) {
|
||||
if (this.imported().includes(SEED_KEY)) return;
|
||||
write(this.main);
|
||||
this.save("main");
|
||||
this.markImported(SEED_KEY);
|
||||
this.log("seeded the first tree from src/seed");
|
||||
}
|
||||
|
||||
/**
|
||||
* Import each starter file that has never been imported (by its file name), as a child of the
|
||||
* root at its end. A file that does not parse is logged and skipped (and tried again next start);
|
||||
* it never stops the server.
|
||||
*/
|
||||
importLibrary(dir: string) {
|
||||
if (!existsSync(dir)) return;
|
||||
const done = new Set(this.imported());
|
||||
let changed = false;
|
||||
for (const f of readdirSync(dir).filter((f) => f.endsWith(".md")).sort()) {
|
||||
const key = slugify(f.slice(0, -3));
|
||||
if (done.has(key)) continue;
|
||||
try {
|
||||
const text = readFileSync(join(dir, f), "utf8");
|
||||
const id = writeText(this.main, text, `library/${f}`);
|
||||
this.markImported(key);
|
||||
changed = true;
|
||||
this.log(`library: imported ${f} as “${this.main.snap().nodes[id].title}”`);
|
||||
} catch (err) {
|
||||
this.log(`library: skipped ${f}:\n ${err instanceof FormatError ? err.problems.join("\n ") : String(err)}`);
|
||||
}
|
||||
}
|
||||
if (changed) this.save("main");
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,14 @@ export class NodeIndex {
|
||||
}
|
||||
private active = false;
|
||||
|
||||
/** Stop keeping the index and write nothing more: the library is being moved aside. */
|
||||
close() {
|
||||
this.active = false;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.vectors.detach();
|
||||
}
|
||||
|
||||
private schedule() {
|
||||
if (this.timer || !this.delay || !this.active) return;
|
||||
this.timer = setTimeout(() => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Suggestions and what was decided about them. Derived data, so they live on the server under
|
||||
* <IE_DATA>/links/pending.json and never in the library.
|
||||
* <IE_DATA>/libraries/<id>/links/pending.json, one file per library, and never in the library.
|
||||
*
|
||||
* A scan replaces what was pending for its node, but what was decided is kept: the model
|
||||
* reviewer's verdict (link or not, and why), a person's decision, and when an approved link was
|
||||
@@ -176,6 +176,14 @@ export class PendingStore {
|
||||
this.timer.unref?.();
|
||||
}
|
||||
|
||||
/** Write what is waiting, then nothing more (the library is being moved aside). */
|
||||
close() {
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.flush();
|
||||
this.file = null;
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (!this.file) return;
|
||||
try {
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Whether a server has a data directory open. A server writes <data>/server.lock (its pid) while
|
||||
* it runs and removes it on the way out; a lock whose process is gone is stale and ignored.
|
||||
*
|
||||
* Servers from before the lock wrote none. For them (the migration must not run under one), on a
|
||||
* system with /proc, every process running `server/index.ts` is looked at: its checkout is found
|
||||
* from its command line and working directory, and it counts if that checkout's default data
|
||||
* directory (`<checkout>/.data`) is this one. Only command lines and working directories are read,
|
||||
* never a process's environment, so a server started with IE_DATA pointing elsewhere is still
|
||||
* reported if it runs from the checkout whose `.data` this is.
|
||||
*/
|
||||
import { existsSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { writeAtomic } from "./util";
|
||||
|
||||
export const LOCK = "server.lock";
|
||||
|
||||
interface Lock {
|
||||
pid: number;
|
||||
port?: number;
|
||||
started?: string;
|
||||
}
|
||||
|
||||
const alive = (pid: number) => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return (err as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
};
|
||||
|
||||
const real = (p: string) => {
|
||||
try {
|
||||
return realpathSync(p);
|
||||
} catch {
|
||||
return resolve(p);
|
||||
}
|
||||
};
|
||||
|
||||
/** The process holding the lock on this data directory, if it is still running (and is not this one). */
|
||||
export function lockHolder(data: string): Lock | null {
|
||||
const file = join(data, LOCK);
|
||||
if (!existsSync(file)) return null;
|
||||
try {
|
||||
const lock = JSON.parse(readFileSync(file, "utf8")) as Lock;
|
||||
if (!Number.isInteger(lock.pid) || lock.pid === process.pid || !alive(lock.pid)) return null;
|
||||
// A pid can be reused: where /proc says what runs under it, it must be a server.
|
||||
const cmd = cmdline(lock.pid);
|
||||
if (cmd && !cmd.some((a) => a.endsWith("server/index.ts"))) return null;
|
||||
return lock;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function cmdline(pid: number): string[] | null {
|
||||
try {
|
||||
return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\u0000").filter(Boolean);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Servers without a lock: processes running server/index.ts from the checkout whose `.data` this is. */
|
||||
export function unlockedServers(data: string): number[] {
|
||||
if (!existsSync("/proc")) return [];
|
||||
const want = real(data);
|
||||
const out: number[] = [];
|
||||
for (const name of readdirSync("/proc")) {
|
||||
if (!/^\d+$/.test(name)) continue;
|
||||
const pid = Number(name);
|
||||
if (pid === process.pid) continue;
|
||||
const args = cmdline(pid);
|
||||
const script = args?.find((a) => a.endsWith("server/index.ts"));
|
||||
if (!script) continue;
|
||||
try {
|
||||
const cwd = readlinkSync(`/proc/${pid}/cwd`);
|
||||
const checkout = dirname(dirname(resolve(cwd, script)));
|
||||
if (real(join(checkout, ".data")) === want) out.push(pid);
|
||||
} catch {
|
||||
/* gone, or not ours to look at */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Why the data directory is not free, or null if no server has it open. */
|
||||
export function busy(data: string): string | null {
|
||||
const lock = lockHolder(data);
|
||||
if (lock) return `a server (pid ${lock.pid}${lock.port ? `, port ${lock.port}` : ""}) has ${data} open`;
|
||||
const pids = unlockedServers(data);
|
||||
if (pids.length) return `a server (pid ${pids.join(", ")}) is running from the checkout whose data directory is ${data}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Take the lock for this process; it is let go on exit. */
|
||||
export function takeLock(data: string, port: number) {
|
||||
const file = join(data, LOCK);
|
||||
writeAtomic(file, JSON.stringify({ pid: process.pid, port, started: new Date().toISOString() }) + "\n");
|
||||
process.on("exit", () => {
|
||||
try {
|
||||
const lock = JSON.parse(readFileSync(file, "utf8")) as Lock;
|
||||
if (lock.pid === process.pid) rmSync(file, { force: true });
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* From one Loro database per document to one library, once, on the first start that finds the
|
||||
* older layout and no library:
|
||||
*
|
||||
* <data>/docs/<id>/<branch>.loro the per-document layout
|
||||
* <data>/<branch>.loro the single-document layout before it (the first document)
|
||||
*
|
||||
* Every document's main branch is imported into one new Loro database, histories and all: each
|
||||
* document's ops keep their ids, so its notes stay anchored, its open conflicts stay open, and
|
||||
* every commit it ever made can still be checked out and verified (a checkout from before the
|
||||
* library shows that document alone, as it stood). One commit then makes the Library root and
|
||||
* moves each document's root under it, in order. A document that shares
|
||||
* history with one already imported (a duplicate, which began as a byte copy) cannot be imported
|
||||
* beside it without merging into it, so it is copied in as content instead.
|
||||
*
|
||||
* The library is written to a temporary directory and renamed into place; only then is the old
|
||||
* `docs` directory renamed to `docs.migrated-<time>` (and flat files moved into
|
||||
* `flat.migrated-<time>`). Nothing in them is changed or deleted.
|
||||
* Branches other than main are not carried over; the log and migrated.json list them.
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { LoroDoc } from "loro-crdt";
|
||||
import { Doc, LIBRARY_TITLE, initRoot, randomPeer, type NodeId } from "../src/core/model";
|
||||
import { encodeVV } from "../src/core/repo";
|
||||
|
||||
/** The first document's old id (its directory, and its entry in library.json). */
|
||||
export const SEED_KEY = "infinite-expand";
|
||||
const SEED_SLUG = SEED_KEY;
|
||||
/** An old document id: also a directory name, so nothing that could leave its directory. */
|
||||
const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
|
||||
|
||||
interface Source {
|
||||
id: string;
|
||||
dir: string | null;
|
||||
main: Uint8Array;
|
||||
/** Every branch's version, for browsers checking what they hold against what was migrated. */
|
||||
versions: Record<string, string>;
|
||||
uid: string | null;
|
||||
changed: number;
|
||||
}
|
||||
|
||||
const stamp = () => new Date().toISOString().replace(/[-:]/g, "").replace(/\..*/, "").replace("T", "-");
|
||||
|
||||
function sources(data: string, log: (m: string) => void): Source[] {
|
||||
const out: Source[] = [];
|
||||
const read = (id: string, dir: string, files: string[]) => {
|
||||
const versions: Record<string, string> = {};
|
||||
let main: Uint8Array | null = null;
|
||||
for (const f of files) {
|
||||
const bytes = readFileSync(join(dir, f));
|
||||
const name = decodeURIComponent(f.slice(0, -5));
|
||||
if (name === "main") main = bytes;
|
||||
try {
|
||||
versions[name] = encodeVV(Doc.load(bytes, "migration").loro.version().toJSON());
|
||||
} catch (err) {
|
||||
log(`migration: ${join(dir, f)} could not be read (${err instanceof Error ? err.message : err}); left as it is`);
|
||||
}
|
||||
}
|
||||
if (!main) return log(`migration: ${dir} has no main.loro; left as it is`);
|
||||
let uid: string | null = null;
|
||||
try {
|
||||
uid = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")).uid ?? null;
|
||||
} catch {
|
||||
/* the single-document layout had no meta.json */
|
||||
}
|
||||
out.push({ id, dir, main, versions, uid, changed: statSync(join(dir, "main.loro")).mtimeMs });
|
||||
};
|
||||
const docs = join(data, "docs");
|
||||
if (existsSync(docs)) {
|
||||
for (const id of readdirSync(docs).sort()) {
|
||||
const dir = join(docs, id);
|
||||
if (!SLUG.test(id) || !statSync(dir).isDirectory()) continue;
|
||||
read(id, dir, readdirSync(dir).filter((f) => f.endsWith(".loro")));
|
||||
}
|
||||
}
|
||||
const flat = readdirSync(data).filter((f) => f.endsWith(".loro"));
|
||||
if (flat.length) {
|
||||
if (out.some((s) => s.id === SEED_SLUG)) log(`migration: ${flat.join(", ")} in ${data} left aside: docs/${SEED_SLUG} is the newer copy`);
|
||||
else read(SEED_SLUG, data, flat);
|
||||
}
|
||||
// The first document first, then the order the documents menu showed: most recently changed first.
|
||||
return out.sort((a, b) => (a.id === SEED_SLUG ? -1 : b.id === SEED_SLUG ? 1 : b.changed - a.changed));
|
||||
}
|
||||
|
||||
/** Build the library from the older layout. Returns false if there was nothing to migrate. */
|
||||
export function migrate(data: string, log: (m: string) => void): boolean {
|
||||
if (!existsSync(data)) return false;
|
||||
const found = sources(data, log);
|
||||
if (!found.length) return false;
|
||||
|
||||
const lib = new Doc(new LoroDoc(), "migration");
|
||||
lib.loro.setPeerId(randomPeer());
|
||||
const plan: { src: Source; snap: ReturnType<Doc["snap"]>; root: NodeId; kept: boolean; commits: number; conflicts: number }[] = [];
|
||||
for (const src of found) {
|
||||
const old = Doc.load(src.main, "migration");
|
||||
const snap = old.snap();
|
||||
const ours = lib.loro.version().toJSON();
|
||||
const shared = [...old.loro.version().toJSON().keys()].some((peer) => ours.has(peer));
|
||||
if (!shared) lib.loro.import(src.main);
|
||||
const commits = [...old.loro.getAllChanges().values()].reduce((n, cs) => n + cs.length, 0);
|
||||
plan.push({ src, snap, root: snap.root, kept: !shared, commits, conflicts: old.conflicts().filter((c) => c.status === "open").length });
|
||||
}
|
||||
|
||||
const message = `Gather ${plan.length} document${plan.length > 1 ? "s" : ""} into the library`;
|
||||
lib.begin(message, "human", "migrate");
|
||||
const tree = lib.tree;
|
||||
const root = tree.createNode();
|
||||
initRoot(root, LIBRARY_TITLE, "", "human");
|
||||
root.data.set("library", true);
|
||||
lib.loro.getMap("meta").set("library", randomPeer().toString(36));
|
||||
for (const p of plan) {
|
||||
if (p.kept) tree.move(p.root, root.id, root.children()?.length ?? 0);
|
||||
else lib.graft(p.snap, p.snap.root, root.id);
|
||||
}
|
||||
lib.reread();
|
||||
lib.commit(message, "human", "migrate");
|
||||
|
||||
// Every document must have come across whole before anything is written. A copied one can
|
||||
// differ only by anchors that were already lost (an orphaned note's empty span is not copied).
|
||||
const snap = lib.snap();
|
||||
for (const [i, p] of plan.entries()) {
|
||||
const id = snap.nodes[root.id].children[i];
|
||||
const same = !!id && lib.shape(snap, id) === lib.shape(p.snap, p.snap.root);
|
||||
if (!same && (p.kept || !id)) throw new Error(`migration: “${p.src.id}” did not come across intact; nothing was changed on disk`);
|
||||
if (!same) log(`migration: “${p.src.id}” was copied without the empty spans of its orphaned notes`);
|
||||
}
|
||||
|
||||
const when = stamp();
|
||||
const moved = existsSync(join(data, "docs")) ? `docs.migrated-${when}` : null;
|
||||
const flatFiles = readdirSync(data).filter((f) => f.endsWith(".loro"));
|
||||
const flatMoved = flatFiles.length ? `flat.migrated-${when}` : null;
|
||||
const record = {
|
||||
at: new Date().toISOString(),
|
||||
from: [moved, flatMoved].filter(Boolean),
|
||||
docs: plan.map((p) => ({
|
||||
slug: p.src.id,
|
||||
uid: p.src.uid,
|
||||
title: p.snap.nodes[p.snap.root].title,
|
||||
nodes: Object.keys(p.snap.nodes).length,
|
||||
history: p.kept ? "kept" : "copied",
|
||||
commits: p.commits,
|
||||
openConflicts: p.kept ? p.conflicts : 0,
|
||||
versions: p.src.versions,
|
||||
})),
|
||||
branchesNotCarried: plan.flatMap((p) => Object.keys(p.src.versions).filter((b) => b !== "main").map((b) => ({ doc: p.src.id, branch: b }))),
|
||||
};
|
||||
|
||||
const tmp = join(data, `library.tmp-${stamp()}`);
|
||||
mkdirSync(tmp, { recursive: true });
|
||||
writeFileSync(join(tmp, "main.loro"), lib.snapshotBytes());
|
||||
writeFileSync(join(tmp, "migrated.json"), JSON.stringify(record, null, 2) + "\n");
|
||||
renameSync(tmp, join(data, "library"));
|
||||
|
||||
// Only now that the library is in place does the old layout move aside, renamed, untouched.
|
||||
if (moved) renameSync(join(data, "docs"), join(data, moved));
|
||||
if (flatMoved) {
|
||||
mkdirSync(join(data, flatMoved));
|
||||
for (const f of flatFiles) renameSync(join(data, f), join(data, flatMoved, f));
|
||||
}
|
||||
const kept = [moved, flatMoved].filter(Boolean).map((d) => join(data, d!)).join(" and ");
|
||||
|
||||
log(`migration: built ${join(data, "library", "main.loro")} from ${plan.length} document${plan.length > 1 ? "s" : ""}:`);
|
||||
for (const d of record.docs) {
|
||||
log(
|
||||
` ${d.slug} “${d.title}” ${d.nodes} nodes, ${d.history === "kept" ? `history kept (${d.commits} changes)` : "copied as content (it shares history with another document, so its history is not carried)"}${d.openConflicts ? `, ${d.openConflicts} open conflict${d.openConflicts > 1 ? "s" : ""}` : ""}`,
|
||||
);
|
||||
}
|
||||
if (record.branchesNotCarried.length) {
|
||||
log(`migration: branches other than main were not carried over (they are still in ${kept}):`);
|
||||
for (const b of record.branchesNotCarried) log(` ${b.doc}: ${b.branch}`);
|
||||
}
|
||||
log(`migration: the old files are in ${kept}, unchanged.`);
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user