1use 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
15pub(crate) struct Contribution {
18 pub(crate) type_id: TypeId,
20 pub(crate) type_name: &'static str,
22 pub(crate) value: Arc<dyn Any + Send + Sync>,
24}
25
26pub(crate) type Instance = Arc<dyn Any + Send + Sync>;
28
29pub(crate) type ErasedFactory =
31 Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Instance, KernelError>> + Send + Sync>;
32
33#[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 pub(crate) multi: bool,
42}
43
44pub struct PassedModule {
68 pub(crate) module: Box<dyn Module>,
70 pub(crate) type_name: &'static str,
73}
74
75impl PassedModule {
76 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 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 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
107pub 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 pub(crate) plugin: Option<PluginInfo>,
120 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 pub fn module_id(&self) -> ModuleId {
143 self.id
144 }
145
146 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 pub fn import(&mut self, module: impl Module) -> &mut Self {
190 self.imports.push(PassedModule::of(module));
191 self
192 }
193
194 pub fn imports(&mut self, modules: impl IntoModules) -> &mut Self {
196 self.imports.extend(modules.into_passed_modules());
197 self
198 }
199
200 pub fn global(&mut self) -> &mut Self {
202 self.global = true;
203 self
204 }
205
206 pub fn provider<T: Injectable>(&mut self) -> &mut Self {
208 self.injectable::<T>(ProviderKey::of::<T>())
209 }
210
211 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 pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
238 self.value_arc(Arc::new(value))
239 }
240
241 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 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 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 pub fn exports<T: ?Sized + 'static>(&mut self) -> &mut Self {
266 self.export_key(ProviderKey::of::<T>())
267 }
268
269 pub fn export_key(&mut self, key: ProviderKey) -> &mut Self {
271 self.exports.push(key);
272 self
273 }
274
275 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 pub fn lifecycle<T: Lifecycle + Send + Sync + 'static>(&mut self) -> &mut Self {
290 self.lifecycles.push(LifecycleDef::of::<T>());
291 self
292 }
293
294 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
329pub struct Factory<T: ?Sized> {
333 scope: Scope,
334 deps: Vec<ProviderKey>,
335 name: Option<Cow<'static, str>>,
336 build: BuildFn<T>,
337}
338
339type 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 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 pub fn scope(mut self, s: Scope) -> Self {
360 self.scope = s;
361 self
362 }
363
364 pub fn deps(mut self, d: Vec<ProviderKey>) -> Self {
366 self.deps = d;
367 self
368 }
369
370 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
413pub(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
430fn 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 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 struct Single;
459
460 impl Module for Single {
461 fn register(&self, _: &mut ModuleBuilder) {}
462 }
463
464 struct First;
466
467 impl Module for First {
468 fn register(&self, _: &mut ModuleBuilder) {}
469 }
470
471 struct Second;
473
474 impl Module for Second {
475 fn register(&self, _: &mut ModuleBuilder) {}
476 }
477
478 struct Boxed;
480
481 impl Module for Boxed {
482 fn register(&self, _: &mut ModuleBuilder) {}
483 }
484
485 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}