//! The Storage engine view: one root record per live device.//!//! A device measures only its own file. An owner-app reading on that device//! evaluates its ledger now; every other reader sees the synced reading, whose//! totals stay absent until that device has measured every byte tool.use cotton_core::records::Data;use serde_json::Value;usesuper::{put, stored, words, Stored};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{now_iso, Valid};usecrate::mcp::protocol::ToolFailure;const TOOLS: [&str; 4] = ["photo", "video", "document", "thread"];/// The byte tools whose files are counted here and not here.const COUNTED: [&str; 3] = ["photo", "video", "document"];fn root_id(ctx: &Ctx<'_>, device: &str) -> String {if ctx.is_owner_app() && ctx.caller_device == Some(device) { "this".to_string() }else { format!("storage:{}:{device}:machine", device.len()) }}fn rows(ctx: &Ctx<'_>) -> Valid<Vec<Vec<cotton_store::storage_rules::StorageRow>>> {let devices = ctx.read.driver().all("SELECT device_id FROM cotton_devices WHERE workspace_id = ? AND revoked_at IS NULL ORDER BY device_id", &[rusqlite::types::Value::Text(ctx.workspace_id.to_string())], ).map_err(|error| ToolFailure::new(error.to_string()))?;letmut out = Vec::new();for device in devices.iter().filter_map(|row| words(row, "device_id")) {let device_rows = if ctx.is_owner_app() && ctx.caller_device == Some(device.as_str()) { cotton_store::storage_rules::evaluate(ctx.db(), ctx.workspace_id, &device, ctx.now.timestamp_millis()) .map_err(|error| ToolFailure::new(error.to_string()))?.rows } else { cotton_store::storage_rules::remote_rows(ctx.db(), ctx.workspace_id, &device) .map_err(|error| ToolFailure::new(error.to_string()))? }; out.push(device_rows); }Ok(out)}fn storage_row(ctx: &Ctx<'_>, rows: Vec<cotton_store::storage_rules::StorageRow>) -> Valid<Stored> {let first = rows.first().ok_or_else(|| ToolFailure::new("Storage has no byte-tool rows"))?;letmut data = Data::new();// The legacy Storage slip calls its title `name`; retain it while the// Swift source moves from device×tool rows to this device root. data.insert("name".into(), Value::from(first.device_name.clone())); data.insert("root".into(), Value::String("machine".into())); data.insert("device_name".into(), Value::from(first.device_name.clone())); data.insert("device_id".into(), Value::from(first.device_id.clone())); data.insert("is_this_device".into(), Value::Bool(first.is_this_device));for tool in TOOLS {let rule = rows.iter().find(|row| row.tool == tool).map(|row| row.keep_rule.clone()); put(&mut data, &format!("{tool}_keep_rule"), rule.map(Value::from)); }let mac = ctx.db().get("SELECT platform FROM cotton_devices WHERE workspace_id=? AND device_id=? AND revoked_at IS NULL LIMIT 1", &[ctx.workspace_id.to_string().into(), first.device_id.clone().into()], ).map_err(|error| ToolFailure::new(error.to_string()))? .is_some_and(|row| row.text("platform") == Some("mac"));let phone = !mac && cotton_store::keep::is_phone(ctx.db(), &first.device_id) .map_err(|error| ToolFailure::new(error.to_string()))?; data.insert("keeps_answered_by".into(), Value::from(if mac { "mac" } elseif phone { "phone" } else { "other" }));if mac {let intent = ctx.db().get("SELECT keep_bytes FROM cotton_devices WHERE workspace_id=? AND device_id=? AND revoked_at IS NULL ORDER BY approved_at DESC LIMIT 1", &[ctx.workspace_id.to_string().into(), first.device_id.clone().into()]).map_err(|error| ToolFailure::new(error.to_string()))? .and_then(|row| row.text("keep_bytes").map(str::to_string)); data.insert("keep_bytes".into(), intent.map(Value::from).unwrap_or(Value::Null)); }// A remote device that has never measured has no totals. Zero would say// it measured and found nothing, which can make someone release bytes.let measured = rows.iter().all(|row| row.is_this_device || row.measured_at.is_some());if measured {// On this device, this database's own file is held too: a phone// that had just copied 3,993 MB said '891 KB', its pictures alone// (walker292). Another device's file is not measured here.let file = if first.is_this_device { database_bytes(ctx)? } else { 0 }; data.insert("held_bytes".into(), Value::from(rows.iter().map(|row| row.held_bytes).sum::<i64>() + file));// Nothing to free is unsaid: 'can free 0 B' read as a fault where a// phone keeps the last copy of what no other device holds.let freeable = rows.iter().map(|row| row.freeable_bytes).sum::<i64>();if freeable > 0 { data.insert("freeable_bytes".into(), Value::from(freeable)); } }// Per byte tool, what of this database is on that device and what is// not fetched yet — counts only, storage.json says them. A tool the// device has not measured, or with nothing in the database, is unsaid.for tool in COUNTED {letSome(row) = rows.iter().find(|row| row.tool == tool) else { continue };if !(row.is_this_device || row.measured_at.is_some()) || row.total_count <= 0 { continue; } data.insert(format!("{tool}_here"), Value::from(row.held_count)); data.insert(format!("{tool}_missing"), Value::from((row.total_count - row.held_count).max(0))); } put(&mut data, "measured_at", measured.then(|| rows.iter().filter_map(|row| row.measured_at.clone()).min()).flatten().map(Value::from));Ok(stored(root_id(ctx, &first.device_id), data, None, None))}/// The size of this database's file as this device holds it: its pages,/// read through the same connection (the write-ahead log is folded into/// them at each checkpoint).fn database_bytes(ctx: &Ctx<'_>) -> Valid<i64> {let row = ctx.db() .get("SELECT page_count * page_size AS bytes FROM pragma_page_count(), pragma_page_size()", &[]) .map_err(|error| ToolFailure::new(error.to_string()))?;Ok(row.and_then(|row| row.int("bytes")).unwrap_or(0))}pub(super) fn read(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {Ok(rows(ctx)?.into_iter().map(|rows| storage_row(ctx, rows)).collect::<Valid<Vec<_>>>()? .into_iter().filter(|row| id.is_none_or(|id| row.id == id)).collect())}/// The owner's local grid reads what the worker last measured. Unknown/// measurements remain absent even though this is the calling device.pub(super) fn facts(ctx: &Ctx<'_>) -> Valid<Stored> {let device = ctx.caller_device.ok_or_else(|| ToolFailure::new("This device has not joined yet"))?;let rows = cotton_store::storage_rules::remote_rows(ctx.db(), ctx.workspace_id, device) .map_err(|e| ToolFailure::new(e.to_string()))?;letmut record = storage_row(ctx, rows)?; record.data.insert("is_this_device".into(), Value::Bool(true));Ok(record)}/// Storage is a view, so this writes its one real setting through the same/// synced writer as `storage.keepRule`; no local SQL update can change it.pub(super) fn update(ctx: &mutCtx<'_>, _definition: &cotton_core::definitions::TableDefinition, id: &str, patch: &Data) -> Valid<()> {if patch.len() != 1 { returnErr(ToolFailure::new("Change one Storage setting at a time")); }let row = read(ctx, Some(id))?.into_iter().next().ok_or_else(|| ToolFailure::new("That Storage row is no longer here"))?;let device = row.data.get("device_id").and_then(Value::as_str).unwrap_or_default();// `remote_rows` is the storage engine's live-device check. It also avoids// accepting an id that no longer belongs to this database. cotton_store::storage_rules::remote_rows(ctx.db(), ctx.workspace_id, device) .map_err(|error| ToolFailure::new(error.to_string()))?;for (column, rule) in patch {if column == "keep_bytes" {super::super::device_writes::write_keep_bytes(ctx, device, rule)?;continue; }let tool = column.strip_suffix("_keep_rule").filter(|tool| TOOLS.contains(tool)) .ok_or_else(|| ToolFailure::new("Storage changes photo, video, document or thread keep rules"))?;let rule = rule.as_str().ok_or_else(|| ToolFailure::new("A keep rule is all, recent_90_days or only_opened"))?; cotton_store::storage_rules::KeepRule::parse(rule).map_err(|error| ToolFailure::new(error.to_string()))?;let rule_id = cotton_store::storage_rules::row_id(device, tool);letmut write = serde_json::Map::new();let exists = ctx.db().get("SELECT id FROM cotton_storage_rules WHERE id = ?", &[rusqlite::types::Value::Text(rule_id.clone())]) .map_err(|error| ToolFailure::new(error.to_string()))?.is_some();if !exists { write.insert("id".into(), Value::from(rule_id.clone())); write.insert("workspace_id".into(), Value::from(ctx.workspace_id)); write.insert("device_id".into(), Value::from(device)); write.insert("tool".into(), Value::from(tool)); write.insert("created_at".into(), Value::from(now_iso(ctx))); } write.insert("keep_rule".into(), Value::from(rule)); write.insert("freeable_bytes".into(), Value::Null); write.insert("measured_at".into(), Value::Null); write.insert("updated_at".into(), Value::from(now_iso(ctx))); ctx.writer()?.upsert(cotton_store::storage_rules::TABLE, &rule_id, write); } ctx.commit()}