Cotton code
766 lines · 33.1 KB · RustRaw
//! THE COTTON PACKAGE — one exchange format for anything a database holds.//!//! A `.cottonpkg` is a zip://!//! - `manifest.json` — `{format, schemaVersion, sourceDatabase, exportedAt,//!   tables: [{table, rows}], media: [{key, hash, table, id}]}`;//! - `<table>.jsonl` — one record per line, in the core's own column names and//!   with the record's own id, each value in its domain form (what an op's//!   patch carries, [`crate::schema::codecs::decode_row`]);//! - `media/<sha256>` — the bytes a record names, once per content.//!//! **An import is a write like any other.** Every record goes through//! [`crate::mint::mint`] as the caller's actor, so the receipts, the link//! rule, the owning parents and the search rows are exactly what a tap would//! have made; nothing is written into a replicated table by hand.//!//! **Records keep their ids, and importing twice changes nothing.** A record//! the file does not hold is created at its id; one it holds is changed in the//! columns that differ, and one that differs in nothing is left alone — no//! receipt, no history. Its `created_at` never moves, and `updated_at` only//! with a real change, so a file read again at a later hour is still nothing new.//!//! **The source database's own id becomes this one's.** A record carries the//! id of the database it was written in — `workspace_id`, and the `{file}/`//! prefix every media key starts with ([`crate::link_rule`] refuses a key under//! another database's prefix). On import, a value that IS the source's id, or//! starts with `{source}/`, is rewritten to this database's; the bytes land at//! the rewritten key ([`MediaSink`]). A reader that makes a package from//! another format (a vCard, a calendar) names any source it likes and writes//! that name where a record names its database.//!//! **The store holds no bytes.** Media is read through a [`MediaSource`] on//! export and written through a [`MediaSink`] on import; the shell that holds//! the bytes implements both. A key whose bytes the source does not have is//! reported ([`Exported::missing_media`]), never silently dropped.use std::collections::{BTreeMap, BTreeSet};use std::io::{Cursor, Read, Write};use rusqlite::types::Value as SqlValue;use serde::{Deserialize, Serialize};use serde_json::{Map, Value as JsonValue};use sha2::{Digest, Sha256};use crate::actor::Actor;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::file_identity::read_file_identity;use crate::mint::{mint, Act, Change, Clock, Held, History, IdSource, Kind};use crate::protocol::types::CottonOp;use crate::schema::codecs::{decode_row, encode_value};use crate::schema::decl::TableSpec;use crate::schema::ddl::SCHEMA_VERSION;use crate::schema::package_shape::spec_on;use crate::schema::table_specs::{is_handed_over, OWNING_REFS};/// The format this build writes and reads.pub const FORMAT: u32 = 1;/// The file extension a package is saved under.pub const EXTENSION: &str = "cottonpkg";const MANIFEST: &str = "manifest.json";const MEDIA_DIR: &str = "media/";/// The columns that stamp a record rather than say what it holds: an import/// never changes them on a record the file holds, unless (`updated_at`) it/// changes something else.const STAMPS: [&str; 2] = ["created_at", "updated_at"];/// How many records one act of an import mints.const BATCH: usize = 200;/// The tables a package never carries, each with why. A system table/// (`_`-prefixed) and a table one device or the serving Mac keeps to itself/// ([`is_handed_over`]) are refused beside these.pub const NOT_PACKAGED: &[(&str, &str)] = &[    ("cotton_workspaces", "a database's own row is what the database is, and it is never moved into another"),    ("cotton_databases", "the list of databases is the server's registry, not a record"),    ("cotton_database_departures", "a departure is a fact of who left this database"),    ("cotton_devices", "a device belongs to the database it was admitted to"),    ("cotton_device_keep", "what a device keeps is that device's own setting"),    ("cotton_device_relay_keys", "a relay key is a device's credential"),    ("cotton_device_statements", "a device statement is a signed fact of this database"),    ("cotton_mcp_tokens", "a token is a credential for this database"),    ("cotton_oauth_clients", "an OAuth client is a credential for this database"),    ("cotton_oauth_grants", "an OAuth grant is a credential for this database"),    ("cotton_grant_rotations", "a grant rotation is a fact of this database's credentials"),    ("cotton_code_credentials", "a code credential is a credential for this database"),    ("cotton_google_accounts", "a connected account is a credential for this database"),    ("cotton_agent_accounts", "an agent account is a credential for this database"),    ("cotton_secrets", "a secret is sealed under this database's vault key and opens nowhere else"),    ("cotton_secret_placements", "a secret's placement names a secret of this database's vault"),    ("cotton_placement_proposals", "a placement proposal names a secret of this database's vault"),    ("cotton_vault_keys", "a vault key is this database's own"),    ("cotton_vault_state", "the vault's state is this database's own"),    ("cotton_vault_retired_keys", "a retired vault key is this database's own"),    ("cotton_authors", "an author is a device's stream in this database"),    ("cotton_revocations", "a revocation is a fact of this database's devices and credentials"),    ("cotton_serving_machine", "which Mac serves a database is that database's own fact"),    ("cotton_person_keys", "a person's key is a membership credential"),    ("cotton_admissions", "an admission is a fact of who may open this database"),    ("cotton_member_person_claims", "a member's claim is a signed fact of this database"),    ("cotton_invites", "an invite admits people to this database"),    ("cotton_joined_places", "a joined place is a membership of this database"),    ("cotton_audiences", "an audience is this database's own sharing rule"),    ("cotton_undos", "an undo names receipts of this database"),    ("cotton_changes", "a change is this database's history of its own receipts"),    ("cotton_media_erasures", "an erasure is a fact of bytes this database let go"),    ("cotton_media_holdings", "a holding says which device holds which bytes"),    ("cotton_media_backups", "a backup record says where this database's bytes were copied"),    ("cotton_media_sightings", "a sighting is a device's own reading of its library"),    ("cotton_repo_clones", "a clone is one Mac's copy of a repository"),    ("cotton_machine_runners", "a runner is a process on one machine"),];/// What a package says about itself.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct Manifest {    pub format: u32,    /// The schema the records were read at. A package from a newer build is    /// refused: it may name columns this one does not hold.    pub schema_version: u32,    /// The id of the database the records were written in (or the name a    /// reader gave its source) — what an import rewrites to its own.    pub source_database: String,    pub exported_at: String,    pub tables: Vec<PackagedTable>,    #[serde(default)]    pub media: Vec<PackagedMedia>,}/// One table's file in the package.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct PackagedTable {    pub table: String,    pub rows: u64,}/// One media object a record names: the key as the source wrote it, the/// sha256 of its bytes (`media/<hash>`), and the record that names it.#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct PackagedMedia {    pub key: String,    pub hash: String,    pub table: String,    pub id: String,}/// A package in memory: what [`Package::to_bytes`] writes and/// [`Package::from_bytes`] reads, and what a reader of another format makes.#[derive(Debug, Clone, PartialEq)]pub struct Package {    pub manifest: Manifest,    /// Each table's records, in the manifest's order.    pub records: Vec<(String, Vec<Map<String, JsonValue>>)>,    /// The bytes, by sha256.    pub media: BTreeMap<String, Vec<u8>>,}/// Which records of one table an export takes.#[derive(Debug, Clone, PartialEq, Default)]pub struct Filter {    /// Only these record ids.    pub ids: Option<Vec<String>>,    /// Column → what it must hold; every entry must hold.    pub columns: Vec<(String, Match)>,}/// What one column of a [`Filter`] must hold.#[derive(Debug, Clone, PartialEq)]pub enum Match {    /// Any one of these values, in their domain form.    Values(Vec<JsonValue>),    /// Set (`true`) or empty (`false`).    Present(bool),}/// One table of an export, and which of its records.#[derive(Debug, Clone, PartialEq)]pub struct Selection {    pub table: String,    pub filter: Filter,}/// Where an export reads the bytes a record names.pub trait MediaSource {    /// The object at `key`, or `None` when this holder does not have it.    fn read(&mut self, key: &str) -> Result<Option<Vec<u8>>>;    /// Whether this holder has the object at `key`. A holder that can say so    /// without reading the bytes says so here.    fn has(&mut self, key: &str) -> Result<bool> {        Ok(self.read(key)?.is_some())    }}/// Where an import lands the bytes a record names.pub trait MediaSink {    /// Hold `bytes` at `key`. Called again with the same key and bytes when a    /// package is imported twice.    fn write(&mut self, key: &str, bytes: &[u8]) -> Result<()>;}/// What an export made.#[derive(Debug, Clone, PartialEq)]pub struct Exported {    /// The `.cottonpkg` file.    pub bytes: Vec<u8>,    pub manifest: Manifest,    /// Keys a record names whose bytes the source does not hold: the record    /// travels, its bytes do not.    pub missing_media: Vec<String>,}/// A record an import could not write, and why.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Refused {    pub table: String,    pub id: String,    pub reason: String,}/// What an import did.#[derive(Debug, Clone, PartialEq, Default)]pub struct Imported {    /// Records made, by table.    pub created: BTreeMap<String, u64>,    /// Records this file held that the package changed, by table.    pub changed: BTreeMap<String, u64>,    /// Records this file held exactly as the package has them, by table.    pub unchanged: BTreeMap<String, u64>,    pub refused: Vec<Refused>,    /// Media objects handed to the sink.    pub media_written: u64,    /// Every op the import minted, in order — what a caller wakes its live    /// channel with.    pub ops: Vec<CottonOp>,}fn refuse(message: impl std::fmt::Display) -> StoreError {    StoreError::refused(message)}fn malformed(message: impl std::fmt::Display) -> StoreError {    StoreError::refused(format!("this is not a Cotton package this build can read: {message}"))}/// The spec of a table a package may carry, or why it may not.pub fn packable(db: &Driver, table: &str) -> Result<&'static TableSpec> {    if table.starts_with('_') {        return Err(refuse(format!("{table} is a system table, and a package carries records")));    }    if let Some((_, why)) = NOT_PACKAGED.iter().find(|(name, _)| *name == table) {        return Err(refuse(format!("a package does not carry {table}: {why}")));    }    if !is_handed_over(table) {        return Err(refuse(format!("a package does not carry {table}: one machine keeps it to itself")));    }    spec_on(db, table)?.ok_or_else(|| refuse(format!("this database holds no table {table}")))}fn quoted(name: &str) -> String {    format!("\"{}\"", name.replace('"', "\"\""))}fn sha256_hex(bytes: &[u8]) -> String {    hex::encode(Sha256::digest(bytes))}fn this_database(db: &Driver) -> Result<crate::file_identity::FileId> {    read_file_identity(db)?        .map(|identity| identity.id().clone())        .ok_or_else(|| refuse("this file has no identity yet, so it has no records to package or to take"))}/// The records of `selection`'s table that its filter takes, live and not in/// the bin, in id order.fn selected_rows(db: &Driver, spec: &TableSpec, filter: &Filter) -> Result<Vec<Map<String, JsonValue>>> {    let mut clauses = Vec::new();    let mut params = Vec::new();    if spec.columns.iter().any(|(name, _)| *name == "trashed_at") {        clauses.push("\"trashed_at\" IS NULL".to_string());    }    // A message the person hid (deleted for me), or the hidden marker of one their own timer erased, is not a    // record they keep: no package carries it (CONTRACT.md "WhatsApp through the Mac").    if spec.columns.iter().any(|(name, _)| *name == "hidden_at") {        clauses.push("\"hidden_at\" IS NULL".to_string());    }    if let Some(ids) = &filter.ids {        if ids.is_empty() {            return Ok(Vec::new());        }        clauses.push(format!("{} IN ({})", quoted(spec.pk), vec!["?"; ids.len()].join(", ")));        params.extend(ids.iter().map(|id| SqlValue::Text(id.clone())));    }    for (column, wanted) in &filter.columns {        let codec = spec            .columns            .iter()            .find(|(name, _)| name == column)            .map(|(_, codec)| *codec)            .ok_or_else(|| refuse(format!("{} has no column {column}", spec.name)))?;        match wanted {            Match::Present(true) => clauses.push(format!("{} IS NOT NULL", quoted(column))),            Match::Present(false) => clauses.push(format!("{} IS NULL", quoted(column))),            Match::Values(values) if values.is_empty() => return Ok(Vec::new()),            Match::Values(values) => {                clauses.push(format!("{} IN ({})", quoted(column), vec!["?"; values.len()].join(", ")));                for value in values {                    params.push(encode_value(codec, value)?);                }            }        }    }    let condition = if clauses.is_empty() { String::new() } else { format!(" WHERE {}", clauses.join(" AND ")) };    let statement = format!("SELECT * FROM {}{condition} ORDER BY {}", quoted(spec.name), quoted(spec.pk));    db.all(&statement, &params)?        .iter()        .map(|row| decode_row(spec.columns, row.columns()))        .collect()}/// Package the records `selections` take, with the bytes they name.////// Refuses a table a package may not carry ([`packable`]), a table named/// twice and a filter column the table does not have. `exported_at` is the/// caller's clock: the store reads none.pub fn export_package(    db: &Driver,    selections: &[Selection],    media: &mut dyn MediaSource,    exported_at: &str,) -> Result<Exported> {    let file = this_database(db)?;    let mut seen = BTreeSet::new();    let mut package = Package {        manifest: Manifest {            format: FORMAT,            schema_version: SCHEMA_VERSION,            source_database: file.as_str().to_string(),            exported_at: exported_at.to_string(),            tables: Vec::new(),            media: Vec::new(),        },        records: Vec::new(),        media: BTreeMap::new(),    };    let mut missing = BTreeSet::new();    for selection in selections {        if !seen.insert(selection.table.clone()) {            return Err(refuse(format!("{} is named twice in one export", selection.table)));        }        let spec = packable(db, &selection.table)?;        let rows = selected_rows(db, spec, &selection.filter)?;        for row in &rows {            let id = row.get(spec.pk).and_then(JsonValue::as_str).unwrap_or_default().to_string();            let stored = crate::media_keys::keys_in_fields(spec.name, |column| row.get(column));            for key in crate::media_keys::keys_of_row(Some(&file), spec.name, &id, |column| row.get(column)) {                match media.read(&key)? {                    Some(bytes) => {                        let hash = sha256_hex(&bytes);                        package.media.entry(hash.clone()).or_insert(bytes);                        package.manifest.media.push(PackagedMedia {                            key,                            hash,                            table: spec.name.to_string(),                            id: id.clone(),                        });                    }                    // An id-built key names every container its record MIGHT                    // be filed under, so most of them have no bytes by design.                    None if !stored.contains(&key) => {}                    None => {                        missing.insert(key);                    }                }            }        }        package.manifest.tables.push(PackagedTable { table: spec.name.to_string(), rows: rows.len() as u64 });        package.records.push((spec.name.to_string(), rows));    }    package.manifest.media.sort();    package.manifest.media.dedup();    Ok(Exported {        bytes: package.to_bytes()?,        manifest: package.manifest,        missing_media: missing.into_iter().collect(),    })}impl Package {    /// The `.cottonpkg` file.    pub fn to_bytes(&self) -> Result<Vec<u8>> {        let zip_error = |error: zip::result::ZipError| refuse(format!("the package could not be written: {error}"));        let io_error = |error: std::io::Error| refuse(format!("the package could not be written: {error}"));        let options =            zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);        let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));        let manifest = serde_json::to_vec_pretty(&self.manifest).map_err(|error| refuse(error.to_string()))?;        writer.start_file(MANIFEST, options).map_err(zip_error)?;        writer.write_all(&manifest).map_err(io_error)?;        for (table, rows) in &self.records {            writer.start_file(format!("{table}.jsonl"), options).map_err(zip_error)?;            for row in rows {                let line = serde_json::to_vec(row).map_err(|error| refuse(error.to_string()))?;                writer.write_all(&line).map_err(io_error)?;                writer.write_all(b"\n").map_err(io_error)?;            }        }        // Media is mostly compressed already (JPEG, HEIC, M4A): stored as is.        let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);        for (hash, bytes) in &self.media {            writer.start_file(format!("{MEDIA_DIR}{hash}"), stored).map_err(zip_error)?;            writer.write_all(bytes).map_err(io_error)?;        }        Ok(writer.finish().map_err(zip_error)?.into_inner())    }    /// Read a `.cottonpkg` file, whole and checked: every table the manifest    /// names has its file with as many records, every record has an id and no    /// id comes twice, and every media object is there with the bytes its    /// hash says.    pub fn from_bytes(bytes: &[u8]) -> Result<Package> {        let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(malformed)?;        let manifest: Manifest = serde_json::from_slice(&entry(&mut archive, MANIFEST)?)            .map_err(|error| malformed(format!("{MANIFEST}: {error}")))?;        if manifest.format != FORMAT {            return Err(malformed(format!("it is format {}, and this build reads format {FORMAT}", manifest.format)));        }        let mut records = Vec::new();        let mut tables = BTreeSet::new();        for packaged in &manifest.tables {            if !tables.insert(packaged.table.clone()) {                return Err(malformed(format!("{} is listed twice", packaged.table)));            }            let text = String::from_utf8(entry(&mut archive, &format!("{}.jsonl", packaged.table))?)                .map_err(|_| malformed(format!("{}.jsonl is not UTF-8", packaged.table)))?;            let mut ids = BTreeSet::new();            let mut rows = Vec::new();            for (number, line) in text.lines().enumerate().filter(|(_, line)| !line.trim().is_empty()) {                let row: Map<String, JsonValue> = serde_json::from_str(line)                    .map_err(|error| malformed(format!("{}.jsonl line {}: {error}", packaged.table, number + 1)))?;                let id = row.get("id").and_then(JsonValue::as_str).unwrap_or_default().to_string();                if id.is_empty() {                    return Err(malformed(format!("{}.jsonl line {} has no id", packaged.table, number + 1)));                }                if !ids.insert(id.clone()) {                    return Err(malformed(format!("{}.jsonl names {id} twice", packaged.table)));                }                rows.push(row);            }            if rows.len() as u64 != packaged.rows {                return Err(malformed(format!(                    "{}.jsonl holds {} records and the manifest says {}",                    packaged.table,                    rows.len(),                    packaged.rows                )));            }            records.push((packaged.table.clone(), rows));        }        let mut media = BTreeMap::new();        for named in &manifest.media {            if media.contains_key(&named.hash) {                continue;            }            let bytes = entry(&mut archive, &format!("{MEDIA_DIR}{}", named.hash))?;            if sha256_hex(&bytes) != named.hash {                return Err(malformed(format!("{MEDIA_DIR}{} does not hold the bytes its name says", named.hash)));            }            media.insert(named.hash.clone(), bytes);        }        Ok(Package { manifest, records, media })    }}fn entry(archive: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str) -> Result<Vec<u8>> {    let mut file = archive.by_name(name).map_err(|_| malformed(format!("it has no {name}")))?;    let mut bytes = Vec::new();    file.read_to_end(&mut bytes).map_err(|error| malformed(format!("{name}: {error}")))?;    Ok(bytes)}/// Import a `.cottonpkg` file into this database ([`import`]).pub fn import_package(    db: &Driver,    bytes: &[u8],    actor: &Actor,    clock: &Clock,    ids: &mut dyn IdSource,    held: Held,    media: &mut dyn MediaSink,) -> Result<Imported> {    import(db, &Package::from_bytes(bytes)?, actor, clock, ids, held, media)}/// Write a package's records into this database as `actor`, through the mint,/// and land the bytes they name.////// Refuses the whole package when it is from a newer schema or names a table/// a package may not carry; a record the mint refuses is named in/// [`Imported::refused`] and the rest still land. Owning parents are written/// before their children, so a package holding both lands both.pub fn import(    db: &Driver,    package: &Package,    actor: &Actor,    clock: &Clock,    ids: &mut dyn IdSource,    held: Held,    media: &mut dyn MediaSink,) -> Result<Imported> {    if package.manifest.schema_version > SCHEMA_VERSION {        return Err(refuse(format!(            "this package was made by a newer Cotton (schema {}, this one reads up to {SCHEMA_VERSION}): update to import it",            package.manifest.schema_version        )));    }    let target = this_database(db)?;    let source = package.manifest.source_database.as_str();    let mut specs = BTreeMap::new();    for (table, _) in &package.records {        specs.insert(table.as_str(), packable(db, table)?);    }    let mut report = Imported::default();    let mut landed = BTreeSet::new();    for (table, rows) in parents_first(&package.records) {        let spec = specs[table.as_str()];        let mut pending = Vec::new();        for row in self_parents_first(table, rows) {            let id = row.get("id").and_then(JsonValue::as_str).unwrap_or_default().to_string();            let patch: Map<String, JsonValue> = row                .iter()                .map(|(column, value)| (column.clone(), rehomed(value, source, target.as_str(), spec.name, column)))                .collect();            match held_row(db, spec, &id)? {                None => pending.push(Change::create(spec.name, &id, patch)),                Some(current) => {                    let mut differs: Map<String, JsonValue> = patch                        .iter()                        .filter(|(column, value)| !STAMPS.contains(&column.as_str()) && current.get(*column) != Some(*value))                        .map(|(column, value)| (column.clone(), value.clone()))                        .collect();                    // A record's stamps are not its content: its birth never                    // moves, and `updated_at` moves only with a real change.                    if !differs.is_empty() {                        if let Some(updated) = patch.get("updated_at") {                            differs.insert("updated_at".to_string(), updated.clone());                        }                    }                    if differs.is_empty() {                        *report.unchanged.entry(table.clone()).or_insert(0) += 1;                        landed.insert((table.clone(), id));                    } else {                        pending.push(Change::update(spec.name, &id, differs));                    }                }            }        }        let mut created = 0;        let mut changed = 0;        let mut refused = Vec::new();        for batch in pending.chunks(BATCH) {            let written: Vec<&Change> = match mint_all(db, batch.to_vec(), actor, clock, ids, held) {                Ok(ops) => {                    report.ops.extend(ops);                    batch.iter().collect()                }                Err(_) => {                    // One record the mint refuses must not hold back the                    // rest: the batch is minted record by record, and each                    // refusal is named.                    let mut written = Vec::new();                    for change in batch {                        match mint_all(db, vec![change.clone()], actor, clock, ids, held) {                            Ok(ops) => {                                report.ops.extend(ops);                                written.push(change);                            }                            Err(error) => refused.push(Refused {                                table: table.clone(),                                id: change.row_id.clone(),                                reason: error.to_string(),                            }),                        }                    }                    written                }            };            for change in written {                if change.kind == Kind::Create {                    created += 1;                } else {                    changed += 1;                }                landed.insert((table.clone(), change.row_id.clone()));            }        }        if created > 0 {            *report.created.entry(table.clone()).or_insert(0) += created;        }        if changed > 0 {            *report.changed.entry(table.clone()).or_insert(0) += changed;        }        report.refused.extend(refused);    }    let mut written = BTreeSet::new();    for named in &package.manifest.media {        if !landed.contains(&(named.table.clone(), named.id.clone())) {            continue;        }        let key = rehomed_text(&named.key, source, target.as_str());        if !written.insert(key.clone()) {            continue;        }        let bytes = package            .media            .get(&named.hash)            .ok_or_else(|| malformed(format!("it names {MEDIA_DIR}{} and does not hold it", named.hash)))?;        media.write(&key, bytes)?;        report.media_written += 1;    }    Ok(report)}fn mint_all(    db: &Driver,    changes: Vec<Change>,    actor: &Actor,    clock: &Clock,    ids: &mut dyn IdSource,    held: Held,) -> Result<Vec<CottonOp>> {    let act = Act { actor: actor.clone(), verb: "import_package".to_string(), history: History::Kept, changes };    mint(db, &act, clock, ids, held).map(|minted| minted.ops)}/// The record at `id` as this file holds it, in domain form.fn held_row(db: &Driver, spec: &TableSpec, id: &str) -> Result<Option<Map<String, JsonValue>>> {    let statement = format!("SELECT * FROM {} WHERE {} = ?", quoted(spec.name), quoted(spec.pk));    db.get(&statement, &[SqlValue::Text(id.to_string())])?        .map(|row| decode_row(spec.columns, row.columns()))        .transpose()}/// `text` with the source database's id rewritten to the target's: the id/// itself, or a key under its `{id}/` prefix.fn rehomed_text(text: &str, source: &str, target: &str) -> String {    if text == source {        return target.to_string();    }    match text.strip_prefix(source).and_then(|rest| rest.strip_prefix('/')) {        Some(rest) => format!("{target}/{rest}"),        None => text.to_string(),    }}/// One value with the source database rewritten to the target. A media/// holder column that keeps its keys inside JSON (a message's items, a/// meeting's segments) has the keys inside rewritten too.fn rehomed(value: &JsonValue, source: &str, target: &str, table: &str, column: &str) -> JsonValue {    let holder = crate::media_keys::holders_of(table).any(|(name, _)| name == column);    match value {        JsonValue::String(text) if holder && matches!(text.trim_start().chars().next(), Some('[' | '{')) => {            match serde_json::from_str::<JsonValue>(text) {                Ok(parsed) => {                    let moved = rehomed_json(&parsed, source, target);                    if moved == parsed {                        value.clone()                    } else {                        JsonValue::String(moved.to_string())                    }                }                Err(_) => JsonValue::String(rehomed_text(text, source, target)),            }        }        JsonValue::String(text) => JsonValue::String(rehomed_text(text, source, target)),        JsonValue::Array(_) | JsonValue::Object(_) if holder => rehomed_json(value, source, target),        other => other.clone(),    }}fn rehomed_json(value: &JsonValue, source: &str, target: &str) -> JsonValue {    match value {        JsonValue::String(text) => JsonValue::String(rehomed_text(text, source, target)),        JsonValue::Array(items) => JsonValue::Array(items.iter().map(|item| rehomed_json(item, source, target)).collect()),        JsonValue::Object(fields) => JsonValue::Object(            fields.iter().map(|(name, field)| (name.clone(), rehomed_json(field, source, target))).collect(),        ),        other => other.clone(),    }}/// The package's tables with every owning parent ([`OWNING_REFS`]) before/// its children, and the definitions a person's own tables are made from/// before everything; otherwise in the package's order.fn parents_first(records: &[(String, Vec<Map<String, JsonValue>>)]) -> Vec<&(String, Vec<Map<String, JsonValue>>)> {    let named: BTreeSet<&str> = records.iter().map(|(table, _)| table.as_str()).collect();    let mut placed: BTreeSet<&str> = BTreeSet::new();    let mut out = Vec::new();    let definitions = records.iter().filter(|(table, _)| table.ends_with("_definitions"));    for entry in definitions {        placed.insert(entry.0.as_str());        out.push(entry);    }    while out.len() < records.len() {        let before = out.len();        for entry in records {            let table = entry.0.as_str();            if placed.contains(table) {                continue;            }            let waits = OWNING_REFS                .iter()                .any(|(child, _, parent)| *child == table && *parent != table && named.contains(parent) && !placed.contains(parent));            if !waits {                placed.insert(table);                out.push(entry);            }        }        if out.len() == before {            // A cycle between tables: the rest in the package's order, and            // the mint names any record whose parent is not there yet.            out.extend(records.iter().filter(|(table, _)| !placed.contains(table.as_str())));            break;        }    }    out}/// A table that owns its own rows (a comment's replies) with each parent/// record before the records under it.fn self_parents_first<'a>(table: &str, rows: &'a [Map<String, JsonValue>]) -> Vec<&'a Map<String, JsonValue>> {    let Some(column) = OWNING_REFS        .iter()        .find(|(child, _, parent)| *child == table && *parent == table)        .map(|(_, column, _)| *column)    else {        return rows.iter().collect();    };    let id_of = |row: &Map<String, JsonValue>| row.get("id").and_then(JsonValue::as_str).unwrap_or_default().to_string();    let present: BTreeSet<String> = rows.iter().map(id_of).collect();    let mut placed = BTreeSet::new();    let mut out = Vec::with_capacity(rows.len());    while out.len() < rows.len() {        let before = out.len();        for row in rows {            let id = id_of(row);            if placed.contains(&id) {                continue;            }            let parent = row.get(column).and_then(JsonValue::as_str);            if parent.is_none_or(|parent| !present.contains(parent) || placed.contains(parent)) {                placed.insert(id);                out.push(row);            }        }        if out.len() == before {            out.extend(rows.iter().filter(|row| !placed.contains(&id_of(row))));            break;        }    }    out}