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::{ContextRegistry, ContextSpec, RouteEntry, RouteIndex, set_current_context};
10
11/// Lazily builds and caches a [`RouteIndex`] from a shared [`ContextRegistry`]
12/// once deferred route closures have run.
13#[derive(Debug, Clone)]
14pub struct SharedRouteIndex {
15    registry: Arc<Mutex<ContextRegistry>>,
16    primary_url: String,
17    built: Arc<OnceLock<Arc<RouteIndex>>>,
18}
19
20impl SharedRouteIndex {
21    pub fn new(registry: Arc<Mutex<ContextRegistry>>, primary_url: impl Into<String>) -> Self {
22        Self {
23            registry,
24            primary_url: primary_url.into(),
25            built: Arc::new(OnceLock::new()),
26        }
27    }
28
29    pub fn index(&self) -> Result<Arc<RouteIndex>, ContextError> {
30        if let Some(index) = self.built.get() {
31            return Ok(Arc::clone(index));
32        }
33
34        let guard = self
35            .registry
36            .lock()
37            .unwrap_or_else(std::sync::PoisonError::into_inner);
38        let built = Arc::new(guard.build_index(&self.primary_url)?);
39        let _ = self.built.set(Arc::clone(&built));
40        Ok(Arc::clone(self.built.get().unwrap_or(&built)))
41    }
42}
43
44/// Middleware recording the active Saola context slug for the incoming request.
45#[derive(Debug, Clone)]
46pub struct SetCurrentContext {
47    slug: Arc<str>,
48}
49
50impl SetCurrentContext {
51    pub fn new(slug: impl AsRef<str>) -> Self {
52        Self {
53            slug: Arc::from(slug.as_ref()),
54        }
55    }
56
57    pub fn slug(&self) -> &str {
58        &self.slug
59    }
60}
61
62impl Middleware for SetCurrentContext {
63    fn handle(
64        &self,
65        request: Request,
66        next: Next,
67    ) -> impl Future<Output = laravel::Result<Response>> + Send {
68        let slug = Arc::clone(&self.slug);
69        async move {
70            set_current_context(&slug);
71            Ok(next.run(request).await)
72        }
73    }
74}
75
76/// Normalizes and joins a base URI prefix with a child segment.
77pub fn join_uri(base: &str, segment: &str) -> String {
78    let base_trimmed = base.trim().trim_end_matches('/');
79    let seg_trimmed = segment.trim().trim_matches('/');
80
81    match (base_trimmed, seg_trimmed) {
82        ("", "") => "/".to_owned(),
83        ("", seg) => format!("/{seg}"),
84        (b, "") => {
85            if b.starts_with('/') {
86                b.to_owned()
87            } else {
88                format!("/{b}")
89            }
90        }
91        (b, seg) => {
92            let normalized_base = if b.starts_with('/') {
93                b.to_owned()
94            } else {
95                format!("/{b}")
96            };
97            format!("{normalized_base}/{seg}")
98        }
99    }
100}
101
102/// Strips a leading `/api` prefix when mounting onto Laravel's `.api(...)` group,
103/// which already prepends `/api` automatically.
104#[cfg(any(feature = "module", test))]
105pub(crate) fn strip_api_prefix(prefix: &str) -> String {
106    let trimmed = prefix.trim().trim_matches('/');
107    if trimmed.is_empty() || trimmed == "api" {
108        String::new()
109    } else if let Some(rest) = trimmed.strip_prefix("api/") {
110        rest.to_owned()
111    } else {
112        trimmed.to_owned()
113    }
114}
115
116/// Context-aware router wrapper passed to `SaolaModule::routes(&self, ctx: &mut ContextRoutes<'_>)`.
117///
118/// Modules register routes once inside a context: `ContextRoutes` handles module URL prefixing,
119/// route name prefixing (`{context}.{module}.{name}`), middleware groups, and automatic
120/// registration into [`ContextRegistry`] for `RouteIndex` / `href()`.
121pub struct ContextRoutes<'a> {
122    router: &'a mut Router,
123    spec: ContextSpec,
124    uri_prefix: String,
125    name_prefix: String,
126    registry: Arc<Mutex<ContextRegistry>>,
127}
128
129impl<'a> ContextRoutes<'a> {
130    pub fn new(
131        router: &'a mut Router,
132        spec: ContextSpec,
133        uri_prefix: impl Into<String>,
134        registry: Arc<Mutex<ContextRegistry>>,
135    ) -> Self {
136        let name_prefix = spec.as_prefix.trim_matches('.').to_owned();
137        Self {
138            router,
139            spec,
140            uri_prefix: join_uri("", &uri_prefix.into()),
141            name_prefix,
142            registry,
143        }
144    }
145
146    pub fn slug(&self) -> &str {
147        &self.spec.slug
148    }
149
150    pub fn spec(&self) -> &ContextSpec {
151        &self.spec
152    }
153
154    pub fn is(&self, slug: &str) -> bool {
155        self.spec.slug == slug
156    }
157
158    pub fn uri_prefix(&self) -> &str {
159        &self.uri_prefix
160    }
161
162    pub fn name_prefix(&self) -> &str {
163        &self.name_prefix
164    }
165
166    /// Direct escape hatch to the underlying Laravel [`Router`].
167    pub fn router(&mut self) -> &mut Router {
168        self.router
169    }
170
171    /// Scopes routes under a module slug (appended to route names) and URL `prefix`.
172    pub fn module(
173        &mut self,
174        slug: &str,
175        prefix: &str,
176        routes: impl FnOnce(&mut ContextRoutes<'_>),
177    ) {
178        let next_uri = join_uri(&self.uri_prefix, prefix);
179        let slug_clean = slug.trim_matches('.');
180        let next_name = match (self.name_prefix.is_empty(), slug_clean.is_empty()) {
181            (_, true) => self.name_prefix.clone(),
182            (true, false) => slug_clean.to_owned(),
183            (false, false) => format!("{}.{slug_clean}", self.name_prefix),
184        };
185        let spec = self.spec.clone();
186        let registry = Arc::clone(&self.registry);
187
188        let clean_prefix = prefix.trim().trim_matches('/');
189        if clean_prefix.is_empty() {
190            let mut child = ContextRoutes {
191                router: self.router,
192                spec,
193                uri_prefix: next_uri,
194                name_prefix: next_name,
195                registry,
196            };
197            routes(&mut child);
198        } else {
199            self.router.prefix(&format!("/{clean_prefix}")).group(move |r| {
200                let mut child = ContextRoutes {
201                    router: r,
202                    spec,
203                    uri_prefix: next_uri,
204                    name_prefix: next_name,
205                    registry,
206                };
207                routes(&mut child);
208            });
209        }
210    }
211
212    /// Applies middleware to a nested group while preserving the context/module prefix and name scope.
213    pub fn group(
214        &mut self,
215        middleware: impl IntoMiddleware,
216        routes: impl FnOnce(&mut ContextRoutes<'_>),
217    ) {
218        let spec = self.spec.clone();
219        let uri_prefix = self.uri_prefix.clone();
220        let name_prefix = self.name_prefix.clone();
221        let registry = Arc::clone(&self.registry);
222
223        self.router.middleware(middleware).group(move |r| {
224            let mut child = ContextRoutes {
225                router: r,
226                spec,
227                uri_prefix,
228                name_prefix,
229                registry,
230            };
231            routes(&mut child);
232        });
233    }
234
235    #[track_caller]
236    pub fn on<H, T>(&mut self, methods: &[Method], uri: &str, handler: H) -> ContextRoute<'_>
237    where
238        H: Handler<T>,
239        T: 'static,
240    {
241        let full_uri = join_uri(&self.uri_prefix, uri);
242        let name_prefix = self.name_prefix.clone();
243        let context_slug = self.spec.slug.clone();
244        let hosts = self.spec.hosts.clone();
245        let registry = Arc::clone(&self.registry);
246        let route = self.router.on(methods, uri, handler);
247        ContextRoute {
248            route,
249            full_uri,
250            name_prefix,
251            context_slug,
252            hosts,
253            registry,
254        }
255    }
256
257    #[track_caller]
258    pub fn get<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
259    where
260        H: Handler<T>,
261        T: 'static,
262    {
263        self.on(&[Method::GET], uri, handler)
264    }
265
266    #[track_caller]
267    pub fn post<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
268    where
269        H: Handler<T>,
270        T: 'static,
271    {
272        self.on(&[Method::POST], uri, handler)
273    }
274
275    #[track_caller]
276    pub fn put<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
277    where
278        H: Handler<T>,
279        T: 'static,
280    {
281        self.on(&[Method::PUT], uri, handler)
282    }
283
284    #[track_caller]
285    pub fn patch<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
286    where
287        H: Handler<T>,
288        T: 'static,
289    {
290        self.on(&[Method::PATCH], uri, handler)
291    }
292
293    #[track_caller]
294    pub fn delete<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
295    where
296        H: Handler<T>,
297        T: 'static,
298    {
299        self.on(&[Method::DELETE], uri, handler)
300    }
301
302    #[track_caller]
303    pub fn any<H, T>(&mut self, uri: &str, handler: H) -> ContextRoute<'_>
304    where
305        H: Handler<T>,
306        T: 'static,
307    {
308        let full_uri = join_uri(&self.uri_prefix, uri);
309        let name_prefix = self.name_prefix.clone();
310        let context_slug = self.spec.slug.clone();
311        let hosts = self.spec.hosts.clone();
312        let registry = Arc::clone(&self.registry);
313        let route = self.router.any(uri, handler);
314        ContextRoute {
315            route,
316            full_uri,
317            name_prefix,
318            context_slug,
319            hosts,
320            registry,
321        }
322    }
323}
324
325/// Handle returned after registering a route on [`ContextRoutes`], supporting fluent chaining.
326pub struct ContextRoute<'a> {
327    route: &'a mut Route,
328    full_uri: String,
329    name_prefix: String,
330    context_slug: String,
331    hosts: Vec<String>,
332    registry: Arc<Mutex<ContextRegistry>>,
333}
334
335impl<'a> ContextRoute<'a> {
336    /// Names the route relative to the active context and module (e.g. `index` -> `api.chat.index`),
337    /// recording its [`RouteEntry`] into [`ContextRegistry`].
338    pub fn name(self, short_name: &str) -> Self {
339        let clean = short_name.trim_matches('.');
340        let full_name = if self.name_prefix.is_empty() {
341            clean.to_owned()
342        } else if clean.is_empty() {
343            self.name_prefix.clone()
344        } else {
345            format!("{}.{clean}", self.name_prefix)
346        };
347
348        let mut guard = self
349            .registry
350            .lock()
351            .unwrap_or_else(std::sync::PoisonError::into_inner);
352        let exists = guard
353            .routes()
354            .iter()
355            .any(|entry| entry.full_name == full_name);
356        if !exists {
357            let mut entry = RouteEntry::new(full_name, &self.full_uri).with_context(&self.context_slug);
358            if !self.hosts.is_empty() {
359                entry = entry.with_hosts(self.hosts.iter().map(String::as_str));
360            }
361            guard.add_route(entry);
362        }
363        drop(guard);
364
365        self
366    }
367
368    pub fn middleware(self, middleware: impl IntoMiddleware) -> Self {
369        self.route.middleware(middleware);
370        self
371    }
372
373    pub fn without_middleware<M: 'static>(self) -> Self {
374        self.route.without_middleware::<M>();
375        self
376    }
377
378    pub fn with_head(self, head: Head) -> Self {
379        self.route.with_head(head);
380        self
381    }
382
383    pub fn scope_bindings(self) -> Self {
384        self.route.scope_bindings();
385        self
386    }
387
388    pub fn without_scoped_bindings(self) -> Self {
389        self.route.without_scoped_bindings();
390        self
391    }
392
393    pub fn route(&mut self) -> &mut Route {
394        self.route
395    }
396}