//! A KEPT ANSWER: what `shell.list` and `shell.deck` answered, kept beside//! the count the file stood at when the ask began, and asked again it is//! answered from here without touching the store while nothing it reads has//! moved. What it reads is said by what it leaves aside: the store tables//! of every drawn table neither its own definition nor theirs names//! (`aside`), and the change log every write names beside its own table.//! A move naming only those leaves the answer standing; any other//! move — its own table's, a table it names, a definition, a move naming no//! table — reads it again. The minute is in the key: an answer that says//! anything of the clock is never older than a minute.usecrate::shell::client::ClientController;use cotton_core::definitions::TableDefinition;use serde_json::Value;use std::collections::{HashMap, HashSet};use std::sync::{Arc, Mutex, OnceLock};/// How many answers are kept before every one is let go.const MOST: usize = 64;/// Where an ask began: the file's bus and how often it had moved on.pub(crate) typeAt = (u64, u64);structKept { bus: u64, at: u64, aside: Arc<HashSet<String>>, answer: Arc<Value>,}static KEPT: OnceLock<Mutex<HashMap<String, Kept>>> = OnceLock::new();fn kept() -> &'staticMutex<HashMap<String, Kept>> { KEPT.get_or_init(Default::default)}/// The ask's key: its method, every word it says, the reader's zone and/// minute, under the bus it is read on.fn key(client: &ClientController, method: &str, request: &Value) -> String {let minute = client.clock().now().timestamp().div_euclid(60); format!("{}:{method}:{minute}:{}:{request}", client.moved().0, client.time_zone().unwrap_or_default())}#[cfg(test)]thread_local! {/// A bench's ask as it was read before answers were kept.static UNKEPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}/// `body` with no answer kept or taken on this thread: the read as it was.#[cfg(test)]pub(crate) fn unkept<T>(body: implFnOnce() -> T) -> T { UNKEPT.with(|unkept| unkept.set(true));let answer = body(); UNKEPT.with(|unkept| unkept.set(false)); answer}fn kept_here() -> bool { #[cfg(test)] { !UNKEPT.with(std::cell::Cell::get) && kept_anywhere() } #[cfg(not(test))] { true }}#[cfg(test)]thread_local! {/// A test's ask read fresh: nothing kept is taken or kept, by any read.static FRESH: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}/// `body` read as a fresh whole read on this thread: no kept answer, cut,/// frame or order taken or kept, and nothing another test keeps let go.#[cfg(test)]pub(crate) fn fresh<T>(body: implFnOnce() -> T) -> T { FRESH.with(|fresh| fresh.set(true));let answer = body(); FRESH.with(|fresh| fresh.set(false)); answer}/// Whether any read on this thread takes or keeps what it read (not inside/// a test's `fresh`).pub(crate) fn kept_anywhere() -> bool { #[cfg(test)] { !FRESH.with(std::cell::Cell::get) } #[cfg(not(test))] { true }}/// The kept answer to this ask, while nothing it reads has moved.pub(crate) fn answer(client: &ClientController, method: &str, request: &Value) -> Option<Arc<Value>> {if !kept_here() { returnNone; }let key = key(client, method, request);let kept = kept().lock().ok()?;let bus = client.bus(); kept.get(&key).filter(|found| bus.stands((found.bus, found.at), &found.aside)).map(|found| Arc::clone(&found.answer))}/// Keeps `answer`, read from `at` on, leaving `aside` aside.pub(crate) fn keep(client: &ClientController, method: &str, request: &Value, at: At, aside: HashSet<String>, answer: &Value) {if at.0 != client.moved().0 || !kept_here() { return; }let key = key(client, method, request);letOk(mut kept) = kept().lock() else { return };letmut spent = Vec::new();let bus = client.bus();// This file's answers that something they read has moved past are// spent; past the cap, so are another file's, and then every one. kept.retain(|_, held| {let stands = held.bus != at.0 || bus.stands((held.bus, held.at), &held.aside);if !stands { spent.push(Arc::clone(&held.answer)); } stands });if kept.len() >= MOST { kept.retain(|_, held| { let ours = held.bus == at.0; if !ours { spent.push(Arc::clone(&held.answer)); } ours }); }if kept.len() >= MOST { spent.extend(kept.drain().map(|(_, held)| held.answer)); } kept.insert(key, Kept { bus: at.0, at: at.1, aside: Arc::new(aside), answer: Arc::new(answer.clone()) }); drop(kept);if !spent.is_empty() { super::shell_list::let_go(spent); }}/// Every answer kept, forgotten: a bench's first ask.#[cfg(test)]pub(crate) fn forget() {ifletOk(mut kept) = kept().lock() { kept.clear(); }}/// The store tables a definition's rows live in.pub(crate) fn stores(definition: &TableDefinition) -> Vec<String> {ifletSome(table) = definition.store_table() { return vec![table.to_string()]; } definition.physical_tables().unwrap_or_default().into_iter().map(|table| table.name).collect()}/// What a read of `reads` leaves aside: the store tables of every drawn/// table (one with a face, neither polled nor live) that `reads` does not/// name and that does not name `reads`, and whose store no table it names/// shares. A table with no store it can name is never aside. A definition/// names a table by a string value that is its id or holds one of its/// stores, never by an object key: a section's `"note"` names no notes.pub(crate) fn aside(tables: &[TableDefinition], reads: &TableDefinition) -> HashSet<String> {let own = said(reads);let own_stores = stores(reads);let names = |said: &[String], id: &str, stores: &[String]| said.iter().any(|text| text == id || stores.iter().any(|store| text.contains(store.as_str())));letmut touching: HashSet<String> = own_stores.iter().cloned().collect();letmut drawn: Vec<Vec<String>> = Vec::new();for other in tables.iter().filter(|other| other.id != reads.id) {let their_stores = stores(other);let leaves = other.has_face() && other.polled != Some(true) && other.live_read.is_none() && !their_stores.is_empty();if !leaves || names(&own, &other.id, &their_stores) || names(&said(other), &reads.id, &own_stores) { touching.extend(their_stores); } else { drawn.push(their_stores); } }letmut aside: HashSet<String> = drawn.into_iter().flatten().filter(|store| !touching.contains(store)).collect();// Every write names the change log beside its own table: a row's byline// is its own change, which moves with its own table, so the log alone// moves nothing a read of another table says.let changes = cotton_tools::mcp::handlers::tables::CHANGES;if !touching.contains(changes) && !own.iter().any(|text| text.contains(changes)) { aside.insert(changes.to_string()); }// The voice vocabulary is the voice pass's own cache of names// (`voice_words`), stored by no table's definition: the pass's move of it// every half minute a name changes moves nothing a list says.if !touching.contains(VOICE_VOCABULARY) && !own.iter().any(|text| text.contains(VOICE_VOCABULARY)) { aside.insert(VOICE_VOCABULARY.to_string()); } aside}/// The voice pass's store of the words it biases speech by.pub(crate) const VOICE_VOCABULARY: &str = "cotton_voice_vocabulary";/// Every string value a definition says, at any depth; keys are not said.fn said(definition: &TableDefinition) -> Vec<String> {fn walk(value: Value, into: &mutVec<String>) {match value {Value::String(text) => into.push(text),Value::Array(items) => items.into_iter().for_each(|item| walk(item, into)),Value::Object(fields) => fields.into_iter().for_each(|(_, item)| walk(item, into)), _ => {} } }letmut into = Vec::new(); walk(serde_json::to_value(definition).unwrap_or_default(), &mut into); into}