/** * MERGE AND UNMERGE TWO PEOPLE, THE SERVER'S HALF (PEOPLE-DESIGN b.3; the contract is * assets/design/shared/CONTACTS-ANSWERS.md §5, `contacts.merge` and `contacts.unmerge`). * * The merge is split where the sealing forces it. The phone decides the sealed part: it fills the person it keeps from * the duplicate and seals that write itself. The server does what no phone can, because a phone holds only its own * app's tables: it repoints every link to a person, on every table, in one transaction. Links are clear, so the server * can read and move them. * * `merge_people {keep, drop}`: * - Every row whose clear link names `drop` names `keep` instead. A single link is replaced. A list of people * (`people`, `member_people`) has `drop` swapped for `keep`, never named twice. * - Suggestions are not moved: a decided one stays as history (b.3). * - A link inside a seal (film `recommended_by`, Health's `person`) cannot be read here. It is named in `left`, and the * phone that holds that app repoints it. * - The duplicate is archived with `merged_into` = keep, never binned, so it can come back. * - Each moved row is recorded with its value before the move (`person_merge`, server only). * * `unmerge_people {id}`: undoes every merge into `id` from the last 30 days that is not yet undone, newest first. * Each recorded row still pointing at `id` gets its earlier value back; a row moved or relinked since is left as it * is. The duplicate comes out of the archive. A row made after the merge stays with `id`. * * Both run inside the act's one transaction: all of it lands, or none of it. */ import type { Engine, Outcome } from "./engine.ts"; import { refuse } from "./http.ts"; import type { StoredRow } from "./store.ts"; type Data = Record; export const SCHEMA = ` CREATE TABLE IF NOT EXISTS person_merge (id TEXT PRIMARY KEY, keep TEXT NOT NULL, dropped TEXT NOT NULL, at TEXT NOT NULL, moved TEXT NOT NULL, undone_at TEXT); CREATE INDEX IF NOT EXISTS person_merge_keep ON person_merge (keep, at); `; /** How long an Unmerge is offered after a merge (CONTACTS-ANSWERS.md §2). */ export const UNMERGE_DAYS = 30; const PERSON = "person"; /** Tables whose person links a merge leaves where they are: a suggestion, decided or not, is history (b.3). */ const NOT_MOVED: ReadonlySet = new Set(["person_suggestion"]); interface Moved { /** Table, row id, column, and the value before the move (an id, or a list of ids). */ t: string; id: string; c: string; was: unknown; } interface Link { table: string; column: string; multiple: boolean; } /** Every link to a person a definition declares, split by whether the server can read it. */ function personLinks(engine: Engine): { clear: Link[]; sealed: string[] } { const clear: Link[] = []; const sealed: string[] = []; for (const t of engine.defs.tables.values()) { if (NOT_MOVED.has(t.id)) continue; for (const c of t.columns) { if (c.type !== "link" || c.link_to !== PERSON || c.computed) continue; if (t.id === PERSON && c.key === "merged_into") continue; if (t.seal && !t.seal.clear.includes(c.key)) sealed.push(`${t.id}.${c.key}`); else clear.push({ table: t.id, column: c.key, multiple: c.multiple === true }); } } return { clear, sealed }; } function idOf(args: Data, key: string, what: string): string { const v = args[key]; if (typeof v !== "string" || v === "") refuse(400, "bad_request", `${key} is ${what}`); return v; } function livePerson(engine: Engine, id: string, which: string): StoredRow { if (!engine.defs.table(PERSON)) refuse(404, "no_people", "this database keeps no people"); const row = engine.store.get(PERSON, id); if (!row || row.deleted) refuse(404, "no_such_person", `${which}: no such person`); return row; } /** The rows of `table` whose list `column` holds `target`. */ function holding(engine: Engine, table: string, column: string, target: string): StoredRow[] { return engine.store.listHolding(table, column, target); } /** `merge_people {keep, drop}`: every clear link to `drop` names `keep`; `drop` is archived, merged into `keep`. */ export function merge(engine: Engine, sql: SqlStorage, args: Data, now: string, version: number, outcome: Outcome): Data { const keepId = idOf(args, "keep", "the id of the person who stays"); const dropId = idOf(args, "drop", "the id of the person merged into keep"); if (keepId === dropId) refuse(400, "same_person", "keep and drop are the same person"); const keep = livePerson(engine, keepId, "keep"); const drop = livePerson(engine, dropId, "drop"); if (typeof keep.data.merged_into === "string" && keep.data.merged_into) refuse(409, "merged_away", "keep was itself merged into someone else: merge into that person instead"); if (typeof drop.data.merged_into === "string" && drop.data.merged_into) refuse(409, "merged_away", "drop was already merged into someone else"); const { clear, sealed } = personLinks(engine); const moved: Moved[] = []; const counts: Record = {}; for (const link of clear) { const rows = link.multiple ? holding(engine, link.table, link.column, dropId) : engine.store.list(link.table, { column: link.column, equals: dropId }); for (const row of rows) { if (link.table === PERSON && row.id === dropId) continue; const was = row.data[link.column]; let next: unknown = keepId; if (link.multiple) { const list = Array.isArray(was) ? (was as unknown[]) : []; next = list.includes(keepId) ? list.filter((v) => v !== dropId) : list.map((v) => (v === dropId ? keepId : v)); } engine.update(row, { [link.column]: next }, version, outcome); moved.push({ t: link.table, id: row.id, c: link.column, was }); counts[`${link.table}.${link.column}`] = (counts[`${link.table}.${link.column}`] ?? 0) + 1; } } engine.update(engine.store.get(PERSON, dropId) ?? drop, { archived_at: now, merged_into: keepId }, version, outcome); sql.exec("INSERT INTO person_merge (id, keep, dropped, at, moved) VALUES (?, ?, ?, ?, ?)", crypto.randomUUID(), keepId, dropId, now, JSON.stringify(moved)); return { id: keepId, drop: dropId, moved: counts, left: sealed }; } /** `unmerge_people {id}`: every merge into `id` from the last UNMERGE_DAYS undone, newest first. */ export function unmerge(engine: Engine, sql: SqlStorage, args: Data, now: string, version: number, outcome: Outcome): Data { const keepId = idOf(args, "id", "the id of the person others were merged into"); livePerson(engine, keepId, "id"); const since = new Date(Date.parse(now) - UNMERGE_DAYS * 86_400_000).toISOString(); const merges = sql .exec<{ id: string; dropped: string; moved: string }>("SELECT id, dropped, moved FROM person_merge WHERE keep = ? AND undone_at IS NULL AND at >= ? ORDER BY at DESC", keepId, since) .toArray(); if (!merges.length) refuse(404, "nothing_to_unmerge", `nobody was merged into this person in the last ${UNMERGE_DAYS} days`); const restored: string[] = []; for (const m of merges) { for (const r of JSON.parse(m.moved) as Moved[]) { const row = engine.store.get(r.t, r.id); if (!row || row.deleted) continue; const now_ = row.data[r.c]; let back: unknown = null; if (Array.isArray(r.was)) { if (!Array.isArray(now_) || !now_.includes(keepId)) continue; const was = r.was as unknown[]; back = was.includes(keepId) ? (now_.includes(m.dropped) ? now_ : [...now_, m.dropped]) : now_.map((v) => (v === keepId ? m.dropped : v)); } else { if (now_ !== keepId) continue; back = r.was; } engine.update(row, { [r.c]: back }, version, outcome); } const drop = engine.store.get(PERSON, m.dropped); if (drop && !drop.deleted) engine.update(drop, { archived_at: null, merged_into: null }, version, outcome); sql.exec("UPDATE person_merge SET undone_at = ? WHERE id = ?", now, m.id); restored.push(m.dropped); } return { ids: [keepId, ...restored] }; }