/** * The id of a `cotton_links` row — the port of `link_id_for` in * `crates/cotton-store/src/protocol/derived_id.rs`. * * A link's id is derived from its ends, so every writer of the same edge * arrives at the same row. The file the target lives in is part of the edge * (schema v53): a link to the personal database's X and a link to another database's X with the same id * are two rows. A `toDatabase` equal to the file the row is written into names * that file, so it reads as none — mint stores it null and the id must be the * one the stored row gives. * * Both implementations are pinned to the same vectors, * `crates/cotton-store/tests/fixtures/link-id-vectors.json`. */ import { createHash } from "node:crypto"; /** * `derived_id`: sha256 over the table name and the parts joined by `|`, as * UTF-8, rendered uuid-shaped (the first 32 hex digits, grouped 8-4-4-4-12). */ export function derivedId(table, parts) { const material = [table, ...parts].join("|"); const hex = createHash("sha256").update(material, "utf8").digest("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`; } /** * THE id of a `cotton_links` row written into the file `ownFile`. * * @param {{ fromKind: string, fromId: string, toKind: string, toId: string, toDatabase?: string | null }} ends * @param {string} ownFile */ export function linkIdFor(ends, ownFile) { const { fromKind, fromId, toKind, toId } = ends; const database = ends.toDatabase ?? null; if (database === null || database === ownFile) { return derivedId("cotton_links", [fromKind, fromId, toKind, toId]); } // `record_link_id_in`: the named database is mixed in LAST, after the four // ends, so a link with none keeps exactly the four-part id. return derivedId("cotton_links", [fromKind, fromId, toKind, toId, database]); }