//! 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`. use crate::methods::MethodError; use crate::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) type Read<'a> = &'a dyn Fn(&Value) -> Result; /// `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: impl Iterator) -> bool { let keys = |value: Value| value.as_object().map(|keys| keys.keys().cloned().collect::>()).unwrap_or_default(); let shown = keys(serde_json::to_value(&definition.shows).unwrap_or_default()); let mut 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())); let mut 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) -> Map { let mut 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, len: usize, id_at: &dyn Fn(usize) -> Value, id: &Value) -> Result, MethodError> { let mut 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 = (from..to).step_by(step).collect(); let kept: Vec = pivots.iter().map(|at| id_at(*at)).collect(); let mut 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); let Some(before) = order.iter().position(|held| *held == id) else { return Ok(None) }; if order.len() != kept.len() + 1 || order.iter().filter(|held| **held != id).zip(&kept).any(|(held, kept)| *held != kept) { return Ok(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, ids: &[&str]) -> Result { let mut 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) } struct Kept { moved: (u64, u64), aside: Arc>, ids: Arc>, } static KEPT: OnceLock>> = OnceLock::new(); fn kept() -> &'static Mutex> { KEPT.get_or_init(Default::default) } /// Every order kept, forgotten: a bench's first ask. #[cfg(test)] pub(crate) fn forget() { if let Ok(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>, ask: &Map, read: Read) -> Result>, 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)))); if let Some((at, aside_then, ids)) = held { if bus.stands(at, &aside_then) { return Ok(ids); } if let Some(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)?; if let Some(ids) = patch { let ids = Arc::new(ids); keep(key, moved, aside, &ids); return Ok(ids); } } } let ids = Arc::new(whole(read, ask)?); keep(key, moved, aside, &ids); Ok(ids) } fn keep(key: String, moved: (u64, u64), aside: &Arc>, ids: &Arc>) { if !crate::methods::shell_kept::kept_anywhere() { return; } let Ok(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, ids: &[Value], changed: &[(String, String)]) -> Result>, MethodError> { let named: HashSet<&str> = changed.iter().map(|(_, id)| id.as_str()).collect(); let mut ids: Vec = ids.iter().filter(|id| !id.as_str().is_some_and(|id| named.contains(id))).cloned().collect(); if named.is_empty() { return Ok(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) { let Some(at) = place(read, ask, ids.len(), &|at| ids[at].clone(), id)? else { return Ok(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) -> Result, MethodError> { let mut ask = Value::Object(ids_only(ask)); ask["limit"] = json!(cotton_tools::mcp::handlers::tables::MAX_LIGHT_PAGE); let mut ids = Vec::new(); let mut page = 0u64; loop { ask["page"] = json!(page); let mut 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(_) => return Err(MethodError::new("unreadable", "a kept order's page did not advance")), None => return Ok(ids), } } }