Skip to main content

navree_orm/
module.rs

1//! [`OrmModule`] (the `[orm]` options, strict modes, runtime global
2//! scopes, the model registry, `model:prune` and `model:show`) and
3//! [`ModuleBuilderOrmExt`] (observers, listeners, scopes and models
4//! registered by modules).
5
6use 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/// The ORM's module. Global; provides and exports [`OrmRuntime`].
31///
32/// - reads the `[orm]` section ([`OrmOptions`]): the strict modes, by
33///   default on except in production;
34/// - installs, at boot, the global scopes modules register
35///   ([`ModuleBuilderOrmExt::global_scope`]); when a module of a plugin
36///   that is not one of the framework's own packages registers one on a
37///   model of another crate, the boot fails before strict mode or any
38///   scope is installed;
39/// - keeps the registry of the app's models
40///   ([`ModuleBuilderOrmExt::model`]) for tooling;
41/// - registers the commands `model:prune` (see [`prune`](crate::prune))
42///   and `model:show` (see [`show`](crate::show)) and the job
43///   `orm.broadcast` (queued model broadcasts, see
44///   [`broadcast`](crate::broadcast)).
45///
46/// The ORM works without it (models need no module); add it to configure
47/// strict modes and their handlers, or let a module that registers scopes
48/// or models import it for you.
49///
50/// ```no_run
51/// use navree_kernel::Navree;
52/// use navree_orm::OrmModule;
53///
54/// # fn main() -> Result<(), navree_kernel::BoxError> {
55/// Navree::app()
56///     .module(
57///         OrmModule::from_config().on_lazy_loading(|violation| {
58///             tracing::warn!(%violation, "lazy loading"); // log instead of failing
59///             Ok(())
60///         }),
61///     )
62///     .run()
63/// # }
64/// ```
65#[derive(Clone, Copy, Debug, Default)]
66pub struct OrmModule;
67
68impl OrmModule {
69    /// The module with explicit options.
70    pub fn for_root(options: OrmOptions) -> ConfiguredOrmModule {
71        ConfiguredOrmModule {
72            options: Some(options),
73            handlers: Handlers::default(),
74        }
75    }
76
77    /// The module configured from the `[orm]` section at boot.
78    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/// `OrmModule::for_root(..)` / `OrmModule::from_config()`: the module with
93/// its options and strict-mode handlers.
94#[derive(Clone)]
95pub struct ConfiguredOrmModule {
96    options: Option<OrmOptions>,
97    handlers: Handlers,
98}
99
100impl ConfiguredOrmModule {
101    /// Lets `handler` decide about missing attributes in strict mode
102    /// (`Ok(())` reads the field's default instead of failing).
103    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    /// Lets `handler` decide about discarded attributes in strict mode
112    /// (`Ok(())` skips them instead of failing).
113    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    /// Lets `handler` decide about lazy loading in strict mode (`Ok(())`
122    /// loads the relation instead of failing).
123    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/// The strict-mode handlers given to the module.
155#[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                // Both strict mode and global scopes apply process-wide once
188                // installed, so a refusal stops before either runs.
189                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
223/// The app's environment (`APP_ENV` or `app.env`), if it names one.
224fn environment(config: &Config) -> Option<String> {
225    config.environment().map(|env| env.to_string())
226}
227
228/// The ORM of a booted app: its options and resolved strict modes.
229/// Provided by [`OrmModule`].
230pub struct OrmRuntime {
231    options: OrmOptions,
232    strictness: Strictness,
233    environment: Option<String>,
234}
235
236impl OrmRuntime {
237    /// The `[orm]` options.
238    pub fn options(&self) -> &OrmOptions {
239        &self.options
240    }
241
242    /// The strict modes and their handlers.
243    pub fn strictness(&self) -> &Strictness {
244        &self.strictness
245    }
246
247    /// The app's environment (`env` / `app.env`), if it names one.
248    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
263/// A global scope a module registered, installed when the app boots.
264struct ScopeRegistration {
265    install: Box<dyn Fn() + Send + Sync>,
266    /// The model's type path, which says whose model it is.
267    model: &'static str,
268    /// The scope's name.
269    name: Cow<'static, str>,
270}
271
272/// The refusal of the first of `scopes` that a module acting for a plugin the kernel does not
273/// find first-party (the `plugins` listing lists it under the plugin) registers on a model that
274/// is not of the plugin's crate, if any.
275fn 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, &registration.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
302/// The plugin the kernel does not find first-party that `module` acts for, if any: the plugin
303/// the `plugins` listing lists it under.
304fn 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
310/// Describes model `M` with the hooks the app registers for it.
311type Describe =
312    fn(AppContext) -> BoxFuture<'static, std::result::Result<ModelDescription, BoxError>>;
313
314/// A model a module registered (see [`ModuleBuilderOrmExt::model`]).
315#[derive(Clone, Copy)]
316pub struct RegisteredModel {
317    meta: fn() -> &'static ModelMeta,
318    describe: Describe,
319}
320
321impl RegisteredModel {
322    /// The registration of model `M`.
323    pub fn of<M: Model>() -> Self {
324        RegisteredModel {
325            meta: M::meta,
326            describe: describe::<M>,
327        }
328    }
329
330    /// The model's metadata.
331    pub fn meta(&self) -> &'static ModelMeta {
332        (self.meta)()
333    }
334
335    /// The model's name, e.g. `Deal`.
336    pub fn name(&self) -> &'static str {
337        self.meta().name()
338    }
339
340    /// The model as `model:show` shows it, with the hooks `app` registers
341    /// for it.
342    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
358/// `M`'s description, with the hooks `app` registers for it.
359fn 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
369/// The models the app's modules registered, in module dependency order
370/// (each once).
371pub 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
385/// ORM registrations on a [`ModuleBuilder`]: observers and closure
386/// listeners of model events, global scopes, and the app's models.
387///
388/// Listeners belong to the app being built, so each app (each test) has
389/// its own. Global scopes apply process-wide once the app boots (scopes
390/// apply where no app is at hand, such as `to_sql`).
391///
392/// ```no_run
393/// # use navree_orm::__doc_models::*;
394/// use navree_kernel::{Module, ModuleBuilder};
395/// use navree_orm::ModuleBuilderOrmExt;
396///
397/// struct DealsModule;
398///
399/// impl Module for DealsModule {
400///     fn register(&self, m: &mut ModuleBuilder) {
401///         m.model::<Deal>()
402///             .global_scope::<Deal>("open", |q| q.where_null(Deal::CLOSED_AT))
403///             .on_model::<Deal, _>(ModelEvent::Saving, |deal, _ctx| {
404///                 Box::pin(async move {
405///                     deal.title = deal.title.trim().to_owned();
406///                     Ok(())
407///                 })
408///             });
409///     }
410/// }
411/// ```
412pub trait ModuleBuilderOrmExt {
413    /// Registers model `M` with the app, so commands and tooling find it
414    /// (`model:prune`, `model:show`, ...). Rust cannot discover types at
415    /// run time: a module lists its models once. Imports [`OrmModule`].
416    fn model<M: Model>(&mut self) -> &mut Self;
417
418    /// Registers `observer` for model `M`'s events (a `dyn ModelHook<M>`
419    /// multi-binding).
420    ///
421    /// A module of a plugin that is not one of the framework's own packages
422    /// hooks only the plugin's own models (the boot fails otherwise); the app
423    /// registers a plugin's hook on any model from a module of its own.
424    fn observe<M: Model>(&mut self, observer: impl Observer<M>) -> &mut Self;
425
426    /// Registers an observer of model `M` that the container builds (with
427    /// the visibility of this module), for observers with dependencies.
428    ///
429    /// A module of a plugin that is not one of the framework's own packages
430    /// hooks only the plugin's own models (the boot fails otherwise); the app
431    /// registers a plugin's hook on any model from a module of its own.
432    fn observer<M: Model, O: Observer<M> + Injectable>(&mut self) -> &mut Self;
433
434    /// Registers `listener` for `event` of model `M`. It may change the
435    /// record; for a cancellable event it may return [`Flow::Cancel`]
436    /// (`Ok(())` goes ahead). Inside a unit of work it hears "-ed" write
437    /// events after the commit, on a snapshot of the record.
438    ///
439    /// The second type parameter is the listener's output (`()` or
440    /// [`Flow`]): write `m.on_model::<Deal, _>(..)`.
441    ///
442    /// A module of a plugin that is not one of the framework's own packages
443    /// hooks only the plugin's own models (the boot fails otherwise); the app
444    /// registers a plugin's hook on any model from a module of its own.
445    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    /// Registers a global scope named `name` for every query of `M`,
458    /// installed when the app boots (it imports [`OrmModule`]). Queries
459    /// leave it out with `without_global_scope_named(name)`.
460    ///
461    /// A module of a plugin that is not one of the framework's own packages
462    /// registers global scopes only on the plugin's own models (the boot
463    /// fails otherwise, and installs no scope); the app registers a plugin's
464    /// scope on any model from a module of its own.
465    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    /// Registers `scope` (a [`GlobalScope`] value) for every query of `M`,
472    /// installed when the app boots (it imports [`OrmModule`]).
473    ///
474    /// A module of a plugin that is not one of the framework's own packages
475    /// registers global scopes only on the plugin's own models (the boot
476    /// fails otherwise, and installs no scope); the app registers a plugin's
477    /// scope on any model from a module of its own.
478    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}