1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//! 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);
}
}