navree-kernel 1.4.0

Navree kernel: module graph, type-keyed DI container, lifecycle and command runner.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! [`ModuleBuilder`] and [`Factory`]: how a module describes what it provides.

use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::fmt;
use std::future::Future;
use std::sync::Arc;

use crate::lifecycle::LifecycleDef;
use crate::{
    BoxError, BoxFuture, CommandSpec, Injectable, IntoModules, KernelError, Lifecycle, Module,
    ModuleId, PluginInfo, ProviderKey, Resolver, Scope,
};

/// A contributed value, typed by `TypeId`, with the type's name for the
/// per-type counts of the plugins report.
pub(crate) struct Contribution {
    /// The type of the value.
    pub(crate) type_id: TypeId,
    /// `std::any::type_name` of the value's type.
    pub(crate) type_name: &'static str,
    /// The value, an `Arc<C>` behind `dyn Any`.
    pub(crate) value: Arc<dyn Any + Send + Sync>,
}

/// A constructed provider value: an `Arc<T>` behind `dyn Any`.
pub(crate) type Instance = Arc<dyn Any + Send + Sync>;

/// A type-erased provider constructor.
pub(crate) type ErasedFactory =
    Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Instance, KernelError>> + Send + Sync>;

/// One provider registration.
#[derive(Clone)]
pub(crate) struct ProviderDef {
    pub(crate) key: ProviderKey,
    pub(crate) scope: Scope,
    pub(crate) deps: Vec<ProviderKey>,
    pub(crate) factory: ErasedFactory,
    /// A multi-binding: collected by `get_all`, invisible to `get`.
    pub(crate) multi: bool,
}

/// A module value as the app or an importing module passed it, with the type
/// it was passed as: the module's own type, which the plugin checks read,
/// whatever type its id names. It is made only from a typed value, so the
/// type it records is always the value's own: no crate can write it out or
/// change it, an implementation of [`IntoModules`] included. Not public API;
/// Navree's own crates use it.
///
/// ```compile_fail
/// use navree_kernel::__private::PassedModule;
/// use navree_kernel::{Module, ModuleBuilder};
///
/// struct Claim;
///
/// impl Module for Claim {
///     fn register(&self, _: &mut ModuleBuilder) {}
/// }
///
/// // The type it records is the kernel's to write: its fields are private.
/// let _ = PassedModule {
///     module: Box::new(Claim),
///     type_name: "navree_flags::module::FlagsModule",
/// };
/// ```
pub struct PassedModule {
    /// The module.
    pub(crate) module: Box<dyn Module>,
    /// `std::any::type_name` of the value passed (that of `Box<dyn Module>` for
    /// a module passed already boxed).
    pub(crate) type_name: &'static str,
}

impl PassedModule {
    /// `module`, passed as a value of type `M`: it records `M`'s concrete type
    /// (unwrapping erased `dyn Module` wrappers).
    pub fn of<M: Module>(module: M) -> PassedModule {
        let type_name = crate::module::resolved_type_name(&module);
        PassedModule {
            module: Box::new(module),
            type_name,
        }
    }

    /// `module`, passed already boxed: it recovers the inner module's concrete
    /// type.
    pub(crate) fn boxed(module: Box<dyn Module>) -> PassedModule {
        let type_name = crate::module::resolved_type_name(module.as_ref());
        PassedModule { module, type_name }
    }

    /// The module's readable name.
    pub fn name(&self) -> &'static str {
        self.module.name()
    }
}

impl fmt::Debug for PassedModule {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PassedModule")
            .field("module", &self.module.name())
            .field("type_name", &self.type_name)
            .finish()
    }
}

/// Collects what a module registers. Passed to [`Module::register`].
pub struct ModuleBuilder {
    pub(crate) id: ModuleId,
    pub(crate) name: &'static str,
    pub(crate) global: bool,
    pub(crate) imports: Vec<PassedModule>,
    pub(crate) providers: Vec<ProviderDef>,
    pub(crate) exports: Vec<ProviderKey>,
    pub(crate) contributions: Vec<Contribution>,
    pub(crate) lifecycles: Vec<LifecycleDef>,
    pub(crate) commands: Vec<CommandSpec>,
    /// The plugin the module names itself, from the first `plugin` call.
    pub(crate) plugin: Option<PluginInfo>,
    /// Whether `plugin` was called more than once (a boot error).
    pub(crate) plugin_twice: bool,
}

impl ModuleBuilder {
    pub(crate) fn new(id: ModuleId, name: &'static str) -> Self {
        Self {
            id,
            name,
            global: false,
            imports: Vec::new(),
            providers: Vec::new(),
            exports: Vec::new(),
            contributions: Vec::new(),
            lifecycles: Vec::new(),
            commands: Vec::new(),
            plugin: None,
            plugin_twice: false,
        }
    }

    /// The id of the module being registered.
    pub fn module_id(&self) -> ModuleId {
        self.id
    }

    /// Names this module a plugin. Call it once in `register`; several modules
    /// of one crate may each call it with the same [`PluginInfo`], and are then
    /// one plugin. The kernel records it
    /// ([`AppContext::plugin`](crate::AppContext::plugin), the `plugins`
    /// command) and checks its name, crate, version and namespace at boot.
    /// Naming a plugin grants nothing.
    ///
    /// A module that acts for a plugin which is not one of the framework's own
    /// packages may not configure a module of another crate, nor provide a
    /// permission check, the route authorizer, the authenticator, a sign-in
    /// strategy, the workspace gate, where native clients sign in, the options
    /// of access, workspaces, authentication or the admin panel, the app's
    /// shell, its clock, an observer of every commit, the sink of its audit
    /// records, its realtime backplane, or the fake that silences its model
    /// listeners, nor hook a model of another crate, nor register a command with
    /// the name of one of the framework's own (`plugins`, `check`, ..): the
    /// boot fails, and the app registers the plugin's from a module of its own.
    ///
    /// ```no_run
    /// use navree_kernel::{Module, ModuleBuilder, Navree};
    ///
    /// struct AnnouncementsModule;
    ///
    /// impl Module for AnnouncementsModule {
    ///     fn register(&self, m: &mut ModuleBuilder) {
    ///         m.plugin(navree_kernel::plugin_info!(title = "Announcements"));
    ///     }
    /// }
    ///
    /// fn main() -> Result<(), navree_kernel::BoxError> {
    ///     Navree::app().module(AnnouncementsModule).run()
    /// }
    /// ```
    pub fn plugin(&mut self, info: PluginInfo) -> &mut Self {
        if self.plugin.is_some() {
            self.plugin_twice = true;
        } else {
            self.plugin = Some(info);
        }
        self
    }

    /// Imports a module: its exports become visible to this module.
    pub fn import(&mut self, module: impl Module) -> &mut Self {
        self.imports.push(PassedModule::of(module));
        self
    }

    /// Imports several modules (a tuple of up to 16 modules or a `Vec<Box<dyn Module>>`).
    pub fn imports(&mut self, modules: impl IntoModules) -> &mut Self {
        self.imports.extend(modules.into_passed_modules());
        self
    }

    /// Marks the module global: its exports are visible to every module.
    pub fn global(&mut self) -> &mut Self {
        self.global = true;
        self
    }

    /// Registers `T` under its unnamed key.
    pub fn provider<T: Injectable>(&mut self) -> &mut Self {
        self.injectable::<T>(ProviderKey::of::<T>())
    }

    /// Registers `T` under `name` (resolved with [`Resolver::get_named`]).
    pub fn provider_named<T: Injectable>(
        &mut self,
        name: impl Into<Cow<'static, str>>,
    ) -> &mut Self {
        self.injectable::<T>(ProviderKey::named::<T>(name))
    }

    fn injectable<T: Injectable>(&mut self, key: ProviderKey) -> &mut Self {
        self.providers.push(ProviderDef {
            key,
            scope: T::scope(),
            deps: T::dependencies(),
            factory: Arc::new(|r| {
                Box::pin(async move {
                    T::construct(r)
                        .await
                        .map(|v| Arc::new(Arc::new(v)) as Instance)
                })
            }),
            multi: false,
        });
        self
    }

    /// Registers an already-built singleton value.
    pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
        self.value_arc(Arc::new(value))
    }

    /// Registers an already-built singleton behind an `Arc` (also for `Arc<dyn Trait>`).
    pub fn value_arc<T: ?Sized + Send + Sync + 'static>(&mut self, value: Arc<T>) -> &mut Self {
        self.providers
            .push(value_def(ProviderKey::of::<T>(), value));
        self
    }

    /// Registers a provider built by a [`Factory`] (unnamed unless [`Factory::named`] was used).
    pub fn factory<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
        self.providers.push(f.into_def());
        self
    }

    /// Adds a multi-binding of `T`. Every multi-binding of `T` in the app (in
    /// module dependency order) is returned by [`Resolver::get_all`] and
    /// [`AppContext::get_all`](crate::AppContext::get_all); `get::<T>()` does not see them.
    pub fn multi<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
        let mut def = f.into_def();
        def.multi = true;
        self.providers.push(def);
        self
    }

    /// Exports the unnamed provider of `T` to importing modules.
    pub fn exports<T: ?Sized + 'static>(&mut self) -> &mut Self {
        self.export_key(ProviderKey::of::<T>())
    }

    /// Exports a provider key (named or unnamed) to importing modules.
    pub fn export_key(&mut self, key: ProviderKey) -> &mut Self {
        self.exports.push(key);
        self
    }

    /// Contributes a value that other modules collect with
    /// [`AppContext::contributions`](crate::AppContext::contributions)
    /// (routes, migrations, job registrations, ...).
    pub fn contribute<C: Send + Sync + 'static>(&mut self, c: C) -> &mut Self {
        self.contributions.push(Contribution {
            type_id: TypeId::of::<C>(),
            type_name: std::any::type_name::<C>(),
            value: Arc::new(c),
        });
        self
    }

    /// Runs the [`Lifecycle`] hooks of provider `T`, which must be a provider
    /// of this module.
    pub fn lifecycle<T: Lifecycle + Send + Sync + 'static>(&mut self) -> &mut Self {
        self.lifecycles.push(LifecycleDef::of::<T>());
        self
    }

    /// Registers a CLI command (names must be unique across the app). A module
    /// of a plugin that is not one of the framework's own may not take the name
    /// of one of the framework's commands (`plugins`, `check`, `help`, ..).
    pub fn command(&mut self, cmd: CommandSpec) -> &mut Self {
        self.commands.push(cmd);
        self
    }
}

impl fmt::Debug for ModuleBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ModuleBuilder")
            .field("module", &self.name)
            .field("global", &self.global)
            .field("imports", &self.imports.len())
            .field(
                "providers",
                &self
                    .providers
                    .iter()
                    .map(|p| p.key.to_string())
                    .collect::<Vec<_>>(),
            )
            .field(
                "exports",
                &self
                    .exports
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

/// A provider definition for an `Arc<T>` built by an async closure. Use it for
/// trait objects (`Factory::<dyn Mailer>::new(...)`), named providers and
/// values that need async setup.
pub struct Factory<T: ?Sized> {
    scope: Scope,
    deps: Vec<ProviderKey>,
    name: Option<Cow<'static, str>>,
    build: BuildFn<T>,
}

/// The closure behind a [`Factory`].
type BuildFn<T> =
    Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Arc<T>, BoxError>> + Send + Sync>;

impl<T: ?Sized + Send + Sync + 'static> Factory<T> {
    /// A singleton factory with no declared dependencies.
    pub fn new<F, Fut>(f: F) -> Self
    where
        F: Fn(Resolver) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Arc<T>, BoxError>> + Send + 'static,
    {
        Self {
            scope: Scope::Singleton,
            deps: Vec::new(),
            name: None,
            build: Arc::new(move |r| Box::pin(f(r))),
        }
    }

    /// Sets the provider scope.
    pub fn scope(mut self, s: Scope) -> Self {
        self.scope = s;
        self
    }

    /// Declares the keys the closure resolves, for the boot-time graph check.
    pub fn deps(mut self, d: Vec<ProviderKey>) -> Self {
        self.deps = d;
        self
    }

    /// Registers the provider under a name instead of the unnamed key.
    pub fn named(mut self, n: impl Into<Cow<'static, str>>) -> Self {
        self.name = Some(n.into());
        self
    }

    pub(crate) fn into_def(self) -> ProviderDef {
        let key = match self.name {
            Some(name) => ProviderKey::named::<T>(name),
            None => ProviderKey::of::<T>(),
        };
        let provider = key.to_string();
        let build = self.build;
        ProviderDef {
            key,
            scope: self.scope,
            deps: self.deps,
            factory: Arc::new(move |r| {
                let fut = build(r);
                let provider = provider.clone();
                Box::pin(async move {
                    match fut.await {
                        Ok(value) => Ok(Arc::new(value) as Instance),
                        Err(error) => Err(into_kernel_error(error, provider)),
                    }
                })
            }),
            multi: false,
        }
    }
}

impl<T: ?Sized> fmt::Debug for Factory<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Factory")
            .field("type", &std::any::type_name::<T>())
            .field("scope", &self.scope)
            .field("deps", &self.deps)
            .field("name", &self.name)
            .finish()
    }
}

/// A singleton definition that always yields `value`.
pub(crate) fn value_def<T: ?Sized + Send + Sync + 'static>(
    key: ProviderKey,
    value: Arc<T>,
) -> ProviderDef {
    ProviderDef {
        key,
        scope: Scope::Singleton,
        deps: Vec::new(),
        factory: Arc::new(move |_| {
            let instance: Instance = Arc::new(value.clone());
            Box::pin(async move { Ok(instance) })
        }),
        multi: false,
    }
}

/// Keeps resolution errors (missing provider, cycle, ...) raised inside a
/// factory as they are; wraps any other error as a construction failure.
fn into_kernel_error(error: BoxError, provider: String) -> KernelError {
    match error.downcast::<KernelError>() {
        Ok(kernel) => *kernel,
        Err(source) => KernelError::Construction { provider, source },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ConfiguredModule;
    use crate::graph::Graph;

    /// The app's module: it imports a module of each shape the kernel takes.
    struct Root;

    impl Module for Root {
        fn register(&self, m: &mut ModuleBuilder) {
            m.import(Single)
                .imports((First, Second))
                .imports(vec![Box::new(Boxed) as Box<dyn Module>])
                .import(ConfiguredModule::<Configured, ()>::for_root((), |_, _| {}));
        }
    }

    /// Imported alone.
    struct Single;

    impl Module for Single {
        fn register(&self, _: &mut ModuleBuilder) {}
    }

    /// Imported in a tuple.
    struct First;

    impl Module for First {
        fn register(&self, _: &mut ModuleBuilder) {}
    }

    /// Imported in a tuple, after `First`.
    struct Second;

    impl Module for Second {
        fn register(&self, _: &mut ModuleBuilder) {}
    }

    /// Imported already boxed.
    struct Boxed;

    impl Module for Boxed {
        fn register(&self, _: &mut ModuleBuilder) {}
    }

    /// Imported configured.
    struct Configured;

    impl Module for Configured {
        fn register(&self, _: &mut ModuleBuilder) {}
    }

    #[test]
    fn each_way_of_passing_a_module_records_the_type_it_was_passed_as() {
        use std::any::type_name;

        let graph = Graph::build_passed(&[PassedModule::of(Root)], &[]).expect("valid");
        let recorded = |id: ModuleId| {
            let m = graph.module_of(id).expect("in the graph");
            graph.modules[m].type_name
        };
        assert_eq!(recorded(ModuleId::of::<Root>()), type_name::<Root>());
        assert_eq!(recorded(ModuleId::of::<Single>()), type_name::<Single>());
        assert_eq!(recorded(ModuleId::of::<First>()), type_name::<First>());
        assert_eq!(recorded(ModuleId::of::<Second>()), type_name::<Second>());
        assert_eq!(recorded(ModuleId::of::<Boxed>()), type_name::<Boxed>());
        assert_eq!(
            recorded(ModuleId::of::<Configured>()),
            type_name::<ConfiguredModule<Configured, ()>>()
        );

        // Nested `Box<dyn Module>` and `Pin<Box<dyn Module>>` wrappers recover the inner
        // concrete module type as well.
        let nested_box: Box<dyn Module> = Box::new(Box::new(Single) as Box<dyn Module>);
        assert_eq!(
            PassedModule::boxed(nested_box).type_name,
            type_name::<Single>()
        );
        let direct_box: Box<dyn Module> = Box::new(Single);
        assert_eq!(
            PassedModule::of(direct_box).type_name,
            type_name::<Single>()
        );
        let pinned: std::pin::Pin<Box<dyn Module>> = Box::pin(Single);
        assert_eq!(PassedModule::of(pinned).type_name, type_name::<Single>());
    }

    #[test]
    fn contribute_records_the_type_name_for_the_counts() {
        struct Notice;
        let mut m = ModuleBuilder::new(ModuleId::of::<Notice>(), "Notice");
        m.contribute(1_u8)
            .contribute(2_u8)
            .contribute(String::from("Ludhiana"));
        let names: Vec<&str> = m.contributions.iter().map(|c| c.type_name).collect();
        assert_eq!(names, ["u8", "u8", "alloc::string::String"]);
        assert_eq!(m.contributions[2].type_id, TypeId::of::<String>());
    }
}