894 lines · 37.2 KB · RustRaw
//! Routes writable `device` columns to their existing engines.use serde_json::{json, Map, Value};use cotton_core::records::Verb;use cotton_core::definitions::TableDefinition;use cotton_tools::mcp::handlers::tables::{self, Stored};use crate::{handle::CottonHandle, methods::MethodError};/// The one optional live read a generic Device page may make.pub const FACTS_METHOD: &str = "device.facts";/// Handle-aware device reads add registry entries that are still asking to/// pair. The generic reader remains the source for synced approvals.pub fn records_read( handle: &CottonHandle, method: &str, request: &Value,) -> Option<Result<Value, MethodError>> { records_read_using(handle, method, request, None)}pub(super) fn records_read_using( handle: &CottonHandle, method: &str, request: &Value, captured: Option<&mut Option<TableDefinition>>,) -> Option<Result<Value, MethodError>> { if !matches!(method, "records.list" | "records.get") || request.get("table").and_then(Value::as_str) != Some("device") { return None; } Some(records_read_device(handle, method, request, captured))}fn records_read_device( handle: &CottonHandle, method: &str, request: &Value, mut captured: Option<&mut Option<TableDefinition>>,) -> Result<Value, MethodError> { let synced = crate::phone::records::call_with_definition(&handle.client(), method, request, captured.as_deref_mut()); if method == "records.get" { return match synced { Ok(mut record) => { merge_writable_local(handle, &mut record)?; Ok(record) } Err(original) => pending_get(handle, request, original), }; } if !handle.client().has_server().map_err(|error| MethodError::new("unreadable", error))? { return synced.and_then(|answer| with_local_choices(handle, answer)); } let pending = match crate::methods::dispatch(handle, "pairing.pending", &json!({})) { Ok(pending) => pending, // Requests to pair need a Mac and are an overlay on the list; the // list itself is the phone's copy — its synced approvals and // device-local removal intents — and reads whatever the overlay met, // never only the failures a status list foresaw (293 walk row 159). Err(_) => return with_local_choices(handle, synced?), }; let rows = pending .get("pending") .and_then(Value::as_array) .ok_or_else(|| { MethodError::new( "unreadable", "The pairing registry did not answer its pending devices", ) })?; // With no requests to pair there is nothing to merge or re-page. Keep // the already validated native page instead of reading every device again. if rows.is_empty() { return with_local_choices(handle, synced?); } let waiting = |row: &Value| { let id = row.get("pairingId")?.as_str()?; Some( json!({"table":"device","id":id,"data":crate::phone::records::waiting_device(&pending, id)?}), ) }; match method { "records.list" => { // Preserve the generic reader's argument validation before the // overlay widens the read to assemble one coherent page. let _ = synced.as_ref().map_err(Clone::clone)?; if let Some(ids) = request.get("ids").and_then(Value::as_array) { let synced = synced?; let mut by_id: std::collections::HashMap<String, Value> = synced["records"] .as_array() .into_iter() .flatten() .filter_map(|record| { record["id"] .as_str() .map(|id| (id.to_string(), record.clone())) }) .collect(); for row in rows { let Some(id) = row.get("pairingId").and_then(Value::as_str) else { return Err(MethodError::new( "unreadable", "A pending device has no pairing id", )); }; if let Some(data) = crate::phone::records::waiting_device(&pending, id) { by_id .entry(id.to_string()) .or_insert_with(|| json!({"table":"device","id":id,"data":data})); } } let records = ordered_ids(ids, &mut by_id); let total = records.len(); return with_local_choices(handle, json!({"table":"device","records":records,"total":total,"next_page":Value::Null}), ); } if request.get("last_changed") == Some(&Value::Bool(true)) { let mut changed = synced?["last_changed"].as_str().map(str::to_string); for row in rows { if let Some(asked) = row.get("createdAt").and_then(Value::as_str) { if changed.as_deref().is_none_or(|current| asked > current) { changed = Some(asked.to_string()); } } } return Ok(json!({"table":"device","last_changed":changed})); } // Fetch synced rows without the caller's narrowing or page, then // apply those once after registry rows join the same collection. let mut source = request.clone(); let fields = source .as_object_mut() .expect("records request is an object"); fields.remove("where"); fields.remove("query"); fields.remove("page"); fields.remove("count_only"); fields.remove("last_changed"); fields.insert("limit".to_string(), Value::from(200)); let mut all = Vec::new(); let mut offset = Value::from(0); loop { source .as_object_mut() .expect("records request is an object") .insert("page".to_string(), offset.clone()); let page = crate::phone::records::call_with_definition(&handle.client(), "records.list", &source, captured.as_deref_mut())?; let page_rows = page["records"].as_array().cloned().unwrap_or_default(); all.extend(page_rows); let Some(next) = page .get("next_page") .filter(|value| !value.is_null()) .cloned() else { break; }; offset = next; } let definition = cotton_core::definitions::builtin_table_definition("device") .ok_or_else(|| MethodError::new(cotton_core::definitions::NO_TOOL_DRAWS_THIS_TABLE, cotton_core::definitions::no_tool_draws_this_table(&[])))?; let clauses = cotton_core::records::parse_where(definition, request.get("where")) .map_err(|error| MethodError::new("bad_request", error.to_string()))?; let query = request.get("query").and_then(Value::as_str); let zone = cotton_core::records::where_zone(request["timezone"].as_str().or(handle.client().time_zone())).on(request["today"].as_str()); let known: std::collections::HashSet<String> = all .iter() .filter_map(|record| record.get("id").and_then(Value::as_str).map(str::to_string)) .collect(); let extra: Vec<Value> = rows .iter() .filter_map(waiting) .filter(|record| !known.contains(record["id"].as_str().unwrap_or_default())) .collect(); all.extend(extra); all.retain(|record| { let data = record["data"].as_object().cloned().unwrap_or_default(); clauses .iter() .all(|clause| cotton_core::records::holds(&data, clause, &zone)) && query.is_none_or(|words| { cotton_core::records::matches_query(definition, &data, words) }) }); let total = all.len(); if request.get("count_only") == Some(&Value::Bool(true)) { return Ok( json!({"table":"device","records":[],"total":total,"next_page":Value::Null}), ); } let start = match request.get("page") { None => 0, Some(value) => value.as_u64().ok_or_else(|| { MethodError::new("bad_request", "page is a non-negative number") })? as usize, }; let limit = match request.get("limit") { None => 50, Some(value) => value .as_u64() .filter(|limit| (1..=200).contains(limit)) .ok_or_else(|| MethodError::new("bad_request", "limit is 1 to 200"))? as usize, }; let end = start.saturating_add(limit).min(total); let records = if start >= total { Vec::new() } else { all[start..end].to_vec() }; let listed = json!({ "table":"device", "records":records, "total":total, "next_page": (end < total).then_some(end), }); with_local_choices(handle, listed) } "records.get" => unreachable!(), _ => unreachable!(), }}/// Apply installation-owned choices once, after every list assembly path.fn with_local_choices(handle: &CottonHandle, mut answer: Value) -> Result<Value, MethodError> { if let Some(records) = answer.get_mut("records").and_then(Value::as_array_mut) { for record in records { merge_writable_local(handle, record)?; } } Ok(answer)}/// The `{ids}` form is a lookup, not a page: preserve the caller's order and/// never repeat a row if the caller repeated an id or registry and file met.fn ordered_ids(ids: &[Value], rows: &mut std::collections::HashMap<String, Value>) -> Vec<Value> { ids.iter() .filter_map(Value::as_str) .filter_map(|id| rows.remove(id)) .collect()}/// Device records retain synced data as their base. On this installation only,/// merge writable host switches from their owner read; this is deliberately/// not `device.facts`, whose optional overlay remains top-level only.fn merge_writable_local(handle: &CottonHandle, record: &mut Value) -> Result<(), MethodError> { let Some(id) = record.get("id").and_then(Value::as_str).map(str::to_string) else { return Ok(()); }; if handle.client().self_device_id().as_deref() != Some(id.as_str()) { return Ok(()); } let host = Value::Null; let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) else { return Ok(()); }; for (snake, camel) in HOST_KEYS { if let Some(value) = host.get(camel) { data.insert(snake.to_string(), value.clone()); } } // Only saved choices are merged here. keep_fetch_status also charges // every local object and builds a fetch queue, neither of which this // record reads. The page's live status remains a separate read. let (cap, byte_rules, table_rules, reach) = handle.client().with_file(|file| { Ok(( cotton_client::media::keep_fetch::cap(file.driver, file.workspace_id, &id).map_err(|error| error.to_string())?, cotton_client::media::keep_fetch::byte_rules(file.driver, file.workspace_id, &id).map_err(|error| error.to_string())?, cotton_store::keep::rules_of(file.driver, &id).map_err(|error| error.to_string())?, crate::phone::front_door::page_answer(file.driver, file.workspace_id), )) }).map_err(|error: String| MethodError::new("unreadable", error))?; data.insert("kept_space_bytes".into(), Value::from(cap.map(|bytes| bytes.to_string()).unwrap_or_else(|| "none".into()))); for (column, tool) in PHONE_FILE_TOOLS { if let Some(rule) = byte_rules.iter().find(|rule| rule.tool == tool) { data.insert(column.to_string(), Value::from(rule.keep_rule.clone())); } } for (column, table) in [ ("keep_mail", "cotton_email_threads"), ("keep_statuses", "cotton_stories"), ] { if let Some(rule) = table_rules .iter() .find(|rule| rule.kind == "table" && rule.target == table) { data.insert(column.to_string(), Value::from(rule.rule.clone())); } } if let Some(through) = reach .pointer("/reach/through") .filter(|value| !value.is_null()) { data.insert("reached_through".to_string(), through.clone()); } Ok(())}fn pending_get( handle: &CottonHandle, request: &Value, original: MethodError,) -> Result<Value, MethodError> { if original.code != "record_not_found" { return Err(original); } let pending = crate::methods::dispatch(handle, "pairing.pending", &json!({}))?; let id = request .get("id") .and_then(Value::as_str) .unwrap_or_default(); crate::phone::records::waiting_device(&pending, id) .map(|data| json!({"table":"device","id":id,"data":data})) .ok_or(original)}const HOST_KEYS: [(&str, &str); 6] = [ ("start_at_login", "startAtLogin"), ("stay_awake", "stayAwake"), ("error_reports", "errorReports"), ("auto_updates", "autoUpdates"), ("error_reports_to", "errorReportsTo"), ("update_feed", "updateFeed"),];const PREFERENCE_KEYS: [&str; 5] = [ "notify", "notify_reminders", "notify_events", "notify_birthdays", "notify_alarms",];const PHONE_FILE_TOOLS: [(&str, &str); 5] = [ ("keep_files_whatsapp", "whatsapp"), ("keep_files_instagram", "instagram"), ("keep_files_photo", "photo"), ("keep_files_video", "video"), ("keep_files_document", "document"),];#[derive(Debug, PartialEq)]pub(crate) struct Route { pub method: &'static str, pub args: Value,}/// Route before any engine is called: one patch has exactly one owner, so a/// refused mixed patch cannot leave its first engine's write behind.pub(crate) fn route(request: &Value) -> Result<Option<Route>, MethodError> { if request.get("table").and_then(Value::as_str) != Some("device") { return Ok(None); } let id = request .get("id") .and_then(Value::as_str) .filter(|id| !id.trim().is_empty()) .ok_or_else(|| MethodError::new("bad_request", "records.update needs a device id"))?; let patch = request .get("patch") .and_then(Value::as_object) .filter(|patch| !patch.is_empty()) .ok_or_else(|| { MethodError::new( "bad_request", "records.update needs a non-empty device patch", ) })?; let engines = patch .keys() .map(|key| engine_for(key)) .collect::<Result<Vec<_>, _>>()?; let first = engines[0]; if engines.iter().any(|found| *found != first) { return Err(MethodError::new( "bad_request", "A device patch changes columns owned by different engines; change one kind at a time", )); } let mut args = Map::new(); args.insert("deviceId".to_string(), json!(id)); match first { "devices.rename" => { args.insert("name".to_string(), patch["name"].clone()); } "device.setSessions" => { args.insert("sessionsCap".to_string(), patch["sessions_cap"].clone()); } "device.setAiCap" => { args.insert("capUsd".to_string(), patch["ai_day_cap_usd"].clone()); } "device.setPlacements" => { args.insert("takesPlacements".to_string(), patch["takes_placements"].clone()); } "device.setHost" => { for (snake, camel) in HOST_KEYS { if let Some(value) = patch.get(snake) { args.insert(camel.to_string(), value.clone()); } } } "storage.setMacFiles" => { let device = args .remove("deviceId") .expect("the route always supplies a device id"); args.insert("device".to_string(), device); args.insert("rule".to_string(), patch["keep_bytes"].clone()); } "device.preferences.set" => { args.insert("patch".to_string(), Value::Object(patch.clone())); } "keep.set" => { if patch.len() != 1 { return Err(MethodError::new( "bad_request", "Change one table keep rule at a time.", )); } let (column, tool) = patch .iter() .next() .and_then(|(column, value)| keep_tool(column).map(|tool| (value, tool))) .expect("keep engine owns a known field"); args.remove("deviceId"); args.insert("device".to_string(), json!(id)); args.insert("kind".to_string(), Value::from("table")); args.insert( "target".to_string(), Value::from(if tool == "mail" { "cotton_email_threads" } else { "cotton_stories" }), ); args.insert("rule".to_string(), column.clone()); } "storage.keepRule" => { if patch.len() != 1 { return Err(MethodError::new( "bad_request", "Change one media keep rule at a time.", )); } let (column, tool) = patch .iter() .next() .and_then(|(column, value)| keep_tool(column).map(|tool| (value, tool))) .expect("storage engine owns a known media field"); args.insert("tool".to_string(), Value::from(tool)); args.insert("keepRule".to_string(), column.clone()); } "storage.keptSpace" => { let value = match patch["kept_space_bytes"].as_str() { Some("none") => Value::Null, Some(value) => value .parse::<u64>() .map(Value::from) .unwrap_or_else(|_| patch["kept_space_bytes"].clone()), None => patch["kept_space_bytes"].clone(), }; args.insert("keptSpaceBytes".to_string(), value); } "workspace.setReach" => { args.remove("deviceId"); args.insert("through".to_string(), patch["reached_through"].clone()); } _ => unreachable!("known device engine"), } Ok(Some(Route { method: first, args: Value::Object(args), }))}fn engine_for(key: &str) -> Result<&'static str, MethodError> { match key { "name" => Ok("devices.rename"), "sessions_cap" => Ok("device.setSessions"), "ai_day_cap_usd" => Ok("device.setAiCap"), "takes_placements" => Ok("device.setPlacements"), "keep_bytes" => Ok("storage.setMacFiles"), "kept_space_bytes" => Ok("storage.keptSpace"), "reached_through" => Ok("workspace.setReach"), "keep_mail" | "keep_statuses" => Ok("keep.set"), key if keep_tool(key).is_some() => Ok("storage.keepRule"), key if PREFERENCE_KEYS.contains(&key) => Ok("device.preferences.set"), key if HOST_KEYS.iter().any(|(snake, _)| *snake == key) => Ok("device.setHost"), _ => Err(MethodError::new( "bad_request", format!("{key} is not writable on a device record"), )), }}fn keep_tool(column: &str) -> Option<&'static str> { match column { "keep_mail" => Some("mail"), "keep_statuses" => Some("statuses"), _ => PHONE_FILE_TOOLS .iter() .find(|(key, _)| *key == column) .map(|(_, tool)| *tool), }}/// Validate the old generic route before any writer is reached. Synced fields/// fall through to the table adapter. A local host switch records its observed/// before/after values as a non-undoable engine change after its own engine/// writes; a direct legacy `device.setHost` keeps its native undo receipt.pub fn update(handle: &CottonHandle, request: &Value) -> Result<Option<Value>, MethodError> { let Some(route) = route(request)? else { return Ok(None); }; // These are synced columns. Their cotton-tools adapter runs inside the // generic record transaction and mints the real change/undo envelope. if matches!( route.method, "devices.rename" | "device.setSessions" | "device.setAiCap" | "device.setPlacements" | "records.update" ) { return Ok(None); } if !matches!( route.method, "device.setHost" | "storage.setMacFiles" | "device.preferences.set" | "keep.set" | "storage.keepRule" | "storage.keptSpace" | "workspace.setReach" ) { return Err(MethodError::new( "command_required", format!( "{} changes this device outside the synced record; use its device command", route.method ), )); } let id = request["id"] .as_str() .expect("route accepted a non-empty device id") .to_string(); if matches!( route.method, "device.preferences.set" | "storage.keepRule" | "storage.keptSpace" | "workspace.setReach" ) && handle.client().self_device_id().as_deref() != Some(id.as_str()) { return Err(MethodError::new( "not_this_device", "This setting belongs to this device.", )); } let stored = crate::phone::records::call( &handle.client(), "records.get", &json!({"table":"device","id":id}), )?; if !matches!( stored["data"]["status"].as_str(), Some("this device" | "approved") ) { return Err(MethodError::new( "readonly_record", "Only a joined device can change its settings", )); } let before_facts = facts(handle, &json!({"deviceId":id}))?["data"].clone(); crate::methods::dispatch(handle, route.method, &route.args)?; let after_facts = facts(handle, &json!({"deviceId":id}))?["data"].clone(); let patch = request["patch"].as_object().expect("route validated patch"); let snapshot = |facts: &Value| { Value::Object( patch .keys() .filter_map(|key| facts.get(key).map(|value| (key.clone(), value.clone()))) .collect(), ) }; let before = snapshot(&before_facts); let after = snapshot(&after_facts); let mut data = crate::phone::records::call( &handle.client(), "records.get", &json!({"table":"device","id":id}), )?["data"] .as_object() .cloned() .unwrap_or_default(); if let Some(live) = after_facts.as_object() { data.extend(live.clone()); } handle .client() .write_rows("records.update.device.host", &mut |ctx| { tables::atomically_noted(ctx, |ctx| { let stored = Stored { id: id.clone(), data: data.clone(), created_at: None, updated_at: None, deleted_at: None, byline: None, }; tables::record_engine_change( ctx, "device", Some(&id), Verb::Update, before.clone(), after.clone(), Some(&stored), false, Some("This Mac setting is undone by its device command.".into()), ) }) .map_err(|failure| failure.to_string()) }) .map(crate::authoring::own_answer) .map(Some) .map_err(|reason| MethodError::new("write_refused", reason))}/// Optional live facts use the existing live read, whose controller path is/// read-only. It is intentionally separate from `records.get` and list.pub fn facts(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> { let device = request .get("deviceId") .or_else(|| request.get("id")) .cloned() .ok_or_else(|| MethodError::new("bad_request", "device.facts needs a device id"))?; let page = crate::phone::read(handle, "read.device", &json!({"deviceId":device}))?; let record = crate::phone::records::call( &handle.client(), "records.get", &json!({"table":"device","id":device}), )?; let mut data = record["data"].as_object().cloned().unwrap_or_default(); for (snake, camel) in HOST_KEYS { if let Some(value) = page .pointer(&format!("/host/{camel}")) .filter(|value| !value.is_null()) { data.insert(snake.to_string(), value.clone()); } } if let Some(answered) = page.get("hostAnsweredBy").filter(|value| !value.is_null()) { let normalized = answered .as_str() .map(|value| Value::from(value.replace('_', " "))) .unwrap_or_else(|| answered.clone()); data.insert("host_answered_by".to_string(), normalized); } if let Some(value) = page .pointer("/host/serving") .filter(|value| !value.is_null()) { data.insert("host_serving".to_string(), value.clone()); } if let Some(backup) = page.get("backup").filter(|value| !value.is_null()) { data.insert( "backup".to_string(), Value::from(crate::methods::host_settings::backup_receipt( backup, data.get("name").and_then(Value::as_str).unwrap_or_default(), )), ); // Why it is not getting through, in the Mac's own sentence — where // Home's "See why" lands, so the page says the reason, never the // backup's line again (walker pass 4, row 10). if cotton_core::records::backup::BackupState::of_receipt(backup).is_some() { let failing = backup["databases"].as_array().into_iter().flatten().filter(|row| row["state"] == "failing"); let why = backup["lastError"].as_str().into_iter().chain(failing.filter_map(|row| row["lastError"].as_str())) .map(str::trim).find(|why| !why.is_empty()); if let Some(why) = why { data.insert("backup_why".to_string(), Value::from(why)); } } if let Some(media) = backup.get("media").filter(|value| !value.is_null()) { data.insert("media_backup".to_string(), media.clone()); } } if let Some(answered) = page.get("backupAnsweredBy").and_then(Value::as_str) { data.insert( "backup_answered_by".to_string(), Value::from(answered.replace('_', " ")), ); } if handle.client().self_device_id().as_deref() == device.as_str() { let change = handle.client().read_rows("device.facts.theme", &mut |ctx| { Ok(json!(cotton_tools::presentation::last_theme_change(ctx.read.driver(), ctx.workspace_id)?)) }).map_err(|why| MethodError::new("unreadable", why))?; // The page's line ("theme changed …") and its Undo read these. data.insert("theme_change_id".into(), change["id"].clone()); data.insert("theme_changed_at".into(), change["at"].clone()); data.insert("theme_undo_available".into(), Value::Bool(change.is_object())); // What the system last told this device about Cotton's notifications, // as this device wrote it on its own row: the tile reads the system's // answer, never only the five switches. let id = rusqlite::types::Value::Text(device.as_str().unwrap_or_default().to_string()); let push = handle.client().read_rows("device.facts.push", &mut |ctx| { let row = ctx.read.driver() .get("SELECT push_authorization FROM cotton_devices WHERE id = ?", std::slice::from_ref(&id)) .map_err(|why| why.to_string())?; Ok(json!(row.and_then(|row| row.text("push_authorization").map(str::to_string)))) }).map_err(|why| MethodError::new("unreadable", why))?; let push = push.as_str().map(str::to_string); if let Some(push) = push.as_deref() { data.insert("notifications_permission".into(), Value::from(cotton_core::device::words::notifications_permission(push))); } data.insert("notify_system".into(), Value::from(cotton_core::device::words::notify_system(push.as_deref()))); // A mobile build contains no local session runner. Its running count // is therefore known zero, unlike an unread Mac measurement. data.insert("sessions_running".into(), Value::from(0)); if let Some(sessions) = cotton_core::device::words::sessions_line( data.get("sessions_running").and_then(Value::as_f64), data.get("sessions_cap").and_then(Value::as_f64), ) { data.insert("sessions".into(), Value::from(sessions)); } data.extend(crate::phone::device_here::facts_for( &handle.client().sync_status(), data.get("platform").and_then(Value::as_str) == Some("ios"), )); // The rows the pull set aside rather than stop on, said on the same // last-try line: the pass moved past them, so only this says so. let parked = handle.client().with_file(|file| { file.driver.get("SELECT COUNT(*) AS n FROM _parked WHERE direction = 'pull' AND class <> 'newer-shape'", &[]) .map(|row| row.and_then(|row| row.int("n")).unwrap_or(0).max(0) as usize) .map_err(|why| why.to_string()) }).map_err(|why| MethodError::new("unreadable", why))?; crate::phone::device_here::with_parked(&mut data, parked); // Where this device's sync stands, as typed columns for its page's // sync groups: the core's one read, with each table's rows. data.extend(crate::phone::device_here::sync_facts(&handle.client().sync_status_of(true)["status"])); // How far this phone's copy of the personal object has got — the // figures the object writes on this phone's device row, as its // answers said them, and the bytes and the stall only the phone // knows (`SyncProgress`): the record's sync columns. if let Some(progress) = handle.client().sync_progress() { let state = progress.state(); data.extend(state.columns()); // What each table is doing — rows arriving, writes sending — for // the deck's counter over the tool showing (owner, 2 Nov 2026). let queued = handle.client().with_file(|file| { cotton_store::outbox::pending_by_table(file.driver).map_err(|why| why.to_string()) }).map_err(|why| MethodError::new("unreadable", why))?; data.insert("sync_table_progress".into(), Value::Object(state.moving(&queued))); } // The base records.get already supplied the shown database's one // sync reading. Do not ask again or merge a device-wide sync stamp. if matches!( data.get("platform").and_then(Value::as_str), Some("ios" | "android") ) { data.insert("keeps_answered_by".into(), Value::from("phone")); } let keep = crate::phone::read(handle, "read.keepFetch", &json!({"deviceId":device}))?; if let Some(value) = keep.get("keptSpaceBytes") { data.insert( "kept_space_bytes".to_string(), value .as_u64() .map(|bytes| Value::from(bytes.to_string())) .unwrap_or_else(|| Value::from("none")), ); } if let Some(rules) = keep.get("byteRules").and_then(Value::as_object) { for (column, tool) in PHONE_FILE_TOOLS { if let Some(rule) = rules.get(tool).filter(|value| !value.is_null()) { data.insert(column.to_string(), rule.clone()); } } } if let Some(state) = handle .client() .device_state() .and_then(|value| value.as_object().cloned()) { for key in ["build", "last_answer"] { if let Some(value) = state.get(key).filter(|value| !value.is_null()) { data.insert(key.to_string(), value.clone()); } } if let Some(value) = state.get("schema").filter(|value| !value.is_null()) { data.insert("schema".to_string(), Value::from(value.to_string())); } } if let Some(preferences) = crate::phone::device_preferences::facts(&handle.client())? .get("data") .and_then(Value::as_object) { data.extend(preferences.clone()); } if !handle.client().syncs() { crate::phone::device_here::without_sync(&mut data); } // The card this record is drawn by, dealt again over the live // columns merged above, so a card naming one of them (the sync // columns its facts list) draws its value: Home's `device` part // draws this card first, always (`board::THIS_DEVICE_KEY`). data.remove(cotton_core::records::card::CARD_KEY); let mut dealt = json!({"table": "device", "id": device, "data": data}); crate::phone::records::resolve_live_slips_on(handle, "records.get", &json!({"table": "device"}), &mut dealt)?; data = dealt["data"].as_object().cloned().unwrap_or_default(); } let live: Vec<Value> = data.keys().cloned().map(Value::from).collect(); Ok(json!({"data":data,"live":live}))}#[cfg(test)]mod tests { use super::*; /// RULE: An ids lookup is exact: pending rows enter only when named, keep /// the caller's order, and a duplicate id cannot draw two approval cards. #[test] fn ids_assembly_is_ordered_exact_and_deduplicated() { let mut rows = std::collections::HashMap::from([ ("synced".to_string(), json!({"id":"synced"})), ("pending".to_string(), json!({"id":"pending"})), ("unasked".to_string(), json!({"id":"unasked"})), ]); let records = ordered_ids( json!(["pending", "synced", "pending", "gone"]) .as_array() .unwrap(), &mut rows, ); assert_eq!( records, vec![json!({"id":"pending"}), json!({"id":"synced"})] ); assert!(rows.contains_key("unasked")); } /// RULE: A device patch has one engine owner, so a mixed patch is refused before any engine can write. #[test] fn routes_one_engine_before_any_write() { // The owner's independent runner grant reaches the synced writer, without a scope change. let grant = route(&json!({"table":"device","id":"runner","patch":{"takes_placements":true}})) .unwrap().unwrap(); assert_eq!(grant.method, "device.setPlacements"); assert_eq!(grant.args, json!({"deviceId":"runner","takesPlacements":true})); let rename = route(&json!({"table":"device","id":"mac","patch":{"name":"Desk Mac"}})) .unwrap() .unwrap(); assert_eq!(rename.method, "devices.rename"); assert_eq!(rename.args, json!({"deviceId":"mac","name":"Desk Mac"})); let host = route( &json!({"table":"device","id":"mac","patch":{"stay_awake":false,"update_feed":null}}), ) .unwrap() .unwrap(); assert_eq!( host.args, json!({"deviceId":"mac","stayAwake":false,"updateFeed":null}) ); let keep = route(&json!({"table":"device","id":"mac","patch":{"keep_bytes":"rows_only"}})) .unwrap() .unwrap(); assert_eq!(keep.method, "storage.setMacFiles"); assert_eq!(keep.args, json!({"device":"mac","rule":"rows_only"})); let preferences = route( &json!({"table":"device","id":"mac","patch":{"notify":false,"notify_events":true}}), ) .unwrap() .unwrap(); assert_eq!(preferences.method, "device.preferences.set"); assert_eq!( preferences.args, json!({"deviceId":"mac","patch":{"notify":false,"notify_events":true}}) ); let mail = route(&json!({"table":"device","id":"mac","patch":{"keep_mail":"days:30"}})) .unwrap() .unwrap(); assert_eq!(mail.method, "keep.set"); assert_eq!( mail.args, json!({"device":"mac","kind":"table","target":"cotton_email_threads","rule":"days:30"}) ); let cap = route(&json!({"table":"device","id":"mac","patch":{"kept_space_bytes":"2000000000"}})) .unwrap() .unwrap(); assert_eq!( cap.args, json!({"deviceId":"mac","keptSpaceBytes":2_000_000_000u64}) ); assert!(route( &json!({"table":"device","id":"mac","patch":{"name":"Desk","sessions_cap":2}}) ) .is_err()); }}