Cotton code
52 lines · 2.3 KB · RustRaw
//! `device.becomeRunner {deviceId}` — THE OWNER'S ORDER: MAKE THIS MAC A RUNNER.//!//! The one tap on the device page. It writes `runner_ordered_at` on the Mac's//! row, as the owner at this device's own screen — the fold refuses that//! column from any other actor, so no token, session or connector can give//! the order. Everything after is held: the Mac asks the serving Mac to//! confirm it holds everything, drops its copy only on that confirmation, and//! pairs again as a runner (`methods::become_runner`); the page shows the two//! steps and where each stands.use cotton_tools::mcp::handlers::common::{now_iso, update_row};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;pub const METHOD: &str = "device.becomeRunner";pub fn call(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let device_id = request        .get("deviceId")        .and_then(Value::as_str)        .filter(|id| !id.is_empty())        .ok_or_else(|| MethodError::new("bad_request", "deviceId names the Mac"))?        .to_string();    let answer = handle.client().write_rows(METHOD, &mut |ctx| {        let row = ctx            .read            .driver()            .get(                "SELECT id, platform, scope FROM cotton_devices \                 WHERE workspace_id = ? AND device_id = ? AND revoked_at IS NULL \                 ORDER BY approved_at DESC LIMIT 1",                &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(device_id.clone())],            )            .map_err(|error| error.to_string())?            .ok_or("That Mac is not in this database")?;        if row.text("platform") != Some("mac") {            return Err("Only a Mac becomes a runner".into());        }        if row.text("scope") != Some("full") {            return Err("That Mac is a runner already".into());        }        let mut patch = Map::new();        patch.insert("runner_ordered_at".into(), Value::from(now_iso(ctx)));        update_row(ctx, "cotton_devices", row.text("id").unwrap_or_default(), patch)            .map_err(|failure| failure.to_string())?;        Ok(json!({ "ordered": true }))    });    answer.map(crate::authoring::own_answer).map_err(|why| MethodError::new("refused", why))}