apalis-rtui 0.1.0-rc.1

A drop-in replacement for apalis-board: HTTP surface, live updates, and the apalis-tui dashboard
Documentation
//! The ported `apalis-board-api` surface: framework-agnostic handler functions, the
//! `framework` module (`ApiBuilder`/`RegisterRoute` plus per-framework route wiring), the
//! `sse` module (`events` feature), and the `ui` module (`ui` feature).
//!
//! Only ever compiled when a host framework feature (`axum` or `actix`) is active, and only ever
//! reached through the [`crate::axum`] / [`crate::actix`] re-exports: it is private on purpose,
//! the same way upstream's `apalis-board-api` crate is reachable only through `apalis-board`'s
//! own `axum`/`actix` feature.

use std::{str::FromStr, sync::Arc};

use apalis_core::{
    backend::{
        Backend, BackendExt, FetchById, Filter, ListAllTasks, ListQueues, ListTasks, ListWorkers,
        Metrics, QueueInfo, RunningWorker, Statistic, TaskSink, codec::Codec,
    },
    task::{Task, builder::TaskBuilder, task_id::TaskId},
};
use apalis_rtui_types::ApiError;
use serde::{Serialize, de::DeserializeOwned};
use tokio::sync::RwLock;

/// Framework-agnostic action functions backing the action routes (`docs/PLAN.md` §4.2).
pub mod actions;
/// The optional-action capability builders (`RegisterReschedule`, `RegisterResume`, ...) and
/// [`Capabilities`](apalis_rtui_types::Capabilities) plumbing (`docs/PLAN.md` §3.6, §4.3).
pub mod capability;
/// Contains different web framework routes.
pub mod framework;
/// Expose Server-Sent Events (SSE) functionality.
#[cfg(feature = "events")]
pub mod sse;
/// Expose UI components and functionality.
#[cfg(feature = "ui")]
pub mod ui;

/// Move a wire-supplied [`Filter`] onto page 1 when it asks for page 0.
///
/// `apalis_core::backend::Filter::offset` computes `(page - 1) * page_size` over `u32`, so
/// `?page=0` subtracts with overflow: a panicked request handler on a debug build, a wrapped
/// `u32::MAX` offset handed to SQL on a release one. `serde`'s `default = "default_page"` only
/// fills a *missing* `page` key, so a `page=0` that is present in the query string reaches the
/// backend as written. Every other malformed value (`page=abc`, `page=-1`, an out-of-range
/// number) is already rejected by the query extractor with a 400 before any handler runs. This
/// is the one value that parses and still cannot be served, and the two list handlers below are
/// the only layer positioned to catch it (`docs/PLAN.md` §7).
fn first_page_floor(mut filter: Filter) -> Filter {
    filter.page = filter.page.max(1);
    filter
}

/// Push a new task to the specified queue.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend's push fails.
pub async fn push_task<Args, B, Compact>(
    task: Args,
    storage: Arc<RwLock<B>>,
) -> Result<(), ApiError>
where
    Args: Serialize + DeserializeOwned + 'static,
    B: TaskSink<Args> + Send + BackendExt,
    B::Error: std::error::Error,
    B::Codec: Codec<Args, Compact = Compact>,
    <<B as BackendExt>::Codec as Codec<Args>>::Error: std::error::Error,
{
    let task = TaskBuilder::new(task).build();
    storage
        .write()
        .await
        .push_task(task)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Get statistics for a specific queue.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend's query fails.
pub async fn stats_by_queue<S>(storage: Arc<RwLock<S>>) -> Result<Vec<Statistic>, ApiError>
where
    S::Error: std::error::Error,
    S: Metrics + BackendExt,
{
    storage
        .read()
        .await
        .fetch_by_queue()
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Get a list of tasks from the specified queue with filtering options.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend's query fails.
pub async fn get_tasks<S, T, Compact>(
    storage: Arc<RwLock<S>>,
    filter: Filter,
) -> Result<Vec<Task<T, S::Context, S::IdType>>, ApiError>
where
    T: Serialize + DeserializeOwned + 'static,
    S: ListTasks<T> + Send + BackendExt,
    S::Context: Serialize,
    S::IdType: Serialize,
    <S as Backend>::Error: std::error::Error,
    S::Codec: Codec<T, Compact = Compact>,
{
    let filter = first_page_floor(filter);
    let storage = storage.read().await;
    storage
        .list_tasks(&filter)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Get workers for a specific queue.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend's query fails.
pub async fn get_workers<S>(storage: Arc<RwLock<S>>) -> Result<Vec<RunningWorker>, ApiError>
where
    S: ListWorkers + BackendExt,
    S::Error: std::error::Error,
{
    let storage = storage.read().await;
    storage
        .list_workers()
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Get a task by its ID.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when `task_id` does not parse as `B::IdType` or the
/// backend's query fails.
pub async fn get_task_by_id<B, T>(
    task_id: String,
    storage: Arc<RwLock<B>>,
) -> Result<Option<Task<T, B::Context, B::IdType>>, ApiError>
where
    T: Serialize + DeserializeOwned + 'static,
    B: FetchById<T> + 'static,
    B::Context: Serialize,
    B::IdType: Serialize,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <<B as Backend>::IdType as FromStr>::Err: std::error::Error,
{
    let task_id = TaskId::<B::IdType>::from_str(&task_id)
        .map_err(|e| ApiError::BackendError(e.to_string()))?;

    storage
        .write()
        .await
        .fetch_by_id(&task_id)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Get all tasks across all queues.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend's query fails.
pub async fn get_all_tasks<S>(
    storage: Arc<RwLock<S>>,
    filter: Filter,
) -> Result<Vec<Task<S::Compact, S::Context, S::IdType>>, ApiError>
where
    S: ListAllTasks + Send,
    S::Context: Serialize,
    S::IdType: Serialize,
    S::Compact: Serialize,
    <S as Backend>::Error: std::error::Error,
    <<S as BackendExt>::Codec as Codec<<S as Backend>::Args>>::Error: std::error::Error,
{
    let filter = first_page_floor(filter);
    storage
        .read()
        .await
        .list_all_tasks(&filter)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Get all workers across all queues.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend's query fails.
pub async fn get_all_workers<S>(storage: Arc<RwLock<S>>) -> Result<Vec<RunningWorker>, ApiError>
where
    S: ListWorkers,
    S::Error: std::error::Error,
{
    storage
        .read()
        .await
        .list_all_workers()
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Fetch all queues.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend's query fails.
pub async fn fetch_queues<S>(storage: Arc<RwLock<S>>) -> Result<Vec<QueueInfo>, ApiError>
where
    S::Error: std::error::Error,
    S: ListQueues,
{
    storage
        .read()
        .await
        .list_queues()
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Get an overview of statistics.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend's query fails.
pub async fn overview<S>(storage: Arc<RwLock<S>>) -> Result<Vec<Statistic>, ApiError>
where
    S::Error: std::error::Error,
    S: Metrics,
{
    storage
        .read()
        .await
        .global()
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}