apalis-rtui 0.1.0-rc.1

A drop-in replacement for apalis-board: HTTP surface, live updates, and the apalis-tui dashboard
Documentation
/// Exposes Actix framework routes.
#[cfg(feature = "actix")]
pub mod actix;
/// Exposes Axum framework routes.
#[cfg(feature = "axum")]
pub mod axum;

use std::sync::{Arc, Mutex};

use apalis_rtui_types::CapabilityMap;

use crate::api::capability::SharedState;
#[cfg(feature = "events")]
use crate::api::sse::EventRing;

/// The default `max_body_size` (`docs/PLAN.md` §7.9): 1 MiB.
pub const DEFAULT_MAX_BODY_SIZE: usize = 1024 * 1024;

/// Trait for registering routes with a backend
pub trait RegisterRoute<B, T> {
    /// Register routes with the given backend
    #[must_use]
    fn register(self, backend: B) -> Self;
}

/// Builder for API routes
#[derive(Clone, Debug)]
pub struct ApiBuilder<R> {
    router: R,
    #[allow(unused)]
    /// may not be used in some conditional compilation
    root: bool,
    /// Per-queue capabilities and capability-upgrade hooks, shared with the routes already
    /// mounted so a later `.with_*()` call is visible to them (`docs/PLAN.md` §3.6, §4.3).
    pub(crate) state: Arc<Mutex<SharedState>>,
    /// The `task-status` ring buffer behind `/events/status`, `/events/activity`, and the
    /// per-task fallback route (`docs/PLAN.md` §6.2, §6.3). One per `ApiBuilder`, shared across
    /// every `.register()`/`.with_*()` call the same way `state` is, so every queue's events feed
    /// the one process-wide activity series.
    #[cfg(feature = "events")]
    pub(crate) ring: Arc<Mutex<EventRing>>,
    /// Applied to every mutating route registered from this point forward
    /// (`.max_body_size(...)` before `.register()`/`.with_*()` is the intended order,
    /// `docs/PLAN.md` §7.9).
    pub(crate) max_body_size: usize,
    /// Applied to every mutating route registered from this point forward, same ordering note as
    /// [`ApiBuilder::max_body_size`] (`docs/PLAN.md` §7.8).
    pub(crate) require_csrf_token: bool,
}

impl<R> ApiBuilder<R> {
    /// Create a new ApiBuilder with default settings
    ///
    /// # One builder per process, not one per actix worker
    ///
    /// Each `ApiBuilder` owns a fresh capability map, `task_id -> queue` index and `task-status`
    /// ring buffer. `actix_web::HttpServer::new` calls its factory closure once **per worker
    /// thread**, so building the `ApiBuilder` inside that closure gives every worker its own
    /// copy of all three. The capability map is deterministic and agrees across workers, but the
    /// `task_id -> queue` index does not: a `GET /queues/{queue}/tasks/{id}` served by worker 1
    /// never teaches worker 2, so whether a later `task-status` event carries a queue name comes
    /// down to which worker answered. The 60-minute activity series is split the same way, and a
    /// browser holding one `/events/status` connection only ever sees the worker it landed on.
    ///
    /// actix gives the factory no way to hand a prebuilt `Scope` to every worker, since
    /// `actix_web::Scope` is not `Clone`, so a host that needs one shared view runs
    /// `HttpServer::new(...).workers(1)`. Otherwise treat `TaskStatusEvent::queue` as best
    /// effort and the activity series as this worker's share of the traffic, which is what the
    /// TUI already does with a queue name it does not get.
    ///
    /// axum has no equivalent split: its `Router` is built once and shared by every connection.
    pub fn new(router: R) -> Self {
        Self {
            router,
            root: true,
            state: Arc::new(Mutex::new(SharedState::default())),
            #[cfg(feature = "events")]
            ring: EventRing::create(),
            max_body_size: DEFAULT_MAX_BODY_SIZE,
            require_csrf_token: false,
        }
    }
    /// Create a new ApiBuilder with a custom scope
    /// If `register_root` is true, the root routes (/queues, /tasks, /workers, /overview)
    /// will be registered on the provided scope.
    pub fn new_with_router(router: R, register_root: bool) -> Self {
        Self {
            router,
            root: register_root,
            state: Arc::new(Mutex::new(SharedState::default())),
            #[cfg(feature = "events")]
            ring: EventRing::create(),
            max_body_size: DEFAULT_MAX_BODY_SIZE,
            require_csrf_token: false,
        }
    }

    /// Finish the builder and return the router
    pub fn build(self) -> R {
        self.router
    }

    /// The per-queue capability map computed so far: every `.register()`/`.register_shared()`
    /// call's default (all `false`) entry, with each `.with_*()` call's flag flipped
    /// (`docs/PLAN.md` §4.3). This is the same map `GET /capabilities` serves once `.build()`'s
    /// router starts serving requests.
    #[must_use]
    pub fn capabilities(&self) -> CapabilityMap {
        self.state
            .lock()
            .expect("invariant: ApiBuilder's capability state mutex is never held across a panic")
            .capabilities
            .clone()
    }

    /// Cap the request body size every mutating route (`PUT`/`PATCH`/`POST` with a JSON body)
    /// accepts, in bytes. Default 1 MiB. Applies to routes registered from this call forward, so
    /// call this before `.register()`/`.with_*()` (`docs/PLAN.md` §7.9).
    #[must_use]
    pub fn max_body_size(mut self, bytes: usize) -> Self {
        self.max_body_size = bytes;
        self
    }

    /// Require a double-submit-cookie CSRF token on every mutating route: the request must carry
    /// both a `csrf_token` cookie and a matching `x-csrf-token` header. Off by default, since
    /// `apalis-rtui` ships no auth/CORS/session layer of its own to pair it with. Applies to
    /// routes registered from this call forward, so call this before `.register()`/`.with_*()`
    /// (`docs/PLAN.md` §7.8).
    #[must_use]
    pub fn require_csrf_token(mut self, enabled: bool) -> Self {
        self.require_csrf_token = enabled;
        self
    }
}