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 {
79 let type_name = crate::module::resolved_type_name(&module);
80 PassedModule {
81 module: Box::new(module),
82 type_name,
83 }
84 }
85
86 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 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
108pub 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 pub(crate) plugin: Option<PluginInfo>,
121 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 pub fn module_id(&self) -> ModuleId {
144 self.id
145 }
146
147 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 pub fn import(&mut self, module: impl Module) -> &mut Self {
191 self.imports.push(PassedModule::of(module));
192 self
193 }
194
195 pub fn imports(&mut self, modules: impl IntoModules) -> &mut Self {
197 self.imports.extend(modules.into_passed_modules());
198 self
199 }
200
201 pub fn global(&mut self) -> &mut Self {
203 self.global = true;
204 self
205 }
206
207 pub fn provider<T: Injectable>(&mut self) -> &mut Self {
209 self.injectable::<T>(ProviderKey::of::<T>())
210 }
211
212 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 pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
239 self.value_arc(Arc::new(value))
240 }
241
242 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 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 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 pub fn exports<T: ?Sized + 'static>(&mut self) -> &mut Self {
267 self.export_key(ProviderKey::of::<T>())
268 }
269
270 pub fn export_key(&mut self, key: ProviderKey) -> &mut Self {
272 self.exports.push(key);
273 self
274 }
275
276 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 pub fn lifecycle<T: Lifecycle + Send + Sync + 'static>(&mut self) -> &mut Self {
291 self.lifecycles.push(LifecycleDef::of::<T>());
292 self
293 }
294
295 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
330pub struct Factory<T: ?Sized> {
334 scope: Scope,
335 deps: Vec<ProviderKey>,
336 name: Option<Cow<'static, str>>,
337 build: BuildFn<T>,
338}
339
340type 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 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 pub fn scope(mut self, s: Scope) -> Self {
361 self.scope = s;
362 self
363 }
364
365 pub fn deps(mut self, d: Vec<ProviderKey>) -> Self {
367 self.deps = d;
368 self
369 }
370
371 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
414pub(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
431fn 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 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 struct Single;
460
461 impl Module for Single {
462 fn register(&self, _: &mut ModuleBuilder) {}
463 }
464
465 struct First;
467
468 impl Module for First {
469 fn register(&self, _: &mut ModuleBuilder) {}
470 }
471
472 struct Second;
474
475 impl Module for Second {
476 fn register(&self, _: &mut ModuleBuilder) {}
477 }
478
479 struct Boxed;
481
482 impl Module for Boxed {
483 fn register(&self, _: &mut ModuleBuilder) {}
484 }
485
486 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 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}