saola-kit 0.1.2

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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};

/// 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()),
        }
    }

    /// Snapshot of the permission matrix collected while routes were registered. Pass it to
    /// `saola_permission::RouteAccess::new` (call after the app booted: routes register lazily).
    #[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)))
    }
}

/// 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>>,
    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
    }

    /// 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 perm = self.perm.module(slug.trim_matches('.'));
        self.module_scoped(slug, prefix, perm, routes);
    }

    /// Like [`Self::module`], declaring the operations required on the module itself
    /// (`->permission(...)` on a module in PHP). Routes inherit them; only `Access` reaches nested modules.
    #[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);
    }

    /// Operations required by every route registered inside `routes` (a permission group, no
    /// URL or name change), e.g. `ctx.require(&[Operation::Access], |ctx| { .. })`.
    #[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);
    }

    /// From here on (this scope and its children), routes carrying permission requirements get a
    /// `RequirePermission<U>` middleware. Without it the declarations are only recorded.
    #[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);
            });
        }
    }

    /// 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);
        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,
        }
    }
}

/// 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>>,
    perm: RoutePerm,
}

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.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
    }

    /// Operations required on this route, on top of those inherited from its module and groups.
    /// Call it before [`Self::name`]: the permission matrix row is recorded when the route is named.
    #[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
    }
}