Cotton code
122 lines · 4.3 KB · RustRaw
//! PUBLISHED DATABASES (owner, 14 Nov 2026): reference rows that live on//! Cotton's server, read-only for everyone signed in, written by their//! publisher alone (`apps/business/src/published.ts`). Cotton publishes four://! `places` (tables `places`, `countries`), `holidays` (`holidays`,//! `coverage`), `airports` (`airports`) and `english_words` (`words`).//!//! [`read`] is THE one way the core reads one. It asks the [`Reader`] the app//! installed ([`install`]: the phone's, over its signed-in door), and answers//! [`Unread`] when there is none (signed out) or the server cannot be reached//! (offline) — a caller says so in a kit line ([`Unread::line`], filled with//! [`Unread::said`]), and what a person already picked//! still draws, because a pick is copied whole into their own record. No app//! bundles a copy: the server is the only place these rows are read from.use std::sync::{Arc, RwLock};use serde_json::{json, Value};/// What a read asks of one published table.#[derive(Debug, Clone, PartialEq)]pub enum Ask {    /// Rows whose names start with `q` (two letters at least), rows of the    /// `prefer` group first, then by rank.    Search { q: String, prefer: Option<String>, limit: usize },    /// The rows nearest a point.    Near { lat: f64, lng: f64, limit: usize },    /// Those rows, at the current version or at `version` while it is held.    Ids { ids: Vec<String>, version: Option<String> },}impl Ask {    /// The body of `POST /v1/published/<publisher>/<name>/<table>/search`.    #[must_use]    pub fn body(&self) -> Value {        match self {            Ask::Search { q, prefer, limit } => json!({"q": q, "prefer": prefer, "limit": limit}),            Ask::Near { lat, lng, limit } => json!({"near": {"lat": lat, "lng": lng}, "limit": limit}),            Ask::Ids { ids, version } => json!({"ids": ids, "version": version}),        }    }}/// A published table's answer: the version it was read at and its rows, each/// an object carrying its `id`.#[derive(Debug, Clone, PartialEq)]pub struct Answer {    pub version: String,    pub rows: Vec<Value>,}/// Why nothing was read.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Unread {    /// No reader: this device is not signed in to Cotton.    SignedOut,    /// The server could not be reached.    Offline(String),    /// The server answered no, in its own code and words.    Refused { code: String, message: String },}impl Unread {    /// The kit line that says it (`refusal.published.*`).    #[must_use]    pub fn line(&self) -> &'static str {        match self {            Unread::SignedOut => "published.signed_out",            Unread::Offline(_) => "published.offline",            Unread::Refused { .. } => "published.refused",        }    }    /// The machine code a method refusal wears.    #[must_use]    pub fn code(&self) -> &str {        match self {            Unread::SignedOut => "published_signed_out",            Unread::Offline(_) => "published_offline",            Unread::Refused { code, .. } => code,        }    }}impl Unread {    /// The server's or the transport's own words, filled into the kit line as `{said}`.    #[must_use]    pub fn said(&self) -> &str {        match self {            Unread::Refused { message, .. } => message,            Unread::Offline(why) => why,            Unread::SignedOut => "",        }    }}/// How the app reaches the server's published databases.pub trait Reader: Send + Sync {    fn read(&self, publisher: &str, name: &str, table: &str, ask: &Ask) -> Result<Answer, Unread>;}static READER: RwLock<Option<Arc<dyn Reader>>> = RwLock::new(None);/// The app's reader, once a process (the phone's, at open); `None` takes it away.pub fn install(reader: Option<Arc<dyn Reader>>) {    if let Ok(mut slot) = READER.write() {        *slot = reader;    }}/// THE one read of a Cotton published database's table.pub fn read(name: &str, table: &str, ask: &Ask) -> Result<Answer, Unread> {    let reader = READER.read().ok().and_then(|slot| slot.clone());    read_with(reader.as_deref(), name, table, ask)}/// [`read`] with its reader named, for a test.pub fn read_with(reader: Option<&dyn Reader>, name: &str, table: &str, ask: &Ask) -> Result<Answer, Unread> {    reader.ok_or(Unread::SignedOut)?.read("cotton", name, table, ask)}#[cfg(test)]#[path = "published_tests.rs"]mod tests;