saola-kit 0.1.0

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
use std::future::Future;
use std::sync::{Arc, Mutex, OnceLock};

use laravel::head::Head;
use laravel::http::{IntoMiddleware, Method, Middleware, Next, Request, Response};
use laravel::routing::{Handler, Route, Router};

use super::hosts::ContextError;
use super::{ContextRegistry, ContextSpec, RouteEntry, RouteIndex, set_current_context};

/// Lazily builds and caches a [`RouteIndex`] from a shared [`ContextRegistry`]
/// once deferred route closures have run.
#[derive(Debug, Clone)]
pub struct SharedRouteIndex {
    registry: Arc<Mutex<ContextRegistry>>,
    primary_url: String,
    built: Arc<OnceLock<Arc<RouteIndex>>>,
}

impl SharedRouteIndex {
    pub fn new(registry: Arc<Mutex<ContextRegistry>>, primary_url: impl Into<String>) -> Self {
        Self {
            registry,
            primary_url: primary_url.into(),
            built: Arc::new(OnceLock::new()),
        }
    }

    pub fn index(&self) -> Result<Arc<RouteIndex>, ContextError> {
        if let Some(index) = self.built.get() {
            return Ok(Arc::clone(index));
        }

        let guard = self
            .registry
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let built = Arc::new(guard.build_index(&self.primary_url)?);
        let _ = self.built.set(Arc::clone(&built));
        Ok(Arc::clone(self.built.get().unwrap_or(&built)))
    }
}

/// Middleware recording the active Saola context slug for the incoming request.
#[derive(Debug, Clone)]
pub struct SetCurrentContext {
    slug: Arc<str>,
}

impl SetCurrentContext {
    pub fn new(slug: impl AsRef<str>) -> Self {
        Self {
            slug: Arc::from(slug.as_ref()),
        }
    }

    pub fn slug(&self) -> &str {
        &self.slug
    }
}

impl Middleware for SetCurrentContext {
    fn handle(
        &self,
        request: Request,
        next: Next,
    ) -> impl Future<Output = laravel::Result<Response>> + Send {
        let slug = Arc::clone(&self.slug);
        async move {
            set_current_context(&slug);
            Ok(next.run(request).await)
        }
    }
}

/// Normalizes and joins a base URI prefix with a child segment.
pub fn join_uri(base: &str, segment: &str) -> String {
    let base_trimmed = base.trim().trim_end_matches('/');
    let seg_trimmed = segment.trim().trim_matches('/');

    match (base_trimmed, seg_trimmed) {
        ("", "") => "/".to_owned(),
        ("", seg) => format!("/{seg}"),
        (b, "") => {
            if b.starts_with('/') {
                b.to_owned()
            } else {
                format!("/{b}")
            }
        }
        (b, seg) => {
            let normalized_base = if b.starts_with('/') {
                b.to_owned()
            } else {
                format!("/{b}")
            };
            format!("{normalized_base}/{seg}")
        }
    }
}

/// Strips a leading `/api` prefix when mounting onto Laravel's `.api(...)` group,
/// which already prepends `/api` automatically.
#[cfg(any(feature = "module", test))]
pub(crate) fn strip_api_prefix(prefix: &str) -> String {
    let trimmed = prefix.trim().trim_matches('/');
    if trimmed.is_empty() || trimmed == "api" {
        String::new()
    } else if let Some(rest) = trimmed.strip_prefix("api/") {
        rest.to_owned()
    } else {
        trimmed.to_owned()
    }
}

/// Context-aware router wrapper passed to `SaolaModule::routes(&self, ctx: &mut ContextRoutes<'_>)`.
///
/// Modules register routes once inside a context: `ContextRoutes` handles module URL prefixing,
/// route name prefixing (`{context}.{module}.{name}`), middleware groups, and automatic
/// registration into [`ContextRegistry`] for `RouteIndex` / `href()`.
pub struct ContextRoutes<'a> {
    router: &'a mut Router,
    spec: ContextSpec,
    uri_prefix: String,
    name_prefix: String,
    registry: Arc<Mutex<ContextRegistry>>,
}

impl<'a> ContextRoutes<'a> {
    pub fn new(
        router: &'a mut Router,
        spec: ContextSpec,
        uri_prefix: impl Into<String>,
        registry: Arc<Mutex<ContextRegistry>>,
    ) -> Self {
        let name_prefix = spec.as_prefix.trim_matches('.').to_owned();
        Self {
            router,
            spec,
            uri_prefix: join_uri("", &uri_prefix.into()),
            name_prefix,
            registry,
        }
    }

    pub fn slug(&self) -> &str {
        &self.spec.slug
    }

    pub fn spec(&self) -> &ContextSpec {
        &self.spec
    }

    pub fn is(&self, slug: &str) -> bool {
        self.spec.slug == slug
    }

    pub fn uri_prefix(&self) -> &str {
        &self.uri_prefix
    }

    pub fn name_prefix(&self) -> &str {
        &self.name_prefix
    }

    /// Direct escape hatch to the underlying Laravel [`Router`].
    pub fn router(&mut self) -> &mut Router {
        self.router
    }

    /// Scopes routes under a module slug (appended to route names) and URL `prefix`.
    pub fn module(
        &mut self,
        slug: &str,
        prefix: &str,
        routes: impl FnOnce(&mut ContextRoutes<'_>),
    ) {
        let next_uri = join_uri(&self.uri_prefix, prefix);
        let slug_clean = slug.trim_matches('.');
        let next_name = match (self.name_prefix.is_empty(), slug_clean.is_empty()) {
            (_, true) => self.name_prefix.clone(),
            (true, false) => slug_clean.to_owned(),
            (false, false) => format!("{}.{slug_clean}", self.name_prefix),
        };
        let spec = self.spec.clone();
        let registry = Arc::clone(&self.registry);

        let clean_prefix = prefix.trim().trim_matches('/');
        if clean_prefix.is_empty() {
            let mut child = ContextRoutes {
                router: self.router,
                spec,
                uri_prefix: next_uri,
                name_prefix: next_name,
                registry,
            };
            routes(&mut child);
        } else {
            self.router.prefix(&format!("/{clean_prefix}")).group(move |r| {
                let mut child = ContextRoutes {
                    router: r,
                    spec,
                    uri_prefix: next_uri,
                    name_prefix: next_name,
                    registry,
                };
                routes(&mut child);
            });
        }
    }

    /// Applies middleware to a nested group while preserving the context/module prefix and name scope.
    pub fn group(
        &mut self,
        middleware: impl IntoMiddleware,
        routes: impl FnOnce(&mut ContextRoutes<'_>),
    ) {
        let spec = self.spec.clone();
        let uri_prefix = self.uri_prefix.clone();
        let name_prefix = self.name_prefix.clone();
        let registry = Arc::clone(&self.registry);

        self.router.middleware(middleware).group(move |r| {
            let mut child = ContextRoutes {
                router: r,
                spec,
                uri_prefix,
                name_prefix,
                registry,
            };
            routes(&mut child);
        });
    }

    #[track_caller]
    pub fn on<H, T>(&mut self, methods: &[Method], uri: &str, handler: H) -> ContextRoute<'_>
    where
        H: Handler<T>,
        T: 'static,
    {
        let full_uri = join_uri(&self.uri_prefix, uri);
        let name_prefix = self.name_prefix.clone();
        let context_slug = self.spec.slug.clone();
        let hosts = self.spec.hosts.clone();
        let registry = Arc::clone(&self.registry);
        let route = self.router.on(methods, uri, handler);
        ContextRoute {
            route,
            full_uri,
            name_prefix,
            context_slug,
            hosts,
            registry,
        }
    }

    #[track_caller]
    pub fn get<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
    where
        H: Handler<T>,
        T: 'static,
    {
        self.on(&[Method::GET], uri, handler)
    }

    #[track_caller]
    pub fn post<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
    where
        H: Handler<T>,
        T: 'static,
    {
        self.on(&[Method::POST], uri, handler)
    }

    #[track_caller]
    pub fn put<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
    where
        H: Handler<T>,
        T: 'static,
    {
        self.on(&[Method::PUT], uri, handler)
    }

    #[track_caller]
    pub fn patch<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
    where
        H: Handler<T>,
        T: 'static,
    {
        self.on(&[Method::PATCH], uri, handler)
    }

    #[track_caller]
    pub fn delete<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
    where
        H: Handler<T>,
        T: 'static,
    {
        self.on(&[Method::DELETE], uri, handler)
    }

    #[track_caller]
    pub fn any<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
    where
        H: Handler<T>,
        T: 'static,
    {
        let full_uri = join_uri(&self.uri_prefix, uri);
        let name_prefix = self.name_prefix.clone();
        let context_slug = self.spec.slug.clone();
        let hosts = self.spec.hosts.clone();
        let registry = Arc::clone(&self.registry);
        let route = self.router.any(uri, handler);
        ContextRoute {
            route,
            full_uri,
            name_prefix,
            context_slug,
            hosts,
            registry,
        }
    }
}

/// Handle returned after registering a route on [`ContextRoutes`], supporting fluent chaining.
pub struct ContextRoute<'a> {
    route: &'a mut Route,
    full_uri: String,
    name_prefix: String,
    context_slug: String,
    hosts: Vec<String>,
    registry: Arc<Mutex<ContextRegistry>>,
}

impl<'a> ContextRoute<'a> {
    /// Names the route relative to the active context and module (e.g. `index` -> `api.chat.index`),
    /// recording its [`RouteEntry`] into [`ContextRegistry`].
    pub fn name(self, short_name: &str) -> Self {
        let clean = short_name.trim_matches('.');
        let full_name = if self.name_prefix.is_empty() {
            clean.to_owned()
        } else if clean.is_empty() {
            self.name_prefix.clone()
        } else {
            format!("{}.{clean}", self.name_prefix)
        };

        let mut guard = self
            .registry
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let exists = guard
            .routes()
            .iter()
            .any(|entry| entry.full_name == full_name);
        if !exists {
            let mut entry = RouteEntry::new(full_name, &self.full_uri).with_context(&self.context_slug);
            if !self.hosts.is_empty() {
                entry = entry.with_hosts(self.hosts.iter().map(String::as_str));
            }
            guard.add_route(entry);
        }
        drop(guard);

        self
    }

    pub fn middleware(self, middleware: impl IntoMiddleware) -> Self {
        self.route.middleware(middleware);
        self
    }

    pub fn without_middleware<M: 'static>(self) -> Self {
        self.route.without_middleware::<M>();
        self
    }

    pub fn with_head(self, head: Head) -> Self {
        self.route.with_head(head);
        self
    }

    pub fn scope_bindings(self) -> Self {
        self.route.scope_bindings();
        self
    }

    pub fn without_scoped_bindings(self) -> Self {
        self.route.without_scoped_bindings();
        self
    }

    pub fn route(&mut self) -> &mut Route {
        self.route
    }
}