Skip to main content

saola_kit/context/
router.rs

1use std::future::Future;
2use std::sync::{Arc, Mutex, OnceLock};
3
4use laravel::head::Head;
5use laravel::http::{IntoMiddleware, Method, Middleware, Next, Request, Response};
6use laravel::routing::{Handler, Route, Router};
7
8use super::hosts::ContextError;
9use super::perm::{PermScope, RoutePerm};
10use super::{ContextRegistry, ContextSpec, RouteEntry, RouteIndex, set_current_context};
11
12/// Lazily builds and caches a [`RouteIndex`] from a shared [`ContextRegistry`]
13/// once deferred route closures have run.
14#[derive(Debug, Clone)]
15pub struct SharedRouteIndex {
16    registry: Arc<Mutex<ContextRegistry>>,
17    primary_url: String,
18    built: Arc<OnceLock<Arc<RouteIndex>>>,
19}
20
21impl SharedRouteIndex {
22    pub fn new(registry: Arc<Mutex<ContextRegistry>>, primary_url: impl Into<String>) -> Self {
23        Self {
24            registry,
25            primary_url: primary_url.into(),
26            built: Arc::new(OnceLock::new()),
27        }
28    }
29
30    /// Snapshot of the permission matrix collected while routes were registered. Pass it to
31    /// `saola_permission::RouteAccess::new` (call after the app booted: routes register lazily).
32    #[cfg(feature = "permission")]
33    pub fn permissions(&self) -> saola_permission::RoutePermissionRegistry {
34        self.registry
35            .lock()
36            .unwrap_or_else(std::sync::PoisonError::into_inner)
37            .permissions()
38            .clone()
39    }
40
41    pub fn index(&self) -> Result<Arc<RouteIndex>, ContextError> {
42        if let Some(index) = self.built.get() {
43            return Ok(Arc::clone(index));
44        }
45
46        let guard = self
47            .registry
48            .lock()
49            .unwrap_or_else(std::sync::PoisonError::into_inner);
50        let built = Arc::new(guard.build_index(&self.primary_url)?);
51        let _ = self.built.set(Arc::clone(&built));
52        Ok(Arc::clone(self.built.get().unwrap_or(&built)))
53    }
54}
55
56/// Middleware recording the active Saola context slug for the incoming request.
57#[derive(Debug, Clone)]
58pub struct SetCurrentContext {
59    slug: Arc<str>,
60}
61
62impl SetCurrentContext {
63    pub fn new(slug: impl AsRef<str>) -> Self {
64        Self {
65            slug: Arc::from(slug.as_ref()),
66        }
67    }
68
69    pub fn slug(&self) -> &str {
70        &self.slug
71    }
72}
73
74impl Middleware for SetCurrentContext {
75    fn handle(
76        &self,
77        request: Request,
78        next: Next,
79    ) -> impl Future<Output = laravel::Result<Response>> + Send {
80        let slug = Arc::clone(&self.slug);
81        async move {
82            set_current_context(&slug);
83            Ok(next.run(request).await)
84        }
85    }
86}
87
88/// Normalizes and joins a base URI prefix with a child segment.
89pub fn join_uri(base: &str, segment: &str) -> String {
90    let base_trimmed = base.trim().trim_end_matches('/');
91    let seg_trimmed = segment.trim().trim_matches('/');
92
93    match (base_trimmed, seg_trimmed) {
94        ("", "") => "/".to_owned(),
95        ("", seg) => format!("/{seg}"),
96        (b, "") => {
97            if b.starts_with('/') {
98                b.to_owned()
99            } else {
100                format!("/{b}")
101            }
102        }
103        (b, seg) => {
104            let normalized_base = if b.starts_with('/') {
105                b.to_owned()
106            } else {
107                format!("/{b}")
108            };
109            format!("{normalized_base}/{seg}")
110        }
111    }
112}
113
114/// Strips a leading `/api` prefix when mounting onto Laravel's `.api(...)` group,
115/// which already prepends `/api` automatically.
116#[cfg(any(feature = "module", test))]
117pub(crate) fn strip_api_prefix(prefix: &str) -> String {
118    let trimmed = prefix.trim().trim_matches('/');
119    if trimmed.is_empty() || trimmed == "api" {
120        String::new()
121    } else if let Some(rest) = trimmed.strip_prefix("api/") {
122        rest.to_owned()
123    } else {
124        trimmed.to_owned()
125    }
126}
127
128/// Context-aware router wrapper passed to `SaolaModule::routes(&self, ctx: &mut ContextRoutes<'_>)`.
129///
130/// Modules register routes once inside a context: `ContextRoutes` handles module URL prefixing,
131/// route name prefixing (`{context}.{module}.{name}`), middleware groups, and automatic
132/// registration into [`ContextRegistry`] for `RouteIndex` / `href()`.
133pub struct ContextRoutes<'a> {
134    router: &'a mut Router,
135    spec: ContextSpec,
136    uri_prefix: String,
137    name_prefix: String,
138    registry: Arc<Mutex<ContextRegistry>>,
139    perm: PermScope,
140}
141
142impl<'a> ContextRoutes<'a> {
143    pub fn new(
144        router: &'a mut Router,
145        spec: ContextSpec,
146        uri_prefix: impl Into<String>,
147        registry: Arc<Mutex<ContextRegistry>>,
148    ) -> Self {
149        let name_prefix = spec.as_prefix.trim_matches('.').to_owned();
150        Self {
151            router,
152            spec,
153            uri_prefix: join_uri("", &uri_prefix.into()),
154            name_prefix,
155            registry,
156            perm: PermScope::default(),
157        }
158    }
159
160    pub fn slug(&self) -> &str {
161        &self.spec.slug
162    }
163
164    pub fn spec(&self) -> &ContextSpec {
165        &self.spec
166    }
167
168    pub fn is(&self, slug: &str) -> bool {
169        self.spec.slug == slug
170    }
171
172    pub fn uri_prefix(&self) -> &str {
173        &self.uri_prefix
174    }
175
176    pub fn name_prefix(&self) -> &str {
177        &self.name_prefix
178    }
179
180    /// Direct escape hatch to the underlying Laravel [`Router`].
181    pub fn router(&mut self) -> &mut Router {
182        self.router
183    }
184
185    /// Records a route that was mounted on the raw router (e.g. by `saola_admin::resource::mount_routes`)
186    /// so `href()` and the client route index know it: `{context}.{module}.{name}` -> `uri` under the current prefix.
187    pub fn declare(&mut self, name: &str, uri: &str) {
188        let clean = name.trim_matches('.');
189        let full_name = if self.name_prefix.is_empty() { clean.to_owned() } else { format!("{}.{clean}", self.name_prefix) };
190        let mut guard = self.registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
191        if guard.routes().iter().any(|entry| entry.full_name == full_name) { return; }
192        let mut entry = RouteEntry::new(full_name, join_uri(&self.uri_prefix, uri)).with_context(&self.spec.slug);
193        if !self.spec.hosts.is_empty() {
194            entry = entry.with_hosts(self.spec.hosts.iter().map(String::as_str));
195        }
196        guard.add_route(entry);
197    }
198
199    /// Scopes routes under a module slug (appended to route names) and URL `prefix`.
200    pub fn module(
201        &mut self,
202        slug: &str,
203        prefix: &str,
204        routes: impl FnOnce(&mut ContextRoutes<'_>),
205    ) {
206        let perm = self.perm.module(slug.trim_matches('.'));
207        self.module_scoped(slug, prefix, perm, routes);
208    }
209
210    /// Like [`Self::module`], declaring the operations required on the module itself
211    /// (`->permission(...)` on a module in PHP). Routes inherit them; only `Access` reaches nested modules.
212    #[cfg(feature = "permission")]
213    pub fn module_with(
214        &mut self,
215        slug: &str,
216        prefix: &str,
217        permissions: &[saola_permission::Operation],
218        routes: impl FnOnce(&mut ContextRoutes<'_>),
219    ) {
220        let perm = self.perm.module_with(slug.trim_matches('.'), permissions);
221        self.module_scoped(slug, prefix, perm, routes);
222    }
223
224    /// Operations required by every route registered inside `routes` (a permission group, no
225    /// URL or name change), e.g. `ctx.require(&[Operation::Access], |ctx| { .. })`.
226    #[cfg(feature = "permission")]
227    pub fn require(
228        &mut self,
229        permissions: &[saola_permission::Operation],
230        routes: impl FnOnce(&mut ContextRoutes<'_>),
231    ) {
232        let mut child = ContextRoutes {
233            router: &mut *self.router,
234            spec: self.spec.clone(),
235            uri_prefix: self.uri_prefix.clone(),
236            name_prefix: self.name_prefix.clone(),
237            registry: Arc::clone(&self.registry),
238            perm: self.perm.group(permissions),
239        };
240        routes(&mut child);
241    }
242
243    /// From here on (this scope and its children), routes carrying permission requirements get a
244    /// `RequirePermission<U>` middleware. Without it the declarations are only recorded.
245    #[cfg(feature = "permission")]
246    pub fn enforce_with<U: laravel::auth::Authenticatable + saola_permission::PermissionSubject>(&mut self) {
247        self.perm.enforce_with::<U>();
248    }
249
250    fn module_scoped(
251        &mut self,
252        slug: &str,
253        prefix: &str,
254        perm: PermScope,
255        routes: impl FnOnce(&mut ContextRoutes<'_>),
256    ) {
257        let next_uri = join_uri(&self.uri_prefix, prefix);
258        let slug_clean = slug.trim_matches('.');
259        let next_name = match (self.name_prefix.is_empty(), slug_clean.is_empty()) {
260            (_, true) => self.name_prefix.clone(),
261            (true, false) => slug_clean.to_owned(),
262            (false, false) => format!("{}.{slug_clean}", self.name_prefix),
263        };
264        let spec = self.spec.clone();
265        let registry = Arc::clone(&self.registry);
266
267        let clean_prefix = prefix.trim().trim_matches('/');
268        if clean_prefix.is_empty() {
269            let mut child = ContextRoutes {
270                router: self.router,
271                spec,
272                uri_prefix: next_uri,
273                name_prefix: next_name,
274                registry,
275                perm,
276            };
277            routes(&mut child);
278        } else {
279            self.router.prefix(&format!("/{clean_prefix}")).group(move |r| {
280                let mut child = ContextRoutes {
281                    router: r,
282                    spec,
283                    uri_prefix: next_uri,
284                    name_prefix: next_name,
285                    registry,
286                    perm,
287                };
288                routes(&mut child);
289            });
290        }
291    }
292
293    /// Applies middleware to a nested group while preserving the context/module prefix and name scope.
294    pub fn group(
295        &mut self,
296        middleware: impl IntoMiddleware,
297        routes: impl FnOnce(&mut ContextRoutes<'_>),
298    ) {
299        let spec = self.spec.clone();
300        let uri_prefix = self.uri_prefix.clone();
301        let name_prefix = self.name_prefix.clone();
302        let registry = Arc::clone(&self.registry);
303        let perm = self.perm.clone();
304
305        self.router.middleware(middleware).group(move |r| {
306            let mut child = ContextRoutes {
307                router: r,
308                spec,
309                uri_prefix,
310                name_prefix,
311                registry,
312                perm,
313            };
314            routes(&mut child);
315        });
316    }
317
318    #[track_caller]
319    pub fn on<H, T>(&mut self, methods: &[Method], uri: &str, handler: H) -> ContextRoute<'_>
320    where
321        H: Handler<T>,
322        T: 'static,
323    {
324        let full_uri = join_uri(&self.uri_prefix, uri);
325        let name_prefix = self.name_prefix.clone();
326        let context_slug = self.spec.slug.clone();
327        let hosts = self.spec.hosts.clone();
328        let registry = Arc::clone(&self.registry);
329        let route = self.router.on(methods, uri, handler);
330        let perm = RoutePerm::new(
331            &self.perm,
332            &context_slug,
333            methods.iter().map(|m| m.as_str().to_owned()).collect(),
334            route,
335        );
336        ContextRoute {
337            route,
338            full_uri,
339            name_prefix,
340            context_slug,
341            hosts,
342            registry,
343            perm,
344        }
345    }
346
347    #[track_caller]
348    pub fn get<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
349    where
350        H: Handler<T>,
351        T: 'static,
352    {
353        self.on(&[Method::GET], uri, handler)
354    }
355
356    #[track_caller]
357    pub fn post<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
358    where
359        H: Handler<T>,
360        T: 'static,
361    {
362        self.on(&[Method::POST], uri, handler)
363    }
364
365    #[track_caller]
366    pub fn put<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
367    where
368        H: Handler<T>,
369        T: 'static,
370    {
371        self.on(&[Method::PUT], uri, handler)
372    }
373
374    #[track_caller]
375    pub fn patch<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
376    where
377        H: Handler<T>,
378        T: 'static,
379    {
380        self.on(&[Method::PATCH], uri, handler)
381    }
382
383    #[track_caller]
384    pub fn delete<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
385    where
386        H: Handler<T>,
387        T: 'static,
388    {
389        self.on(&[Method::DELETE], uri, handler)
390    }
391
392    #[track_caller]
393    pub fn any<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
394    where
395        H: Handler<T>,
396        T: 'static,
397    {
398        let full_uri = join_uri(&self.uri_prefix, uri);
399        let name_prefix = self.name_prefix.clone();
400        let context_slug = self.spec.slug.clone();
401        let hosts = self.spec.hosts.clone();
402        let registry = Arc::clone(&self.registry);
403        let route = self.router.any(uri, handler);
404        let perm = RoutePerm::new(&self.perm, &context_slug, vec!["ANY".to_owned()], route);
405        ContextRoute {
406            route,
407            full_uri,
408            name_prefix,
409            context_slug,
410            hosts,
411            registry,
412            perm,
413        }
414    }
415}
416
417/// Handle returned after registering a route on [`ContextRoutes`], supporting fluent chaining.
418pub struct ContextRoute<'a> {
419    route: &'a mut Route,
420    full_uri: String,
421    name_prefix: String,
422    context_slug: String,
423    hosts: Vec<String>,
424    registry: Arc<Mutex<ContextRegistry>>,
425    perm: RoutePerm,
426}
427
428impl<'a> ContextRoute<'a> {
429    /// Names the route relative to the active context and module (e.g. `index` -> `api.chat.index`),
430    /// recording its [`RouteEntry`] into [`ContextRegistry`].
431    pub fn name(self, short_name: &str) -> Self {
432        let clean = short_name.trim_matches('.');
433        let full_name = if self.name_prefix.is_empty() {
434            clean.to_owned()
435        } else if clean.is_empty() {
436            self.name_prefix.clone()
437        } else {
438            format!("{}.{clean}", self.name_prefix)
439        };
440
441        let mut guard = self
442            .registry
443            .lock()
444            .unwrap_or_else(std::sync::PoisonError::into_inner);
445        let exists = guard
446            .routes()
447            .iter()
448            .any(|entry| entry.full_name == full_name);
449        if !exists {
450            let mut entry = RouteEntry::new(full_name.clone(), &self.full_uri).with_context(&self.context_slug);
451            if !self.hosts.is_empty() {
452                entry = entry.with_hosts(self.hosts.iter().map(String::as_str));
453            }
454            guard.add_route(entry);
455            self.perm.record(&mut guard, &full_name);
456        }
457        drop(guard);
458
459        self
460    }
461
462    /// Operations required on this route, on top of those inherited from its module and groups.
463    /// Call it before [`Self::name`]: the permission matrix row is recorded when the route is named.
464    #[cfg(feature = "permission")]
465    pub fn permission(mut self, operations: &[saola_permission::Operation]) -> Self {
466        self.perm.add(self.route, operations);
467        self
468    }
469
470    pub fn middleware(self, middleware: impl IntoMiddleware) -> Self {
471        self.route.middleware(middleware);
472        self
473    }
474
475    pub fn without_middleware<M: 'static>(self) -> Self {
476        self.route.without_middleware::<M>();
477        self
478    }
479
480    pub fn with_head(self, head: Head) -> Self {
481        self.route.with_head(head);
482        self
483    }
484
485    pub fn scope_bindings(self) -> Self {
486        self.route.scope_bindings();
487        self
488    }
489
490    pub fn without_scoped_bindings(self) -> Self {
491        self.route.without_scoped_bindings();
492        self
493    }
494
495    pub fn route(&mut self) -> &mut Route {
496        self.route
497    }
498}