glacier-web 0.1.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>,
}

/// `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;
}

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()
}

/// 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);
}

/// 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())
}