//! 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};usecrate::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.pubfn apply(client: &ClientController) -> Result<usize, String> {letSome(device) = client.self_device_id() else {returnOk(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()?;letSome(personal) = databases.first() else {returnOk(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)), } })?;letSome(choice) = choice else {returnOk(0); };let desired = match choice.as_str() {"everything" => MacKeeps::Everything,"rows_only" => MacKeeps::RowsOnly, _ => returnErr(format!("this Mac has invalid keep_bytes `{choice}`")), };letmut changed = 0;letmut refused = Vec::new();for database in &databases {let result = (|| -> Result<bool, String> {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 { returnOk(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() { returnErr(refused.join("; ")); }Ok(changed)}