// Projection: the files a closed set of atoms produces. A pure function of the // set. Each file is a tree of lines hanging off its start node; linearizing it // depth-first, children in descending priority, gives the file's sequence. A // line hangs off the node it was written after, unless a move in the set gave // it another parent (#28): then the newest such move decides. // // A laid-out file is kept as arrays of line numbers (the graph's n), not as a // record per line (#46): a record, its id and two index entries cost about // 370 bytes a line, and the view cache holds up to 200,000 lines. Records are // made when a caller asks for them, and the latest asked for is kept. import type { Graph, RelocationInfo } from "./graph.ts"; import { isStartNode } from "./keys.ts"; import { joinLines } from "./text.ts"; import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts"; /** A line in a file's full sequence, tombstones included. */ export interface SeqLine { readonly id: LineId; readonly text: string; /** The atom that wrote it. */ readonly atom: AtomId; /** Atoms in the set that delete it, by seq. Empty when it is visible. */ readonly deletedBy: readonly AtomId[]; readonly visible: boolean; } /** A visible line of a projected file. */ export interface VisibleLine { readonly id: LineId; readonly text: string; readonly atom: AtomId; } /** A file's attributes in a view. */ export interface FileAttrs { /** Kept with no lines (an empty file). */ readonly exists: boolean; readonly exec: boolean; /** The target, when the file is a symbolic link. */ readonly link: string | null; /** The SHA-256 of its bytes, when the file is binary. */ readonly blob: string | null; } const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null }; const NONE: readonly never[] = Object.freeze([]); interface FileState { readonly attrs: FileAttrs; /** The file's sequence, tombstones included: each line's n. */ readonly seq: Int32Array; /** Its visible lines' n, in order. */ readonly vis: Int32Array; /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */ readonly deletedBy: ReadonlyMap; /** Positions by n, built the first time they're asked for. */ seqIndex?: Map; visIndex?: Map; } interface Child { readonly n: number; /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */ readonly replaces: number; readonly lamport: number; readonly seq: number; readonly k: number; } const EMPTY_INTS = new Int32Array(0); const NO_FILE: FileState = { attrs: NO_ATTRS, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() }; /** * The projection of a closed set. Construct once, then ask for files, lines * and sequences. Throws `not-closed` if some atom's dependency is missing. * Each file is laid out the first time it is asked for, so a view of a large * set costs little until files are read. */ export class View { readonly graph: Graph; /** The set, made from #in the first time it's asked for: a view keeps a byte per atom, not a copy of the set (#46). */ #set: Set | undefined; #files = new Map(); /** Every file the set wrote in, sorted; worked out the first time it's asked for. */ #knownList: string[] | undefined; /** 1 for each atom (by seq) in the set. */ #in: Uint8Array; /** Atoms in the set that move lines. */ #movers: AtomId[]; /** Each moved line's relocation that counts in this set; built on first use. */ #relocs: Map | undefined; /** The same, by n, with the new parent's code. */ #relocsN: Map | undefined; #fileOf = new Map(); /** The latest records asked for: one file's lines, one file's sequence, one file's text. */ #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined; #seqCache: { path: string; seq: readonly SeqLine[] } | undefined; #textCache: { path: string; text: string } | undefined; constructor(graph: Graph, set: Iterable) { const inSet = new Uint8Array(graph.size); const atoms: { readonly id: AtomId; readonly deps: readonly AtomId[] }[] = []; for (const id of set) { const atom = graph.atom(id); inSet[atom.seq] = 1; atoms.push(atom); } for (const atom of atoms) { for (const d of atom.deps) { if (inSet[graph.atom(d).seq] !== 1) throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`); } } this.graph = graph; this.#in = inSet; this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1); this.#relocs = this.#movers.length === 0 ? new Map() : undefined; this.#relocsN = this.#movers.length === 0 ? new Map() : undefined; } /** The set of atoms this view projects. */ get set(): AtomSet { if (!this.#set) { const out = new Set(); for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq)); this.#set = out; } return this.#set; } /** Whether the atom with this seq is in the set. */ #has(seq: number): boolean { return seq < this.#in.length && this.#in[seq] === 1; } /** * The relocation that counts for each moved line: the newest (by priority) * in the set. Two moves made apart can loop lines into each other, so no * start node reaches them; then the oldest relocation on the loop is * ignored, and the next newest of that line counts, until none loop. */ #relocations(): Map { if (this.#relocs) return this.#relocs; const graph = this.graph; const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0; const ignored = new Set(); const pick = (line: LineId): RelocationInfo | undefined => { let best: RelocationInfo | undefined; for (const r of graph.relocationsOf(line)) { if (this.#has(graph.atom(r.atom).seq) && !ignored.has(r) && (!best || stronger(r, best))) best = r; } return best; }; const relocs = new Map(); for (const id of this.#movers) { for (const m of graph.atom(id).moves!) { if (!relocs.has(m.line)) relocs.set(m.line, pick(m.line)!); } } const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!; const reaches = new Set(); for (const line of [...relocs.keys()]) { for (;;) { const path: LineId[] = []; const onPath = new Map(); let cur: NodeId = line; let loopAt = -1; while (!isStartNode(cur) && !reaches.has(cur)) { const at = onPath.get(cur); if (at !== undefined) { loopAt = at; break; } onPath.set(cur, path.length); path.push(cur); cur = parentOf(cur); } if (loopAt < 0) { for (const l of path) reaches.add(l); break; } let weakest: RelocationInfo | undefined; for (const l of path.slice(loopAt)) { const r = relocs.get(l); if (r && (!weakest || stronger(weakest, r))) weakest = r; } ignored.add(weakest!); const next = pick(weakest!.line); if (next) relocs.set(weakest!.line, next); else relocs.delete(weakest!.line); } } this.#relocs = relocs; return relocs; } /** The relocations by n, with each new parent's code. */ #relocationsN(): Map { if (this.#relocsN) return this.#relocsN; const out = new Map(); for (const [line, r] of this.#relocations()) out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! }); this.#relocsN = out; return out; } /** The node a line hangs off in this set: where it was written, or where a move put it. */ parentOf(line: LineId): NodeId { const r = this.#movers.length === 0 ? undefined : this.#relocations().get(line); if (r) return r.parent; const parent = this.graph.lineParent(line); if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`); return parent; } /** Whether any atom in the set moves lines. */ hasMoves(): boolean { return this.#movers.length > 0; } /** The file a line is in, in this set: the one its chain of parents reaches. */ fileOf(line: LineId): string { const n = this.graph.lineN(line); if (n < 0) throw new EngineError("unknown-line", `no line ${line}`); return this.#fileOfN(n); } #fileOfN(n: number): string { const graph = this.graph; if (this.#movers.length === 0) return graph.writtenIn(n); const relocs = this.#relocationsN(); const path: number[] = []; let cur = n; let file: string | undefined; while (file === undefined) { if (cur < 0) file = graph.nodeOf(cur).slice(1); else { file = this.#fileOf.get(cur); if (file === undefined) { path.push(cur); cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur); } } } for (const l of path) this.#fileOf.set(l, file); return file; } /** The lines hanging off a node in this set, in layout order. */ #children(code: number): Child[] { const graph = this.graph; const relocs = this.#movers.length === 0 ? undefined : this.#relocationsN(); const ns: number[] = []; graph.childrenN(code, ns); const out: Child[] = []; for (const n of ns) { const seq = graph.writerSeqOf(n); if (!this.#has(seq) || relocs?.has(n)) continue; out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) }); } if (relocs) { for (const r of graph.relocatedToCode(code)) { const n = graph.lineN(r.line); if (relocs.get(n)?.r !== r) continue; const seq = graph.atom(r.atom).seq; out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k }); } } // A line's replacements (runs of atoms that deleted it) first, then the // rest; each group in descending priority (lamport, then seq); lines of // one atom keep k order. A replacement already outranks every insertion // after the line that reads it (it depends on them, or conflicts with // them); the grouping also puts it above a `before` insertion, which // doesn't read the line above, so the new text lands in the replaced // line's place. A moved line ranks like an insertion by the moving atom. if (out.length > 1) out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k); return out; } /** Lay out one file: its line tree from the set's atoms, linearized. */ #layout(path: string): FileState { const graph = this.graph; // For each attribute, the highest-priority setter in the set wins. const setters = new Map(); for (const id of graph.atomsIn(path)) { if (!this.#has(graph.atom(id).seq)) continue; for (const a of graph.atom(id).attrs ?? []) { if (a.file !== path) continue; const best = setters.get(a.name); if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value }); } } const seq: number[] = []; const vis: number[] = []; const deletedBy = new Map(); // Depth-first, iteratively (a file of n lines can be a chain n deep). const stack: number[] = []; const pushChildren = (code: number): void => { const list = this.#children(code); for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n); }; const start = graph.startCodeOf(path); if (start !== undefined) pushChildren(start); const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b; while (stack.length > 0) { const n = stack.pop()!; const deleters = graph.deleterSeqsOf(n); const by = deleters.length === 0 ? NONE : deleters.filter((d) => this.#has(d)); if (by.length > 0) deletedBy.set(seq.length, by.length > 1 ? [...by].sort(priority) : by); else vis.push(n); seq.push(n); pushChildren(n); } const attrs: FileAttrs = { exists: setters.get("exists")?.value === "1", exec: setters.get("exec")?.value === "1", link: setters.get("link")?.value ?? null, blob: setters.get("blob")?.value ?? null, }; return { attrs, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy }; } get #known(): string[] { if (!this.#knownList) { const known = new Set(); for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file); this.#knownList = [...known].sort(); } return this.#knownList; } /** Files with at least one visible line, sorted. */ paths(): string[] { return this.#known.filter((p) => this.hasFile(p)); } /** Every file the set has ever written a line in, including fully deleted ones. */ knownPaths(): string[] { return [...this.#known]; } /** Whether the file exists in this projection (has a visible line). */ hasFile(path: string): boolean { const f = this.#file(path); return f.vis.length > 0 || f.attrs.exists || f.attrs.link !== null || f.attrs.blob !== null; } /** A file's attributes: kept while empty, executable, a link's target. */ attrs(path: string): FileAttrs { return this.#file(path).attrs; } /** The projected text of a file ("" if it has no visible lines). */ text(path: string): string { if (this.#textCache?.path === path) return this.#textCache.text; const vis = this.#file(path).vis; const lines: string[] = new Array(vis.length); for (let i = 0; i < vis.length; i++) lines[i] = this.graph.textOf(vis[i]!); const text = joinLines(lines); this.#textCache = { path, text }; return text; } /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */ sameText(path: string, other: View): boolean { const a = this.#file(path).vis; const b = other.#file(path).vis; if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false; return true; } /** Visible lines with their ids. */ lines(path: string): readonly VisibleLine[] { if (this.#linesCache?.path === path) return this.#linesCache.lines; const graph = this.graph; const vis = this.#file(path).vis; const lines: VisibleLine[] = new Array(vis.length); for (let i = 0; i < vis.length; i++) { const n = vis[i]!; lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) }; } this.#linesCache = { path, lines }; return lines; } /** The full linearized sequence of a file, tombstones included. */ sequence(path: string): readonly SeqLine[] { if (this.#seqCache?.path === path) return this.#seqCache.seq; const graph = this.graph; const f = this.#file(path); const out: SeqLine[] = new Array(f.seq.length); for (let i = 0; i < f.seq.length; i++) { const n = f.seq[i]!; const by = f.deletedBy.get(i); out[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)), deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE, visible: by === undefined, }; } this.#seqCache = { path, seq: out }; return out; } /** Index of a line in `sequence(path)`, or -1. */ sequenceIndex(path: string, line: LineId): number { const f = this.#file(path); if (!f.seqIndex) { f.seqIndex = new Map(); for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i); } return f.seqIndex.get(this.graph.lineN(line)) ?? -1; } /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */ lineNumber(path: string, line: LineId): number { const f = this.#file(path); if (!f.visIndex) { f.visIndex = new Map(); for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i); } return f.visIndex.get(this.graph.lineN(line)) ?? -1; } /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */ files(): Record { const out: Record = {}; for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path); return out; } /** Binary files, path -> the SHA-256 of their bytes, in path order. */ blobs(): Record { const out: Record = {}; for (const path of this.paths()) { const blob = this.#file(path).attrs.blob; if (blob !== null) out[path] = blob; } return out; } /** * About how many bytes keeping this view costs (#46): its laid-out files * (4 bytes a line, and more for a deleted line and for positions once asked * for), and the records it keeps for the file it was last asked about. */ weight(): number { let n = 0; for (const f of this.#files.values()) n += 4 * (f.seq.length + f.vis.length) + 40 * f.deletedBy.size + 24 * ((f.seqIndex?.size ?? 0) + (f.visIndex?.size ?? 0)); n += 100 * (this.#linesCache?.lines.length ?? 0) + 120 * (this.#seqCache?.seq.length ?? 0) + 2 * (this.#textCache?.text.length ?? 0); return n; } #file(path: string): FileState { let state = this.#files.get(path); if (!state) { state = this.graph.atomsIn(path).length === 0 ? NO_FILE : this.#layout(path); this.#files.set(path, state); } return state; } } /** The files of a closed set, path -> text. */ export function project(graph: Graph, set: Iterable): Record { return new View(graph, set).files(); } /** Where a node sits in a file's sequence: the index just after it (0 for a start node). */ export function indexAfter(view: View, path: string, node: NodeId): number { if (isStartNode(node)) return 0; const i = view.sequenceIndex(path, node); if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`); return i + 1; }