//! Apply the synced Storage Files choice this Mac received in `cotton_devices`. //! //! The device row is the declaration. This consumer runs after a fold and //! writes the existing per-file `bytes` rules; it never writes the declaration //! back or dials a live host. use cotton_store::storage_rules::{MacKeeps, mac_keeps}; use serde_json::{Map, Value}; use crate::shell::client::ClientController; /// Apply Mine's nullable `keep_bytes` choice to every database this Mac holds. /// A null declaration is no override. Failures deliberately reach the caller: /// the after-pass hook logs them and retries the idempotent writer next pass. pub fn apply(client: &ClientController) -> Result { let Some(device) = client.self_device_id() else { return Ok(0); }; // A UI may have named a shared database; the declaration is always Mine. // `held_databases` guarantees the personal database is first. let databases = client.held_databases()?; let Some(personal) = databases.first() else { return Ok(0); }; let choice = client.with_file_in(personal, |file| { let row = file .driver .get( "SELECT keep_bytes, platform FROM cotton_devices \ WHERE workspace_id = ? AND device_id = ? AND revoked_at IS NULL", &[ rusqlite::types::Value::Text(file.workspace_id.to_string()), rusqlite::types::Value::Text(device.clone()), ], ) .map_err(|error| error.to_string())?; match row { None => Ok(None), Some(row) if row.text("platform") != Some("mac") => Ok(None), Some(row) => Ok(row.text("keep_bytes").map(str::to_owned)), } })?; let Some(choice) = choice else { return Ok(0); }; let desired = match choice.as_str() { "everything" => MacKeeps::Everything, "rows_only" => MacKeeps::RowsOnly, _ => return Err(format!("this Mac has invalid keep_bytes `{choice}`")), }; let mut changed = 0; let mut refused = Vec::new(); for database in &databases { let result = (|| -> Result { let already = client.with_file_in(database, |file| { mac_keeps(file.driver, file.workspace_id, &device) .map(|keeps| keeps == desired) .map_err(|error| error.to_string()) })?; if already { return Ok(false); } let _named = client.name_database(Some(database))?; let args = Map::from_iter([ ("device".into(), Value::String(device.clone())), ("kind".into(), Value::String("bytes".into())), ("rule".into(), Value::String(choice.clone())), ]); client.write("set_keep_rule", &args)?; Ok(true) })(); match result { Ok(true) => changed += 1, Ok(false) => {}, Err(error) => refused.push(format!("Files in {database}: {error}")), } } if !refused.is_empty() { return Err(refused.join("; ")); } Ok(changed) }