Cotton code
48 lines · 2.1 KB · RustRaw
//! What a Post read computes over the whole mailbox (every sender's tallies, the facts of senders, the senders list),//! kept while the copy is unchanged: keyed by the store's own change stamp (`Driver::change_stamp`, which moves with//! any write on this connection and any commit elsewhere), so a screen opened again over the same mail answers at//! once and a new mail is counted the moment it lands. Only data is kept here, never words that age ("just now").//!//! At his size (110,000 mails) these took 0.2 to 0.6 s each on every open (25 Nov 2026).use std::any::Any;use std::collections::HashMap;use std::sync::{Arc, Mutex, OnceLock};use super::super::*;type Stamp = (String, usize, u64, i64, i64);fn kept_map() -> &'static Mutex<HashMap<String, (Stamp, Arc<dyn Any + Send + Sync>)>> {    static KEPT: OnceLock<Mutex<HashMap<String, (Stamp, Arc<dyn Any + Send + Sync>)>>> = OnceLock::new();    KEPT.get_or_init(|| Mutex::new(HashMap::new()))}fn stamp(ctx: &mut Ctx<'_>) -> Option<Stamp> {    let (conn, changes, version, schema) = ctx.db().change_stamp().ok()?;    Some((ctx.workspace_id.to_string(), conn, changes, version, schema))}/// `make`'s answer for `key`, kept while the copy is unchanged.pub(super) fn kept<T: Clone + Send + Sync + 'static>(ctx: &mut Ctx<'_>, key: &str, make: impl FnOnce(&mut Ctx<'_>) -> Result<T, String>) -> Result<T, String> {    let Some(now) = stamp(ctx) else { return make(ctx) };    // Reads lease a connection from a pool, and a stamp is one connection's: each keeps its own.    let key = format!("{key}@{}", now.1);    if let Some((at, value)) = kept_map().lock().ok().and_then(|m| m.get(&key).cloned()) {        if at == now {            if let Some(value) = value.downcast_ref::<T>() {                return Ok(value.clone());            }        }    }    let value = make(ctx)?;    // What `make` read is what the stamp before it described: a write meanwhile moves the stamp, and the next read    // makes it again.    if let Ok(mut map) = kept_map().lock() {        if map.len() > 256 {            map.clear();        }        map.insert(key, (now, Arc::new(value.clone())));    }    Ok(value)}