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, ProviderKey, Resolver, Scope,
13};
14
15/// A contributed value, typed by `TypeId`.
16pub(crate) type Contribution = (TypeId, Arc<dyn Any + Send + Sync>);
17
18/// A constructed provider value: an `Arc<T>` behind `dyn Any`.
19pub(crate) type Instance = Arc<dyn Any + Send + Sync>;
20
21/// A type-erased provider constructor.
22pub(crate) type ErasedFactory =
23    Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Instance, KernelError>> + Send + Sync>;
24
25/// One provider registration.
26#[derive(Clone)]
27pub(crate) struct ProviderDef {
28    pub(crate) key: ProviderKey,
29    pub(crate) scope: Scope,
30    pub(crate) deps: Vec<ProviderKey>,
31    pub(crate) factory: ErasedFactory,
32    /// A multi-binding: collected by `get_all`, invisible to `get`.
33    pub(crate) multi: bool,
34}
35
36/// Collects what a module registers. Passed to [`Module::register`].
37pub struct ModuleBuilder {
38    pub(crate) id: ModuleId,
39    pub(crate) name: &'static str,
40    pub(crate) global: bool,
41    pub(crate) imports: Vec<Box<dyn Module>>,
42    pub(crate) providers: Vec<ProviderDef>,
43    pub(crate) exports: Vec<ProviderKey>,
44    pub(crate) contributions: Vec<Contribution>,
45    pub(crate) lifecycles: Vec<LifecycleDef>,
46    pub(crate) commands: Vec<CommandSpec>,
47}
48
49impl ModuleBuilder {
50    pub(crate) fn new(id: ModuleId, name: &'static str) -> Self {
51        Self {
52            id,
53            name,
54            global: false,
55            imports: Vec::new(),
56            providers: Vec::new(),
57            exports: Vec::new(),
58            contributions: Vec::new(),
59            lifecycles: Vec::new(),
60            commands: Vec::new(),
61        }
62    }
63
64    /// The id of the module being registered.
65    pub fn module_id(&self) -> ModuleId {
66        self.id
67    }
68
69    /// Imports a module: its exports become visible to this module.
70    pub fn import(&mut self, module: impl Module) -> &mut Self {
71        self.imports.push(Box::new(module));
72        self
73    }
74
75    /// Imports several modules (a tuple of up to 16 modules or a `Vec<Box<dyn Module>>`).
76    pub fn imports(&mut self, modules: impl IntoModules) -> &mut Self {
77        self.imports.extend(modules.into_modules());
78        self
79    }
80
81    /// Marks the module global: its exports are visible to every module.
82    pub fn global(&mut self) -> &mut Self {
83        self.global = true;
84        self
85    }
86
87    /// Registers `T` under its unnamed key.
88    pub fn provider<T: Injectable>(&mut self) -> &mut Self {
89        self.injectable::<T>(ProviderKey::of::<T>())
90    }
91
92    /// Registers `T` under `name` (resolved with [`Resolver::get_named`]).
93    pub fn provider_named<T: Injectable>(
94        &mut self,
95        name: impl Into<Cow<'static, str>>,
96    ) -> &mut Self {
97        self.injectable::<T>(ProviderKey::named::<T>(name))
98    }
99
100    fn injectable<T: Injectable>(&mut self, key: ProviderKey) -> &mut Self {
101        self.providers.push(ProviderDef {
102            key,
103            scope: T::scope(),
104            deps: T::dependencies(),
105            factory: Arc::new(|r| {
106                Box::pin(async move {
107                    T::construct(r)
108                        .await
109                        .map(|v| Arc::new(Arc::new(v)) as Instance)
110                })
111            }),
112            multi: false,
113        });
114        self
115    }
116
117    /// Registers an already-built singleton value.
118    pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
119        self.value_arc(Arc::new(value))
120    }
121
122    /// Registers an already-built singleton behind an `Arc` (also for `Arc<dyn Trait>`).
123    pub fn value_arc<T: ?Sized + Send + Sync + 'static>(&mut self, value: Arc<T>) -> &mut Self {
124        self.providers
125            .push(value_def(ProviderKey::of::<T>(), value));
126        self
127    }
128
129    /// Registers a provider built by a [`Factory`] (unnamed unless [`Factory::named`] was used).
130    pub fn factory<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
131        self.providers.push(f.into_def());
132        self
133    }
134
135    /// Adds a multi-binding of `T`. Every multi-binding of `T` in the app (in
136    /// module dependency order) is returned by [`Resolver::get_all`] and
137    /// [`AppContext::get_all`](crate::AppContext::get_all); `get::<T>()` does not see them.
138    pub fn multi<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
139        let mut def = f.into_def();
140        def.multi = true;
141        self.providers.push(def);
142        self
143    }
144
145    /// Exports the unnamed provider of `T` to importing modules.
146    pub fn exports<T: ?Sized + 'static>(&mut self) -> &mut Self {
147        self.export_key(ProviderKey::of::<T>())
148    }
149
150    /// Exports a provider key (named or unnamed) to importing modules.
151    pub fn export_key(&mut self, key: ProviderKey) -> &mut Self {
152        self.exports.push(key);
153        self
154    }
155
156    /// Contributes a value that other modules collect with
157    /// [`AppContext::contributions`](crate::AppContext::contributions)
158    /// (routes, migrations, job registrations, ...).
159    pub fn contribute<C: Send + Sync + 'static>(&mut self, c: C) -> &mut Self {
160        self.contributions.push((TypeId::of::<C>(), Arc::new(c)));
161        self
162    }
163
164    /// Runs the [`Lifecycle`] hooks of provider `T`, which must be a provider
165    /// of this module.
166    pub fn lifecycle<T: Lifecycle + Send + Sync + 'static>(&mut self) -> &mut Self {
167        self.lifecycles.push(LifecycleDef::of::<T>());
168        self
169    }
170
171    /// Registers a CLI command (names must be unique across the app).
172    pub fn command(&mut self, cmd: CommandSpec) -> &mut Self {
173        self.commands.push(cmd);
174        self
175    }
176}
177
178impl fmt::Debug for ModuleBuilder {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        f.debug_struct("ModuleBuilder")
181            .field("module", &self.name)
182            .field("global", &self.global)
183            .field("imports", &self.imports.len())
184            .field(
185                "providers",
186                &self
187                    .providers
188                    .iter()
189                    .map(|p| p.key.to_string())
190                    .collect::<Vec<_>>(),
191            )
192            .field(
193                "exports",
194                &self
195                    .exports
196                    .iter()
197                    .map(ToString::to_string)
198                    .collect::<Vec<_>>(),
199            )
200            .finish()
201    }
202}
203
204/// A provider definition for an `Arc<T>` built by an async closure. Use it for
205/// trait objects (`Factory::<dyn Mailer>::new(...)`), named providers and
206/// values that need async setup.
207pub struct Factory<T: ?Sized> {
208    scope: Scope,
209    deps: Vec<ProviderKey>,
210    name: Option<Cow<'static, str>>,
211    build: BuildFn<T>,
212}
213
214/// The closure behind a [`Factory`].
215type BuildFn<T> =
216    Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Arc<T>, BoxError>> + Send + Sync>;
217
218impl<T: ?Sized + Send + Sync + 'static> Factory<T> {
219    /// A singleton factory with no declared dependencies.
220    pub fn new<F, Fut>(f: F) -> Self
221    where
222        F: Fn(Resolver) -> Fut + Send + Sync + 'static,
223        Fut: Future<Output = Result<Arc<T>, BoxError>> + Send + 'static,
224    {
225        Self {
226            scope: Scope::Singleton,
227            deps: Vec::new(),
228            name: None,
229            build: Arc::new(move |r| Box::pin(f(r))),
230        }
231    }
232
233    /// Sets the provider scope.
234    pub fn scope(mut self, s: Scope) -> Self {
235        self.scope = s;
236        self
237    }
238
239    /// Declares the keys the closure resolves, for the boot-time graph check.
240    pub fn deps(mut self, d: Vec<ProviderKey>) -> Self {
241        self.deps = d;
242        self
243    }
244
245    /// Registers the provider under a name instead of the unnamed key.
246    pub fn named(mut self, n: impl Into<Cow<'static, str>>) -> Self {
247        self.name = Some(n.into());
248        self
249    }
250
251    pub(crate) fn into_def(self) -> ProviderDef {
252        let key = match self.name {
253            Some(name) => ProviderKey::named::<T>(name),
254            None => ProviderKey::of::<T>(),
255        };
256        let provider = key.to_string();
257        let build = self.build;
258        ProviderDef {
259            key,
260            scope: self.scope,
261            deps: self.deps,
262            factory: Arc::new(move |r| {
263                let fut = build(r);
264                let provider = provider.clone();
265                Box::pin(async move {
266                    match fut.await {
267                        Ok(value) => Ok(Arc::new(value) as Instance),
268                        Err(error) => Err(into_kernel_error(error, provider)),
269                    }
270                })
271            }),
272            multi: false,
273        }
274    }
275}
276
277impl<T: ?Sized> fmt::Debug for Factory<T> {
278    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279        f.debug_struct("Factory")
280            .field("type", &std::any::type_name::<T>())
281            .field("scope", &self.scope)
282            .field("deps", &self.deps)
283            .field("name", &self.name)
284            .finish()
285    }
286}
287
288/// A singleton definition that always yields `value`.
289pub(crate) fn value_def<T: ?Sized + Send + Sync + 'static>(
290    key: ProviderKey,
291    value: Arc<T>,
292) -> ProviderDef {
293    ProviderDef {
294        key,
295        scope: Scope::Singleton,
296        deps: Vec::new(),
297        factory: Arc::new(move |_| {
298            let instance: Instance = Arc::new(value.clone());
299            Box::pin(async move { Ok(instance) })
300        }),
301        multi: false,
302    }
303}
304
305/// Keeps resolution errors (missing provider, cycle, ...) raised inside a
306/// factory as they are; wraps any other error as a construction failure.
307fn into_kernel_error(error: BoxError, provider: String) -> KernelError {
308    match error.downcast::<KernelError>() {
309        Ok(kernel) => *kernel,
310        Err(source) => KernelError::Construction { provider, source },
311    }
312}