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,
};
pub(crate) struct Contribution {
pub(crate) type_id: TypeId,
pub(crate) type_name: &'static str,
pub(crate) value: Arc<dyn Any + Send + Sync>,
}
pub(crate) type Instance = Arc<dyn Any + Send + Sync>;
pub(crate) type ErasedFactory =
Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Instance, KernelError>> + Send + Sync>;
#[derive(Clone)]
pub(crate) struct ProviderDef {
pub(crate) key: ProviderKey,
pub(crate) scope: Scope,
pub(crate) deps: Vec<ProviderKey>,
pub(crate) factory: ErasedFactory,
pub(crate) multi: bool,
}
pub struct PassedModule {
pub(crate) module: Box<dyn Module>,
pub(crate) type_name: &'static str,
}
impl PassedModule {
pub fn of<M: Module>(module: M) -> PassedModule {
PassedModule {
module: Box::new(module),
type_name: std::any::type_name::<M>(),
}
}
pub(crate) fn boxed(module: Box<dyn Module>) -> PassedModule {
PassedModule {
module,
type_name: std::any::type_name::<Box<dyn Module>>(),
}
}
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()
}
}
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>,
pub(crate) plugin: Option<PluginInfo>,
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,
}
}
pub fn module_id(&self) -> ModuleId {
self.id
}
pub fn plugin(&mut self, info: PluginInfo) -> &mut Self {
if self.plugin.is_some() {
self.plugin_twice = true;
} else {
self.plugin = Some(info);
}
self
}
pub fn import(&mut self, module: impl Module) -> &mut Self {
self.imports.push(PassedModule::of(module));
self
}
pub fn imports(&mut self, modules: impl IntoModules) -> &mut Self {
self.imports.extend(modules.into_passed_modules());
self
}
pub fn global(&mut self) -> &mut Self {
self.global = true;
self
}
pub fn provider<T: Injectable>(&mut self) -> &mut Self {
self.injectable::<T>(ProviderKey::of::<T>())
}
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
}
pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
self.value_arc(Arc::new(value))
}
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
}
pub fn factory<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
self.providers.push(f.into_def());
self
}
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
}
pub fn exports<T: ?Sized + 'static>(&mut self) -> &mut Self {
self.export_key(ProviderKey::of::<T>())
}
pub fn export_key(&mut self, key: ProviderKey) -> &mut Self {
self.exports.push(key);
self
}
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
}
pub fn lifecycle<T: Lifecycle + Send + Sync + 'static>(&mut self) -> &mut Self {
self.lifecycles.push(LifecycleDef::of::<T>());
self
}
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()
}
}
pub struct Factory<T: ?Sized> {
scope: Scope,
deps: Vec<ProviderKey>,
name: Option<Cow<'static, str>>,
build: BuildFn<T>,
}
type BuildFn<T> =
Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Arc<T>, BoxError>> + Send + Sync>;
impl<T: ?Sized + Send + Sync + 'static> Factory<T> {
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))),
}
}
pub fn scope(mut self, s: Scope) -> Self {
self.scope = s;
self
}
pub fn deps(mut self, d: Vec<ProviderKey>) -> Self {
self.deps = d;
self
}
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()
}
}
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,
}
}
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;
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((), |_, _| {}));
}
}
struct Single;
impl Module for Single {
fn register(&self, _: &mut ModuleBuilder) {}
}
struct First;
impl Module for First {
fn register(&self, _: &mut ModuleBuilder) {}
}
struct Second;
impl Module for Second {
fn register(&self, _: &mut ModuleBuilder) {}
}
struct Boxed;
impl Module for Boxed {
fn register(&self, _: &mut ModuleBuilder) {}
}
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::<Box<dyn Module>>()
);
assert_eq!(
recorded(ModuleId::of::<Configured>()),
type_name::<ConfiguredModule<Configured, ()>>()
);
}
#[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>());
}
}