Skip to main content

saola_kit/
module.rs

1use std::sync::{Arc, Mutex};
2
3use laravel::container::Registrar;
4use laravel::prelude::Router;
5use serde::Serialize;
6
7use crate::context::router::{SetCurrentContext, join_uri, strip_api_prefix};
8use crate::context::{ContextRegistry, ContextRoutes, ContextSpec, ContextTarget};
9
10/// Modular registration unit mirroring Saola's `ModuleServiceProvider` / `ModuleService`.
11pub trait SaolaModule: Send + Sync + 'static {
12    fn name(&self) -> &'static str;
13
14    fn context(&self) -> &'static str {
15        "web"
16    }
17
18    fn priority(&self) -> i32 {
19        0
20    }
21
22    fn register(&self, _app: &mut Registrar) {}
23
24    /// Registers routes into any declared Saola context (`web`, `admin`, `api`, subdomains...).
25    fn routes(&self, _ctx: &mut ContextRoutes<'_>) {}
26
27    fn web_routes(&self, _route: &mut Router) {}
28
29    fn api_routes(&self, _route: &mut Router) {}
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
33pub struct ModuleMeta {
34    pub name: &'static str,
35    pub context: &'static str,
36    pub priority: i32,
37}
38
39/// Ordered registry of [`SaolaModule`]s executed during provider registration.
40#[derive(Clone, Default)]
41pub struct ModuleRegistry {
42    modules: Vec<Arc<dyn SaolaModule>>,
43}
44
45impl std::fmt::Debug for ModuleRegistry {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.debug_struct("ModuleRegistry")
48            .field("modules", &self.metadata())
49            .finish()
50    }
51}
52
53impl ModuleRegistry {
54    pub fn new() -> Self {
55        Self::default()
56    }
57
58    pub fn add<M: SaolaModule>(&mut self, module: M) -> &mut Self {
59        self.modules.push(Arc::new(module));
60        self
61    }
62
63    pub fn add_arc(&mut self, module: Arc<dyn SaolaModule>) -> &mut Self {
64        self.modules.push(module);
65        self
66    }
67
68    pub fn ordered(&self) -> Vec<Arc<dyn SaolaModule>> {
69        let mut ordered = self.modules.clone();
70        ordered.sort_by(|a, b| {
71            b.priority()
72                .cmp(&a.priority())
73                .then_with(|| a.name().cmp(b.name()))
74        });
75        ordered
76    }
77
78    pub fn metadata(&self) -> Vec<ModuleMeta> {
79        self.ordered()
80            .into_iter()
81            .map(|m| ModuleMeta {
82                name: m.name(),
83                context: m.context(),
84                priority: m.priority(),
85            })
86            .collect()
87    }
88
89    pub fn register_all(&self, app: &mut Registrar) {
90        let ordered = self.ordered();
91
92        for module in &ordered {
93            module.register(app);
94        }
95
96        let web_modules = ordered.clone();
97        app.routing().web(move |route| {
98            for module in &web_modules {
99                module.web_routes(route);
100            }
101        });
102
103        app.routing().api(move |route| {
104            for module in &ordered {
105                module.api_routes(route);
106            }
107        });
108    }
109
110    /// Mounts every module's `routes(&mut ctx)` across all declared [`ContextSpec`]s.
111    pub fn register_context_routes(
112        &self,
113        app: &mut Registrar,
114        specs: Vec<ContextSpec>,
115        registry: Arc<Mutex<ContextRegistry>>,
116    ) {
117        let ordered = self.ordered();
118        if ordered.is_empty() || specs.is_empty() {
119            return;
120        }
121
122        let mut sorted_specs = specs;
123        sorted_specs.sort_by(|a, b| b.priority.cmp(&a.priority).then_with(|| a.slug.cmp(&b.slug)));
124
125        for spec in sorted_specs {
126            let modules = ordered.clone();
127            let reg = Arc::clone(&registry);
128            if spec.target == ContextTarget::Api {
129                let inner_prefix = strip_api_prefix(&spec.prefix);
130                let tracked_uri = join_uri("/api", &inner_prefix);
131                app.routing().api(move |route| {
132                    mount_spec(route, spec, &inner_prefix, tracked_uri, modules, reg);
133                });
134            } else {
135                let inner_prefix = spec.prefix.trim().trim_matches('/').to_owned();
136                let tracked_uri = join_uri("", &spec.prefix);
137                app.routing().web(move |route| {
138                    mount_spec(route, spec, &inner_prefix, tracked_uri, modules, reg);
139                });
140            }
141        }
142    }
143}
144
145fn mount_spec(
146    route: &mut Router,
147    spec: ContextSpec,
148    inner_prefix: &str,
149    tracked_uri: String,
150    modules: Vec<Arc<dyn SaolaModule>>,
151    registry: Arc<Mutex<ContextRegistry>>,
152) {
153    let ctx_mw = SetCurrentContext::new(&spec.slug);
154    if spec.hosts.is_empty() {
155        mount_target(
156            route,
157            None,
158            ctx_mw,
159            spec,
160            inner_prefix,
161            tracked_uri,
162            modules,
163            registry,
164        );
165    } else {
166        for host in spec.hosts.clone() {
167            mount_target(
168                route,
169                Some(&host),
170                ctx_mw.clone(),
171                spec.clone(),
172                inner_prefix,
173                tracked_uri.clone(),
174                modules.clone(),
175                Arc::clone(&registry),
176            );
177        }
178    }
179}
180
181#[allow(clippy::too_many_arguments)]
182fn mount_target(
183    route: &mut Router,
184    domain: Option<&str>,
185    ctx_mw: SetCurrentContext,
186    spec: ContextSpec,
187    inner_prefix: &str,
188    tracked_uri: String,
189    modules: Vec<Arc<dyn SaolaModule>>,
190    registry: Arc<Mutex<ContextRegistry>>,
191) {
192    let run = move |r: &mut Router| {
193        let mut ctx = ContextRoutes::new(r, spec, tracked_uri, registry);
194        for module in &modules {
195            module.routes(&mut ctx);
196        }
197    };
198
199    match (domain, inner_prefix.is_empty()) {
200        (Some(host), false) => route
201            .domain(host)
202            .prefix(&format!("/{inner_prefix}"))
203            .middleware(ctx_mw)
204            .group(run),
205        (Some(host), true) => route.domain(host).middleware(ctx_mw).group(run),
206        (None, false) => route
207            .prefix(&format!("/{inner_prefix}"))
208            .middleware(ctx_mw)
209            .group(run),
210        (None, true) => route.middleware(ctx_mw).group(run),
211    }
212}