glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! The query cache, as Rails': within one request, a model query run again
//! with the same SQL and values is answered from memory instead of the
//! database. Any write in the request (an insert, an update, a delete, raw
//! SQL that isn't a `SELECT`) and the end of any transaction empty it, so
//! a read after a write always sees it.
//!
//! Only reads made through models and queries are kept, never raw
//! [`db::sql`](super::sql) or a locking read (`FOR UPDATE`), and at most
//! the latest [`MAX_ENTRIES`] of them. Outside a request (a job, a script)
//! nothing is cached. [`uncached`] turns it off for some work.

use std::collections::VecDeque;
use std::future::Future;
use std::sync::{Arc, Mutex};

use super::Row;

/// The most queries a request keeps, as Rails 7.1's default.
pub const MAX_ENTRIES: usize = 100;

/// A query's rows, shared between the cache and its readers.
pub(crate) type Rows = Arc<[Row]>;

#[derive(Default)]
struct Cache {
    entries: VecDeque<(String, Rows)>,
}

tokio::task_local! {
    static CACHE: Arc<Mutex<Cache>>;
    static UNCACHED: bool;
}

fn with_cache<T>(f: impl FnOnce(&mut Cache) -> T) -> Option<T> {
    CACHE
        .try_with(|cache| f(&mut cache.lock().unwrap_or_else(|e| e.into_inner())))
        .ok()
}

fn enabled() -> bool {
    !UNCACHED.try_with(|off| *off).unwrap_or(false)
}

/// Runs `fut` with an empty cache of its own: each request does.
pub(crate) async fn scope<F: Future>(fut: F) -> F::Output {
    CACHE.scope(Arc::default(), fut).await
}

/// Runs `fut` without the query cache: its reads go to the database even
/// if the request made them before, and aren't kept. Writes inside still
/// empty the request's cache.
pub async fn uncached<F: Future>(fut: F) -> F::Output {
    UNCACHED.scope(true, fut).await
}

/// The rows kept for `key`, if any.
pub(crate) fn get(key: &str) -> Option<Rows> {
    if !enabled() {
        return None;
    }
    with_cache(|cache| {
        let at = cache.entries.iter().position(|(k, _)| k == key)?;
        // Most recently used last, so the oldest goes first.
        let entry = cache.entries.remove(at)?;
        let rows = entry.1.clone();
        cache.entries.push_back(entry);
        Some(rows)
    })
    .flatten()
}

/// Keeps `rows` for `key`, in a request.
pub(crate) fn put(key: String, rows: Rows) {
    if !enabled() {
        return;
    }
    with_cache(|cache| {
        cache.entries.retain(|(k, _)| *k != key);
        if cache.entries.len() == MAX_ENTRIES {
            cache.entries.pop_front();
        }
        cache.entries.push_back((key, rows));
    });
}

/// Whether this work keeps its reads: in a request, and not `uncached`.
pub(crate) fn active() -> bool {
    enabled() && CACHE.try_with(|_| ()).is_ok()
}

/// Empties the request's cache: after a write, or a transaction's end.
pub(crate) fn clear() {
    with_cache(|cache| cache.entries.clear());
}

/// How many queries the request has kept, for tests.
#[cfg(test)]
fn len() -> usize {
    with_cache(|cache| cache.entries.len()).unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rows() -> Rows {
        Arc::from(Vec::new())
    }

    #[tokio::test]
    async fn keeps_reads_in_a_request_only() {
        put("a".into(), rows());
        assert!(get("a").is_none(), "outside a request");
        scope(async {
            put("a".into(), rows());
            assert!(get("a").is_some());
            clear();
            assert!(get("a").is_none());
        })
        .await;
    }

    #[tokio::test]
    async fn uncached_work_neither_reads_nor_keeps() {
        scope(async {
            put("a".into(), rows());
            uncached(async {
                assert!(!active());
                assert!(get("a").is_none());
                put("b".into(), rows());
                clear();
            })
            .await;
            assert!(get("b").is_none());
            assert!(get("a").is_none(), "a write inside still empties it");
        })
        .await;
    }

    #[tokio::test]
    async fn drops_the_least_recently_used_beyond_the_limit() {
        scope(async {
            for i in 0..MAX_ENTRIES {
                put(i.to_string(), rows());
            }
            assert!(get("0").is_some(), "0 is now the most recent");
            put("new".into(), rows());
            assert_eq!(len(), MAX_ENTRIES);
            assert!(get("1").is_none(), "the oldest went");
            assert!(get("0").is_some());
            assert!(get("new").is_some());
        })
        .await;
    }
}