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    /// Scopes routes under a module slug (appended to route names) and URL `prefix`.
186    pub fn module(
187        &mut self,
188        slug: &str,
189        prefix: &str,
190        routes: impl FnOnce(&mut ContextRoutes<'_>),
191    ) {
192        let perm = self.perm.module(slug.trim_matches('.'));
193        self.module_scoped(slug, prefix, perm, routes);
194    }
195
196    /// Like [`Self::module`], declaring the operations required on the module itself
197    /// (`->permission(...)` on a module in PHP). Routes inherit them; only `Access` reaches nested modules.
198    #[cfg(feature = "permission")]
199    pub fn module_with(
200        &mut self,
201        slug: &str,
202        prefix: &str,
203        permissions: &[saola_permission::Operation],
204        routes: impl FnOnce(&mut ContextRoutes<'_>),
205    ) {
206        let perm = self.perm.module_with(slug.trim_matches('.'), permissions);
207        self.module_scoped(slug, prefix, perm, routes);
208    }
209
210    /// Operations required by every route registered inside `routes` (a permission group, no
211    /// URL or name change), e.g. `ctx.require(&[Operation::Access], |ctx| { .. })`.
212    #[cfg(feature = "permission")]
213    pub fn require(
214        &mut self,
215        permissions: &[saola_permission::Operation],
216        routes: impl FnOnce(&mut ContextRoutes<'_>),
217    ) {
218        let mut child = ContextRoutes {
219            router: &mut *self.router,
220            spec: self.spec.clone(),
221            uri_prefix: self.uri_prefix.clone(),
222            name_prefix: self.name_prefix.clone(),
223            registry: Arc::clone(&self.registry),
224            perm: self.perm.group(permissions),
225        };
226        routes(&mut child);
227    }
228
229    /// From here on (this scope and its children), routes carrying permission requirements get a
230    /// `RequirePermission<U>` middleware. Without it the declarations are only recorded.
231    #[cfg(feature = "permission")]
232    pub fn enforce_with<U: laravel::auth::Authenticatable + saola_permission::PermissionSubject>(&mut self) {
233        self.perm.enforce_with::<U>();
234    }
235
236    fn module_scoped(
237        &mut self,
238        slug: &str,
239        prefix: &str,
240        perm: PermScope,
241        routes: impl FnOnce(&mut ContextRoutes<'_>),
242    ) {
243        let next_uri = join_uri(&self.uri_prefix, prefix);
244        let slug_clean = slug.trim_matches('.');
245        let next_name = match (self.name_prefix.is_empty(), slug_clean.is_empty()) {
246            (_, true) => self.name_prefix.clone(),
247            (true, false) => slug_clean.to_owned(),
248            (false, false) => format!("{}.{slug_clean}", self.name_prefix),
249        };
250        let spec = self.spec.clone();
251        let registry = Arc::clone(&self.registry);
252
253        let clean_prefix = prefix.trim().trim_matches('/');
254        if clean_prefix.is_empty() {
255            let mut child = ContextRoutes {
256                router: self.router,
257                spec,
258                uri_prefix: next_uri,
259                name_prefix: next_name,
260                registry,
261                perm,
262            };
263            routes(&mut child);
264        } else {
265            self.router.prefix(&format!("/{clean_prefix}")).group(move |r| {
266                let mut child = ContextRoutes {
267                    router: r,
268                    spec,
269                    uri_prefix: next_uri,
270                    name_prefix: next_name,
271                    registry,
272                    perm,
273                };
274                routes(&mut child);
275            });
276        }
277    }
278
279    /// Applies middleware to a nested group while preserving the context/module prefix and name scope.
280    pub fn group(
281        &mut self,
282        middleware: impl IntoMiddleware,
283        routes: impl FnOnce(&mut ContextRoutes<'_>),
284    ) {
285        let spec = self.spec.clone();
286        let uri_prefix = self.uri_prefix.clone();
287        let name_prefix = self.name_prefix.clone();
288        let registry = Arc::clone(&self.registry);
289        let perm = self.perm.clone();
290
291        self.router.middleware(middleware).group(move |r| {
292            let mut child = ContextRoutes {
293                router: r,
294                spec,
295                uri_prefix,
296                name_prefix,
297                registry,
298                perm,
299            };
300            routes(&mut child);
301        });
302    }
303
304    #[track_caller]
305    pub fn on<H, T>(&mut self, methods: &[Method], uri: &str, handler: H) -> ContextRoute<'_>
306    where
307        H: Handler<T>,
308        T: 'static,
309    {
310        let full_uri = join_uri(&self.uri_prefix, uri);
311        let name_prefix = self.name_prefix.clone();
312        let context_slug = self.spec.slug.clone();
313        let hosts = self.spec.hosts.clone();
314        let registry = Arc::clone(&self.registry);
315        let route = self.router.on(methods, uri, handler);
316        let perm = RoutePerm::new(
317            &self.perm,
318            &context_slug,
319            methods.iter().map(|m| m.as_str().to_owned()).collect(),
320            route,
321        );
322        ContextRoute {
323            route,
324            full_uri,
325            name_prefix,
326            context_slug,
327            hosts,
328            registry,
329            perm,
330        }
331    }
332
333    #[track_caller]
334    pub fn get<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
335    where
336        H: Handler<T>,
337        T: 'static,
338    {
339        self.on(&[Method::GET], uri, handler)
340    }
341
342    #[track_caller]
343    pub fn post<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
344    where
345        H: Handler<T>,
346        T: 'static,
347    {
348        self.on(&[Method::POST], uri, handler)
349    }
350
351    #[track_caller]
352    pub fn put<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
353    where
354        H: Handler<T>,
355        T: 'static,
356    {
357        self.on(&[Method::PUT], uri, handler)
358    }
359
360    #[track_caller]
361    pub fn patch<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
362    where
363        H: Handler<T>,
364        T: 'static,
365    {
366        self.on(&[Method::PATCH], uri, handler)
367    }
368
369    #[track_caller]
370    pub fn delete<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
371    where
372        H: Handler<T>,
373        T: 'static,
374    {
375        self.on(&[Method::DELETE], uri, handler)
376    }
377
378    #[track_caller]
379    pub fn any<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
380    where
381        H: Handler<T>,
382        T: 'static,
383    {
384        let full_uri = join_uri(&self.uri_prefix, uri);
385        let name_prefix = self.name_prefix.clone();
386        let context_slug = self.spec.slug.clone();
387        let hosts = self.spec.hosts.clone();
388        let registry = Arc::clone(&self.registry);
389        let route = self.router.any(uri, handler);
390        let perm = RoutePerm::new(&self.perm, &context_slug, vec!["ANY".to_owned()], route);
391        ContextRoute {
392            route,
393            full_uri,
394            name_prefix,
395            context_slug,
396            hosts,
397            registry,
398            perm,
399        }
400    }
401}
402
403/// Handle returned after registering a route on [`ContextRoutes`], supporting fluent chaining.
404pub struct ContextRoute<'a> {
405    route: &'a mut Route,
406    full_uri: String,
407    name_prefix: String,
408    context_slug: String,
409    hosts: Vec<String>,
410    registry: Arc<Mutex<ContextRegistry>>,
411    perm: RoutePerm,
412}
413
414impl<'a> ContextRoute<'a> {
415    /// Names the route relative to the active context and module (e.g. `index` -> `api.chat.index`),
416    /// recording its [`RouteEntry`] into [`ContextRegistry`].
417    pub fn name(self, short_name: &str) -> Self {
418        let clean = short_name.trim_matches('.');
419        let full_name = if self.name_prefix.is_empty() {
420            clean.to_owned()
421        } else if clean.is_empty() {
422            self.name_prefix.clone()
423        } else {
424            format!("{}.{clean}", self.name_prefix)
425        };
426
427        let mut guard = self
428            .registry
429            .lock()
430            .unwrap_or_else(std::sync::PoisonError::into_inner);
431        let exists = guard
432            .routes()
433            .iter()
434            .any(|entry| entry.full_name == full_name);
435        if !exists {
436            let mut entry = RouteEntry::new(full_name.clone(), &self.full_uri).with_context(&self.context_slug);
437            if !self.hosts.is_empty() {
438                entry = entry.with_hosts(self.hosts.iter().map(String::as_str));
439            }
440            guard.add_route(entry);
441            self.perm.record(&mut guard, &full_name);
442        }
443        drop(guard);
444
445        self
446    }
447
448    /// Operations required on this route, on top of those inherited from its module and groups.
449    /// Call it before [`Self::name`]: the permission matrix row is recorded when the route is named.
450    #[cfg(feature = "permission")]
451    pub fn permission(mut self, operations: &[saola_permission::Operation]) -> Self {
452        self.perm.add(self.route, operations);
453        self
454    }
455
456    pub fn middleware(self, middleware: impl IntoMiddleware) -> Self {
457        self.route.middleware(middleware);
458        self
459    }
460
461    pub fn without_middleware<M: 'static>(self) -> Self {
462        self.route.without_middleware::<M>();
463        self
464    }
465
466    pub fn with_head(self, head: Head) -> Self {
467        self.route.with_head(head);
468        self
469    }
470
471    pub fn scope_bindings(self) -> Self {
472        self.route.scope_bindings();
473        self
474    }
475
476    pub fn without_scoped_bindings(self) -> Self {
477        self.route.without_scoped_bindings();
478        self
479    }
480
481    pub fn route(&mut self) -> &mut Route {
482        self.route
483    }
484}