Cotton code
201 lines · 8.9 KB · RustRaw
//! A KEPT PLAN: each row's section of a list of work still to do (Todos'//! today, late, the days ahead, later, undated, done, dropped), read once//! by the store's plan (`records.list` `sectioned`), kept beside where the//! file stood when it was read, and patched for the rows each write names//! (`EventBus::rows_since`) rather than read again: a named row's section//! is read through the plan narrowed to it (`among`), one the list no//! longer keeps is gone. The plan's counts are told off it, and a//! section's page is the plan's own read narrowed to that section's rows//! (`among`), so no read walks the whole table. Where what moved cannot be//! told (a pull, a bulk write, a definition, a table it reads beside its//! own) it is read whole. `shell.list` and `shell.deck` both read by it.use crate::methods::MethodError;use serde_json::{json, Map, Value};use std::collections::{HashMap, HashSet};use std::sync::{Arc, Mutex, OnceLock};/// A `records.list` read.pub(crate) type Read<'a> = &'a dyn Fn(&Value) -> Result<Value, MethodError>;/// Where a read stands: its file's bus and how often it had moved on, the/// store tables its rows live in, and what it leaves aside.#[derive(Clone, Copy)]pub(crate) struct At<'a> {    pub bus: &'a crate::events::EventBus,    pub moved: (u64, u64),    pub own: &'a [String],    pub aside: &'a Arc<HashSet<String>>,}/// How many rows a section's page is read among before it is read by the/// plan's own walk: a long `IN` list costs what the walk would.const MOST_AMONG: usize = 2_000;/// How many plans are kept before every one is let go.const MOST: usize = 32;/// Each row's section, and the plan's keys in the order drawn.pub(crate) struct Sections {    keys: Vec<String>,    of: HashMap<String, String>,}impl Sections {    fn of_answer(answer: &Value) -> Option<Sections> {        let sectioned = &answer["sectioned"];        let keys = sectioned["keys"].as_array()?.iter().map(|key| key.as_str().map(str::to_string)).collect::<Option<Vec<_>>>()?;        let mut of = HashMap::new();        for row in sectioned["rows"].as_array()? {            of.insert(row[0].as_str()?.to_string(), row[1].as_str()?.to_string());        }        Some(Sections { keys, of })    }    /// How many rows stand in section `key`.    fn count(&self, key: &str) -> usize {        self.of.values().filter(|held| *held == key).count()    }    /// The rows standing in section `key`, in no order.    fn ids(&self, key: &str) -> Vec<&str> {        self.of.iter().filter(|(_, held)| *held == key).map(|(id, _)| id.as_str()).collect()    }    /// The `sections` a whole plan read answers (`day_plan::Plan::sections_of`):    /// `[{key, count}]` (a day ahead also `day`), in the order drawn, an    /// empty one left out.    fn said(&self) -> Vec<Value> {        let mut counts: HashMap<&str, u64> = HashMap::new();        for key in self.of.values() { *counts.entry(key.as_str()).or_default() += 1; }        self.keys.iter().filter_map(|key| {            let count = *counts.get(key.as_str())?;            Some(match key.strip_prefix("day:") {                Some(day) => json!({"key": "day", "day": day, "count": count}),                None => json!({"key": key, "count": count}),            })        }).collect()    }}struct Kept {    moved: (u64, u64),    aside: Arc<HashSet<String>>,    sections: Arc<Sections>,}static KEPT: OnceLock<Mutex<HashMap<String, Kept>>> = OnceLock::new();fn kept() -> &'static Mutex<HashMap<String, Kept>> {    KEPT.get_or_init(Default::default)}#[cfg(test)]thread_local! {    /// How many kept plans this thread patched.    static PATCHED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };}/// How many kept plans this thread has patched.#[cfg(test)]pub(crate) fn patched_count() -> u64 { PATCHED.with(std::cell::Cell::get) }/// Whether a bench reads as before a plan was kept (`SHELL_PLAN_OFF`).fn off() -> bool {    #[cfg(test)]    { std::env::var_os("SHELL_PLAN_OFF").is_some() }    #[cfg(not(test))]    { false }}/// Every plan kept, forgotten: a bench's first ask.#[cfg(test)]pub(crate) fn forget() {    if let Ok(mut kept) = kept().lock() { kept.clear(); }}/// The plan's read of `ask` (a planned list's own read, unpaged, in no/// section), on the reader's day `today`: kept while nothing it reads has/// moved, patched for the rows moves named in `own` (the store tables its/// rows live in), else read whole. `aside` is what the read leaves aside/// (`shell_kept::aside`). None where the plan is not one a kept plan reads.fn sections(at: At, ask: &Map<String, Value>, today: &str, read: Read) -> Result<Option<Arc<Sections>>, MethodError> {    let At { bus, moved, own, aside } = at;    let key = format!("{}:{today}:{}", moved.0, Value::Object(ask.clone()));    let held = kept().lock().ok().and_then(|kept| kept.get(&key).map(|held| (held.moved, Arc::clone(&held.aside), Arc::clone(&held.sections))));    if let Some((at, aside_then, sections)) = held {        if bus.stands(at, &aside_then) { return Ok(Some(sections)); }        let changed = bus.rows_since(at, &aside_then)            .filter(|changed| changed.len() <= crate::methods::shell_order::MOST_PATCHED && changed.iter().all(|(table, _)| own.contains(table)));        if let Some(changed) = changed {            #[cfg(test)]            PATCHED.with(|patched| patched.set(patched.get() + 1));            let sections = Arc::new(patched(read, ask, &sections, &changed)?);            keep(key, moved, aside, &sections);            return Ok(Some(sections));        }    }    let mut asked = Value::Object(ask.clone());    asked["sectioned"] = json!(true);    let Some(sections) = Sections::of_answer(&read(&asked)?) else { return Ok(None) };    let sections = Arc::new(sections);    keep(key, moved, aside, &sections);    Ok(Some(sections))}fn keep(key: String, moved: (u64, u64), aside: &Arc<HashSet<String>>, sections: &Arc<Sections>) {    let Ok(mut kept) = kept().lock() else { return };    if kept.len() >= MOST && !kept.contains_key(&key) {        let spent: Vec<Arc<Sections>> = kept.drain().map(|(_, held)| held.sections).collect();        super::shell_list::let_go(spent);    }    kept.insert(key, Kept { moved, aside: Arc::clone(aside), sections: Arc::clone(sections) });}/// `sections` patched for the rows `changed` named: each left out, then/// those the plan still keeps filed under the section it reads them in now.fn patched(read: Read, ask: &Map<String, Value>, sections: &Sections, changed: &[(String, String)]) -> Result<Sections, MethodError> {    let named: Vec<&str> = changed.iter().map(|(_, id)| id.as_str()).collect::<HashSet<_>>().into_iter().collect();    let mut of = sections.of.clone();    for id in &named { of.remove(*id); }    if !named.is_empty() {        let mut asked = Value::Object(ask.clone());        asked["sectioned"] = json!(true);        asked[crate::methods::shell_order::AMONG] = json!(named);        let answer = read(&asked)?;        for row in answer["sectioned"]["rows"].as_array().into_iter().flatten() {            if let (Some(id), Some(key)) = (row[0].as_str(), row[1].as_str()) { of.insert(id.to_string(), key.to_string()); }        }    }    Ok(Sections { keys: sections.keys.clone(), of })}/// One section's page of a planned list, as the plan reads it whole: `ask`/// is the list's own read with its `section` (and `day`), `page` and/// `limit`. Read off the kept plan: the page among that section's rows/// alone, and the whole plan's `sections` said from the kept one. None/// where it is not read so (a section past `MOST_AMONG` rows, a plan whose/// rows' sections are not their own, nothing kept here): the caller reads/// the plan itself.pub(crate) fn page(at: At, ask: &Map<String, Value>, today: &str, read: Read) -> Result<Option<Value>, MethodError> {    if !crate::methods::shell_kept::kept_anywhere() || off() { return Ok(None); }    let Some(section) = ask.get("section").and_then(Value::as_str) else { return Ok(None) };    let key = match (section, ask.get("day").and_then(Value::as_str)) {        ("day", Some(day)) => format!("day:{day}"),        (section, None) => section.to_string(),        _ => return Ok(None),    };    let mut whole = ask.clone();    for paged in ["section", "day", "page", "limit"] { whole.remove(paged); }    let Some(sections) = sections(at, &whole, today, read)? else { return Ok(None) };    if !sections.keys.contains(&key) { return Ok(None); }    let ids = sections.ids(&key);    if ids.len() > MOST_AMONG { return Ok(None); }    let mut asked = Value::Object(ask.clone());    asked[crate::methods::shell_order::AMONG] = json!(ids);    let mut answer = read(&asked)?;    // The section's rows read among themselves are the section; the plan    // counts every section over the whole list.    if answer.get("total").is_some() { answer["total"] = json!(sections.count(&key)); }    answer["sections"] = Value::Array(sections.said());    Ok(Some(answer))}