glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! The current request, available without passing `Context` around.
//!
//! Glacier runs every request inside a task-local scope holding its session
//! and path, so templates and helpers can read the flash or the CSRF token
//! directly. It holds request-scoped *presentation* data only.
//!
//! Task-locals don't cross `tokio::spawn`; code spawned from a handler
//! runs outside the request.

use std::future::Future;

use crate::session::Session;

#[derive(Clone)]
pub(crate) struct Scope {
    pub(crate) session: Session,
    pub(crate) path: String,
    /// `http://host`, as Rails' `request.base_url`.
    pub(crate) base_url: String,
    pub(crate) query: Option<String>,
    /// The app's secret key, for signing (pagination cursors).
    pub(crate) key: std::sync::Arc<cookie::Key>,
    /// Values for the layout, by prop name: [`assign`].
    pub(crate) assigns: std::sync::Arc<std::sync::Mutex<Assigns>>,
    /// `after_response` work.
    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>>;

/// `scheme://host` for a request: `X-Forwarded-Proto` or the URI's scheme
/// (else `http`), and the `Host` header.
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;
}

/// The id of the request this code runs for, as Rails'
/// `request.request_id`: the client's `X-Request-Id` when it sends a
/// sensible one, else one made up, and sent back in `X-Request-Id`. A
/// job queued in a request runs with that request's id, so its logs and
/// traces join up. `None` outside both.
pub fn id() -> Option<String> {
    ID.try_with(Clone::clone).ok()
}

/// Runs `fut` with `id` as the request id.
pub(crate) fn with_id<F: Future>(id: String, fut: F) -> impl Future<Output = F::Output> {
    ID.scope(id, fut)
}

/// The id for a request sending `header`: it, if it's 1 to 200 letters,
/// digits, `-`, `_` or `.`, else a new one.
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()
}

/// The app's secret key inside a request; outside one, a key made once
/// per process (so what it signs still checks within that process).
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()
        })
}

/// The app's key from its `secret_key_base`, for signing outside a request
/// (a job mailing a reset link): what the web process verifies with.
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()));
}

/// Keys from earlier `secret_key_base`s (`previous_secret_key_bases`):
/// what they signed or encrypted is still read, while the current key
/// signs and encrypts anything new.
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()
}

/// Whether code is running inside a request.
pub fn active() -> bool {
    with(|_| ()).is_some()
}

/// The current request's session.
///
/// # Panics
///
/// Outside a request.
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",
    )
}

/// The current request's path, or `None` outside a request.
pub fn path() -> Option<String> {
    with(|s| s.path.clone())
}

/// `scheme://host` for the current request (`http://example.com`), as
/// Rails' `request.base_url`, or `None` outside a request.
pub fn base_url() -> Option<String> {
    with(|s| s.base_url.clone())
}

/// The current request's URL without its query string
/// (`http://example.com/posts`), or `None` outside a request.
pub fn url() -> Option<String> {
    with(|s| format!("{}{}", s.base_url, s.path))
}

/// The current request's query string, if it has one.
pub fn query() -> Option<String> {
    with(|s| s.query.clone()).flatten()
}

/// A flash message set by the previous request. `None` outside a request,
/// so templates using it still render in unit tests.
pub fn flash(kind: &str) -> Option<String> {
    with(|s| s.session.flash(kind)).flatten()
}

/// Sets a flash message for the next request.
///
/// # Panics
///
/// Outside a request.
pub fn put_flash(kind: &str, message: impl Into<String>) {
    session().put_flash(kind, message);
}

/// Gives the layout's `name` prop a value for this request, as Phoenix's
/// `assign` does: a pipeline's middleware or a controller's `before`
/// hook loads what every page shows (the account's custom styles), and
/// any layout with a `name` prop of that type shows it, when the action
/// doesn't set it. Does nothing outside a request.
///
/// ```ignore
/// glacier::request::assign("custom_styles", Some(account.custom_styles));
/// ```
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));
    });
}

/// Work for after the response: `after_response do … end`.
pub(crate) type Deferred =
    std::pin::Pin<Box<dyn std::future::Future<Output = crate::Result<()>> + Send + 'static>>;

/// Runs `work` once the response is sent, as Laravel's `defer`: a slow
/// call the page needn't wait for (`after_response do … end` in
/// `.glacier`). It runs with the app's database; an error is logged.
/// Outside a request it runs now, in the background. In tests it runs
/// before the response returns, so a test sees what it did.
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");
    }
}

/// The work queued for after this request's response.
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()
}

/// A value `cache::memo` kept for this request.
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));
    });
}

/// The value [`assign`]ed to `name` in this request, if it's a `T`.
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()
}

/// The session's CSRF token, created on first use.
///
/// # Panics
///
/// Outside a request: a form rendered without a session could never be
/// submitted successfully, so failing loudly beats rendering a dead form.
pub fn csrf_token() -> String {
    crate::csrf::token_for(&session())
}