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