glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Who a piece of work acts for: a signed-in user, an organisation, or
//! the system itself. Glacier's name for what Phoenix calls a scope.
//!
//! This is the seam 0.4's accounts build on: requests will set the access
//! from the signed-in user, and queries will be limited to what it may
//! see. For now it records who work is done for, and work that runs for
//! nobody in particular (webhooks, pruning, recurring jobs) says so
//! explicitly, with a reason:
//!
//! ```ignore
//! glacier::access::unscoped("nightly digest", async {
//!     // …
//! })
//! .await
//! ```

use std::future::Future;
use std::sync::Arc;

/// Who work is done for.
pub trait Access: Send + Sync + 'static {
    /// For logs and traces: `user:12`, `org:3`, `system (webhooks)`.
    fn describe(&self) -> String;
}

/// Work done for nobody in particular, with why.
#[derive(Debug, Clone, Copy)]
pub struct SystemAccess {
    pub reason: &'static str,
}

impl Access for SystemAccess {
    fn describe(&self) -> String {
        format!("system ({})", self.reason)
    }
}

tokio::task_local! {
    static CURRENT: Arc<dyn Access>;
}

/// The access the current work runs with, if any.
pub fn current() -> Option<Arc<dyn Access>> {
    CURRENT.try_with(Arc::clone).ok()
}

/// Runs `fut` for `access`.
pub async fn with_access<F: Future>(access: impl Access, fut: F) -> F::Output {
    CURRENT.scope(Arc::new(access), fut).await
}

/// Runs `fut` for the system, saying why: what webhooks, pruning and
/// recurring jobs run as. In 0.4 it's the explicit way past the limits a
/// user's access puts on queries.
pub async fn unscoped<F: Future>(reason: &'static str, fut: F) -> F::Output {
    with_access(SystemAccess { reason }, fut).await
}

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

    #[tokio::test]
    async fn work_knows_who_it_is_for() {
        assert!(current().is_none());
        let seen = unscoped("pruning", async { current().map(|a| a.describe()) }).await;
        assert_eq!(seen.as_deref(), Some("system (pruning)"));
    }
}