Cotton code
267 lines · 12.1 KB · RustRaw
//! `workspace.setReach` — how the world reaches this household.//!//! THE WORD. The row and the engines call this the household's front door//! (`cotton_core::front_door`); a person is never shown that word, and the//! phone's sources may not say it (it is a retired metaphor there). What a//! page and a method say is what the household is REACHED THROUGH.//!//! The door is two columns of the household's own row//! (`cotton_core::front_door`): which door its serving Mac keeps open, and the//! host the world dials through it. This is the one place they are written.//!//! IT WRITES THOSE TWO AND NOTHING ELSE. The household's name and the relay it//! lives under are in the same row and are not a door's to change: a person//! who tries Funnel for an afternoon and comes back finds the name they had,//! bound to the Mac it was bound to.//!//! THE HOUSEHOLD'S, NOT A PROJECT'S. A shared database is reached wherever//! its household is, so it has no door of its own and is refused one here.use cotton_core::front_door::{Door, FrontDoor};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{maybe_row, update_row};use cotton_tools::mcp::read_db::Query;use serde_json::{json, Map, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;/// The door as a page offers it: FOUR words, because a person is shown the two/// relays apart — Cotton's and the household's own — although the row holds/// them as one door and says which relay in the columns beside its name.pub const OFFERED: [&str; 4] = ["cotton_relay", "own_relay", "tailscale_funnel", "direct"];/// What a page calls the door a row holds: see [`OFFERED`].pub fn offered(door: &FrontDoor, relay: &cotton_core::relay_address::RelayAddress) -> &'static str {    match door.door() {        Door::Relay if *relay == cotton_core::relay_address::RelayAddress::cotton() => OFFERED[0],        Door::Relay => OFFERED[1],        Door::TailscaleFunnel => OFFERED[2],        Door::Direct => OFFERED[3],    }}/// `workspace.setReach { through, address? }` — `through` is one of/// [`OFFERED`] (or plain `relay`, for whichever relay the household is on);/// `address` is the host the world dials (a Funnel's may be left for the/// serving Mac to fill; a direct door's is the household's domain and is/// required; a relay takes none).pub fn set_front_door(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    set_front_door_named(handle, request, &|_| None)}/// [`set_front_door`], with the name of the Mac it was chosen on.////// `own` is asked only for a Funnel chosen with no address, and answers what/// that Mac's Tailscale said its name is — when it serves and has one. A/// phone, and a Mac that does not serve, answer nothing, and the choice is/// left for the serving Mac to open (`shell::front_door::set_reach` is the/// Mac's caller; this module names no Mac-only code).pub fn set_front_door_named(    handle: &CottonHandle,    request: &Value,    own: &dyn Fn(&Asked) -> Option<Result<String, String>>,) -> Result<Value, MethodError> {    let asked = asked(request)?;    let unaddressed = asked.door.door() == Door::TailscaleFunnel && asked.door.address().is_none();    let named = if unaddressed { own(&asked) } else { None };    let asked = named_by_this_mac(asked, named);    handle        .client()        .write_rows("workspace.setReach", &mut |ctx| {            write_front_door(ctx, &asked)        })        .map(crate::authoring::own_answer)        .map_err(|reason| MethodError::new("write_refused", reason))}/// What was asked: the door, and — when a page named one of the two relays —/// which relay it believes the household is on.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Asked {    pub door: FrontDoor,    /// `Some(true)` for `own_relay`, `Some(false)` for `cotton_relay`.    pub own_relay: Option<bool>,}impl From<FrontDoor> for Asked {    fn from(door: FrontDoor) -> Asked {        Asked { door, own_relay: None }    }}/// A Funnel chosen with no address, given the name of the Mac it was chosen/// on (`own`: what its Tailscale answered, when it serves and has one). Every/// other door, an addressed Funnel, and a Tailscale that did not answer are/// left exactly as asked.pub fn named_by_this_mac(asked: Asked, own: Option<Result<String, String>>) -> Asked {    if asked.door.door() != Door::TailscaleFunnel || asked.door.address().is_some() {        return asked;    }    match own.and_then(Result::ok).and_then(|name| FrontDoor::new(Door::TailscaleFunnel, Some(&name)).ok()) {        Some(door) => Asked { door, ..asked },        None => asked,    }}/// The door asked for, checked before a row is touched.pub fn asked(request: &Value) -> Result<Asked, MethodError> {    let bad = |message: String| MethodError::new("bad_request", message);    let (door, own_relay) = match request.get("through").and_then(Value::as_str) {        Some("cotton_relay") => (Door::Relay, Some(false)),        Some("own_relay") => (Door::Relay, Some(true)),        Some(name) => (            Door::from_name(name)                .ok_or_else(|| bad("`through` is relay, tailscale_funnel or direct".to_string()))?,            None,        ),        None => return Err(bad("`through` is relay, tailscale_funnel or direct".to_string())),    };    let address = match request.get("address") {        None | Some(Value::Null) => None,        Some(Value::String(said)) => Some(said.as_str()),        Some(_) => return Err(bad("`address` is a hostname, or nothing".to_string())),    };    let door = FrontDoor::new(door, address).map_err(|refusal| bad(refusal.to_string()))?;    Ok(Asked { door, own_relay })}pub fn write_front_door(ctx: &mut Ctx<'_>, asked: &Asked) -> Result<Value, String> {    let door = &asked.door;    // The workspace is the FILE's, never the caller's.    let workspace_id = ctx.workspace_id.to_string();    let row = maybe_row(        ctx,        &Query::on("cotton_workspaces")            .columns(&["id", "kind", "relay_name", "relay_domain", "front_door", "front_door_address"])            .eq("id", workspace_id.clone()),    )    .map_err(|failure| failure.to_string())?    .ok_or_else(|| "this file has no workspace row to set".to_string())?;    if row.get("kind").and_then(Value::as_str) == Some("shared") {        return Err(            "a shared database is reached wherever its household is — set how it is reached \             in your personal database"                .to_string(),        );    }    // WHICH RELAY is not a door's to change: it was written with the row and    // every device that joined holds it. A page that offers the other relay    // is told so, in words — never obeyed by quietly staying where it was.    let on_own = row.get("relay_domain").and_then(Value::as_str).is_some();    match asked.own_relay {        Some(true) if !on_own => {            return Err(                "this household was made on Cotton's relay — a household is on a relay from the \                 day it is made, and moving one to a relay of its own is not built yet"                    .to_string(),            )        }        Some(false) if on_own => {            return Err(                "this household was made on a relay of its own — a household is on a relay from \                 the day it is made, and moving one to Cotton's is not built yet"                    .to_string(),            )        }        _ => {}    }    // EXPLICIT NULLs, never omitted keys: going back to the relay is a write    // that has to reach the other devices, and so is a Funnel chosen before    // any Mac has named itself. And exactly these two keys — the name and the    // relay beside them are not in the patch, so no door write can move them.    let (stored_door, stored_address) = door.stored();    let mut patch = Map::new();    patch.insert(        "front_door".to_string(),        stored_door.map_or(Value::Null, Value::from),    );    patch.insert(        "front_door_address".to_string(),        stored_address.map_or(Value::Null, Value::from),    );    update_row(ctx, "cotton_workspaces", &workspace_id, patch)        .map_err(|failure| failure.to_string())?;    // THE WAY BACK is the door it was, when this build could read it: a door    // it could not read is not offered again by an undo.    let before = FrontDoor::from_stored(        row.get("front_door").and_then(Value::as_str),        row.get("front_door_address").and_then(Value::as_str),    )    .ok()    .filter(|before| before != door);    Ok(json!({        "through": door.door().as_str(),        "address": door.address(),        "relayName": row.get("relay_name").cloned().unwrap_or(Value::Null),        // THE SERVING MAC FOLLOWS IT WHILE IT RUNS, and the receipt says        // when: at once when it was chosen there, within a minute of the        // change arriving when it was chosen anywhere else        // (`shell::front_door::follow`).        "receipt": receipt(door.door(), on_own),        "undo": before.map(|before| json!({            "method": "workspace.setReach",            "args": { "through": before.door().as_str(), "address": before.address() },        })),    }))}/// What a person reads after choosing: the choice in its page's own words/// (`device.json`'s labels), WHEN it takes hold — the Mac that serves follows/// it while it runs, within a minute — and, behind a Funnel, that a phone away/// from home follows it there once the Mac at the address has proved its key/// (`cotton_client::transport::reach_route`).fn receipt(door: Door, on_own_relay: bool) -> String {    match door {        Door::Relay => format!(            "Reached through {} \u{2014} the Mac that serves follows within a minute",            if on_own_relay { "your own relay" } else { "Cotton relay" }        ),        Door::TailscaleFunnel => "Reached through Tailscale Funnel \u{2014} the Mac that serves follows within a \             minute, and phones away from home follow it there once that Mac has proved itself"            .to_string(),        Door::Direct => "Reached directly \u{2014} which this version cannot open yet".to_string(),    }}/// `read.devices`' `reach`: how the world reaches this household, in the/// device page's words, off the file's own row — so a phone on a train draws/// it as readily as the serving Mac.////// `through` is one of [`OFFERED`]. WHERE it is reached is not said here,/// nor anywhere a person reads. A row this build cannot read answers/// `unreadable` with the reason and no choice at all: an unknown one is never/// drawn as the relay.pub fn page_answer(driver: &cotton_store::driver::Driver, workspace_id: &str) -> Value {    let household =        cotton_tools::household_address::read_household_address(driver, Some(workspace_id));    let door = cotton_tools::household_address::read_front_door(driver, Some(workspace_id));    match (household, door) {        (Ok(household), Ok(door)) => json!({            "through": offered(&door, household.relay()),            "address": door.address(),        }),        (Err(reason), _) | (_, Err(reason)) => json!({ "unreadable": reason }),    }}/// WHERE A DEVICE AWAY FROM HOME DIALS BEFORE THE RELAY, off its own copy/// of the household's row: `https://<address>` while the household is reached/// through a Funnel or directly at an address, and `None` on the relay (its/// name under the relay is the device's remembered address already), for a/// Funnel no Mac has opened, and for a row this build cannot read. The address/// is only where to ask: the transport sends it nothing until the Mac there/// proves its device key (`cotton_client::transport::reach_route`).pub fn away_origin(driver: &cotton_store::driver::Driver, workspace_id: &str) -> Option<String> {    let household =        cotton_tools::household_address::read_household_address(driver, Some(workspace_id)).ok()?;    match cotton_tools::household_address::read_front_door(driver, Some(workspace_id)) {        Ok(door) if door.door() != Door::Relay => door.origin(&household),        _ => None,    }}#[cfg(test)]#[path = "front_door_tests.rs"]mod tests;