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
35/// The configured form of module `M`: what `M::for_root(options)` and
36/// `M::from_config()` return, so a module does not repeat the wrapper that
37/// carries its id, says it is configured and hands its options to `register`.
38///
39/// `register` is the module's own function. It gets `Some(options)` from
40/// [`for_root`](ConfiguredModule::for_root), and `None` from
41/// [`from_config`](ConfiguredModule::from_config), which means "read the
42/// section of the app's configuration" (a plain `M` registers with `None`
43/// too).
44///
45/// A module of a plugin that is not one of the framework's own packages may
46/// configure only modules whose type names the plugin's crate; it imports any
47/// other module by type, and the app configures it.
48///
49/// ```
50/// use navree_kernel::{ConfiguredModule, Module, ModuleBuilder, Navree};
51///
52/// #[derive(Clone)]
53/// struct GreetingOptions(&'static str);
54///
55/// struct GreetingModule;
56///
57/// impl GreetingModule {
58///     pub fn for_root(options: GreetingOptions) -> impl Module {
59///         ConfiguredModule::<GreetingModule, _>::for_root(options, register)
60///     }
61/// }
62///
63/// impl Module for GreetingModule {
64///     fn register(&self, m: &mut ModuleBuilder) {
65///         register(m, None);
66///     }
67/// }
68///
69/// fn register(m: &mut ModuleBuilder, options: Option<GreetingOptions>) {
70///     let greeting = options.map_or("hello", |options| options.0);
71///     m.value(greeting.to_owned()).exports::<String>();
72/// }
73///
74/// // The configured instance has the plain module's id.
75/// let configured = GreetingModule::for_root(GreetingOptions("namaste"));
76/// assert_eq!(configured.id(), GreetingModule.id());
77/// assert!(configured.is_configured());
78/// let report = Navree::app().module(configured).validate().expect("valid");
79/// // The app's root module and GreetingModule.
80/// assert_eq!(report.modules.len(), 2);
81/// ```
82pub struct ConfiguredModule<M, O> {
83    options: Option<O>,
84    register: fn(&mut ModuleBuilder, Option<O>),
85    module: PhantomData<fn() -> M>,
86}
87
88impl<M, O> ConfiguredModule<M, O> {
89    /// `M` configured with `options` (configure a module once, in the app
90    /// root).
91    pub fn for_root(options: O, register: fn(&mut ModuleBuilder, Option<O>)) -> Self {
92        Self {
93            options: Some(options),
94            register,
95            module: PhantomData,
96        }
97    }
98
99    /// `M` configured from the app's configuration: `register` gets `None`.
100    pub fn from_config(register: fn(&mut ModuleBuilder, Option<O>)) -> Self {
101        Self {
102            options: None,
103            register,
104            module: PhantomData,
105        }
106    }
107}
108
109impl<M: 'static, O: Clone + Send + Sync + 'static> Module for ConfiguredModule<M, O> {
110    fn id(&self) -> ModuleId {
111        ModuleId::of::<M>()
112    }
113
114    fn is_configured(&self) -> bool {
115        true
116    }
117
118    fn register(&self, m: &mut ModuleBuilder) {
119        if self.options.is_some() {
120            m.contribute(CodeConfigured {
121                module: ModuleId::of::<M>().name(),
122            });
123        }
124        (self.register)(m, self.options.clone());
125    }
126}
127
128/// Contributed by a module that was given its options in code
129/// (`for_root(options)`), so tools can tell that the section of the
130/// configuration it would otherwise read is not read. navree-config warns
131/// when the configuration has such a section.
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub struct CodeConfigured {
134    module: &'static str,
135}
136
137impl CodeConfigured {
138    /// The short name of the module (`CacheModule`).
139    pub fn module(&self) -> &'static str {
140        self.module
141    }
142}
143
144/// A type the container can construct (what `#[injectable]` implements).
145pub trait Injectable: Sized + Send + Sync + 'static {
146    /// The provider scope; singletons by default.
147    fn scope() -> Scope {
148        Scope::Singleton
149    }
150
151    /// The keys `construct` resolves, used by the boot-time graph check.
152    /// Keys resolved through [`Lazy`](crate::Lazy) are left out.
153    fn dependencies() -> Vec<ProviderKey> {
154        Vec::new()
155    }
156
157    /// Builds the value, resolving dependencies through `r`.
158    fn construct(r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>>;
159}
160
161/// Values accepted by [`ModuleBuilder::imports`]: a module, a tuple of up to
162/// 16 modules, or a `Vec<Box<dyn Module>>`.
163pub trait IntoModules {
164    /// Converts into boxed modules, in order.
165    fn into_modules(self) -> Vec<Box<dyn Module>>;
166
167    /// Converts into modules, in order, each with the type of the value it was
168    /// given as: a module given already boxed has the type `Box<dyn Module>`.
169    /// The kernel reads a module's own type from it, and only a typed value
170    /// makes a `PassedModule`. Not public API; the kernel calls it.
171    #[doc(hidden)]
172    fn into_passed_modules(self) -> Vec<PassedModule>
173    where
174        Self: Sized,
175    {
176        self.into_modules()
177            .into_iter()
178            .map(PassedModule::boxed)
179            .collect()
180    }
181}
182
183impl<M: Module> IntoModules for M {
184    fn into_modules(self) -> Vec<Box<dyn Module>> {
185        vec![Box::new(self)]
186    }
187
188    fn into_passed_modules(self) -> Vec<PassedModule> {
189        vec![PassedModule::of(self)]
190    }
191}
192
193impl IntoModules for Vec<Box<dyn Module>> {
194    fn into_modules(self) -> Vec<Box<dyn Module>> {
195        self
196    }
197}
198
199macro_rules! tuple_into_modules {
200    ($($name:ident),+) => {
201        impl<$($name: Module),+> IntoModules for ($($name,)+) {
202            #[allow(non_snake_case)]
203            fn into_modules(self) -> Vec<Box<dyn Module>> {
204                let ($($name,)+) = self;
205                vec![$(Box::new($name) as Box<dyn Module>),+]
206            }
207
208            #[allow(non_snake_case)]
209            fn into_passed_modules(self) -> Vec<PassedModule> {
210                let ($($name,)+) = self;
211                vec![$(PassedModule::of($name)),+]
212            }
213        }
214    };
215}
216
217tuple_into_modules!(A);
218tuple_into_modules!(A, B);
219tuple_into_modules!(A, B, C);
220tuple_into_modules!(A, B, C, D);
221tuple_into_modules!(A, B, C, D, E);
222tuple_into_modules!(A, B, C, D, E, F);
223tuple_into_modules!(A, B, C, D, E, F, G);
224tuple_into_modules!(A, B, C, D, E, F, G, H);
225tuple_into_modules!(A, B, C, D, E, F, G, H, I);
226tuple_into_modules!(A, B, C, D, E, F, G, H, I, J);
227tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K);
228tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L);
229tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M);
230tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
231tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
232tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);