Cotton code
350 lines · 12.5 KB · RustRaw
//! Database projections whose rows are composed from//! phone reads rather than stored records.  Their writers deliberately live//! beside their native engines; this file is read-only.use serde_json::{json, Map, Value};use crate::{methods::MethodError, shell::client::ClientController};/// List the cheap rows for a supporting settings table.  A database list is/// intentionally only `read.databases`: opening every database for page facts/// would make the switcher wake idle replicas.pub fn list_rows(client: &ClientController, table: &str) -> Result<Vec<Value>, MethodError> {    match table {        "database" => databases(client),        _ => Err(MethodError::new(            "unknown_table",            format!("no support reader for `{table}`"),        )),    }}/// Read one supporting settings row.  Database detail reads are scoped before/// asking for its page, storage and theme: an id can never/// silently fall back to the currently shown database.pub fn get(client: &ClientController, table: &str, id: &str) -> Result<Value, MethodError> {    if id.trim().is_empty() {        return Err(MethodError::new(            "bad_request",            "`records.get` needs a record id",        ));    }    match table {        "database" => database(client, id),        _ => Err(MethodError::new(            "unknown_table",            format!("no support reader for `{table}`"),        )),    }}fn row(id: impl Into<String>, data: Map<String, Value>) -> Value {    json!({"id": id.into(), "data": data, "deleted_at": Value::Null})}fn unreadable(reason: String) -> MethodError {    MethodError::new("unreadable", reason)}fn databases(client: &ClientController) -> Result<Vec<Value>, MethodError> {    let answer = crate::phone::databases::list(client, &Map::new()).map_err(unreadable)?;    Ok(answer["databases"]        .as_array()        .into_iter()        .flatten()        .filter_map(|database| {            let id = database["databaseId"].as_str()?;            let people = database["people"]                .as_array()                .map(|people| {                    people                        .iter()                        .filter_map(Value::as_str)                        .collect::<Vec<_>>()                        .join(", ")                })                .unwrap_or_default();            Some(row(                id,                Map::from_iter([                    ("name".into(), database["name"].clone()),                    ("colour".into(), database["colour"].clone()),                    ("kind".into(), database["kind"].clone()),                    ("people".into(), Value::String(people)),                ]),            ))        })        .collect())}fn database(client: &ClientController, id: &str) -> Result<Value, MethodError> {    // name_database is the guard.  Both storage and the project reader use    // the named read context after this point.    let _named = client        .name_database(Some(id))        .map_err(|reason| MethodError::new("database_not_held", reason))?;    let page = crate::phone::database_appearance::page(        client,        &Map::from_iter([("databaseId".into(), Value::String(id.into()))]),    )    .map_err(unreadable)?;    let storage =        crate::phone::storage::database_storage(client, &Map::new()).map_err(unreadable)?;    let members = crate::phone::members::read(client, &Map::new()).map_err(unreadable)?;    let theme = client        .read_rows("settings_support_reads.database_theme", &mut |ctx| {            cotton_tools::presentation::theme(ctx.read.driver(), ctx.workspace_id)                .map(|theme| theme.definition)        })        .map_err(unreadable)?;    let here = storage["devices"]        .as_array()        .into_iter()        .flatten()        .find(|device| device["thisDevice"] == Value::Bool(true));    let elsewhere = storage["devices"]        .as_array()        .into_iter()        .flatten()        .filter(|device| device["thisDevice"] != Value::Bool(true))        .filter_map(|device| {            device["name"].as_str().map(|name| {                format!(                    "{name} · {}",                    bytes_line(&device["keptBytes"], &device["freeableBytes"])                )            })        })        .collect::<Vec<_>>()        .join("\n");    let (people, rights) = people_and_rights(&members);    let reader = client.device_scope().map_err(unreadable)?        == cotton_core::device::scope::DeviceScope::Reader;    let rights = database_role(rights, reader);    let mut data = Map::from_iter([        ("name".into(), page["name"].clone()),        ("colour".into(), page["colour"].clone()),        (            "kind".into(),            Value::String(if page["personal"] == Value::Bool(true) {                "personal".into()            } else {                "shared".into()            }),        ),        (            "owner_name".into(),            members["ownership"]["ownerName"].clone(),        ),        (            "ownership_since".into(),            members["ownership"]["admittedAt"].clone(),        ),        ("people".into(), Value::String(people)),        (            "rights".into(),            rights.map(Value::String).unwrap_or(Value::Null),        ),        (            "kept_here".into(),            here.map(|device| {                Value::String(bytes_line(&device["keptBytes"], &device["freeableBytes"]))            })            .unwrap_or(Value::Null),        ),        (            "kept_elsewhere".into(),            if elsewhere.is_empty() { Value::Null } else { Value::String(elsewhere) },        ),        // Notification permission/prefs are native app state.  This FFI layer        // has no authority answer, so it is unknown rather than invented.        ("notifications".into(), Value::Null),        ("can_leave".into(), page["canLeave"].clone()),        ("family".into(), theme["family"].clone()),        ("cap_texture".into(), theme["cap"]["texture"].clone()),    ]);    let person = super::reads::personal_database(client)        .map_err(unreadable)?        .map(|mine| {            client.with_file_in(&mine, |file| {                cotton_store::membership::owner(file.driver).map_err(|error| error.to_string())            })        })        .transpose()        .map_err(unreadable)?        .flatten();    let policy = if let Some(person) = person {        client            .with_file_in(id, |file| {                cotton_store::database_bin::may_delete(file.driver, id, &person)                    .map_err(|error| error.to_string())            })            .map_err(unreadable)?    } else {        Err(cotton_store::database_bin::DeleteRefusal::NotCreator)    };    let count = match &policy {        Err(cotton_store::database_bin::DeleteRefusal::Members { count }) => *count,        _ => 0,    };    data.insert(        "can_delete".into(),        json!(            policy.is_ok()                || matches!(                    policy,                    Err(cotton_store::database_bin::DeleteRefusal::Members { .. })                )        ),    );    data.insert("member_count".into(), json!(count));    // DatabaseTableSource merges the worn theme after the switcher row, so    // the worn cap's explicit colour is the displayed colour.    if !theme["cap"]["colour"].is_null() {        data.insert("colour".into(), theme["cap"]["colour"].clone());    }    // Who serves it, as this device's own copy names that Mac — offline too.    let serving = super::sync_state::copies(client, &json!({"where": {"database": id}}))        .ok()        .and_then(|rows| {            rows.into_iter()                .find(|row| row["data"]["role"] == "serving")        })        .and_then(|row| row["data"]["name"].as_str().map(Value::from));    data.insert("served_by".into(), serving.unwrap_or(Value::Null));    Ok(row(id, data))}fn people_and_rights(answer: &Value) -> (String, Option<String>) {    let me = answer["me"].as_str();    let members = answer["members"].as_array().cloned().unwrap_or_default();    let others = members        .iter()        .filter(|member| member["personKey"].as_str() != me)        .filter_map(|member| member["name"].as_str())        .filter(|name| !name.is_empty())        .collect::<Vec<_>>();    let people = match others.as_slice() {        [] => "Only you".into(),        [one] => format!("With {one}"),        many => format!(            "With {} and {}",            many[..many.len() - 1].join(", "),            many[many.len() - 1]        ),    };    let rights = me        .and_then(|me| {            members                .iter()                .find(|member| member["personKey"].as_str() == Some(me))        })        .and_then(|member| {            if member["isOwner"] == Value::Bool(true) {                Some("owner")            } else {                member["rights"].as_str()            }        })        .map(str::to_string);    (people, rights)}/// The database sheet's role is the local admission when this copy is a/// reader. Membership says what a full device may do; it cannot turn a/// read-only copy into an owner in the sheet's words.fn database_role(membership_rights: Option<String>, reader: bool) -> Option<String> {    reader.then_some("reader".to_string()).or(membership_rights)}fn bytes_line(held: &Value, freeable: &Value) -> String {    let Some(held) = held.as_i64() else {        return "not measured yet".into();    };    let mut line = bytes(held);    if let Some(freeable) = freeable.as_i64().filter(|value| *value > 0) {        line.push_str(&format!(" · {} can be freed", bytes(freeable)));    }    line}fn bytes(value: i64) -> String {    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];    let mut amount = value as f64;    let mut unit = 0;    while amount >= 1000.0 && unit < UNITS.len() - 1 {        amount /= 1000.0;        unit += 1;    }    if amount.fract() == 0.0 {        format!("{} {}", amount as i64, UNITS[unit])    } else {        format!("{amount:.1} {}", UNITS[unit])    }}#[cfg(test)]mod tests {    use super::*;    /// RULE: storage readings use decimal units without locale grouping, so a    /// generic settings page names the same quantity on every device.    #[test]    fn storage_bytes_are_decimal_and_ungrouped() {        assert_eq!(bytes(2_300_000_000), "2.3 GB");        assert_eq!(bytes(400_000_000), "400 MB");    }    /// RULE: a database page derives its membership facts only after its    /// named-file read; the switcher's empty idle roster must never become an    /// empty people field or a fabricated rights value on that page.    #[test]    fn database_page_membership_mapping_uses_the_scoped_native_read() {        let (people, rights) = people_and_rights(&json!({            "me":"owner", "members":[                {"personKey":"owner", "name":"Asha", "rights":"admin"},                {"personKey":"ravi", "name":"Ravi", "rights":"member"},                {"personKey":"mo", "name":"Mo", "rights":"member"}            ]        }));        assert_eq!(people, "With Ravi and Mo");        assert_eq!(rights.as_deref(), Some("admin"));        let (solo, missing) = people_and_rights(&json!({"me":"owner", "members":[]}));        assert_eq!(solo, "Only you");        assert_eq!(missing, None);    }    /// RULE: The Databases sheet says a reader's local role as the one word    /// "reader", while a full copy keeps its membership role; otherwise a    /// read-only copy looks like it can use the write acts it no longer has.    #[test]    fn database_role_names_the_local_reader_scope() {        assert_eq!(            database_role(Some("owner".into()), true).as_deref(),            Some("reader")        );        assert_eq!(            database_role(Some("admin".into()), false).as_deref(),            Some("admin")        );    }}#[cfg(test)]mod ownership_role_tests {    use super::*;    /// RULE: The database act sees the actual owner role, even though the legacy Members wire spelling groups owners with admins; staff never receives the owner-only handover act.    #[test]    fn database_role_distinguishes_owner_from_staff_and_admin() {        for (owner, rights, expected) in [            (true, "admin", "owner"),            (false, "admin", "admin"),            (false, "member", "member"),        ] {            let (_, role) = people_and_rights(                &json!({"me":"key","members":[{"personKey":"key","name":"Synthetic person","rights":rights,"isOwner":owner}]}),            );            assert_eq!(role.as_deref(), Some(expected));        }    }}