use std::future::Future;
use crate::session::Session;
#[derive(Clone)]
pub(crate) struct Scope {
pub(crate) session: Session,
pub(crate) path: String,
pub(crate) base_url: String,
pub(crate) query: Option<String>,
pub(crate) key: std::sync::Arc<cookie::Key>,
pub(crate) assigns: std::sync::Arc<std::sync::Mutex<Assigns>>,
pub(crate) deferred: std::sync::Arc<std::sync::Mutex<Vec<Deferred>>>,
}
type Assigns = std::collections::HashMap<String, std::sync::Arc<dyn std::any::Any + Send + Sync>>;
pub(crate) fn base_url_of(parts: &http::request::Parts) -> String {
let header = |name| parts.headers.get(name).and_then(|v| v.to_str().ok());
let scheme = header("x-forwarded-proto")
.or_else(|| parts.uri.scheme_str())
.unwrap_or("http");
let host = header("host")
.or_else(|| parts.uri.authority().map(|a| a.as_str()))
.unwrap_or("localhost");
format!("{scheme}://{host}")
}
tokio::task_local! {
static CURRENT: Scope;
static ID: String;
}
pub fn id() -> Option<String> {
ID.try_with(Clone::clone).ok()
}
pub(crate) fn with_id<F: Future>(id: String, fut: F) -> impl Future<Output = F::Output> {
ID.scope(id, fut)
}
pub(crate) fn id_from(header: Option<&str>) -> String {
match header {
Some(id)
if !id.is_empty()
&& id.len() <= 200
&& id
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) =>
{
id.to_owned()
}
_ => crate::random::token(),
}
}
pub(crate) fn scope<F: Future>(scope: Scope, fut: F) -> impl Future<Output = F::Output> {
CURRENT.scope(scope, fut)
}
fn with<R>(f: impl FnOnce(&Scope) -> R) -> Option<R> {
CURRENT.try_with(f).ok()
}
pub(crate) fn signing_key() -> std::sync::Arc<cookie::Key> {
static FALLBACK: std::sync::OnceLock<std::sync::Arc<cookie::Key>> = std::sync::OnceLock::new();
with(|s| s.key.clone())
.or_else(|| INSTALLED.read().unwrap_or_else(|e| e.into_inner()).clone())
.unwrap_or_else(|| {
FALLBACK
.get_or_init(|| std::sync::Arc::new(cookie::Key::generate()))
.clone()
})
}
static INSTALLED: std::sync::RwLock<Option<std::sync::Arc<cookie::Key>>> =
std::sync::RwLock::new(None);
pub(crate) fn install_key(key: &cookie::Key) {
*INSTALLED.write().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(key.clone()));
}
static PREVIOUS: std::sync::RwLock<Vec<cookie::Key>> = std::sync::RwLock::new(Vec::new());
pub(crate) fn install_previous_keys(keys: Vec<cookie::Key>) {
*PREVIOUS.write().unwrap_or_else(|e| e.into_inner()) = keys;
}
pub(crate) fn previous_keys() -> Vec<cookie::Key> {
PREVIOUS.read().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn active() -> bool {
with(|_| ()).is_some()
}
pub fn session() -> Session {
with(|s| s.session.clone()).expect(
"glacier::request::session() called outside a request; \
use ctx.session() or pass the data in explicitly",
)
}
pub fn path() -> Option<String> {
with(|s| s.path.clone())
}
pub fn base_url() -> Option<String> {
with(|s| s.base_url.clone())
}
pub fn url() -> Option<String> {
with(|s| format!("{}{}", s.base_url, s.path))
}
pub fn query() -> Option<String> {
with(|s| s.query.clone()).flatten()
}
pub fn flash(kind: &str) -> Option<String> {
with(|s| s.session.flash(kind)).flatten()
}
pub fn put_flash(kind: &str, message: impl Into<String>) {
session().put_flash(kind, message);
}
pub fn assign<T: Clone + Send + Sync + 'static>(name: &str, value: T) {
with(|s| {
s.assigns
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(name.to_owned(), std::sync::Arc::new(value));
});
}
pub(crate) type Deferred =
std::pin::Pin<Box<dyn std::future::Future<Output = crate::Result<()>> + Send + 'static>>;
pub fn after_response(work: impl std::future::Future<Output = crate::Result<()>> + Send + 'static) {
let work: Deferred = Box::pin(work);
let rest = with(|s| {
s.deferred
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(work);
});
if rest.is_none() {
tracing::warn!(target: "glacier", "after_response outside a request: nothing to wait for");
}
}
pub(crate) fn take_deferred() -> Vec<Deferred> {
with(|s| std::mem::take(&mut *s.deferred.lock().unwrap_or_else(|e| e.into_inner())))
.unwrap_or_default()
}
pub(crate) fn memo_get<T: Clone + 'static>(key: &str) -> Option<T> {
with(|s| {
s.assigns
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&format!("\0memo:{key}"))
.and_then(|value| value.downcast_ref::<T>().cloned())
})
.flatten()
}
pub(crate) fn memo_set<T: Send + Sync + 'static>(key: &str, value: T) {
with(|s| {
s.assigns
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(format!("\0memo:{key}"), std::sync::Arc::new(value));
});
}
pub fn assigned<T: Clone + 'static>(name: &str) -> Option<T> {
with(|s| {
s.assigns
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(name)
.and_then(|value| {
let typed = value.downcast_ref::<T>().cloned();
if typed.is_none() {
tracing::warn!(
"`{name}` was assigned a value of another type than {}; the layout shows its default",
std::any::type_name::<T>()
);
}
typed
})
})
.flatten()
}
pub fn csrf_token() -> String {
crate::csrf::token_for(&session())
}