apalis-rtui 0.1.0-rc.1

A drop-in replacement for apalis-board: HTTP surface, live updates, and the apalis-tui dashboard
Documentation
use include_dir::{Dir, File, include_dir};

/// Embed the built `apalis-tui` web bundle into the lib.
static APP_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/assets/tui-web-dist");

/// The token `ServeUI` substitutes with [`ServeUI`]'s configured API base, and only when
/// serving `index.html`. Every other embedded file is served as opaque bytes.
const API_BASE_TOKEN: &str = "%%APALIS_RTUI_API_BASE%%";

/// The default API base a fresh [`ServeUI`] templates into `index.html`.
const DEFAULT_API_BASE: &str = "/api/v1";

/// A `Content-Security-Policy` header value [`ServeUI`] attaches to every response it serves.
///
/// Off by default: a host opts in with [`ServeUI::csp`]. [`CspPolicy::default`] carries the
/// policy this crate ships with, tuned to the bundle it serves:
///
/// - `default-src 'self'`, `connect-src 'self'`: the bundle loads and talks to its own origin
///   only, so a script injected into a task's arguments cannot reach an outside host.
/// - `'wasm-unsafe-eval'`: same-origin WebAssembly instantiation. Some browsers, Firefox among
///   them, need it even under a strict `script-src`.
/// - `'unsafe-inline'` in `style-src`: `ratzilla` paints with a per-cell inline `style`
///   attribute.
/// - `'unsafe-inline'` in `script-src`: the shipped `index.html` boots the wasm module from an
///   inline `<script type="module">`, which any policy without it blocks, leaving a blank page.
///   `ServeUI` serves a static file, so there is no request-time nonce to hand that script
///   instead. Moving the bootstrap into its own `.js` file would let this come back out.
///   `apalis-tui/tests/e2e` serves the UI under this exact policy and fails on any violation a
///   real browser reports, so what is written here is what a browser accepts.
///
/// `'unsafe-eval'` is never included: nothing the bundle ships calls `eval` or `new Function`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CspPolicy(String);

impl Default for CspPolicy {
    fn default() -> Self {
        Self(
            "default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; \
             connect-src 'self'; style-src 'self' 'unsafe-inline'"
                .to_owned(),
        )
    }
}

impl CspPolicy {
    /// Build a policy from a raw `Content-Security-Policy` header value.
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// The literal header value this policy sends.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A utility to serve the embedded `apalis-tui` web bundle.
#[derive(Clone, Debug)]
pub struct ServeUI {
    /// The API base path templated into `index.html` in place of `%%APALIS_RTUI_API_BASE%%`.
    api_base: String,
    /// The `Content-Security-Policy` header to attach to every response, when set.
    csp: Option<CspPolicy>,
}

impl Default for ServeUI {
    // Spelled `ServeUI` rather than `Self` on purpose: upstream `apalis-board-api` derives
    // `Default` here, and rustdoc prints a derived `default` as `-> ServeUI`. The drop-in gate
    // (`scripts/public-api-diff.sh`) compares those rendered signatures, so the written return
    // type has to match.
    #[allow(clippy::use_self)]
    fn default() -> ServeUI {
        Self::new()
    }
}

impl ServeUI {
    /// Create a new `ServeUI` instance, with API base `/api/v1` and no CSP header.
    #[must_use]
    pub fn new() -> Self {
        Self {
            api_base: DEFAULT_API_BASE.to_owned(),
            csp: None,
        }
    }

    /// Set the API base path a served `index.html` reports to the compiled `apalis-tui` bundle.
    ///
    /// A host that mounts [`crate::api::framework::ApiBuilder`]'s router at a prefix other than
    /// the default `/api/v1` sets the same prefix here, so the bundle discovers it without a
    /// rebuild.
    #[must_use]
    pub fn with_api_base(mut self, base: impl Into<String>) -> Self {
        self.api_base = base.into();
        self
    }

    /// Attach a `Content-Security-Policy` header to every response this `ServeUI` serves.
    ///
    /// No CSP header is sent unless this is called. Use [`CspPolicy::default`] for the policy
    /// this crate ships with, or [`CspPolicy::new`] for a custom value.
    #[must_use]
    pub fn csp(mut self, policy: CspPolicy) -> Self {
        self.csp = Some(policy);
        self
    }

    /// Get an embedded file by URI path.
    #[must_use]
    pub fn get_file(path: &str) -> Option<&File<'static>> {
        let normalized = path.trim_start_matches('/');

        APP_DIST.get_file(normalized).or_else(|| {
            if normalized.is_empty() || !normalized.contains('.') {
                APP_DIST.get_file("index.html")
            } else {
                None
            }
        })
    }

    /// Return a MIME type based on file extension.
    #[must_use]
    pub fn content_type(path: &str) -> &'static str {
        if path.ends_with(".html") {
            "text/html; charset=utf-8"
        } else if path.ends_with(".js") {
            "application/javascript"
        } else if path.ends_with(".css") {
            "text/css"
        } else if path.ends_with(".wasm") {
            "application/wasm"
        } else {
            "application/octet-stream"
        }
    }

    /// Return cache control headers based on file type.
    #[must_use]
    pub fn cache_control(path: &str) -> Option<&'static str> {
        if path.ends_with(".html") {
            // Don't cache HTML files.
            Some("no-cache")
        } else if path.ends_with(".js") || path.ends_with(".css") || path.ends_with(".wasm") {
            // Cache static assets aggressively (1 year).
            Some("public, max-age=31536000, immutable")
        } else {
            None
        }
    }

    /// Render the response body and headers for a request path, falling back to `index.html`
    /// for any path with no exact match in the embedded bundle (the SPA-fallback behavior a
    /// client-side-routed bundle needs). Returns `None` only when the bundle carries no
    /// `index.html` at all to fall back to.
    ///
    /// Every file is served as opaque bytes, except `index.html`, which has this `ServeUI`'s
    /// configured API base templated in wherever `%%APALIS_RTUI_API_BASE%%` appears.
    #[must_use]
    pub(crate) fn render(&self, path: &str) -> Option<Rendered> {
        let file = Self::get_file(path).or_else(|| Self::get_file("index.html"))?;

        let path_str = file.path().to_str().unwrap_or("");
        let content_type = Self::content_type(path_str);
        let cache_control = Self::cache_control(path_str);
        let body = if path_str == "index.html" {
            String::from_utf8_lossy(file.contents())
                .replace(API_BASE_TOKEN, &self.api_base)
                .into_bytes()
        } else {
            file.contents().to_vec()
        };

        Some(Rendered {
            content_type,
            cache_control,
            body,
        })
    }

    /// The `Content-Security-Policy` header value to attach, when [`ServeUI::csp`] was called.
    #[must_use]
    pub(crate) fn csp_header(&self) -> Option<&str> {
        self.csp.as_ref().map(CspPolicy::as_str)
    }
}

/// A rendered embedded-asset response, framework-agnostic.
pub(crate) struct Rendered {
    pub(crate) content_type: &'static str,
    pub(crate) cache_control: Option<&'static str>,
    pub(crate) body: Vec<u8>,
}

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

    #[test]
    fn default_api_base_is_api_v1() {
        assert_eq!(ServeUI::new().api_base, "/api/v1");
        assert_eq!(ServeUI::default().api_base, "/api/v1");
    }

    #[test]
    fn with_api_base_overrides_default() {
        let ui = ServeUI::new().with_api_base("/custom/v2");
        assert_eq!(ui.api_base, "/custom/v2");
    }

    #[test]
    fn index_html_gets_api_base_substituted() {
        let ui = ServeUI::new().with_api_base("/custom/v2");
        let rendered = ui.render("/index.html").expect("index.html is embedded");
        let body = String::from_utf8(rendered.body).expect("index.html is UTF-8");
        assert!(body.contains("data-api-base=\"/custom/v2\""));
        assert!(!body.contains(API_BASE_TOKEN));
    }

    #[test]
    fn unmatched_path_falls_back_to_index_html() {
        let ui = ServeUI::new();
        let rendered = ui
            .render("/tasks/01K7EXAMPLE")
            .expect("falls back to index.html");
        let body = String::from_utf8(rendered.body).expect("index.html is UTF-8");
        assert!(body.contains("<html"));
        assert_eq!(rendered.content_type, "text/html; charset=utf-8");
    }

    #[test]
    fn non_html_asset_is_served_as_opaque_bytes() {
        // The placeholder bundle carries no non-HTML asset yet, so this exercises the
        // extension-based dispatch in `content_type`/`cache_control` directly.
        assert_eq!(
            ServeUI::content_type("pkg/app.js"),
            "application/javascript"
        );
        assert_eq!(ServeUI::content_type("pkg/app.css"), "text/css");
        assert_eq!(ServeUI::content_type("pkg/app_bg.wasm"), "application/wasm");
        assert_eq!(
            ServeUI::content_type("pkg/app.unknown"),
            "application/octet-stream"
        );
    }

    #[test]
    fn cache_control_by_extension() {
        assert_eq!(ServeUI::cache_control("index.html"), Some("no-cache"));
        assert_eq!(
            ServeUI::cache_control("pkg/app.js"),
            Some("public, max-age=31536000, immutable")
        );
        assert_eq!(
            ServeUI::cache_control("pkg/app.wasm"),
            Some("public, max-age=31536000, immutable")
        );
        assert_eq!(ServeUI::cache_control("robots.txt"), None);
    }

    #[test]
    fn no_csp_header_by_default() {
        let ui = ServeUI::new();
        assert_eq!(ui.csp_header(), None);
    }

    #[test]
    fn csp_builder_sets_the_header() {
        let ui = ServeUI::new().csp(CspPolicy::default());
        assert_eq!(
            ui.csp_header(),
            Some(
                "default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; \
                 connect-src 'self'; style-src 'self' 'unsafe-inline'"
            )
        );
    }

    #[test]
    fn custom_csp_policy_is_used_verbatim() {
        let ui = ServeUI::new().csp(CspPolicy::new("default-src 'none'"));
        assert_eq!(ui.csp_header(), Some("default-src 'none'"));
    }

    #[test]
    fn extensionless_path_resolves_get_file_to_index_html() {
        // `get_file`'s own fallback (distinct from `render`'s SPA fallback): an extensionless
        // path resolves straight to `index.html`.
        let file = ServeUI::get_file("/tasks").expect("extensionless path falls back");
        assert_eq!(file.path().to_str(), Some("index.html"));
    }

    #[test]
    fn path_with_unknown_extension_has_no_get_file_match() {
        // `get_file` alone (no SPA fallback) returns `None` for a dotted path that isn't a real
        // embedded file; `render` is what additionally falls back to `index.html`.
        assert!(ServeUI::get_file("/missing.js").is_none());
    }
}