Cotton code
373 lines · 16.1 KB · RustRaw
//! The phone fold: every stored phone into the form `protocol::phone` writes//! now (libphonenumber, 22 Oct 2026). A data move, not a schema change.//!//! SHAPE (data, no version): `cotton_person_handles.normalised` (and the id//! derived from it), `cotton_msg_contacts.phone_e164` and the phone rows of//! `cotton_msg_contact_handles` (and their derived ids) lose the trunk 0 the//! earlier normaliser kept after the country code — "+91 098765 43210" was//! 9109876543210 and is 919876543210, "+44 (0)20 7946 0958" was 4402079460958//! and is 442079460958 — so the same number from another source matches.//!//! It runs ONCE per file, at the first open by a build that has it, in one//! transaction that also sets its done-marker: bit [`FOLDED`] of the file//! header's `application_id`, which is no schema object (a marker row or//! column would be a schema change) and travels with every copy of the file.//! Every later open reads that one header word and nothing else. Every device//! runs the same pass over the same rows, so the ids and values agree wherever//! it ran; like the shape move's folds it writes in place and keeps each//! row's own stamp. The pass is idempotent, so a copy that lost its header//! word folds again and changes nothing.//!//! A SECOND pass, with its own marker bit [`FOLDED_IN_REGION`], reads the//! numbers stored WITHOUT a code in the owner's region ([`region_hint`]: the//! country of the owner's own number, from the owner's person record) —//! "09876543210" and "9876543210" become 919876543210 for an Indian owner.//! With no owner number there is no region: nothing changes and the bit stays//! clear, so the pass runs once the owner's number is there.//!//! When two rows coincide://! - two handles of ONE person collapse to one (the row already holding the//!   number, else the oldest);//! - handles of TWO people: the row already holding the number keeps it, else//!   the oldest; the other person keeps their handle as it was stored. People//!   are never merged here (the person suggestion that once linked the two//!   left with TABLE DROP 1);//! - two message contacts: the oldest takes the number, the other keeps the//!   one it had; a contact that kept its number keeps its handle too.use std::collections::{BTreeMap, BTreeSet};use rusqlite::types::Value;use crate::driver::Driver;use crate::error::Result;use crate::file_identity::{read_file_identity, Namespace};use crate::protocol::derived_id::{contact_handle_id, person_handle_id};use crate::protocol::person_handles::{normalise_handle, normalise_handle_in, HandleKind, PERSON_HANDLES};use crate::protocol::phone::{refold_stored_phone, refold_stored_phone_in, region_of, Region};const CONTACTS: &str = "cotton_msg_contacts";const CONTACT_HANDLES: &str = "cotton_msg_contact_handles";/// What one pass did, in counts only.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct PhoneFoldReport {    /// Person handles now under the new form.    pub handles_moved: usize,    /// Person handles removed because the same person already holds the number.    pub handles_collapsed: usize,    /// Person handles left as stored because another person holds the number.    pub handles_kept: usize,    pub contacts_moved: usize,    /// Contacts left as stored because another contact holds the number.    pub contacts_kept: usize,    pub contact_handles_moved: usize,    pub contact_handles_collapsed: usize,    pub contact_handles_kept: usize,    /// Whether the region pass ran in this call.    pub region_pass: bool,}impl PhoneFoldReport {    /// Nothing moved, collapsed or asked: the file was already folded.    pub fn wrote_nothing(&self) -> bool {        // `region_pass` alone writes its marker and nothing else.        self.handles_moved + self.handles_collapsed + self.contacts_moved            + self.contact_handles_moved + self.contact_handles_collapsed            == 0    }}impl std::fmt::Display for PhoneFoldReport {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        write!(            f,            "phone fold{}: handles {} moved, {} collapsed, {} kept; contacts {} moved, {} kept; contact handles {} moved, {} collapsed, {} kept",            if self.region_pass { " (with the owner's region)" } else { "" },            self.handles_moved,            self.handles_collapsed,            self.handles_kept,            self.contacts_moved,            self.contacts_kept,            self.contact_handles_moved,            self.contact_handles_collapsed,            self.contact_handles_kept        )    }}/// The done-marker of the first pass: this bit of `PRAGMA application_id`/// says the file's phones were folded. The other bits are left as they are.pub const FOLDED: i64 = 1;/// The done-marker of the region pass.pub const FOLDED_IN_REGION: i64 = 2;/// Whether this file's phones were already folded (the first pass).pub fn folded(db: &Driver) -> Result<bool> {    Ok(application_id(db)? & FOLDED != 0)}fn application_id(db: &Driver) -> Result<i64> {    Ok(db.get("PRAGMA application_id", &[])?.and_then(|row| row.int("application_id")).unwrap_or(0))}/// The country to read a workspace's code-less numbers in: the country of the/// owner's own phone (the person `cotton_workspaces.owner_person_id` names),/// their first number libphonenumber holds valid, in the page's order. `None`/// when the owner has no such number — then there is no region at all.pub fn region_hint(db: &Driver, workspace_id: &str) -> Result<Option<Region>> {    let rows = db.all(        &format!(            "SELECT h.normalised FROM {PERSON_HANDLES} h JOIN cotton_workspaces w ON w.owner_person_id = h.person_id \             WHERE w.id = ? AND h.kind = 'phone' AND h.trashed_at IS NULL ORDER BY h.position, h.created_at, h.id"        ),        &[text(workspace_id)],    )?;    Ok(rows.iter().find_map(|row| region_of(row.text("normalised").unwrap_or_default())))}/// Fold this file's phones once per pass: nothing when both done-markers are/// set; else each pass not yet made, with its marker, in its own transaction./// A file with no identity (not yet a database) or without the tables has/// nothing to fold and is not marked, so it folds once it is one.pub fn fold_phones(db: &Driver) -> Result<PhoneFoldReport> {    let id = application_id(db)?;    if id & FOLDED != 0 && id & FOLDED_IN_REGION != 0 {        return Ok(PhoneFoldReport::default());    }    let Some(identity) = read_file_identity(db)? else {        return Ok(PhoneFoldReport::default());    };    for table in [PERSON_HANDLES, CONTACTS, CONTACT_HANDLES] {        if !db.table_exists(table)? {            return Ok(PhoneFoldReport::default());        }    }    let namespace = identity.namespace();    let mut report = PhoneFoldReport::default();    if id & FOLDED == 0 {        db.transaction(|db| {            person_handles(db, namespace, &mut report, &|_, value| normalise_handle(HandleKind::Phone, value))?;            let kept = contacts(db, &mut report, &may_fold("phone_e164"), &|_, stored| refold_stored_phone(stored))?;            contact_handles(db, namespace, &kept, &mut report, &may_fold("value"), &|_, stored| refold_stored_phone(stored))?;            // The header word is written in the same transaction as the rows.            db.exec(&format!("PRAGMA application_id = {}", application_id(db)? | FOLDED))        })?;    }    if id & FOLDED_IN_REGION == 0 {        let mut regions: BTreeMap<String, Region> = BTreeMap::new();        for row in db.all("SELECT id FROM cotton_workspaces", &[])? {            let workspace = row.text("id").unwrap_or_default().to_string();            if let Some(region) = region_hint(db, &workspace)? {                regions.insert(workspace, region);            }        }        if !regions.is_empty() {            let hinted = |workspace: &str| regions.get(workspace).copied();            db.transaction(|db| {                person_handles(db, namespace, &mut report, &|workspace, value| {                    normalise_handle_in(HandleKind::Phone, value, hinted(workspace))                })?;                let refold = |workspace: &str, stored: &str| hinted(workspace).and_then(|region| refold_stored_phone_in(stored, region));                let kept = contacts(db, &mut report, "1", &refold)?;                contact_handles(db, namespace, &kept, &mut report, "1", &refold)?;                db.exec(&format!("PRAGMA application_id = {}", application_id(db)? | FOLDED_IN_REGION))            })?;            report.region_pass = true;        }    }    Ok(report)}fn text(value: &str) -> Value {    Value::Text(value.to_string())}/// The row `old_id` of `table` again under `new_id`, with `column` = `value`/// and every other cell as it was, and the old row gone.fn move_row(db: &Driver, table: &str, old_id: &str, new_id: &str, column: &str, value: &str) -> Result<()> {    let columns: Vec<String> = db        .all(&format!("SELECT name FROM pragma_table_info('{table}') ORDER BY cid"), &[])?        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect();    let names = columns.iter().map(|name| format!("\"{name}\"")).collect::<Vec<_>>().join(",");    let cells = columns        .iter()        .map(|name| match name.as_str() {            "id" => "?1".to_string(),            name if name == column => "?2".to_string(),            name => format!("\"{name}\""),        })        .collect::<Vec<_>>()        .join(",");    db.run(        &format!("INSERT INTO \"{table}\" ({names}) SELECT {cells} FROM \"{table}\" WHERE id = ?3"),        &[text(new_id), text(value), text(old_id)],    )?;    remove_row(db, table, old_id)}fn remove_row(db: &Driver, table: &str, id: &str) -> Result<()> {    crate::receipts::implied::materialize_row(db, table, id)?;    db.run(&format!("DELETE FROM \"{table}\" WHERE id = ?"), &[text(id)])?;    Ok(())}struct Handle {    id: String,    workspace: String,    person: String,    normalised: String,    hlc: String,    created_at: String,}/// The form a handle's typed value takes, in its workspace.type HandleForm<'a> = dyn Fn(&str, &str) -> Option<String> + 'a;fn person_handles(db: &Driver, namespace: &Namespace, report: &mut PhoneFoldReport, form: &HandleForm<'_>) -> Result<()> {    let rows = db.all(        &format!(            "SELECT id, workspace_id, person_id, value, normalised, _hlc, created_at FROM {PERSON_HANDLES} \             WHERE kind = 'phone' ORDER BY created_at, id"        ),        &[],    )?;    // Who holds each number once the pass is done: every row that stays.    let mut holder: BTreeMap<(String, String), (String, String, String)> = BTreeMap::new();    let mut moving: Vec<(Handle, String)> = Vec::new();    for row in &rows {        let handle = Handle {            id: row.text("id").unwrap_or_default().to_string(),            workspace: row.text("workspace_id").unwrap_or_default().to_string(),            person: row.text("person_id").unwrap_or_default().to_string(),            normalised: row.text("normalised").unwrap_or_default().to_string(),            hlc: row.text("_hlc").unwrap_or_default().to_string(),            created_at: row.text("created_at").unwrap_or_default().to_string(),        };        match form(&handle.workspace, row.text("value").unwrap_or_default()) {            Some(new) if new != handle.normalised => moving.push((handle, new)),            _ => {                holder.insert(                    (handle.workspace.clone(), handle.normalised.clone()),                    (handle.person.clone(), handle.hlc.clone(), handle.created_at.clone()),                );            }        }    }    // Oldest first, so the older row keeps the number.    for (handle, new) in moving {        let key = (handle.workspace.clone(), new.clone());        match holder.get(&key).cloned() {            None => {                let id = person_handle_id(namespace, HandleKind::Phone.as_str(), &new);                move_row(db, PERSON_HANDLES, &handle.id, &id, "normalised", &new)?;                holder.insert(key, (handle.person.clone(), handle.hlc.clone(), handle.created_at.clone()));                report.handles_moved += 1;            }            Some((person, _, _)) if person == handle.person => {                remove_row(db, PERSON_HANDLES, &handle.id)?;                report.handles_collapsed += 1;            }            Some(_) => {                report.handles_kept += 1;                holder.insert((handle.workspace.clone(), handle.normalised.clone()), (handle.person.clone(), handle.hlc.clone(), handle.created_at.clone()));            }        }    }    Ok(())}/// A stored number whose digits could have kept a trunk 0 or a `00`: a 0 in/// the second, third or fourth place, after a country code of one to three.const MAY_FOLD: &str = "(substr({c}, 1, 2) = '00' OR substr({c}, 2, 1) = '0' OR substr({c}, 3, 1) = '0' OR substr({c}, 4, 1) = '0')";fn may_fold(column: &str) -> String {    MAY_FOLD.replace("{c}", column)}/// Fold the contacts' numbers; the ids of the contacts that kept theirs./// The new form of a stored number in its workspace, or `None` to leave it.type StoredForm<'a> = dyn Fn(&str, &str) -> Option<String> + 'a;fn contacts(db: &Driver, report: &mut PhoneFoldReport, candidates: &str, refold: &StoredForm<'_>) -> Result<BTreeSet<String>> {    let rows = db.all(        &format!(            "SELECT id, workspace_id, phone_e164 FROM {CONTACTS} WHERE phone_e164 IS NOT NULL AND phone_e164 <> '' AND {candidates} ORDER BY created_at, id"        ),        &[],    )?;    let mut kept = BTreeSet::new();    for row in &rows {        let (id, workspace, stored) = (            row.text("id").unwrap_or_default(),            row.text("workspace_id").unwrap_or_default(),            row.text("phone_e164").unwrap_or_default(),        );        let Some(new) = refold(workspace, stored) else { continue };        let taken = db.get(            &format!("SELECT 1 AS taken FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"),            &[text(workspace), text(&new)],        )?;        if taken.is_some() {            kept.insert(id.to_string());            report.contacts_kept += 1;            continue;        }        // A row's implied receipt is whole again before the row says something else (receipts/implied.rs).        crate::receipts::implied::materialize_row(db, CONTACTS, id)?;        db.run(&format!("UPDATE {CONTACTS} SET phone_e164 = ? WHERE id = ?"), &[text(&new), text(id)])?;        report.contacts_moved += 1;    }    Ok(kept)}fn contact_handles(    db: &Driver,    namespace: &Namespace,    kept: &BTreeSet<String>,    report: &mut PhoneFoldReport,    candidates: &str,    refold: &StoredForm<'_>,) -> Result<()> {    let rows = db.all(        &format!(            "SELECT id, workspace_id, contact_id, value FROM {CONTACT_HANDLES} WHERE kind = 'phone' AND {candidates} ORDER BY created_at, id"        ),        &[],    )?;    for row in &rows {        let (id, workspace, contact, stored) = (            row.text("id").unwrap_or_default(),            row.text("workspace_id").unwrap_or_default(),            row.text("contact_id").unwrap_or_default(),            row.text("value").unwrap_or_default(),        );        let Some(new) = refold(workspace, stored) else { continue };        if kept.contains(contact) {            report.contact_handles_kept += 1;            continue;        }        let holder = db.get(            &format!("SELECT contact_id FROM {CONTACT_HANDLES} WHERE workspace_id = ? AND kind = 'phone' AND value = ?"),            &[text(workspace), text(&new)],        )?;        match holder.as_ref().and_then(|row| row.text("contact_id")) {            None => {                move_row(db, CONTACT_HANDLES, id, &contact_handle_id(namespace, "phone", &new), "value", &new)?;                report.contact_handles_moved += 1;            }            Some(holder) if holder == contact => {                remove_row(db, CONTACT_HANDLES, id)?;                report.contact_handles_collapsed += 1;            }            Some(_) => report.contact_handles_kept += 1,        }    }    Ok(())}#[cfg(test)]#[path = "phone_fold_tests.rs"]mod tests;