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::perm::{PermScope, RoutePerm};
use super::{ContextRegistry, ContextSpec, RouteEntry, RouteIndex, set_current_context};
#[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()),
}
}
#[cfg(feature = "permission")]
pub fn permissions(&self) -> saola_permission::RoutePermissionRegistry {
self.registry
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.permissions()
.clone()
}
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)))
}
}
#[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)
}
}
}
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}")
}
}
}
#[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()
}
}
pub struct ContextRoutes<'a> {
router: &'a mut Router,
spec: ContextSpec,
uri_prefix: String,
name_prefix: String,
registry: Arc<Mutex<ContextRegistry>>,
perm: PermScope,
}
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,
perm: PermScope::default(),
}
}
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
}
pub fn router(&mut self) -> &mut Router {
self.router
}
pub fn declare(&mut self, name: &str, uri: &str) {
let clean = name.trim_matches('.');
let full_name = if self.name_prefix.is_empty() { clean.to_owned() } else { format!("{}.{clean}", self.name_prefix) };
let mut guard = self.registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if guard.routes().iter().any(|entry| entry.full_name == full_name) { return; }
let mut entry = RouteEntry::new(full_name, join_uri(&self.uri_prefix, uri)).with_context(&self.spec.slug);
if !self.spec.hosts.is_empty() {
entry = entry.with_hosts(self.spec.hosts.iter().map(String::as_str));
}
guard.add_route(entry);
}
pub fn module(
&mut self,
slug: &str,
prefix: &str,
routes: impl FnOnce(&mut ContextRoutes<'_>),
) {
let perm = self.perm.module(slug.trim_matches('.'));
self.module_scoped(slug, prefix, perm, routes);
}
#[cfg(feature = "permission")]
pub fn module_with(
&mut self,
slug: &str,
prefix: &str,
permissions: &[saola_permission::Operation],
routes: impl FnOnce(&mut ContextRoutes<'_>),
) {
let perm = self.perm.module_with(slug.trim_matches('.'), permissions);
self.module_scoped(slug, prefix, perm, routes);
}
#[cfg(feature = "permission")]
pub fn require(
&mut self,
permissions: &[saola_permission::Operation],
routes: impl FnOnce(&mut ContextRoutes<'_>),
) {
let mut child = ContextRoutes {
router: &mut *self.router,
spec: self.spec.clone(),
uri_prefix: self.uri_prefix.clone(),
name_prefix: self.name_prefix.clone(),
registry: Arc::clone(&self.registry),
perm: self.perm.group(permissions),
};
routes(&mut child);
}
#[cfg(feature = "permission")]
pub fn enforce_with<U: laravel::auth::Authenticatable + saola_permission::PermissionSubject>(&mut self) {
self.perm.enforce_with::<U>();
}
fn module_scoped(
&mut self,
slug: &str,
prefix: &str,
perm: PermScope,
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,
perm,
};
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,
perm,
};
routes(&mut child);
});
}
}
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);
let perm = self.perm.clone();
self.router.middleware(middleware).group(move |r| {
let mut child = ContextRoutes {
router: r,
spec,
uri_prefix,
name_prefix,
registry,
perm,
};
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);
let perm = RoutePerm::new(
&self.perm,
&context_slug,
methods.iter().map(|m| m.as_str().to_owned()).collect(),
route,
);
ContextRoute {
route,
full_uri,
name_prefix,
context_slug,
hosts,
registry,
perm,
}
}
#[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);
let perm = RoutePerm::new(&self.perm, &context_slug, vec!["ANY".to_owned()], route);
ContextRoute {
route,
full_uri,
name_prefix,
context_slug,
hosts,
registry,
perm,
}
}
}
pub struct ContextRoute<'a> {
route: &'a mut Route,
full_uri: String,
name_prefix: String,
context_slug: String,
hosts: Vec<String>,
registry: Arc<Mutex<ContextRegistry>>,
perm: RoutePerm,
}
impl<'a> ContextRoute<'a> {
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.clone(), &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);
self.perm.record(&mut guard, &full_name);
}
drop(guard);
self
}
#[cfg(feature = "permission")]
pub fn permission(mut self, operations: &[saola_permission::Operation]) -> Self {
self.perm.add(self.route, operations);
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
}
}