Cotton code
233 lines · 7.9 KB · RustRaw
//! Pure Everything catalogue composition shared by phone and tools readers.use serde_json::{json, Map, Value};#[derive(Debug)]pub struct Error {    pub code: &'static str,    pub message: String,}impl Error {    fn new(code: &'static str, message: impl Into<String>) -> Self {        Self {            code,            message: message.into(),        }    }}/// The resolved table catalogue, in the database's own order.pub fn identities(definitions: &[crate::definitions::TableDefinition]) -> Vec<Value> {    definitions        .iter()        .map(|definition| {            json!({                "id": definition.id, "name": definition.name, "plural": definition.plural,                "route": definition.tool.as_ref().and_then(|tool| tool.route.clone())            })        })        .collect()}pub struct Plan {    answer: Value,    filter_after: bool,}impl Plan {    pub fn tables(&self) -> Vec<&str> {        self.answer["records"]            .as_array()            .into_iter()            .flatten()            .filter_map(|record| record["id"].as_str())            .collect()    }}/// Table identities are already in the catalogue. Select the page before/// reading facts unless a fact is itself the filter.pub fn plan(definitions: &[Value], request: &Value) -> Result<Plan, Error> {    let ids = requested_ids(request)?;    let definition =        crate::definitions::builtin_table_definition("everything").ok_or_else(|| {            Error::new(                crate::definitions::NO_TOOL_DRAWS_THIS_TABLE,                crate::definitions::no_tool_draws_this_table(&[]),            )        })?;    let clauses = crate::records::parse_where(definition, request.get("where"))        .map_err(|error| Error::new("bad_request", error.to_string()))?;    let filter_after =        clauses.iter().any(|clause| clause.column != "name") || request["last_changed"] == true;    let listed: std::collections::HashSet<&str> = definitions        .iter()        .filter_map(|definition| definition["id"].as_str())        .collect();    let records: Vec<Value> = definitions        .iter()        .filter_map(|definition| {            let table = definition["id"].as_str().filter(|id| !id.is_empty())?;            if table == "everything" || ids.as_ref().is_some_and(|ids| !ids.contains(&table)) {                return None;            }            // A tool whose home is another table's list is that kind, which            // Everything already names (Feedback opens project_feedback's list).            let opens = definition["route"]                .as_str()                .and_then(|route| route.strip_prefix("/lists/"));            if opens.is_some_and(|other| other != table && listed.contains(other)) {                return None;            }            let name = definition["plural"]                .as_str()                .or_else(|| definition["name"].as_str())                .unwrap_or(table);            let singular = definition["name"].as_str().unwrap_or(name);            Some(row(table, name, singular, None, None))        })        .collect();    let answer = if filter_after {        json!({"records":records})    } else {        filter_and_page(records, request)?    };    Ok(Plan {        answer,        filter_after,    })}pub fn finish(    mut plan: Plan,    request: &Value,    mut facts: impl FnMut(&str) -> (Option<i64>, Option<Value>),) -> Result<Value, Error> {    for record in plan        .answer        .get_mut("records")        .and_then(Value::as_array_mut)        .into_iter()        .flatten()    {        let table = record["id"].as_str().expect("catalogue id");        let name = record["data"]["name"].as_str().expect("catalogue name");        let singular = record["data"]["count_one"]            .as_str()            .expect("catalogue singular");        let (total, changed) = facts(table);        *record = row(table, name, singular, total, changed.as_ref());    }    if plan.filter_after {        filter_and_page(            std::mem::take(plan.answer["records"].as_array_mut().expect("planned rows")),            request,        )    } else {        Ok(plan.answer)    }}fn row(    table: &str,    name: &str,    singular: &str,    total: Option<i64>,    changed: Option<&Value>,) -> Value {    let mut data = Map::from_iter([("name".into(), Value::String(name.into()))]);    data.insert(        "count".into(),        total.map(Value::from).unwrap_or(Value::Null),    );    data.insert("count_one".into(), Value::from(singular.to_lowercase()));    data.insert("count_other".into(), Value::from(name.to_lowercase()));    data.insert(        "changed".into(),        changed            .cloned()            .filter(|value| !value.is_null())            .unwrap_or(Value::Null),    );    json!({"id":table,"data":data,"deleted_at":Value::Null})}fn filter_and_page(mut records: Vec<Value>, request: &Value) -> Result<Value, Error> {    let definition =        crate::definitions::builtin_table_definition("everything").ok_or_else(|| {            Error::new(                crate::definitions::NO_TOOL_DRAWS_THIS_TABLE,                crate::definitions::no_tool_draws_this_table(&[]),            )        })?;    let clauses = crate::records::parse_where(definition, request.get("where"))        .map_err(|error| Error::new("bad_request", error.to_string()))?;    let query = request.get("query").and_then(Value::as_str);    let zone = crate::records::where_zone(request.get("timezone").and_then(Value::as_str)).on(request.get("today").and_then(Value::as_str));    records.retain(|record| {        let data = record["data"].as_object().cloned().unwrap_or_default();        clauses            .iter()            .all(|clause| crate::records::holds(&data, clause, &zone))            && query.is_none_or(|words| crate::records::matches_query(definition, &data, words))    });    let total = records.len();    if request.get("last_changed") == Some(&Value::Bool(true)) {        let changed = records            .iter()            .filter_map(|record| record["data"]["changed"].as_str())            .max();        return Ok(json!({"table":"everything","last_changed":changed}));    }    if request.get("count_only") == Some(&Value::Bool(true)) {        return Ok(            json!({"table":"everything","records":[],"next_page":Value::Null,"total":total}),        );    }    let start = request.get("page").map_or(Ok(0usize), |page| {        page.as_u64()            .map(|page| page as usize)            .ok_or_else(|| Error::new("bad_request", "page is a non-negative number"))    })?;    let limit = request.get("limit").map_or(Ok(50usize), |limit| {        limit            .as_u64()            .filter(|limit| (1..=200).contains(limit))            .map(|limit| limit as usize)            .ok_or_else(|| Error::new("bad_request", "limit is 1 to 200"))    })?;    let end = start.saturating_add(limit).min(total);    let next_page = if end < total {        Value::from(end)    } else {        Value::Null    };    let records = if start < total {        records[start..end].to_vec()    } else {        Vec::new()    };    Ok(json!({"table":"everything", "records":records, "next_page":next_page, "total":total}))}fn requested_ids(request: &Value) -> Result<Option<Vec<&str>>, Error> {    let Some(ids) = request.get("ids") else {        return Ok(None);    };    let ids = ids        .as_array()        .ok_or_else(|| Error::new("bad_request", "`ids` is an array of record ids"))?;    Ok(Some(ids.iter().filter_map(Value::as_str).collect()))}#[cfg(test)]mod tests {    use super::*;    /// RULE: A reader that cannot answer while offline is unknown, never the    /// fabricated statement that its table has zero rows.    #[test]    fn an_unavailable_reader_has_no_count() {        let row = row("remote", "Remote", "Remote", None, None);        assert!(row["data"]["count"].is_null());    }}