glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! The cache: fetch, expiry, keys from records, one computation per
//! key, flexible freshness, and the database store.

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use glacier::cache;
use glacier::db::migration::Migration;
use glacier::db::{self, Repo};
use glacier::prelude::*;
use glacier::testing::travel;

#[glacier::test]
async fn fetch_computes_once_until_it_expires() {
    let computed = AtomicUsize::new(0);
    let compute = || async {
        computed.fetch_add(1, Ordering::SeqCst);
        Ok::<_, glacier::Error>(vec![1, 2, 3])
    };
    assert_eq!(
        cache::fetch("numbers", chrono::TimeDelta::minutes(10), compute)
            .await
            .unwrap(),
        [1, 2, 3]
    );
    assert_eq!(
        cache::fetch("numbers", chrono::TimeDelta::minutes(10), compute)
            .await
            .unwrap(),
        [1, 2, 3]
    );
    assert_eq!(computed.load(Ordering::SeqCst), 1);
    travel(chrono::TimeDelta::minutes(11));
    cache::fetch("numbers", chrono::TimeDelta::minutes(10), compute)
        .await
        .unwrap();
    assert_eq!(computed.load(Ordering::SeqCst), 2, "expired");

    // Errors aren't cached.
    let failed: glacier::Result<i32> =
        cache::fetch("broken", chrono::TimeDelta::minutes(1), || async {
            Err(Error::internal("no"))
        })
        .await;
    assert!(failed.is_err());
    assert_eq!(cache::read::<i32>("broken").await.unwrap(), None);

    cache::write("greeting", "hello", chrono::TimeDelta::minutes(1))
        .await
        .unwrap();
    assert_eq!(
        cache::read::<String>("greeting").await.unwrap().as_deref(),
        Some("hello")
    );
    cache::delete("greeting").await.unwrap();
    assert_eq!(cache::read::<String>("greeting").await.unwrap(), None);
}

#[glacier::test]
async fn each_test_has_its_own_cache() {
    // `fetch_computes_once…` cached `numbers`; this test doesn't see it.
    assert_eq!(cache::read::<Vec<i32>>("numbers").await.unwrap(), None);
}

#[glacier::test]
async fn callers_missing_together_compute_once() {
    let computed = Arc::new(AtomicUsize::new(0));
    let calls = (0..8).map(|_| {
        let computed = computed.clone();
        async move {
            cache::fetch("slow", chrono::TimeDelta::minutes(1), || async {
                computed.fetch_add(1, Ordering::SeqCst);
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                Ok::<_, glacier::Error>(42)
            })
            .await
            .unwrap()
        }
    });
    let values = futures_util::future::join_all(calls).await;
    assert!(values.iter().all(|v| *v == 42));
    assert_eq!(computed.load(Ordering::SeqCst), 1);
}

#[glacier::test]
async fn flexible_serves_stale_while_refreshing() {
    let version = AtomicUsize::new(0);
    let compute = || async { Ok::<_, glacier::Error>(version.fetch_add(1, Ordering::SeqCst)) };
    let fresh = chrono::TimeDelta::minutes(1);
    let stale = chrono::TimeDelta::minutes(5);
    assert_eq!(
        cache::fetch_flexible("v", fresh, stale, compute)
            .await
            .unwrap(),
        0
    );
    travel(chrono::TimeDelta::seconds(30));
    assert_eq!(
        cache::fetch_flexible("v", fresh, stale, compute)
            .await
            .unwrap(),
        0,
        "fresh"
    );
    travel(chrono::TimeDelta::minutes(2));
    // Stale: this caller refreshes (and gets the new value).
    assert_eq!(
        cache::fetch_flexible("v", fresh, stale, compute)
            .await
            .unwrap(),
        1
    );
    travel(chrono::TimeDelta::minutes(10));
    assert_eq!(
        cache::fetch_flexible("v", fresh, stale, compute)
            .await
            .unwrap(),
        2,
        "too old"
    );
}

#[glacier::model(timestamps = true)]
pub struct Card {
    title: String,
}

#[test]
fn keys_change_when_records_are_saved() {
    let mut card = Card {
        id: 7,
        title: "A".into(),
        ..Default::default()
    };
    card.updated_at = "2026-10-05T01:02:03Z".parse().unwrap();
    let first = cache::key(&card, "html");
    assert!(first.starts_with("cards/7-"), "{first}");
    assert!(first.ends_with("/html"), "{first}");
    card.updated_at = "2026-10-05T01:02:04Z".parse().unwrap();
    assert_ne!(cache::key(&card, "html"), first);
}

#[tokio::test]
async fn the_database_store_is_shared() {
    let repo = Repo::connect("sqlite::memory:").await.unwrap();
    db::sandbox(&repo, async {
        for statement in Migration::new("m1", cache::create_table, |_| {}).up_sql(repo.dialect()) {
            db::sql(&statement).execute().await.unwrap();
        }
        let config =
            glacier::Config::from_toml(glacier::Env::Test, "[cache]\nstore = \"database\"\n")
                .unwrap();
        let _app = App::new().config(config).unwrap();
        cache::write("shared", &5, chrono::TimeDelta::minutes(1))
            .await
            .unwrap();
        let rows = db::sql("SELECT value FROM glacier_cache WHERE key = 'shared'")
            .fetch_all()
            .await
            .unwrap();
        assert_eq!(rows[0].get::<String>("value").unwrap(), "5");
        assert_eq!(cache::read::<i32>("shared").await.unwrap(), Some(5));
        let past = glacier::time::now() - chrono::TimeDelta::minutes(1);
        db::sql("UPDATE glacier_cache SET expires_at = ?")
            .bind(past)
            .execute()
            .await
            .unwrap();
        assert_eq!(cache::prune().await.unwrap(), 1);

        let minute = chrono::TimeDelta::minutes(1);
        for key in ["report:1", "report:2", "Report:3", "report_x", "other"] {
            cache::write(key, &1, minute).await.unwrap();
        }
        // Exactly the prefix: not `Report:` (SQLite's LIKE would match it)
        // or `report_` (a LIKE pattern's `_`).
        assert_eq!(cache::delete_prefix("report:").await.unwrap(), 2);
        assert_eq!(cache::read::<i32>("report:1").await.unwrap(), None);
        assert_eq!(cache::read::<i32>("Report:3").await.unwrap(), Some(1));
        assert_eq!(cache::read::<i32>("report_x").await.unwrap(), Some(1));
        assert_eq!(cache::clear().await.unwrap(), 3);
        assert_eq!(cache::read::<i32>("other").await.unwrap(), None);
    })
    .await
    .unwrap();
}

#[glacier::test]
async fn pull_reads_once_and_prefixes_delete_together() {
    let minute = chrono::TimeDelta::minutes(1);
    cache::write("token", &"abc", minute).await.unwrap();
    assert_eq!(
        cache::pull::<String>("token").await.unwrap(),
        Some("abc".to_owned())
    );
    assert_eq!(cache::pull::<String>("token").await.unwrap(), None);
    for key in ["stats:1", "stats:2", "page:1"] {
        cache::write(key, &1, minute).await.unwrap();
    }
    assert_eq!(cache::delete_prefix("stats:").await.unwrap(), 2);
    assert_eq!(cache::read::<i32>("page:1").await.unwrap(), Some(1));
    assert_eq!(cache::clear().await.unwrap(), 1);
}

#[glacier::test]
async fn counters_count_and_expire() {
    assert_eq!(
        cache::increment("views", 1, chrono::TimeDelta::minutes(1))
            .await
            .unwrap(),
        1
    );
    assert_eq!(
        cache::increment("views", 2, chrono::TimeDelta::minutes(1))
            .await
            .unwrap(),
        3
    );
    assert_eq!(
        cache::decrement("views", 1, chrono::TimeDelta::minutes(1))
            .await
            .unwrap(),
        2
    );
    assert_eq!(cache::read::<i64>("views").await.unwrap(), Some(2));
    // A counter keeps its first expiry; once it passes, counting restarts.
    travel(chrono::TimeDelta::seconds(61));
    assert_eq!(
        cache::increment("views", 1, chrono::TimeDelta::minutes(1))
            .await
            .unwrap(),
        1
    );
}

#[tokio::test]
async fn database_counters_are_one_statement() {
    let mut urls = vec!["sqlite::memory:".to_owned()];
    if let Ok(url) = std::env::var("GLACIER_TEST_POSTGRES_URL") {
        urls.push(url);
    }
    for url in urls {
        let repo = Repo::connect(&url).await.unwrap();
        db::sandbox(&repo, async {
            for statement in
                Migration::new("m1", cache::create_table, |_| {}).up_sql(repo.dialect())
            {
                db::sql(&statement).execute().await.unwrap();
            }
            let config =
                glacier::Config::from_toml(glacier::Env::Test, "[cache]\nstore = \"database\"\n")
                    .unwrap();
            let _app = App::new().config(config).unwrap();
            let minute = chrono::TimeDelta::minutes(1);
            assert_eq!(cache::increment("hits", 1, minute).await.unwrap(), 1);
            assert_eq!(cache::increment("hits", 4, minute).await.unwrap(), 5);
            assert_eq!(cache::read::<i64>("hits").await.unwrap(), Some(5));
            assert!(RateLimit::attempt("api:ada", 1, minute).await.unwrap());
            assert!(!RateLimit::attempt("api:ada", 1, minute).await.unwrap());
            // An expired counter starts again.
            let past = glacier::time::now() - minute;
            db::sql("UPDATE glacier_cache SET expires_at = ? WHERE key = 'hits'")
                .bind(past)
                .execute()
                .await
                .unwrap();
            assert_eq!(cache::increment("hits", 1, minute).await.unwrap(), 1);
        })
        .await
        .unwrap();
    }
}

#[tokio::test]
async fn database_locks_and_adds() {
    let mut urls = vec!["sqlite::memory:".to_owned()];
    if let Ok(url) = std::env::var("GLACIER_TEST_POSTGRES_URL") {
        urls.push(url);
    }
    for url in urls {
        let repo = Repo::connect(&url).await.unwrap();
        db::sandbox(&repo, async {
            for statement in
                Migration::new("m1", cache::create_table, |_| {}).up_sql(repo.dialect())
            {
                db::sql(&statement).execute().await.unwrap();
            }
            let config =
                glacier::Config::from_toml(glacier::Env::Test, "[cache]\nstore = \"database\"\n")
                    .unwrap();
            let _app = App::new().config(config).unwrap();
            let minute = chrono::TimeDelta::minutes(1);
            assert!(cache::add("once", &1, minute).await.unwrap());
            assert!(!cache::add("once", &2, minute).await.unwrap());
            assert_eq!(cache::read::<i32>("once").await.unwrap(), Some(1));
            cache::delete_if("once", &2).await.unwrap();
            assert_eq!(
                cache::read::<i32>("once").await.unwrap(),
                Some(1),
                "not its value"
            );
            cache::delete_if("once", &1).await.unwrap();
            assert!(cache::add("once", &3, minute).await.unwrap());

            let value = Lock::new("db-lock")
                .run(async {
                    let other = Lock::new("db-lock").run(async { Ok(()) }).await;
                    assert_eq!(other.unwrap_err().status(), StatusCode::CONFLICT);
                    Ok(5)
                })
                .await
                .unwrap();
            assert_eq!(value, 5);
            assert!(!Lock::held("db-lock").await.unwrap());
        })
        .await
        .unwrap();
    }
}

#[tokio::test]
async fn memo_computes_once_a_request() {
    static COMPUTED: AtomicUsize = AtomicUsize::new(0);
    async fn total() -> glacier::Result<usize> {
        cache::memo("total", || async {
            Ok::<_, glacier::Error>(COMPUTED.fetch_add(1, Ordering::SeqCst) + 1)
        })
        .await
    }
    let client = glacier::testing::TestClient::new(App::new().routes(|r| {
        r.get("/", |_ctx: Context| async {
            let (first, second) = (total().await?, total().await?);
            Ok::<_, Error>(Response::text(format!("{first} {second}")))
        });
    }));
    let body = |res: Response| String::from_utf8(res.body().to_vec()).unwrap();
    assert_eq!(body(client.get("/").await), "1 1");
    // The next request computes it again.
    assert_eq!(body(client.get("/").await), "2 2");
    // Outside a request, every time.
    assert_eq!(total().await.unwrap(), 3);
    assert_eq!(total().await.unwrap(), 4);
}