glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Values for the rest of a request, as Rails' `Current`: set one in
//! middleware or an action, and read it wherever the request's work runs,
//! templates and layouts included, without passing it down.
//!
//! ```ignore
//! // In an authentication middleware:
//! glacier::current::set(user.clone());
//! // In a layout, a helper or a model method:
//! let user = glacier::current::get::<User>();
//! ```
//!
//! One value per type, as with app state: wrap a value in a type of the
//! app's own to keep two of the same kind. Each request starts empty, and
//! nothing outlives it.

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

tokio::task_local! {
    static STORE: Arc<Mutex<http::Extensions>>;
}

/// Keeps `value` for the rest of this request, replacing any earlier
/// value of its type. `false` outside a request (or `with_current`).
pub fn set<T: Clone + Send + Sync + 'static>(value: T) -> bool {
    STORE
        .try_with(|store| {
            store
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .insert(value);
        })
        .is_ok()
}

/// The value of type `T` set earlier in this request, if any.
pub fn get<T: Clone + Send + Sync + 'static>() -> Option<T> {
    STORE
        .try_with(|store| {
            store
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .get::<T>()
                .cloned()
        })
        .ok()
        .flatten()
}

/// Runs `fut` with an empty store of its own: each request does; so can a
/// job or a test that wants one.
pub async fn with_current<F: Future>(fut: F) -> F::Output {
    STORE.scope(Arc::default(), fut).await
}

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

    #[derive(Clone, Debug, PartialEq)]
    struct Shop(&'static str);

    #[tokio::test]
    async fn values_last_for_their_scope() {
        assert!(!set(Shop("none")), "no store outside a request");
        let seen = with_current(async {
            assert_eq!(get::<Shop>(), None);
            set(Shop("Glacier"));
            get::<Shop>()
        })
        .await;
        assert_eq!(seen, Some(Shop("Glacier")));
        assert_eq!(get::<Shop>(), None);
    }
}