//! 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.usecrate::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) typeRead<'a> = &'a dynFn(&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) structAt<'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) structSections { keys: Vec<String>, of: HashMap<String, String>,}implSections {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<_>>>()?;letmut 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> {letmut counts: HashMap<&str, u64> = HashMap::new();for key inself.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() }}structKept { moved: (u64, u64), aside: Arc<HashSet<String>>, sections: Arc<Sections>,}static KEPT: OnceLock<Mutex<HashMap<String, Kept>>> = OnceLock::new();fn kept() -> &'staticMutex<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() {ifletOk(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> {letAt { 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))));ifletSome((at, aside_then, sections)) = held {if bus.stands(at, &aside_then) { returnOk(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)));ifletSome(changed) = changed { #[cfg(test)] PATCHED.with(|patched| patched.set(patched.get() + 1));let sections = Arc::new(patched(read, ask, §ions, &changed)?); keep(key, moved, aside, §ions);returnOk(Some(sections)); } }letmut asked = Value::Object(ask.clone()); asked["sectioned"] = json!(true);letSome(sections) = Sections::of_answer(&read(&asked)?) else { returnOk(None) };let sections = Arc::new(sections); keep(key, moved, aside, §ions);Ok(Some(sections))}fn keep(key: String, moved: (u64, u64), aside: &Arc<HashSet<String>>, sections: &Arc<Sections>) {letOk(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();letmut of = sections.of.clone();for id in &named { of.remove(*id); }if !named.is_empty() {letmut 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() {iflet (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() { returnOk(None); }letSome(section) = ask.get("section").and_then(Value::as_str) else { returnOk(None) };let key = match (section, ask.get("day").and_then(Value::as_str)) { ("day", Some(day)) => format!("day:{day}"), (section, None) => section.to_string(), _ => returnOk(None), };letmut whole = ask.clone();for paged in ["section", "day", "page", "limit"] { whole.remove(paged); }letSome(sections) = sections(at, &whole, today, read)? else { returnOk(None) };if !sections.keys.contains(&key) { returnOk(None); }let ids = sections.ids(&key);if ids.len() > MOST_AMONG { returnOk(None); }letmut asked = Value::Object(ask.clone()); asked[crate::methods::shell_order::AMONG] = json!(ids);letmut 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))}