//! A KEPT ORDER: the ids a list's own read holds, in the store's order,//! kept beside where the file stood when they were read, and patched for//! the rows each write names (`EventBus::rows_since`) rather than read//! again. A named row is read through the list's own read narrowed to the//! rows named (`among`), so one its filter no longer keeps is gone, and is//! placed by the store's own order among a few kept rows at a time//! (`place`). 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.deck` pages a plain deck off it; `shell.list` places a kept//! cut's rows by `place`.usecrate::methods::MethodError;usecrate::shell::client::ClientController;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>;/// `records.list` narrowed to some ids, its filters and order kept.pub(crate) const AMONG: &str = "among";/// How many kept rows one ask of the store places a moved row among.const PIVOTS: usize = 48;/// How many moved rows a kept order is patched for before it is read whole.pub(crate) const MOST_PATCHED: usize = 128;/// How many orders are kept before every one is let go.const MOST: usize = 32;/// Whether a table's list stands in an order each row holds of itself,/// narrowed by `filter` (its `where` keys): its sort, date, order, `shows`/// and source's `where` each a column it stores, none computed (a running/// balance moves with every row before it).pub(crate) fn row_local<'a>(definition: &cotton_core::definitions::TableDefinition, filter: implIterator<Item = &'a String>) -> bool {let keys = |value: Value| value.as_object().map(|keys| keys.keys().cloned().collect::<Vec<_>>()).unwrap_or_default();let shown = keys(serde_json::to_value(&definition.shows).unwrap_or_default());letmut source = serde_json::to_value(&definition.source).unwrap_or_default();let sourced = keys(source["where"].take());let sort = definition.sort.iter().flat_map(|sort| std::iter::once(sort.column.clone()).chain(sort.tie.clone()));letmut read = sort.chain(definition.date.clone()).chain(definition.order.clone()).chain(filter.cloned()).chain(shown).chain(sourced); !read.any(|key| definition.column(&key).is_some_and(|column| column.computed.is_some()))}/// `ask` as a read of ids alone: a narrow cut of no column, no heads.fn ids_only(ask: &Map<String, Value>) -> Map<String, Value> {letmut ask = ask.clone();for (key, value) in [("light", json!(true)), ("columns", json!([])), ("cut", json!(true)), ("heads", json!(false))] { ask.insert(key.into(), value); } ask}/// The ids an answer holds, in its order: a cut's `[id]` rows or its records'.fn ids_of(answer: &Value) -> Vec<&Value> {match answer["rows"].as_array() {Some(cut) => cut.iter().map(|row| &row[0]).collect(),None => answer["records"].as_array().into_iter().flatten().map(|row| &row["id"]).collect(), }}/// Where the row `id`, one `ask` (the list's own read) keeps, falls among/// the `len` kept rows `id_at` names in the store's order: asked of the/// store over at most `PIVOTS` kept rows at a time, each answer naming the/// gap the row falls in, until the gap is one place. None where the store/// orders the kept rows otherwise than they are kept, or leaves one out.pub(crate) fn place(read: Read, ask: &Map<String, Value>, len: usize, id_at: &dynFn(usize) -> Value, id: &Value) -> Result<Option<usize>, MethodError> {letmut ask = Value::Object(ids_only(ask));let (mut from, mut to) = (0usize, len);while from < to {let step = (to - from).div_ceil(PIVOTS);let pivots: Vec<usize> = (from..to).step_by(step).collect();let kept: Vec<Value> = pivots.iter().map(|at| id_at(*at)).collect();letmut among = kept.clone(); among.push(id.clone()); ask[AMONG] = Value::Array(among); ask["page"] = json!(0); ask["limit"] = json!(pivots.len() + 1);let answer = read(&ask)?;let order = ids_of(&answer);letSome(before) = order.iter().position(|held| *held == id) else { returnOk(None) };if order.len() != kept.len() + 1 || order.iter().filter(|held| **held != id).zip(&kept).any(|(held, kept)| *held != kept) {returnOk(None); } from = if before == 0 { from } else { pivots[before - 1] + 1 }; to = pivots.get(before).copied().unwrap_or(to); }Ok(Some(from))}/// Every row `ask` keeps among `ids`, as `ask` reads it, in the store's order.pub(crate) fn read_among(read: Read, ask: &Map<String, Value>, ids: &[&str]) -> Result<Value, MethodError> {letmut ask = Value::Object(ask.clone()); ask[AMONG] = json!(ids);// The order counted the list: rows among it never count it again. ask["total"] = json!(false); ask["page"] = json!(0); ask["limit"] = json!(ids.len().max(1)); read(&ask)}structKept { moved: (u64, u64), aside: Arc<HashSet<String>>, ids: Arc<Vec<Value>>,}static KEPT: OnceLock<Mutex<HashMap<String, Kept>>> = OnceLock::new();fn kept() -> &'staticMutex<HashMap<String, Kept>> { KEPT.get_or_init(Default::default)}/// Every order kept, forgotten: a bench's first ask.#[cfg(test)]pub(crate) fn forget() {ifletOk(mut kept) = kept().lock() { kept.clear(); }}/// The ids `ask` (a list's own read, unpaged) holds, in the store's order:/// 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`).pub(crate) fn ids(client: &ClientController, own: &[String], aside: &Arc<HashSet<String>>, ask: &Map<String, Value>, read: Read) -> Result<Arc<Vec<Value>>, MethodError> {let bus = client.bus();let moved = client.moved();let key = format!("{}:{}", moved.0, Value::Object(ask.clone()));let kept_here = crate::methods::shell_kept::kept_anywhere();let held = kept().lock().ok().filter(|_| kept_here).and_then(|kept| kept.get(&key).map(|held| (held.moved, Arc::clone(&held.aside), Arc::clone(&held.ids))));ifletSome((at, aside_then, ids)) = held {if bus.stands(at, &aside_then) { returnOk(ids); }ifletSome(changed) = bus.rows_since(at, &aside_then).filter(|changed| changed.len() <= MOST_PATCHED && changed.iter().all(|(table, _)| own.contains(table))) {let patch = patched(read, ask, &ids, &changed)?;ifletSome(ids) = patch {let ids = Arc::new(ids); keep(key, moved, aside, &ids);returnOk(ids); } } }let ids = Arc::new(whole(read, ask)?); keep(key, moved, aside, &ids);Ok(ids)}fn keep(key: String, moved: (u64, u64), aside: &Arc<HashSet<String>>, ids: &Arc<Vec<Value>>) {if !crate::methods::shell_kept::kept_anywhere() { return; }letOk(mut kept) = kept().lock() else { return };if kept.len() >= MOST && !kept.contains_key(&key) { kept.clear(); } kept.insert(key, Kept { moved, aside: Arc::clone(aside), ids: Arc::clone(ids) });}/// `ids` patched for the rows `changed` named: each left out, then those/// the read still keeps placed again. None where one cannot be placed.fn patched(read: Read, ask: &Map<String, Value>, ids: &[Value], changed: &[(String, String)]) -> Result<Option<Vec<Value>>, MethodError> {let named: HashSet<&str> = changed.iter().map(|(_, id)| id.as_str()).collect();letmut ids: Vec<Value> = ids.iter().filter(|id| !id.as_str().is_some_and(|id| named.contains(id))).cloned().collect();if named.is_empty() { returnOk(Some(ids)); }let named: Vec<&str> = named.into_iter().collect();let answer = read_among(read, &ids_only(ask), &named)?;for id in ids_of(&answer) {letSome(at) = place(read, ask, ids.len(), &|at| ids[at].clone(), id)? else { returnOk(None) }; ids.insert(at, id.clone()); }Ok(Some(ids))}/// Every id `ask` reads, page after page of a narrow cut.fn whole(read: Read, ask: &Map<String, Value>) -> Result<Vec<Value>, MethodError> {letmut ask = Value::Object(ids_only(ask)); ask["limit"] = json!(cotton_tools::mcp::handlers::tables::MAX_LIGHT_PAGE);letmut ids = Vec::new();letmut page = 0u64;loop { ask["page"] = json!(page);letmut answer = read(&ask)?; ids.extend(ids_of(&answer).into_iter().cloned());let next = answer["next_page"].take();match next.as_u64() {Some(next) if next > page => page = next,Some(_) => returnErr(MethodError::new("unreadable", "a kept order's page did not advance")),None => returnOk(ids), } }}