Skip to main content

navree_kernel/
module.rs

1//! The [`Module`] and [`Injectable`] traits, and [`ConfiguredModule`].
2
3use std::marker::PhantomData;
4
5use crate::builder::PassedModule;
6use crate::{BoxFuture, KernelError, ModuleBuilder, ModuleId, ProviderKey, Resolver, Scope};
7
8/// A unit of an app: it registers providers, exports, imports, contributions,
9/// lifecycle hooks and commands through a [`ModuleBuilder`].
10///
11/// `register` is called once per [`ModuleId`] per boot. A configured instance
12/// (`for_root(...)`, [`is_configured`](Module::is_configured) returns `true`)
13/// wins over plain imports of the same module type.
14pub trait Module: Send + Sync + 'static {
15    /// The module identity. `for_root` wrappers override this to return the id
16    /// of the module type they configure.
17    fn id(&self) -> ModuleId {
18        ModuleId::of::<Self>()
19    }
20
21    /// The readable module name used in errors and reports.
22    fn name(&self) -> &'static str {
23        self.id().name()
24    }
25
26    /// `for_root(...)` values return true; at most one configured instance per id.
27    fn is_configured(&self) -> bool {
28        false
29    }
30
31    /// Registers everything the module contributes.
32    fn register(&self, m: &mut ModuleBuilder);
33
34    /// The concrete type name of `self` when erased behind `dyn Module`.
35    /// Sealed by an unnameable parameter so crates outside `navree-kernel`
36    /// cannot override it. Not public API.
37    #[doc(hidden)]
38    #[allow(private_interfaces)]
39    fn __module_type(&self, _: sealed::Witness<'_>) -> sealed::ModuleType {
40        sealed::ModuleType {
41            type_name: std::any::type_name::<Self>(),
42        }
43    }
44}
45
46mod sealed {
47    use std::marker::PhantomData;
48
49    #[derive(Clone, Copy)]
50    pub struct Witness<'a>(PhantomData<fn(&'a ()) -> &'a ()>);
51
52    impl Witness<'_> {
53        pub(super) fn new() -> Self {
54            Self(PhantomData)
55        }
56    }
57
58    #[derive(Clone, Copy)]
59    pub struct ModuleType {
60        pub(super) type_name: &'static str,
61    }
62}
63
64impl Module for Box<dyn Module> {
65    fn id(&self) -> ModuleId {
66        (**self).id()
67    }
68
69    fn name(&self) -> &'static str {
70        (**self).name()
71    }
72
73    fn is_configured(&self) -> bool {
74        (**self).is_configured()
75    }
76
77    fn register(&self, m: &mut ModuleBuilder) {
78        (**self).register(m);
79    }
80
81    #[allow(private_interfaces)]
82    fn __module_type(&self, witness: sealed::Witness<'_>) -> sealed::ModuleType {
83        (**self).__module_type(witness)
84    }
85}
86
87impl Module for std::pin::Pin<Box<dyn Module>> {
88    fn id(&self) -> ModuleId {
89        self.as_ref().get_ref().id()
90    }
91
92    fn name(&self) -> &'static str {
93        self.as_ref().get_ref().name()
94    }
95
96    fn is_configured(&self) -> bool {
97        self.as_ref().get_ref().is_configured()
98    }
99
100    fn register(&self, m: &mut ModuleBuilder) {
101        self.as_ref().get_ref().register(m);
102    }
103
104    #[allow(private_interfaces)]
105    fn __module_type(&self, witness: sealed::Witness<'_>) -> sealed::ModuleType {
106        self.as_ref().get_ref().__module_type(witness)
107    }
108}
109
110/// Unwraps erased `dyn Module` wrappers (`Box`, `Pin`) and returns the inner
111/// value's `std::any::type_name`.
112pub(crate) fn resolved_type_name(module: &dyn Module) -> &'static str {
113    module.__module_type(sealed::Witness::new()).type_name
114}
115
116/// The configured form of module `M`: what `M::for_root(options)` and
117/// `M::from_config()` return, so a module does not repeat the wrapper that
118/// carries its id, says it is configured and hands its options to `register`.
119///
120/// `register` is the module's own function. It gets `Some(options)` from
121/// [`for_root`](ConfiguredModule::for_root), and `None` from
122/// [`from_config`](ConfiguredModule::from_config), which means "read the
123/// section of the app's configuration" (a plain `M` registers with `None`
124/// too).
125///
126/// A module of a plugin that is not one of the framework's own packages may
127/// configure only modules whose type names the plugin's crate; it imports any
128/// other module by type, and the app configures it.
129///
130/// ```
131/// use navree_kernel::{ConfiguredModule, Module, ModuleBuilder, Navree};
132///
133/// #[derive(Clone)]
134/// struct GreetingOptions(&'static str);
135///
136/// struct GreetingModule;
137///
138/// impl GreetingModule {
139///     pub fn for_root(options: GreetingOptions) -> impl Module {
140///         ConfiguredModule::<GreetingModule, _>::for_root(options, register)
141///     }
142/// }
143///
144/// impl Module for GreetingModule {
145///     fn register(&self, m: &mut ModuleBuilder) {
146///         register(m, None);
147///     }
148/// }
149///
150/// fn register(m: &mut ModuleBuilder, options: Option<GreetingOptions>) {
151///     let greeting = options.map_or("hello", |options| options.0);
152///     m.value(greeting.to_owned()).exports::<String>();
153/// }
154///
155/// // The configured instance has the plain module's id.
156/// let configured = GreetingModule::for_root(GreetingOptions("namaste"));
157/// assert_eq!(configured.id(), GreetingModule.id());
158/// assert!(configured.is_configured());
159/// let report = Navree::app().module(configured).validate().expect("valid");
160/// // The app's root module and GreetingModule.
161/// assert_eq!(report.modules.len(), 2);
162/// ```
163pub struct ConfiguredModule<M, O> {
164    options: Option<O>,
165    register: fn(&mut ModuleBuilder, Option<O>),
166    module: PhantomData<fn() -> M>,
167}
168
169impl<M, O> ConfiguredModule<M, O> {
170    /// `M` configured with `options` (configure a module once, in the app
171    /// root).
172    pub fn for_root(options: O, register: fn(&mut ModuleBuilder, Option<O>)) -> Self {
173        Self {
174            options: Some(options),
175            register,
176            module: PhantomData,
177        }
178    }
179
180    /// `M` configured from the app's configuration: `register` gets `None`.
181    pub fn from_config(register: fn(&mut ModuleBuilder, Option<O>)) -> Self {
182        Self {
183            options: None,
184            register,
185            module: PhantomData,
186        }
187    }
188}
189
190impl<M: 'static, O: Clone + Send + Sync + 'static> Module for ConfiguredModule<M, O> {
191    fn id(&self) -> ModuleId {
192        ModuleId::of::<M>()
193    }
194
195    fn is_configured(&self) -> bool {
196        true
197    }
198
199    fn register(&self, m: &mut ModuleBuilder) {
200        if self.options.is_some() {
201            m.contribute(CodeConfigured {
202                module: ModuleId::of::<M>().name(),
203            });
204        }
205        (self.register)(m, self.options.clone());
206    }
207}
208
209/// Expands, in the crate that calls it, to a configured-module wrapper type of
210/// that crate with one private field holding [`ConfiguredModule`], two
211/// crate-private constructors (`for_root(options)` and `from_config()`) bound
212/// to the crate's own `register` function, and [`Module`] forwarding `id`,
213/// `is_configured` and `register`.
214///
215/// A framework package that names itself a plugin uses this in place of
216/// returning [`ConfiguredModule`] directly, so its configured forms have a type
217/// of the package's own crate and no other crate can build the wrapper with
218/// another `register` function. Not public API; Navree's own crates use it.
219///
220/// ```
221/// use navree_kernel::{Module, ModuleBuilder, Navree, configured_module};
222///
223/// #[derive(Clone)]
224/// struct GreetingOptions(&'static str);
225///
226/// struct GreetingModule;
227///
228/// impl GreetingModule {
229///     pub fn for_root(options: GreetingOptions) -> impl Module {
230///         ConfiguredGreetingModule::for_root(options)
231///     }
232///
233///     pub fn from_config() -> impl Module {
234///         ConfiguredGreetingModule::from_config()
235///     }
236/// }
237///
238/// impl Module for GreetingModule {
239///     fn register(&self, m: &mut ModuleBuilder) {
240///         register(m, None);
241///     }
242/// }
243///
244/// configured_module!(ConfiguredGreetingModule, GreetingModule, GreetingOptions, register);
245///
246/// fn register(m: &mut ModuleBuilder, options: Option<GreetingOptions>) {
247///     let greeting = options.map_or("sat sri akal", |options| options.0);
248///     m.value(greeting.to_owned()).exports::<String>();
249/// }
250///
251/// let configured = GreetingModule::for_root(GreetingOptions("namaste"));
252/// assert_eq!(configured.id(), GreetingModule.id());
253/// assert!(configured.is_configured());
254/// Navree::app().module(configured).validate().expect("valid");
255/// ```
256///
257/// Outside the crate that wrote a configured form, neither its constructors
258/// nor its private field can build one:
259///
260/// ```compile_fail
261/// use navree_kernel::__private::ConfiguredPlainModule;
262///
263/// let _ = ConfiguredPlainModule::from_config();
264/// ```
265///
266/// ```compile_fail
267/// use navree_kernel::ConfiguredModule;
268/// use navree_kernel::__private::{ConfiguredPlainModule, PlainModule};
269///
270/// let _ = ConfiguredPlainModule(ConfiguredModule::<PlainModule, ()>::from_config(|_, _| {}));
271/// ```
272#[doc(hidden)]
273#[macro_export]
274macro_rules! configured_module {
275    (
276        $(#[$meta:meta])*
277        $vis:vis $name:ident,
278        $module:ty,
279        $options:ty,
280        $register:expr $(,)?
281    ) => {
282        #[allow(missing_docs)]
283        $(#[$meta])*
284        $vis struct $name($crate::ConfiguredModule<$module, $options>);
285
286        impl $name {
287            #[allow(dead_code)]
288            pub(crate) fn for_root(options: $options) -> Self {
289                Self($crate::ConfiguredModule::for_root(options, $register))
290            }
291
292            #[allow(dead_code)]
293            pub(crate) fn from_config() -> Self {
294                Self($crate::ConfiguredModule::from_config($register))
295            }
296        }
297
298        impl $crate::Module for $name {
299            fn id(&self) -> $crate::ModuleId {
300                $crate::Module::id(&self.0)
301            }
302
303            fn is_configured(&self) -> bool {
304                $crate::Module::is_configured(&self.0)
305            }
306
307            fn register(&self, m: &mut $crate::ModuleBuilder) {
308                $crate::Module::register(&self.0, m);
309            }
310        }
311    };
312}
313
314mod sample {
315    /// A module of the kernel that registers nothing, for the doctests of
316    /// [`configured_module!`](crate::configured_module) and the plugin tests.
317    /// Not public API.
318    ///
319    /// Outside `navree-kernel`, `Module::__module_type` cannot be overridden:
320    ///
321    /// ```compile_fail
322    /// use navree_kernel::{Module, ModuleBuilder};
323    ///
324    /// struct OutsideModule;
325    ///
326    /// impl Module for OutsideModule {
327    ///     fn register(&self, _: &mut ModuleBuilder) {}
328    ///
329    ///     fn __module_type(&self, _: _) -> _ {
330    ///         unreachable!()
331    ///     }
332    /// }
333    /// ```
334    pub struct PlainModule;
335
336    impl PlainModule {
337        /// Configured form of [`PlainModule`], for plugin tests.
338        pub fn from_config() -> ConfiguredPlainModule {
339            ConfiguredPlainModule::from_config()
340        }
341    }
342
343    impl crate::Module for PlainModule {
344        fn register(&self, _: &mut crate::ModuleBuilder) {}
345    }
346
347    fn register(_: &mut crate::ModuleBuilder, _: Option<()>) {}
348
349    crate::configured_module!(pub ConfiguredPlainModule, PlainModule, (), register);
350}
351
352pub use sample::{ConfiguredPlainModule, PlainModule};
353
354/// Contributed by a module that was given its options in code
355/// (`for_root(options)`), so tools can tell that the section of the
356/// configuration it would otherwise read is not read. navree-config warns
357/// when the configuration has such a section.
358#[derive(Clone, Copy, Debug, PartialEq, Eq)]
359pub struct CodeConfigured {
360    module: &'static str,
361}
362
363impl CodeConfigured {
364    /// The short name of the module (`CacheModule`).
365    pub fn module(&self) -> &'static str {
366        self.module
367    }
368}
369
370/// A type the container can construct (what `#[injectable]` implements).
371pub trait Injectable: Sized + Send + Sync + 'static {
372    /// The provider scope; singletons by default.
373    fn scope() -> Scope {
374        Scope::Singleton
375    }
376
377    /// The keys `construct` resolves, used by the boot-time graph check.
378    /// Keys resolved through [`Lazy`](crate::Lazy) are left out.
379    fn dependencies() -> Vec<ProviderKey> {
380        Vec::new()
381    }
382
383    /// Builds the value, resolving dependencies through `r`.
384    fn construct(r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>>;
385}
386
387/// Values accepted by [`ModuleBuilder::imports`]: a module, a tuple of up to
388/// 16 modules, or a `Vec<Box<dyn Module>>`.
389pub trait IntoModules {
390    /// Converts into boxed modules, in order.
391    fn into_modules(self) -> Vec<Box<dyn Module>>;
392
393    /// Converts into modules, in order, each with the type of the value it was
394    /// given as: a module given already boxed has the type `Box<dyn Module>`.
395    /// The kernel reads a module's own type from it, and only a typed value
396    /// makes a `PassedModule`. Not public API; the kernel calls it.
397    #[doc(hidden)]
398    fn into_passed_modules(self) -> Vec<PassedModule>
399    where
400        Self: Sized,
401    {
402        self.into_modules()
403            .into_iter()
404            .map(PassedModule::boxed)
405            .collect()
406    }
407}
408
409impl<M: Module> IntoModules for M {
410    fn into_modules(self) -> Vec<Box<dyn Module>> {
411        vec![Box::new(self)]
412    }
413
414    fn into_passed_modules(self) -> Vec<PassedModule> {
415        vec![PassedModule::of(self)]
416    }
417}
418
419impl IntoModules for Vec<Box<dyn Module>> {
420    fn into_modules(self) -> Vec<Box<dyn Module>> {
421        self
422    }
423}
424
425macro_rules! tuple_into_modules {
426    ($($name:ident),+) => {
427        impl<$($name: Module),+> IntoModules for ($($name,)+) {
428            #[allow(non_snake_case)]
429            fn into_modules(self) -> Vec<Box<dyn Module>> {
430                let ($($name,)+) = self;
431                vec![$(Box::new($name) as Box<dyn Module>),+]
432            }
433
434            #[allow(non_snake_case)]
435            fn into_passed_modules(self) -> Vec<PassedModule> {
436                let ($($name,)+) = self;
437                vec![$(PassedModule::of($name)),+]
438            }
439        }
440    };
441}
442
443tuple_into_modules!(A);
444tuple_into_modules!(A, B);
445tuple_into_modules!(A, B, C);
446tuple_into_modules!(A, B, C, D);
447tuple_into_modules!(A, B, C, D, E);
448tuple_into_modules!(A, B, C, D, E, F);
449tuple_into_modules!(A, B, C, D, E, F, G);
450tuple_into_modules!(A, B, C, D, E, F, G, H);
451tuple_into_modules!(A, B, C, D, E, F, G, H, I);
452tuple_into_modules!(A, B, C, D, E, F, G, H, I, J);
453tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K);
454tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L);
455tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M);
456tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
457tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
458tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use crate::Navree;
464    use crate::graph::Graph;
465    use crate::plugin::{FIRST_PARTY, PluginInfo, is_first_party};
466
467    /// Stands for a framework package's module and its configured form written in that crate.
468    mod navree_flags_probe {
469        use crate::{Module, ModuleBuilder};
470
471        #[derive(Clone)]
472        pub struct FlagsOptions(pub &'static str);
473
474        pub struct FlagsModule;
475
476        impl FlagsModule {
477            pub fn for_root(options: FlagsOptions) -> impl Module {
478                ConfiguredFlagsModule::for_root(options)
479            }
480
481            pub fn from_config() -> impl Module {
482                ConfiguredFlagsModule::from_config()
483            }
484        }
485
486        impl Module for FlagsModule {
487            fn register(&self, m: &mut ModuleBuilder) {
488                register(m, None);
489            }
490        }
491
492        crate::configured_module!(ConfiguredFlagsModule, FlagsModule, FlagsOptions, register);
493
494        fn register(m: &mut ModuleBuilder, options: Option<FlagsOptions>) {
495            let city = options.map_or("from_config", |options| options.0);
496            m.contribute(city);
497        }
498    }
499
500    #[test]
501    fn a_configured_form_written_in_a_crate_is_a_type_of_that_crate_with_the_modules_id() {
502        use navree_flags_probe::{FlagsModule, FlagsOptions};
503
504        let plain_id = ModuleId::of::<FlagsModule>();
505        let krate = concat!(module_path!(), "::navree_flags_probe");
506        let prefix = format!("{krate}::");
507
508        let for_root = FlagsModule::for_root(FlagsOptions("Ludhiana"));
509        assert_eq!(for_root.id(), plain_id);
510        assert_eq!(for_root.name(), "FlagsModule");
511        assert!(for_root.is_configured());
512        let passed_root = PassedModule::of(for_root);
513        assert!(
514            passed_root.type_name.starts_with(prefix.as_str()),
515            "{}",
516            passed_root.type_name
517        );
518        assert!(
519            !passed_root.type_name.contains('<'),
520            "{}",
521            passed_root.type_name
522        );
523
524        let graph = Graph::build_passed(&[passed_root], &[]).expect("valid");
525        let m = graph.module_of(plain_id).expect("in the graph");
526        let code_configured: Vec<&str> = graph.modules[m]
527            .contributions
528            .iter()
529            .filter_map(|c| c.value.downcast_ref::<CodeConfigured>())
530            .map(|c| c.module())
531            .collect();
532        assert_eq!(code_configured, ["FlagsModule"]);
533        let cities: Vec<&str> = graph.modules[m]
534            .contributions
535            .iter()
536            .filter_map(|c| c.value.downcast_ref::<&'static str>().copied())
537            .collect();
538        assert_eq!(cities, ["Ludhiana"]);
539
540        let from_config = FlagsModule::from_config();
541        assert_eq!(from_config.id(), plain_id);
542        assert!(from_config.is_configured());
543        let passed_config = PassedModule::of(from_config);
544        assert!(
545            passed_config.type_name.starts_with(prefix.as_str()),
546            "{}",
547            passed_config.type_name
548        );
549        let listed = [("navree-flags", krate)];
550        let info = PluginInfo::new("navree-flags", krate, "flags", "1.4.0");
551        assert!(is_first_party(
552            &info,
553            &[passed_config.type_name],
554            &listed,
555            "1.4.0"
556        ));
557
558        let graph = Graph::build_passed(&[passed_config], &[]).expect("valid");
559        let m = graph.module_of(plain_id).expect("in the graph");
560        let has_code_configured = graph.modules[m]
561            .contributions
562            .iter()
563            .any(|c| c.value.downcast_ref::<CodeConfigured>().is_some());
564        assert!(!has_code_configured);
565        let cities: Vec<&str> = graph.modules[m]
566            .contributions
567            .iter()
568            .filter_map(|c| c.value.downcast_ref::<&'static str>().copied())
569            .collect();
570        assert_eq!(cities, ["from_config"]);
571    }
572
573    #[test]
574    fn the_kernels_own_configured_wrapper_never_makes_a_plugin_first_party() {
575        use navree_flags_probe::{FlagsModule, FlagsOptions};
576
577        let version = env!("CARGO_PKG_VERSION");
578        let krate = concat!(module_path!(), "::navree_flags_probe");
579        let listed = [("navree-flags", krate)];
580        let info = PluginInfo::new("navree-flags", krate, "flags", version);
581
582        let for_root = PassedModule::of(ConfiguredModule::<FlagsModule, FlagsOptions>::for_root(
583            FlagsOptions("Ludhiana"),
584            |_, _| {},
585        ));
586        let from_config = PassedModule::of(
587            ConfiguredModule::<FlagsModule, FlagsOptions>::from_config(|_, _| {}),
588        );
589        for wrapped in [&for_root, &from_config] {
590            assert!(
591                !is_first_party(&info, &[wrapped.type_name], &listed, version),
592                "{}",
593                wrapped.type_name
594            );
595        }
596
597        // Even when the module and options inside `ConfiguredModule` are types of the listed
598        // first-party crate, the wrapper's own outer type is the kernel's: not first-party, and
599        // refused in the reserved namespace.
600        let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", version);
601        let kernel_wrapped = "navree_kernel::module::ConfiguredModule<navree_flags::module::FlagsModule, navree_flags::options::FlagsOptions>";
602        assert!(!is_first_party(
603            &flags,
604            &[kernel_wrapped],
605            FIRST_PARTY,
606            version
607        ));
608
609        let mut graph =
610            Graph::build_passed(&[PassedModule::of(PlainModule)], &[]).expect("a plain module");
611        let m = graph
612            .module_of(ModuleId::of::<PlainModule>())
613            .expect("in the graph");
614        graph.modules[m].type_name = kernel_wrapped;
615        graph.modules[m].plugin = Some(flags);
616        let mut errors = Vec::new();
617        graph.check_plugins(&mut errors);
618        assert!(
619            matches!(
620                errors.as_slice(),
621                [KernelError::NamespaceReserved {
622                    plugin: "navree-flags",
623                    namespace: "flags",
624                }]
625            ),
626            "{errors:?}"
627        );
628        assert!(!graph.first_party.contains("navree-flags"));
629
630        let claimed = ConfiguredModule::<FlagsModule, ()>::from_config(|m, _| {
631            m.plugin(PluginInfo::new(
632                "navree-flags",
633                "navree_kernel",
634                "flags",
635                env!("CARGO_PKG_VERSION"),
636            ));
637        });
638        let refused = Navree::app()
639            .module(claimed)
640            .validate()
641            .expect_err("the kernel's own wrapper is never first-party");
642        assert!(
643            matches!(
644                refused.0.as_slice(),
645                [KernelError::NamespaceReserved {
646                    plugin: "navree-flags",
647                    namespace: "flags",
648                }]
649            ),
650            "{refused:?}"
651        );
652    }
653}