use std::sync::{Arc, Mutex};
use laravel::container::Registrar;
use laravel::prelude::Router;
use serde::Serialize;
use crate::context::router::{SetCurrentContext, join_uri, strip_api_prefix};
use crate::context::{ContextRegistry, ContextRoutes, ContextSpec, ContextTarget};
pub trait SaolaModule: Send + Sync + 'static {
fn name(&self) -> &'static str;
fn context(&self) -> &'static str {
"web"
}
fn priority(&self) -> i32 {
0
}
fn register(&self, _app: &mut Registrar) {}
fn routes(&self, _ctx: &mut ContextRoutes<'_>) {}
fn web_routes(&self, _route: &mut Router) {}
fn api_routes(&self, _route: &mut Router) {}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ModuleMeta {
pub name: &'static str,
pub context: &'static str,
pub priority: i32,
}
#[derive(Clone, Default)]
pub struct ModuleRegistry {
modules: Vec<Arc<dyn SaolaModule>>,
}
impl std::fmt::Debug for ModuleRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ModuleRegistry")
.field("modules", &self.metadata())
.finish()
}
}
impl ModuleRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn add<M: SaolaModule>(&mut self, module: M) -> &mut Self {
self.modules.push(Arc::new(module));
self
}
pub fn add_arc(&mut self, module: Arc<dyn SaolaModule>) -> &mut Self {
self.modules.push(module);
self
}
pub fn ordered(&self) -> Vec<Arc<dyn SaolaModule>> {
let mut ordered = self.modules.clone();
ordered.sort_by(|a, b| {
b.priority()
.cmp(&a.priority())
.then_with(|| a.name().cmp(b.name()))
});
ordered
}
pub fn metadata(&self) -> Vec<ModuleMeta> {
self.ordered()
.into_iter()
.map(|m| ModuleMeta {
name: m.name(),
context: m.context(),
priority: m.priority(),
})
.collect()
}
pub fn register_all(&self, app: &mut Registrar) {
let ordered = self.ordered();
for module in &ordered {
module.register(app);
}
let web_modules = ordered.clone();
app.routing().web(move |route| {
for module in &web_modules {
module.web_routes(route);
}
});
app.routing().api(move |route| {
for module in &ordered {
module.api_routes(route);
}
});
}
pub fn register_context_routes(
&self,
app: &mut Registrar,
specs: Vec<ContextSpec>,
registry: Arc<Mutex<ContextRegistry>>,
) {
let ordered = self.ordered();
if ordered.is_empty() || specs.is_empty() {
return;
}
let mut sorted_specs = specs;
sorted_specs.sort_by(|a, b| b.priority.cmp(&a.priority).then_with(|| a.slug.cmp(&b.slug)));
for spec in sorted_specs {
let modules = ordered.clone();
let reg = Arc::clone(®istry);
if spec.target == ContextTarget::Api {
let inner_prefix = strip_api_prefix(&spec.prefix);
let tracked_uri = join_uri("/api", &inner_prefix);
app.routing().api(move |route| {
mount_spec(route, spec, &inner_prefix, tracked_uri, modules, reg);
});
} else {
let inner_prefix = spec.prefix.trim().trim_matches('/').to_owned();
let tracked_uri = join_uri("", &spec.prefix);
app.routing().web(move |route| {
mount_spec(route, spec, &inner_prefix, tracked_uri, modules, reg);
});
}
}
}
}
fn mount_spec(
route: &mut Router,
spec: ContextSpec,
inner_prefix: &str,
tracked_uri: String,
modules: Vec<Arc<dyn SaolaModule>>,
registry: Arc<Mutex<ContextRegistry>>,
) {
let ctx_mw = SetCurrentContext::new(&spec.slug);
if spec.hosts.is_empty() {
mount_target(
route,
None,
ctx_mw,
spec,
inner_prefix,
tracked_uri,
modules,
registry,
);
} else {
for host in spec.hosts.clone() {
mount_target(
route,
Some(&host),
ctx_mw.clone(),
spec.clone(),
inner_prefix,
tracked_uri.clone(),
modules.clone(),
Arc::clone(®istry),
);
}
}
}
#[allow(clippy::too_many_arguments)]
fn mount_target(
route: &mut Router,
domain: Option<&str>,
ctx_mw: SetCurrentContext,
spec: ContextSpec,
inner_prefix: &str,
tracked_uri: String,
modules: Vec<Arc<dyn SaolaModule>>,
registry: Arc<Mutex<ContextRegistry>>,
) {
let run = move |r: &mut Router| {
let mut ctx = ContextRoutes::new(r, spec, tracked_uri, registry);
for module in &modules {
module.routes(&mut ctx);
}
};
match (domain, inner_prefix.is_empty()) {
(Some(host), false) => route
.domain(host)
.prefix(&format!("/{inner_prefix}"))
.middleware(ctx_mw)
.group(run),
(Some(host), true) => route.domain(host).middleware(ctx_mw).group(run),
(None, false) => route
.prefix(&format!("/{inner_prefix}"))
.middleware(ctx_mw)
.group(run),
(None, true) => route.middleware(ctx_mw).group(run),
}
}