Skip to main content

navree_kernel/
module.rs

1//! The [`Module`] and [`Injectable`] traits, and [`ConfiguredModule`].
2
3use std::marker::PhantomData;
4
5use crate::{BoxFuture, KernelError, ModuleBuilder, ModuleId, ProviderKey, Resolver, Scope};
6
7/// A unit of an app: it registers providers, exports, imports, contributions,
8/// lifecycle hooks and commands through a [`ModuleBuilder`].
9///
10/// `register` is called once per [`ModuleId`] per boot. A configured instance
11/// (`for_root(...)`, [`is_configured`](Module::is_configured) returns `true`)
12/// wins over plain imports of the same module type.
13pub trait Module: Send + Sync + 'static {
14    /// The module identity. `for_root` wrappers override this to return the id
15    /// of the module type they configure.
16    fn id(&self) -> ModuleId {
17        ModuleId::of::<Self>()
18    }
19
20    /// The readable module name used in errors and reports.
21    fn name(&self) -> &'static str {
22        self.id().name()
23    }
24
25    /// `for_root(...)` values return true; at most one configured instance per id.
26    fn is_configured(&self) -> bool {
27        false
28    }
29
30    /// Registers everything the module contributes.
31    fn register(&self, m: &mut ModuleBuilder);
32}
33
34/// The configured form of module `M`: what `M::for_root(options)` and
35/// `M::from_config()` return, so a module does not repeat the wrapper that
36/// carries its id, says it is configured and hands its options to `register`.
37///
38/// `register` is the module's own function. It gets `Some(options)` from
39/// [`for_root`](ConfiguredModule::for_root), and `None` from
40/// [`from_config`](ConfiguredModule::from_config), which means "read the
41/// section of the app's configuration" (a plain `M` registers with `None`
42/// too).
43///
44/// ```
45/// use navree_kernel::{ConfiguredModule, Module, ModuleBuilder, Navree};
46///
47/// #[derive(Clone)]
48/// struct GreetingOptions(&'static str);
49///
50/// struct GreetingModule;
51///
52/// impl GreetingModule {
53///     pub fn for_root(options: GreetingOptions) -> impl Module {
54///         ConfiguredModule::<GreetingModule, _>::for_root(options, register)
55///     }
56/// }
57///
58/// impl Module for GreetingModule {
59///     fn register(&self, m: &mut ModuleBuilder) {
60///         register(m, None);
61///     }
62/// }
63///
64/// fn register(m: &mut ModuleBuilder, options: Option<GreetingOptions>) {
65///     let greeting = options.map_or("hello", |options| options.0);
66///     m.value(greeting.to_owned()).exports::<String>();
67/// }
68///
69/// // The configured instance has the plain module's id.
70/// let configured = GreetingModule::for_root(GreetingOptions("namaste"));
71/// assert_eq!(configured.id(), GreetingModule.id());
72/// assert!(configured.is_configured());
73/// let report = Navree::app().module(configured).validate().expect("valid");
74/// // The app's root module and GreetingModule.
75/// assert_eq!(report.modules.len(), 2);
76/// ```
77pub struct ConfiguredModule<M, O> {
78    options: Option<O>,
79    register: fn(&mut ModuleBuilder, Option<O>),
80    module: PhantomData<fn() -> M>,
81}
82
83impl<M, O> ConfiguredModule<M, O> {
84    /// `M` configured with `options` (configure a module once, in the app
85    /// root).
86    pub fn for_root(options: O, register: fn(&mut ModuleBuilder, Option<O>)) -> Self {
87        Self {
88            options: Some(options),
89            register,
90            module: PhantomData,
91        }
92    }
93
94    /// `M` configured from the app's configuration: `register` gets `None`.
95    pub fn from_config(register: fn(&mut ModuleBuilder, Option<O>)) -> Self {
96        Self {
97            options: None,
98            register,
99            module: PhantomData,
100        }
101    }
102}
103
104impl<M: 'static, O: Clone + Send + Sync + 'static> Module for ConfiguredModule<M, O> {
105    fn id(&self) -> ModuleId {
106        ModuleId::of::<M>()
107    }
108
109    fn is_configured(&self) -> bool {
110        true
111    }
112
113    fn register(&self, m: &mut ModuleBuilder) {
114        if self.options.is_some() {
115            m.contribute(CodeConfigured {
116                module: ModuleId::of::<M>().name(),
117            });
118        }
119        (self.register)(m, self.options.clone());
120    }
121}
122
123/// Contributed by a module that was given its options in code
124/// (`for_root(options)`), so tools can tell that the section of the
125/// configuration it would otherwise read is not read. navree-config warns
126/// when the configuration has such a section.
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub struct CodeConfigured {
129    module: &'static str,
130}
131
132impl CodeConfigured {
133    /// The short name of the module (`CacheModule`).
134    pub fn module(&self) -> &'static str {
135        self.module
136    }
137}
138
139/// A type the container can construct (what `#[injectable]` implements).
140pub trait Injectable: Sized + Send + Sync + 'static {
141    /// The provider scope; singletons by default.
142    fn scope() -> Scope {
143        Scope::Singleton
144    }
145
146    /// The keys `construct` resolves, used by the boot-time graph check.
147    /// Keys resolved through [`Lazy`](crate::Lazy) are left out.
148    fn dependencies() -> Vec<ProviderKey> {
149        Vec::new()
150    }
151
152    /// Builds the value, resolving dependencies through `r`.
153    fn construct(r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>>;
154}
155
156/// Values accepted by [`ModuleBuilder::imports`]: a module, a tuple of up to
157/// 16 modules, or a `Vec<Box<dyn Module>>`.
158pub trait IntoModules {
159    /// Converts into boxed modules, in order.
160    fn into_modules(self) -> Vec<Box<dyn Module>>;
161}
162
163impl<M: Module> IntoModules for M {
164    fn into_modules(self) -> Vec<Box<dyn Module>> {
165        vec![Box::new(self)]
166    }
167}
168
169impl IntoModules for Vec<Box<dyn Module>> {
170    fn into_modules(self) -> Vec<Box<dyn Module>> {
171        self
172    }
173}
174
175macro_rules! tuple_into_modules {
176    ($($name:ident),+) => {
177        impl<$($name: Module),+> IntoModules for ($($name,)+) {
178            #[allow(non_snake_case)]
179            fn into_modules(self) -> Vec<Box<dyn Module>> {
180                let ($($name,)+) = self;
181                vec![$(Box::new($name) as Box<dyn Module>),+]
182            }
183        }
184    };
185}
186
187tuple_into_modules!(A);
188tuple_into_modules!(A, B);
189tuple_into_modules!(A, B, C);
190tuple_into_modules!(A, B, C, D);
191tuple_into_modules!(A, B, C, D, E);
192tuple_into_modules!(A, B, C, D, E, F);
193tuple_into_modules!(A, B, C, D, E, F, G);
194tuple_into_modules!(A, B, C, D, E, F, G, H);
195tuple_into_modules!(A, B, C, D, E, F, G, H, I);
196tuple_into_modules!(A, B, C, D, E, F, G, H, I, J);
197tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K);
198tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L);
199tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M);
200tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
201tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
202tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);