Skip to main content

navree_kernel/
builder.rs

1//! [`ModuleBuilder`] and [`Factory`]: how a module describes what it provides.
2
3use std::any::{Any, TypeId};
4use std::borrow::Cow;
5use std::fmt;
6use std::future::Future;
7use std::sync::Arc;
8
9use crate::lifecycle::LifecycleDef;
10use crate::{
11    BoxError, BoxFuture, CommandSpec, Injectable, IntoModules, KernelError, Lifecycle, Module,
12    ModuleId, PluginInfo, ProviderKey, Resolver, Scope,
13};
14
15/// A contributed value, typed by `TypeId`, with the type's name for the
16/// per-type counts of the plugins report.
17pub(crate) struct Contribution {
18    /// The type of the value.
19    pub(crate) type_id: TypeId,
20    /// `std::any::type_name` of the value's type.
21    pub(crate) type_name: &'static str,
22    /// The value, an `Arc<C>` behind `dyn Any`.
23    pub(crate) value: Arc<dyn Any + Send + Sync>,
24}
25
26/// A constructed provider value: an `Arc<T>` behind `dyn Any`.
27pub(crate) type Instance = Arc<dyn Any + Send + Sync>;
28
29/// A type-erased provider constructor.
30pub(crate) type ErasedFactory =
31    Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Instance, KernelError>> + Send + Sync>;
32
33/// One provider registration.
34#[derive(Clone)]
35pub(crate) struct ProviderDef {
36    pub(crate) key: ProviderKey,
37    pub(crate) scope: Scope,
38    pub(crate) deps: Vec<ProviderKey>,
39    pub(crate) factory: ErasedFactory,
40    /// A multi-binding: collected by `get_all`, invisible to `get`.
41    pub(crate) multi: bool,
42}
43
44/// A module value as the app or an importing module passed it, with the type
45/// it was passed as: the module's own type, which the plugin checks read,
46/// whatever type its id names. It is made only from a typed value, so the
47/// type it records is always the value's own: no crate can write it out or
48/// change it, an implementation of [`IntoModules`] included. Not public API;
49/// Navree's own crates use it.
50///
51/// ```compile_fail
52/// use navree_kernel::__private::PassedModule;
53/// use navree_kernel::{Module, ModuleBuilder};
54///
55/// struct Claim;
56///
57/// impl Module for Claim {
58///     fn register(&self, _: &mut ModuleBuilder) {}
59/// }
60///
61/// // The type it records is the kernel's to write: its fields are private.
62/// let _ = PassedModule {
63///     module: Box::new(Claim),
64///     type_name: "navree_flags::module::FlagsModule",
65/// };
66/// ```
67pub struct PassedModule {
68    /// The module.
69    pub(crate) module: Box<dyn Module>,
70    /// `std::any::type_name` of the value passed (that of `Box<dyn Module>` for
71    /// a module passed already boxed).
72    pub(crate) type_name: &'static str,
73}
74
75impl PassedModule {
76    /// `module`, passed as a value of type `M`: it records `M`'s type.
77    pub fn of<M: Module>(module: M) -> PassedModule {
78        PassedModule {
79            module: Box::new(module),
80            type_name: std::any::type_name::<M>(),
81        }
82    }
83
84    /// `module`, passed already boxed: it records the type `Box<dyn Module>`.
85    pub(crate) fn boxed(module: Box<dyn Module>) -> PassedModule {
86        PassedModule {
87            module,
88            type_name: std::any::type_name::<Box<dyn Module>>(),
89        }
90    }
91
92    /// The module's readable name.
93    pub fn name(&self) -> &'static str {
94        self.module.name()
95    }
96}
97
98impl fmt::Debug for PassedModule {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.debug_struct("PassedModule")
101            .field("module", &self.module.name())
102            .field("type_name", &self.type_name)
103            .finish()
104    }
105}
106
107/// Collects what a module registers. Passed to [`Module::register`].
108pub struct ModuleBuilder {
109    pub(crate) id: ModuleId,
110    pub(crate) name: &'static str,
111    pub(crate) global: bool,
112    pub(crate) imports: Vec<PassedModule>,
113    pub(crate) providers: Vec<ProviderDef>,
114    pub(crate) exports: Vec<ProviderKey>,
115    pub(crate) contributions: Vec<Contribution>,
116    pub(crate) lifecycles: Vec<LifecycleDef>,
117    pub(crate) commands: Vec<CommandSpec>,
118    /// The plugin the module names itself, from the first `plugin` call.
119    pub(crate) plugin: Option<PluginInfo>,
120    /// Whether `plugin` was called more than once (a boot error).
121    pub(crate) plugin_twice: bool,
122}
123
124impl ModuleBuilder {
125    pub(crate) fn new(id: ModuleId, name: &'static str) -> Self {
126        Self {
127            id,
128            name,
129            global: false,
130            imports: Vec::new(),
131            providers: Vec::new(),
132            exports: Vec::new(),
133            contributions: Vec::new(),
134            lifecycles: Vec::new(),
135            commands: Vec::new(),
136            plugin: None,
137            plugin_twice: false,
138        }
139    }
140
141    /// The id of the module being registered.
142    pub fn module_id(&self) -> ModuleId {
143        self.id
144    }
145
146    /// Names this module a plugin. Call it once in `register`; several modules
147    /// of one crate may each call it with the same [`PluginInfo`], and are then
148    /// one plugin. The kernel records it
149    /// ([`AppContext::plugin`](crate::AppContext::plugin), the `plugins`
150    /// command) and checks its name, crate, version and namespace at boot.
151    /// Naming a plugin grants nothing.
152    ///
153    /// A module that acts for a plugin which is not one of the framework's own
154    /// packages may not configure a module of another crate, nor provide a
155    /// permission check, the route authorizer, the authenticator, a sign-in
156    /// strategy, the workspace gate, where native clients sign in, the options
157    /// of access, workspaces, authentication or the admin panel, the app's
158    /// shell, its clock, an observer of every commit, the sink of its audit
159    /// records, its realtime backplane, or the fake that silences its model
160    /// listeners, nor hook a model of another crate, nor register a command with
161    /// the name of one of the framework's own (`plugins`, `check`, ..): the
162    /// boot fails, and the app registers the plugin's from a module of its own.
163    ///
164    /// ```no_run
165    /// use navree_kernel::{Module, ModuleBuilder, Navree};
166    ///
167    /// struct AnnouncementsModule;
168    ///
169    /// impl Module for AnnouncementsModule {
170    ///     fn register(&self, m: &mut ModuleBuilder) {
171    ///         m.plugin(navree_kernel::plugin_info!(title = "Announcements"));
172    ///     }
173    /// }
174    ///
175    /// fn main() -> Result<(), navree_kernel::BoxError> {
176    ///     Navree::app().module(AnnouncementsModule).run()
177    /// }
178    /// ```
179    pub fn plugin(&mut self, info: PluginInfo) -> &mut Self {
180        if self.plugin.is_some() {
181            self.plugin_twice = true;
182        } else {
183            self.plugin = Some(info);
184        }
185        self
186    }
187
188    /// Imports a module: its exports become visible to this module.
189    pub fn import(&mut self, module: impl Module) -> &mut Self {
190        self.imports.push(PassedModule::of(module));
191        self
192    }
193
194    /// Imports several modules (a tuple of up to 16 modules or a `Vec<Box<dyn Module>>`).
195    pub fn imports(&mut self, modules: impl IntoModules) -> &mut Self {
196        self.imports.extend(modules.into_passed_modules());
197        self
198    }
199
200    /// Marks the module global: its exports are visible to every module.
201    pub fn global(&mut self) -> &mut Self {
202        self.global = true;
203        self
204    }
205
206    /// Registers `T` under its unnamed key.
207    pub fn provider<T: Injectable>(&mut self) -> &mut Self {
208        self.injectable::<T>(ProviderKey::of::<T>())
209    }
210
211    /// Registers `T` under `name` (resolved with [`Resolver::get_named`]).
212    pub fn provider_named<T: Injectable>(
213        &mut self,
214        name: impl Into<Cow<'static, str>>,
215    ) -> &mut Self {
216        self.injectable::<T>(ProviderKey::named::<T>(name))
217    }
218
219    fn injectable<T: Injectable>(&mut self, key: ProviderKey) -> &mut Self {
220        self.providers.push(ProviderDef {
221            key,
222            scope: T::scope(),
223            deps: T::dependencies(),
224            factory: Arc::new(|r| {
225                Box::pin(async move {
226                    T::construct(r)
227                        .await
228                        .map(|v| Arc::new(Arc::new(v)) as Instance)
229                })
230            }),
231            multi: false,
232        });
233        self
234    }
235
236    /// Registers an already-built singleton value.
237    pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
238        self.value_arc(Arc::new(value))
239    }
240
241    /// Registers an already-built singleton behind an `Arc` (also for `Arc<dyn Trait>`).
242    pub fn value_arc<T: ?Sized + Send + Sync + 'static>(&mut self, value: Arc<T>) -> &mut Self {
243        self.providers
244            .push(value_def(ProviderKey::of::<T>(), value));
245        self
246    }
247
248    /// Registers a provider built by a [`Factory`] (unnamed unless [`Factory::named`] was used).
249    pub fn factory<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
250        self.providers.push(f.into_def());
251        self
252    }
253
254    /// Adds a multi-binding of `T`. Every multi-binding of `T` in the app (in
255    /// module dependency order) is returned by [`Resolver::get_all`] and
256    /// [`AppContext::get_all`](crate::AppContext::get_all); `get::<T>()` does not see them.
257    pub fn multi<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
258        let mut def = f.into_def();
259        def.multi = true;
260        self.providers.push(def);
261        self
262    }
263
264    /// Exports the unnamed provider of `T` to importing modules.
265    pub fn exports<T: ?Sized + 'static>(&mut self) -> &mut Self {
266        self.export_key(ProviderKey::of::<T>())
267    }
268
269    /// Exports a provider key (named or unnamed) to importing modules.
270    pub fn export_key(&mut self, key: ProviderKey) -> &mut Self {
271        self.exports.push(key);
272        self
273    }
274
275    /// Contributes a value that other modules collect with
276    /// [`AppContext::contributions`](crate::AppContext::contributions)
277    /// (routes, migrations, job registrations, ...).
278    pub fn contribute<C: Send + Sync + 'static>(&mut self, c: C) -> &mut Self {
279        self.contributions.push(Contribution {
280            type_id: TypeId::of::<C>(),
281            type_name: std::any::type_name::<C>(),
282            value: Arc::new(c),
283        });
284        self
285    }
286
287    /// Runs the [`Lifecycle`] hooks of provider `T`, which must be a provider
288    /// of this module.
289    pub fn lifecycle<T: Lifecycle + Send + Sync + 'static>(&mut self) -> &mut Self {
290        self.lifecycles.push(LifecycleDef::of::<T>());
291        self
292    }
293
294    /// Registers a CLI command (names must be unique across the app). A module
295    /// of a plugin that is not one of the framework's own may not take the name
296    /// of one of the framework's commands (`plugins`, `check`, `help`, ..).
297    pub fn command(&mut self, cmd: CommandSpec) -> &mut Self {
298        self.commands.push(cmd);
299        self
300    }
301}
302
303impl fmt::Debug for ModuleBuilder {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        f.debug_struct("ModuleBuilder")
306            .field("module", &self.name)
307            .field("global", &self.global)
308            .field("imports", &self.imports.len())
309            .field(
310                "providers",
311                &self
312                    .providers
313                    .iter()
314                    .map(|p| p.key.to_string())
315                    .collect::<Vec<_>>(),
316            )
317            .field(
318                "exports",
319                &self
320                    .exports
321                    .iter()
322                    .map(ToString::to_string)
323                    .collect::<Vec<_>>(),
324            )
325            .finish()
326    }
327}
328
329/// A provider definition for an `Arc<T>` built by an async closure. Use it for
330/// trait objects (`Factory::<dyn Mailer>::new(...)`), named providers and
331/// values that need async setup.
332pub struct Factory<T: ?Sized> {
333    scope: Scope,
334    deps: Vec<ProviderKey>,
335    name: Option<Cow<'static, str>>,
336    build: BuildFn<T>,
337}
338
339/// The closure behind a [`Factory`].
340type BuildFn<T> =
341    Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Arc<T>, BoxError>> + Send + Sync>;
342
343impl<T: ?Sized + Send + Sync + 'static> Factory<T> {
344    /// A singleton factory with no declared dependencies.
345    pub fn new<F, Fut>(f: F) -> Self
346    where
347        F: Fn(Resolver) -> Fut + Send + Sync + 'static,
348        Fut: Future<Output = Result<Arc<T>, BoxError>> + Send + 'static,
349    {
350        Self {
351            scope: Scope::Singleton,
352            deps: Vec::new(),
353            name: None,
354            build: Arc::new(move |r| Box::pin(f(r))),
355        }
356    }
357
358    /// Sets the provider scope.
359    pub fn scope(mut self, s: Scope) -> Self {
360        self.scope = s;
361        self
362    }
363
364    /// Declares the keys the closure resolves, for the boot-time graph check.
365    pub fn deps(mut self, d: Vec<ProviderKey>) -> Self {
366        self.deps = d;
367        self
368    }
369
370    /// Registers the provider under a name instead of the unnamed key.
371    pub fn named(mut self, n: impl Into<Cow<'static, str>>) -> Self {
372        self.name = Some(n.into());
373        self
374    }
375
376    pub(crate) fn into_def(self) -> ProviderDef {
377        let key = match self.name {
378            Some(name) => ProviderKey::named::<T>(name),
379            None => ProviderKey::of::<T>(),
380        };
381        let provider = key.to_string();
382        let build = self.build;
383        ProviderDef {
384            key,
385            scope: self.scope,
386            deps: self.deps,
387            factory: Arc::new(move |r| {
388                let fut = build(r);
389                let provider = provider.clone();
390                Box::pin(async move {
391                    match fut.await {
392                        Ok(value) => Ok(Arc::new(value) as Instance),
393                        Err(error) => Err(into_kernel_error(error, provider)),
394                    }
395                })
396            }),
397            multi: false,
398        }
399    }
400}
401
402impl<T: ?Sized> fmt::Debug for Factory<T> {
403    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        f.debug_struct("Factory")
405            .field("type", &std::any::type_name::<T>())
406            .field("scope", &self.scope)
407            .field("deps", &self.deps)
408            .field("name", &self.name)
409            .finish()
410    }
411}
412
413/// A singleton definition that always yields `value`.
414pub(crate) fn value_def<T: ?Sized + Send + Sync + 'static>(
415    key: ProviderKey,
416    value: Arc<T>,
417) -> ProviderDef {
418    ProviderDef {
419        key,
420        scope: Scope::Singleton,
421        deps: Vec::new(),
422        factory: Arc::new(move |_| {
423            let instance: Instance = Arc::new(value.clone());
424            Box::pin(async move { Ok(instance) })
425        }),
426        multi: false,
427    }
428}
429
430/// Keeps resolution errors (missing provider, cycle, ...) raised inside a
431/// factory as they are; wraps any other error as a construction failure.
432fn into_kernel_error(error: BoxError, provider: String) -> KernelError {
433    match error.downcast::<KernelError>() {
434        Ok(kernel) => *kernel,
435        Err(source) => KernelError::Construction { provider, source },
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442    use crate::ConfiguredModule;
443    use crate::graph::Graph;
444
445    /// The app's module: it imports a module of each shape the kernel takes.
446    struct Root;
447
448    impl Module for Root {
449        fn register(&self, m: &mut ModuleBuilder) {
450            m.import(Single)
451                .imports((First, Second))
452                .imports(vec![Box::new(Boxed) as Box<dyn Module>])
453                .import(ConfiguredModule::<Configured, ()>::for_root((), |_, _| {}));
454        }
455    }
456
457    /// Imported alone.
458    struct Single;
459
460    impl Module for Single {
461        fn register(&self, _: &mut ModuleBuilder) {}
462    }
463
464    /// Imported in a tuple.
465    struct First;
466
467    impl Module for First {
468        fn register(&self, _: &mut ModuleBuilder) {}
469    }
470
471    /// Imported in a tuple, after `First`.
472    struct Second;
473
474    impl Module for Second {
475        fn register(&self, _: &mut ModuleBuilder) {}
476    }
477
478    /// Imported already boxed.
479    struct Boxed;
480
481    impl Module for Boxed {
482        fn register(&self, _: &mut ModuleBuilder) {}
483    }
484
485    /// Imported configured.
486    struct Configured;
487
488    impl Module for Configured {
489        fn register(&self, _: &mut ModuleBuilder) {}
490    }
491
492    #[test]
493    fn each_way_of_passing_a_module_records_the_type_it_was_passed_as() {
494        use std::any::type_name;
495
496        let graph = Graph::build_passed(&[PassedModule::of(Root)], &[]).expect("valid");
497        let recorded = |id: ModuleId| {
498            let m = graph.module_of(id).expect("in the graph");
499            graph.modules[m].type_name
500        };
501        assert_eq!(recorded(ModuleId::of::<Root>()), type_name::<Root>());
502        assert_eq!(recorded(ModuleId::of::<Single>()), type_name::<Single>());
503        assert_eq!(recorded(ModuleId::of::<First>()), type_name::<First>());
504        assert_eq!(recorded(ModuleId::of::<Second>()), type_name::<Second>());
505        assert_eq!(
506            recorded(ModuleId::of::<Boxed>()),
507            type_name::<Box<dyn Module>>()
508        );
509        assert_eq!(
510            recorded(ModuleId::of::<Configured>()),
511            type_name::<ConfiguredModule<Configured, ()>>()
512        );
513    }
514
515    #[test]
516    fn contribute_records_the_type_name_for_the_counts() {
517        struct Notice;
518        let mut m = ModuleBuilder::new(ModuleId::of::<Notice>(), "Notice");
519        m.contribute(1_u8)
520            .contribute(2_u8)
521            .contribute(String::from("Ludhiana"));
522        let names: Vec<&str> = m.contributions.iter().map(|c| c.type_name).collect();
523        assert_eq!(names, ["u8", "u8", "alloc::string::String"]);
524        assert_eq!(m.contributions[2].type_id, TypeId::of::<String>());
525    }
526}