1use std::borrow::Cow;
7use std::fmt;
8use std::sync::Arc;
9
10use navree_config::{Config, ModuleBuilderConfigExt};
11use navree_contracts::ModuleBuilderJobsExt;
12use navree_kernel::{
13 AppContext, BoxError, BoxFuture, CommandSpec, Contributed, Factory, Injectable, Module,
14 ModuleBuilder, ModuleId, PluginReport, Resolver,
15};
16
17use crate::error::Result;
18use crate::events::{ClosureListener, Observer, ObserverHook};
19use crate::exec::ExecContext;
20use crate::global_scopes::ClosureScope;
21use crate::hooks::{Flow, ModelEvent, ModelHook};
22use crate::model::{Model, ModelMeta};
23use crate::options::OrmOptions;
24use crate::query::Builder;
25use crate::record::Record;
26use crate::scope::GlobalScope;
27use crate::show::ModelDescription;
28use crate::strict::{self, Strictness, Violation};
29
30#[derive(Clone, Copy, Debug, Default)]
66pub struct OrmModule;
67
68impl OrmModule {
69 pub fn for_root(options: OrmOptions) -> ConfiguredOrmModule {
71 ConfiguredOrmModule {
72 options: Some(options),
73 handlers: Handlers::default(),
74 }
75 }
76
77 pub fn from_config() -> ConfiguredOrmModule {
79 ConfiguredOrmModule {
80 options: None,
81 handlers: Handlers::default(),
82 }
83 }
84}
85
86impl Module for OrmModule {
87 fn register(&self, m: &mut ModuleBuilder) {
88 register(m, None, Handlers::default());
89 }
90}
91
92#[derive(Clone)]
95pub struct ConfiguredOrmModule {
96 options: Option<OrmOptions>,
97 handlers: Handlers,
98}
99
100impl ConfiguredOrmModule {
101 pub fn on_missing_attribute(
104 mut self,
105 handler: impl Fn(&Violation) -> Result<()> + Send + Sync + 'static,
106 ) -> Self {
107 self.handlers.missing_attribute = Some(Arc::new(handler));
108 self
109 }
110
111 pub fn on_discarded_attributes(
114 mut self,
115 handler: impl Fn(&Violation) -> Result<()> + Send + Sync + 'static,
116 ) -> Self {
117 self.handlers.discarded_attributes = Some(Arc::new(handler));
118 self
119 }
120
121 pub fn on_lazy_loading(
124 mut self,
125 handler: impl Fn(&Violation) -> Result<()> + Send + Sync + 'static,
126 ) -> Self {
127 self.handlers.lazy_loading = Some(Arc::new(handler));
128 self
129 }
130}
131
132impl Module for ConfiguredOrmModule {
133 fn id(&self) -> ModuleId {
134 ModuleId::of::<OrmModule>()
135 }
136
137 fn is_configured(&self) -> bool {
138 true
139 }
140
141 fn register(&self, m: &mut ModuleBuilder) {
142 register(m, self.options.clone(), self.handlers.clone());
143 }
144}
145
146impl fmt::Debug for ConfiguredOrmModule {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 f.debug_struct("ConfiguredOrmModule")
149 .field("options", &self.options)
150 .finish_non_exhaustive()
151 }
152}
153
154#[derive(Clone, Default)]
156struct Handlers {
157 missing_attribute: Option<strict::ViolationHandler>,
158 discarded_attributes: Option<strict::ViolationHandler>,
159 lazy_loading: Option<strict::ViolationHandler>,
160}
161
162impl Handlers {
163 fn apply(self, mut strictness: Strictness) -> Strictness {
164 if let Some(handler) = self.missing_attribute {
165 strictness = strictness.on_missing_attribute(move |violation| handler(violation));
166 }
167 if let Some(handler) = self.discarded_attributes {
168 strictness = strictness.on_discarded_attributes(move |violation| handler(violation));
169 }
170 if let Some(handler) = self.lazy_loading {
171 strictness = strictness.on_lazy_loading(move |violation| handler(violation));
172 }
173 strictness
174 }
175}
176
177fn register(m: &mut ModuleBuilder, options: Option<OrmOptions>, handlers: Handlers) {
178 if options.is_none() {
179 m.config_section::<OrmOptions>();
180 }
181 m.global()
182 .factory(Factory::<OrmRuntime>::new(move |r: Resolver| {
183 let options = options.clone();
184 let handlers = handlers.clone();
185 async move {
186 let app = r.app();
187 let scopes = app.contributions::<ScopeRegistration>();
190 if let Some(refusal) = plugin_scope_refusal(&app, &scopes) {
191 return Err(BoxError::from(refusal));
192 }
193 let config = app.try_get::<Config>().await;
194 let options = match (options, &config) {
195 (Some(options), _) => options,
196 (None, Some(config)) => config.typed::<OrmOptions>()?,
197 (None, None) => OrmOptions::default(),
198 };
199 let environment = config.as_deref().and_then(environment);
200 let strictness =
201 handlers.apply(Strictness::from_options(&options, environment.as_deref()));
202 strict::install(strictness.clone());
203 for registration in scopes {
204 (registration.value.install)();
205 }
206 Ok(Arc::new(OrmRuntime {
207 options,
208 strictness,
209 environment,
210 }))
211 }
212 }))
213 .exports::<OrmRuntime>()
214 .job::<crate::broadcast::BroadcastModelEvent>()
215 .command(CommandSpec::new(
216 "model:prune",
217 "Prune the registered prunable models ([--model M]... [--except M]... [--chunk N] [--pretend])",
218 crate::prune::prune_command,
219 ))
220 .command(crate::show::command());
221}
222
223fn environment(config: &Config) -> Option<String> {
225 config.environment().map(|env| env.to_string())
226}
227
228pub struct OrmRuntime {
231 options: OrmOptions,
232 strictness: Strictness,
233 environment: Option<String>,
234}
235
236impl OrmRuntime {
237 pub fn options(&self) -> &OrmOptions {
239 &self.options
240 }
241
242 pub fn strictness(&self) -> &Strictness {
244 &self.strictness
245 }
246
247 pub fn environment(&self) -> Option<&str> {
249 self.environment.as_deref()
250 }
251}
252
253impl fmt::Debug for OrmRuntime {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.debug_struct("OrmRuntime")
256 .field("options", &self.options)
257 .field("strictness", &self.strictness)
258 .field("environment", &self.environment)
259 .finish()
260 }
261}
262
263struct ScopeRegistration {
265 install: Box<dyn Fn() + Send + Sync>,
266 model: &'static str,
268 name: Cow<'static, str>,
270}
271
272fn plugin_scope_refusal(
276 app: &AppContext,
277 scopes: &[Contributed<ScopeRegistration>],
278) -> Option<String> {
279 if scopes.is_empty() {
280 return None;
281 }
282 let plugins = app.plugins().plugins;
283 scopes.iter().find_map(|contributed| {
284 let plugin = community_plugin(&plugins, contributed.module.id)?;
285 let registration = &contributed.value;
286 let own = registration
287 .model
288 .strip_prefix(plugin.info.crate_name)
289 .is_some_and(|rest| rest.starts_with("::"));
290 if own {
291 return None;
292 }
293 let (name, scope, model) = (plugin.info.name, ®istration.name, registration.model);
294 let module = contributed.module.name;
295 let reason = navree_kernel::__private::acts_for_reason(app, contributed.module.id);
296 Some(format!(
297 "plugin `{name}` registers the global scope `{scope}` on `{model}` in `{module}`{reason}, a model of another crate; only a module of the app registers a global scope on it: remove the plugin or update it to a version that leaves the scope to the app, and to use the plugin's scope, register it from a module of the app"
298 ))
299 })
300}
301
302fn community_plugin(plugins: &[PluginReport], module: ModuleId) -> Option<&PluginReport> {
305 plugins.iter().find(|plugin| {
306 !plugin.first_party && plugin.modules.iter().any(|member| member.id == module)
307 })
308}
309
310type Describe =
312 fn(AppContext) -> BoxFuture<'static, std::result::Result<ModelDescription, BoxError>>;
313
314#[derive(Clone, Copy)]
316pub struct RegisteredModel {
317 meta: fn() -> &'static ModelMeta,
318 describe: Describe,
319}
320
321impl RegisteredModel {
322 pub fn of<M: Model>() -> Self {
324 RegisteredModel {
325 meta: M::meta,
326 describe: describe::<M>,
327 }
328 }
329
330 pub fn meta(&self) -> &'static ModelMeta {
332 (self.meta)()
333 }
334
335 pub fn name(&self) -> &'static str {
337 self.meta().name()
338 }
339
340 pub async fn describe(
343 &self,
344 app: &AppContext,
345 ) -> std::result::Result<ModelDescription, BoxError> {
346 (self.describe)(app.clone()).await
347 }
348}
349
350impl fmt::Debug for RegisteredModel {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 f.debug_tuple("RegisteredModel")
353 .field(&self.name())
354 .finish()
355 }
356}
357
358fn describe<M: Model>(
360 app: AppContext,
361) -> BoxFuture<'static, std::result::Result<ModelDescription, BoxError>> {
362 Box::pin(async move {
363 let registered = app.get_all::<dyn ModelHook<M>>().await?;
364 let app_hooks = registered.iter().map(|hook| hook.name()).collect();
365 Ok(ModelDescription::of::<M>(app_hooks))
366 })
367}
368
369pub fn registered_models(app: &AppContext) -> Vec<RegisteredModel> {
372 let mut models: Vec<RegisteredModel> = Vec::new();
373 for registration in app.contributions::<RegisteredModel>() {
374 let model = *registration.value;
375 if !models
376 .iter()
377 .any(|known| std::ptr::eq(known.meta(), model.meta()))
378 {
379 models.push(model);
380 }
381 }
382 models
383}
384
385pub trait ModuleBuilderOrmExt {
413 fn model<M: Model>(&mut self) -> &mut Self;
417
418 fn observe<M: Model>(&mut self, observer: impl Observer<M>) -> &mut Self;
425
426 fn observer<M: Model, O: Observer<M> + Injectable>(&mut self) -> &mut Self;
433
434 fn on_model<M, O>(
446 &mut self,
447 event: ModelEvent,
448 listener: impl for<'a> Fn(&'a mut Record<M>, &'a ExecContext) -> BoxFuture<'a, Result<O>>
449 + Send
450 + Sync
451 + 'static,
452 ) -> &mut Self
453 where
454 M: Model,
455 O: Into<Flow> + 'static;
456
457 fn global_scope<M: Model>(
466 &mut self,
467 name: impl Into<Cow<'static, str>>,
468 scope: impl Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
469 ) -> &mut Self;
470
471 fn global_scope_of<M: Model>(&mut self, scope: impl GlobalScope<M>) -> &mut Self;
479}
480
481impl ModuleBuilderOrmExt for ModuleBuilder {
482 fn model<M: Model>(&mut self) -> &mut Self {
483 self.import(OrmModule)
484 .contribute(RegisteredModel::of::<M>())
485 }
486
487 fn observe<M: Model>(&mut self, observer: impl Observer<M>) -> &mut Self {
488 let hook: Arc<dyn ModelHook<M>> = Arc::new(ObserverHook::new(observer));
489 self.multi(Factory::<dyn ModelHook<M>>::new(move |_| {
490 let hook = hook.clone();
491 async move { Ok(hook) }
492 }))
493 }
494
495 fn observer<M: Model, O: Observer<M> + Injectable>(&mut self) -> &mut Self {
496 self.multi(
497 Factory::<dyn ModelHook<M>>::new(|r: Resolver| async move {
498 let observer = O::construct(r).await?;
499 Ok(Arc::new(ObserverHook::new(observer)) as Arc<dyn ModelHook<M>>)
500 })
501 .deps(O::dependencies()),
502 )
503 }
504
505 fn on_model<M, O>(
506 &mut self,
507 event: ModelEvent,
508 listener: impl for<'a> Fn(&'a mut Record<M>, &'a ExecContext) -> BoxFuture<'a, Result<O>>
509 + Send
510 + Sync
511 + 'static,
512 ) -> &mut Self
513 where
514 M: Model,
515 O: Into<Flow> + 'static,
516 {
517 let hook: Arc<dyn ModelHook<M>> = Arc::new(ClosureListener::new(event, listener));
518 self.multi(Factory::<dyn ModelHook<M>>::new(move |_| {
519 let hook = hook.clone();
520 async move { Ok(hook) }
521 }))
522 }
523
524 fn global_scope<M: Model>(
525 &mut self,
526 name: impl Into<Cow<'static, str>>,
527 scope: impl Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
528 ) -> &mut Self {
529 self.global_scope_of::<M>(ClosureScope::new(name, scope))
530 }
531
532 fn global_scope_of<M: Model>(&mut self, scope: impl GlobalScope<M>) -> &mut Self {
533 let name = scope.name();
534 let scope: Arc<dyn GlobalScope<M>> = Arc::new(scope);
535 self.import(OrmModule).contribute(ScopeRegistration {
536 install: Box::new(move || crate::global_scopes::register::<M>(scope.clone())),
537 model: std::any::type_name::<M>(),
538 name,
539 })
540 }
541}