Cotton code
222 lines · 9.3 KB · RustRaw
//! `read.you` — the owner's own person (Spec 10.3 "You").//!//! The database's owner IS a person in People, and the OBJECT says which//! (owner, 27 Oct 2026: people sign in with their phone number, so the person//! carrying that number is them, made when nobody does). The personal object//! links the person whose phone is the sign-in number and serves the link with//! the database's meta (`apps/business/src/owner.ts`); this phone's copy takes//! it onto its own workspace row, `cotton_workspaces.owner_person_id`//! (`cotton_client::transport::object::served_owner`), and nothing on a phone//! writes it. `read.you` answers that id and nothing else: it never makes a//! person, never links one, and never reads a name to find one. A name is//! shared, renamed and misspelt, and the "Me" card and every shared//! database's row for the owner key on this id; an owner found by name is lost//! by a rename. So a renamed person or a renamed database never loses "You".//!//! Until the copy holds the link and the person it names — a copy whose first//! pass has not landed them yet — `read.you` ANSWERS the typed//! `owner: "none_yet"` ([`NO_OWNER_YET`]) with no person: an ordinary state//! the next pass ends, not a failure, and nobody is guessed meanwhile. A//! person the object names is never in the bin: it follows a binned or merged//! owner by number on its next request. Nothing here asks a server, so a//! linked "You" opens with nothing reachable.//!//! The answer is the person (`person_id`, `name`, `print`: the face cut that//! travels with the row) and how this database is signed into NOW, in words//! (`sign_in`): this device's admission, how many devices are admitted, and//! which Mac serves the database. Nothing about an account — no email, no//! session, no GoTrue — because the admission IS how a person signs in.use serde_json::{json, Map, Value};use crate::shell::client::ClientController;use crate::shell::file::ReadFile;/// `read.you`'s `owner` while this copy does not hold the person the object/// names as you yet: no person, and nobody is guessed.pub const NO_OWNER_YET: &str = "none_yet";/// `read.you`'s `owner` once the copy holds the person the object names.pub const OWNER_LINKED: &str = "linked";/// `read.you`. A pure read of the PERSONAL database.pub fn read(client: &ClientController, _args: &Map<String, Value>) -> Result<Value, String> {    // You are a person of the PERSONAL database alone: read there whichever    // database the call names (methods::dispatch sets the scope from    // `database`), so a shared database never answers its own owner as "You".    client.require_personal()?;    let _personal = client.name_database(None)?;    let zone = client.time_zone().unwrap_or("UTC").to_string();    let this_device = client.self_device_id();    client.with_file(|file| {        let database_id = file.workspace_id.to_string();        let (sign_in, devices_count) = sign_in(file, this_device.as_deref(), &zone)?;        let person = match owner_of(file)? {            Some(id) => present_person(file, &id)?,            None => None,        };        let Some((person_id, name, print)) = person else {            return Ok(json!({                "database_id": database_id,                "owner": NO_OWNER_YET,                "person_id": null,                "name": null,                "print": null,                "sign_in": sign_in,                "devices_count": devices_count,            }));        };        Ok(json!({            "database_id": database_id,            "owner": OWNER_LINKED,            "person_id": person_id,            "name": name,            "print": print,            "sign_in": sign_in,            "devices_count": devices_count,        }))    })}/// The owner person's name while the link names a present person — what/// `read.account` answers `ownerName` by before it falls back to the/// workspace's own name.pub(super) fn owner_person_name(file: &ReadFile<'_>) -> Result<Option<String>, String> {    match owner_of(file)? {        Some(id) => Ok(present_person(file, &id)?.map(|(_, name, _)| name)),        None => Ok(None),    }}/// The person the link names — present or not — or `None` with no link.pub(super) fn owner_of(file: &ReadFile<'_>) -> Result<Option<String>, String> {    let row = file        .driver        .get(            "SELECT owner_person_id FROM cotton_workspaces WHERE id = ?",            &[rusqlite::types::Value::Text(file.workspace_id.to_string())],        )        .map_err(|error| error.to_string())?        .ok_or_else(|| "this database has no workspace row".to_string())?;    Ok(row.text("owner_person_id").filter(|id| !id.is_empty()).map(str::to_string))}/// `(id, full_name, avatar_key)` of a person this copy holds and not in the/// bin — the object's own rule for who may be the owner (`owner.ts`).pub(super) fn present_person(    file: &ReadFile<'_>,    id: &str,) -> Result<Option<(String, String, Option<String>)>, String> {    let row = file        .driver        .get(            "SELECT id, full_name, avatar_key FROM cotton_people WHERE id = ? AND trashed_at IS NULL",            &[rusqlite::types::Value::Text(id.to_string())],        )        .map_err(|error| error.to_string())?;    Ok(row.map(|row| {        (            row.text("id").unwrap_or(id).to_string(),            row.text("full_name").unwrap_or_default().to_string(),            row.text("avatar_key")                .filter(|key| !key.is_empty())                .map(str::to_string),        )    }))}/// The three facts about current admission, and the count of admitted devices.////// 1. this device: "This device, {name}, was admitted on {d Mon yyyy}." — or///    "…, was cut off on {date}." once revoked, or "This device is not///    admitted to this database." when the file holds no row for it;/// 2. "No device is admitted." / "1 device is admitted." / "{n} devices are///    admitted.";/// 3. "{Mac name} serves this database now." — "This device serves this///    database now." when it is this one, "No Mac serves this database yet."///    with no serving fact.fn sign_in(    file: &ReadFile<'_>,    this_device: Option<&str>,    zone: &str,) -> Result<(Vec<String>, i64), String> {    let workspace = rusqlite::types::Value::Text(file.workspace_id.to_string());    let mine = match this_device {        Some(key) => file            .driver            .get(                "SELECT name, approved_at, revoked_at FROM cotton_devices \                 WHERE workspace_id = ? AND device_id = ? \                 ORDER BY approved_at DESC LIMIT 1",                &[                    workspace.clone(),                    rusqlite::types::Value::Text(key.to_string()),                ],            )            .map_err(|error| error.to_string())?,        None => None,    };    let admission = match mine {        Some(row) => {            let name = row.text("name").unwrap_or_default();            match row.text("revoked_at").filter(|at| !at.is_empty()) {                Some(at) => format!("This device, {name}, was cut off on {}.", day(at, zone)),                None => format!(                    "This device, {name}, was admitted on {}.",                    day(row.text("approved_at").unwrap_or_default(), zone)                ),            }        }        None => "This device is not admitted to this database.".to_string(),    };    let count = file        .driver        .get(            "SELECT COUNT(*) AS n FROM cotton_devices WHERE workspace_id = ? AND revoked_at IS NULL",            std::slice::from_ref(&workspace),        )        .map_err(|error| error.to_string())?        .and_then(|row| row.int("n"))        .unwrap_or(0);    let admitted = match count {        0 => "No device is admitted.".to_string(),        1 => "1 device is admitted.".to_string(),        n => format!("{n} devices are admitted."),    };    let serving = cotton_store::serving::serving_fact(file.driver, file.workspace_id)        .map_err(|error| error.to_string())?        .map(|fact| fact.device_credential_id);    let serves = match serving {        None => "No Mac serves this database yet.".to_string(),        Some(key) if Some(key.as_str()) == this_device => {            "This device serves this database now.".to_string()        }        Some(key) => {            let name = file                .driver                .get(                    "SELECT name FROM cotton_devices WHERE workspace_id = ? AND device_id = ? \                     ORDER BY approved_at DESC LIMIT 1",                    &[workspace, rusqlite::types::Value::Text(key)],                )                .map_err(|error| error.to_string())?                .and_then(|row| row.text("name").map(str::to_string));            match name {                Some(name) => format!("{name} serves this database now."),                None => "A Mac this database does not list serves it now.".to_string(),            }        }    };    Ok((vec![admission, admitted, serves], count))}/// "8 Sep 2026", in the device's zone; the stored text itself if it does not/// parse.fn day(at: &str, zone: &str) -> String {    let zone = cotton_core::device::words::Clock::in_zone(0, zone).zone;    chrono::DateTime::parse_from_rfc3339(at)        .map(|at| at.with_timezone(&zone).format("%-d %b %Y").to_string())        .unwrap_or_else(|_| at.to_string())}