Cotton code
415 lines · 18.1 KB · RustRaw
//! Storage's device × tool rows and its two acts. A scoped handle selects the//! database; only Free up now is local to the calling device.use crate::{handle::CottonHandle, methods::MethodError, shell::client::ClientController};use cotton_store::storage_rules;use serde_json::{json, Map, Value};pub const METHODS: [&str; 5] = [    "storage.keepRule",    "storage.freeUp",    "storage.keptSpace",    "storage.measure",    "storage.setMacFiles",];/// Measure this device's Storage root on the read-only snapshot.  Measurement/// is a reading of local bytes, not an invented write or a receipt row: the/// generic root record contains the values the snapshot actually found.pub fn measure(client: &ClientController, args: &Value) -> Result<Value, MethodError> {    let own = client        .self_device_id()        .ok_or_else(|| MethodError::new("not_ready", "This device has not joined yet"))?;    let requested = args        .get("deviceId")        .or_else(|| args.get("device"))        .and_then(Value::as_str);    if requested.is_some_and(|device| device != own)        || args            .get("id")            .and_then(Value::as_str)            .is_some_and(|id| id != "this")    {        return Err(MethodError::new(            "not_this_device",            "Storage measurement runs only for this device",        ));    }    let record = crate::phone::records::call(        client,        "records.get",        &json!({            "table": "storage",            "id": "this",        }),    )?;    let held = record["data"]["held_bytes"].as_i64();    let freeable = record["data"]["freeable_bytes"].as_i64();    let receipt = match (held, freeable) {        (Some(held), Some(freeable)) => {            format!("Measured {held} bytes; {freeable} bytes can be freed.")        }        (Some(held), None) => format!("Measured {held} bytes."),        _ => "Measured this device's Storage.".to_string(),    };    Ok(json!({"record": record, "receipt": receipt}))}/// The Storage root writes the same durable device preference as its Files/// card. The answer retains the real device change and its Undo identity.pub fn records_update(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let id = required(request, "id")?;    let patch = request        .get("patch")        .and_then(Value::as_object)        .ok_or_else(|| MethodError::new("bad_request", "Storage updates need a patch"))?;    let Some(rule) = patch.get("keep_bytes").and_then(Value::as_str) else {        return Err(MethodError::new(            "bad_request",            "only Storage Files can change here",        ));    };    if patch.len() != 1 {        return Err(MethodError::new(            "bad_request",            "only Storage Files can change here",        ));    }    let before = crate::phone::records::call(        &handle.client(),        "records.get",        &json!({            "table": "storage",            "id": id,        }),    )?;    if before["data"]["root"] != "machine" {        return Err(MethodError::new(            "bad_request",            "Files is one choice on a machine Storage root",        ));    }    let device = before["data"]["device_id"]        .as_str()        .ok_or_else(|| MethodError::new("record_not_found", "Storage root has no device"))?;    let engine = mac_files(&handle.client(), &json!({"device": device, "rule": rule}))?;    let record = crate::phone::records::call(        &handle.client(),        "records.get",        &json!({            "table": "storage",            "id": id,        }),    )?;    let mut answer = engine.as_object().cloned().ok_or_else(|| MethodError::new("unreadable", "Files writer returned no change"))?;    answer.insert("before".into(), before);    answer.insert("record".into(), record);    Ok(Value::Object(answer))}/// Files writes durable device intent. The Mac applies it after its next fold;/// this call never claims that remote disks have already changed their rules.pub fn mac_files(client: &ClientController, args: &Value) -> Result<Value, MethodError> {    let device = required(args, "device")?;    let rule = required(args, "rule")?;    storage_rules::MacKeeps::parse(rule)        .map_err(|error| MethodError::new("bad_request", error.to_string()))?;    // A device setting is written by the app, never through a drawn table    // (architect, 21 Oct 2026): Mine's device row is the declaration    // (`phone::device_keep_bytes`).    client        .write_rows("storage.setMacFiles", &mut |ctx| {            cotton_tools::mcp::handlers::tables::device_writes::write_keep_bytes(ctx, device, &json!(rule))                .map(|()| json!({ "device": device, "keep_bytes": rule }))                .map_err(|error| error.message().to_string())        })        .map(crate::authoring::own_answer)        .map_err(|reason| MethodError::new("write_refused", reason))}pub fn keep_fetch(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> {    let own = client.self_device_id();    let device = args        .get("deviceId")        .and_then(Value::as_str)        .or(own.as_deref())        .ok_or("This device has not joined yet")?;    if own.as_deref() == Some(device) {        return serde_json::to_value(client.keep_fetch_status(device)?).map_err(|e| e.to_string());    }    client.with_file(|f| {        let cap=cotton_client::media::keep_fetch::cap(f.driver,f.workspace_id,device).map_err(|e|e.to_string())?;        // Another device's local paths say nothing about that phone's usage.        let rules=cotton_client::media::keep_fetch::byte_rules(f.driver,f.workspace_id,device).map_err(|e|e.to_string())?;        Ok(json!({"keptSpaceBytes":cap,"fetchedBytes":null,"full":null,"fullLine":null,"coming":[],"byteRules":rules}))    })}pub fn rows(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> {    let own = client.self_device_id();    let device = args        .get("deviceId")        .and_then(Value::as_str)        .or(own.as_deref());    let Some(device) = device else {        return Ok(            json!({"rows":[],"totalHeldBytes":null,"totalFreeableBytes":null,"unavailable":"This device has not joined yet"}),        );    };    let now = client.clock().now().timestamp_millis();    let rows = client.with_file(|f| {        if own.as_deref() == Some(device) {            storage_rules::evaluate(f.driver, f.workspace_id, device, now).map(|p| p.rows)        } else {            storage_rules::remote_rows(f.driver, f.workspace_id, device)        }        .map_err(|e| e.to_string())    })?;    let known = rows.iter().all(|r| r.measured_at.is_some());    let held = known.then(|| rows.iter().map(|r| r.held_bytes).sum::<i64>());    let free = known.then(|| rows.iter().map(|r| r.freeable_bytes).sum::<i64>());    let mut wire = serde_json::to_value(&rows).map_err(|e| e.to_string())?;    for row in wire.as_array_mut().expect("rows") {        if row["measuredAt"].is_null() {            for key in [                "heldBytes",                "freeableBytes",                "heldCount",                "totalCount",                "onDemandBytes",            ] {                row[key] = Value::Null;            }        }    }    Ok(json!({"totalHeldBytes":held,"totalFreeableBytes":free,"rows":wire}))}/// `read.databaseStorage` — Spec 10.5's Storage on the database page: every/// live device of this database, each with what it keeps per tool. This/// device is measured now; another says what it last wrote into the synced/// `cotton_storage_rules`, and a device that never measured says null, never 0.pub fn database_storage(    client: &ClientController,    _args: &Map<String, Value>,) -> Result<Value, String> {    let own = client.self_device_id();    let now = client.clock().now().timestamp_millis();    client.with_file(|f| {        let devices = f            .driver            .all(                "SELECT device_id, name, platform FROM cotton_devices \                 WHERE workspace_id = ? AND revoked_at IS NULL ORDER BY approved_at, device_id",                &[rusqlite::types::Value::Text(f.workspace_id.to_string())],            )            .map_err(|e| e.to_string())?;        let mut answer = Vec::new();        let mut total: Option<i64> = Some(0);        for device in &devices {            let id = device.text("device_id").unwrap_or_default();            let this = own.as_deref() == Some(id);            let rows = if this {                storage_rules::evaluate(f.driver, f.workspace_id, id, now).map(|p| p.rows)            } else {                storage_rules::remote_rows(f.driver, f.workspace_id, id)            }            .map_err(|e| e.to_string())?;            let known = rows.iter().all(|r| r.measured_at.is_some());            let kept = known.then(|| rows.iter().map(|r| r.held_bytes).sum::<i64>());            let freeable = known.then(|| rows.iter().map(|r| r.freeable_bytes).sum::<i64>());            total = total.zip(kept).map(|(a, b)| a + b);            let by_tool: Vec<Value> = rows                .iter()                .map(|r| {                    let measured = r.measured_at.is_some();                    json!({                        "tool": r.tool,                        "name": r.name,                        "keepRule": r.keep_rule,                        "heldBytes": measured.then_some(r.held_bytes),                        "freeableBytes": measured.then_some(r.freeable_bytes),                        // Of heldBytes, what this device holds on demand (outside                        // its rule, thirty days from the last opening); the rest                        // is kept. Only a device's own measuring knows it.                        "onDemandBytes": r.on_demand_bytes.filter(|_| measured),                        "heldCount": measured.then_some(r.held_count),                        "totalCount": measured.then_some(r.total_count),                        "measuredAt": r.measured_at,                    })                })                .collect();            answer.push(json!({                "deviceId": id,                "name": device.text("name"),                "platform": device.text("platform"),                "thisDevice": this,                "keptBytes": kept,                "freeableBytes": freeable,                "measuredAt": rows.iter().filter_map(|r| r.measured_at.clone()).min(),                "byTool": by_tool,            }));        }        Ok(json!({ "devices": answer, "totalKeptBytes": if devices.is_empty() { None } else { total } }))    })}pub(crate) fn held(f: &crate::shell::file::ReadFile<'_>) -> cotton_store::mint::Held {    match f.held {        crate::shell::file::FileHeld::Replica => cotton_store::mint::Held::Replica,        crate::shell::file::FileHeld::Served => cotton_store::mint::Held::Served,    }}fn required<'a>(args: &'a Value, key: &str) -> Result<&'a str, MethodError> {    args.get(key)        .and_then(Value::as_str)        .filter(|s| !s.is_empty())        .ok_or_else(|| MethodError::new("bad_request", format!("Storage needs {key}")))}pub fn dispatch(    handle: &CottonHandle,    method: &str,    request: &Value,) -> Result<Value, MethodError> {    let args = request.get("args").unwrap_or(request);    let client = handle.client();    let now = client.clock().now().timestamp_millis();    let mut ids = cotton_client::seams::op_ids(client.random());    match method {        "storage.setMacFiles" => mac_files(&client, args),        "storage.measure" => measure(&client, args),        "storage.keptSpace" => {            let device = required(args, "deviceId")?;            let value = args                .get("keptSpaceBytes")                .ok_or_else(|| MethodError::new("bad_request", "Choose Space for kept things"))?;            if !value.is_null()                && !matches!(                    value.as_u64(),                    Some(1_000_000_000 | 2_000_000_000 | 5_000_000_000 | 10_000_000_000)                )            {                return Err(MethodError::new(                    "bad_request",                    "Space for kept things is 1, 2, 5, 10 GB or no limit",                ));            }            let workspace = client.with_writer(|f| {                let row = f.driver.get("SELECT id FROM cotton_devices WHERE workspace_id=? AND device_id=? AND revoked_at IS NULL", &[rusqlite::types::Value::Text(f.workspace_id.into()),rusqlite::types::Value::Text(device.into())]).map_err(|e|e.to_string())?.ok_or("Choose a live device")?;                let id = row.text("id").ok_or("Device has no row")?;                let change = cotton_store::outbox::LocalChange { delete: Default::default(), kind:cotton_store::protocol::types::OpKind::Upsert, table:"cotton_devices".into(),row_id:id.into(),patch:Some(json!({"kept_space_bytes":value}).as_object().unwrap().clone()) };                let clock = cotton_store::mint::clock::writer_clock(f.driver,now,&mut ids).map_err(|e|e.to_string())?;                cotton_store::mint::mint(f.driver,&cotton_store::mint::Act { actor:cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("storage").map_err(|e|e.to_string())?),verb:"storage".into(),history:cotton_store::mint::History::None,changes:cotton_store::mint::changes_of(f.driver,&[change])},&clock,&mut ids,held(f)).map_err(|e|e.to_string())?;                Ok(f.workspace_id.to_string())            }).map_err(|e|MethodError::new("refused",e))?;            client.emit_data(&workspace, vec!["cotton_devices".into()], "local");            client.nudge_sync();            Ok(json!({"deviceId":device,"keptSpaceBytes":value}))        }        "storage.keepRule" => {            let device = required(args, "deviceId")?;            let tool = required(args, "tool")?;            let rule = required(args, "keepRule")?;            let workspace = client                .with_writer(|f| {                    storage_rules::set_rule(                        f.driver,                        f.workspace_id,                        device,                        tool,                        rule,                        now,                        &mut ids,                        held(f),                    )                    .map_err(|e| e.to_string())?;                    Ok(f.workspace_id.to_string())                })                .map_err(|e| MethodError::new("refused", e))?;            client.emit_data(&workspace, vec![storage_rules::TABLE.into()], "local");            client.nudge_sync();            Ok(                json!({"id":storage_rules::row_id(device,tool),"deviceId":device,"tool":tool,"keepRule":rule}),            )        }        "storage.freeUp" => {            if args.get("confirmed").and_then(Value::as_bool) != Some(true) {                return Err(MethodError::new(                    "confirmation_required",                    "Confirm how much space the current keep rules will free before applying them",                ));            }            let device = client                .self_device_id()                .ok_or_else(|| MethodError::new("not_ready", "This device has not joined yet"))?;            if args                .get("deviceId")                .and_then(Value::as_str)                .is_some_and(|d| d != device)            {                return Err(MethodError::new(                    "refused",                    "Free up space runs only on this device",                ));            }            let approved = args                .get("expectedFreeableBytes")                .and_then(Value::as_u64)                .ok_or_else(|| {                    MethodError::new("bad_request", "Confirm the displayed expectedFreeableBytes")                })?;            let (workspace, applied) = client                .with_writer(|f| {                    let current = storage_rules::evaluate(f.driver, f.workspace_id, &device, now)                        .map_err(|e| e.to_string())?;                    let free = current                        .rows                        .iter()                        .map(|r| r.freeable_bytes.max(0) as u64)                        .sum::<u64>();                    if free > approved {                        return Err(                            "Storage changed; open it again to confirm the new amount".into()                        );                    }                    let result = cotton_client::media::storage::apply_in(                        f.driver,                        f.workspace_id,                        &device,                        client.layout(),                        &cotton_client::media::SystemEvictDisk,                        now,                        &mut ids,                        held(f),                        usize::MAX,                    )?;                    Ok((f.workspace_id.to_string(), result))                })                .map_err(|e| MethodError::new("refused", e))?;            client.emit_data(                &workspace,                vec![                    "_media".into(),                    storage_rules::TABLE.into(),                    "cotton_media_holdings".into(),                ],                "local",            );            client.nudge_sync();            Ok(                json!({"removed":applied.removed,"freedBytes":applied.freed_bytes,"receipt":if applied.removed == 0 { "No files were freed on this device.".to_string() } else { format!("Freed {} {} on this device. Originals are kept in Cotton.", applied.removed, if applied.removed == 1 { "file" } else { "files" }) },"undoable":false,"rows":applied.rows,"errors":applied.errors}),            )        }        _ => Err(MethodError::new("unknown_method", method)),    }}#[cfg(test)]#[path = "storage_machine_tests.rs"]mod machine_tests;/// Stored Storage measurements for a list's head. Opening Photos must not/// measure the catalogue again; the storage worker owns those measurements.pub fn facts(client: &ClientController, _args: &Map<String, Value>) -> Result<Value, String> {    client.read_rows_snapshot("storage.facts", &mut |ctx| {        cotton_tools::mcp::handlers::tables::stored_storage_facts(ctx).map_err(|e|e.to_string())    })}