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, ProviderKey, Resolver, Scope,
};
pub(crate) type Contribution = (TypeId, 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 ModuleBuilder {
pub(crate) id: ModuleId,
pub(crate) name: &'static str,
pub(crate) global: bool,
pub(crate) imports: Vec<Box<dyn Module>>,
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>,
}
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(),
}
}
pub fn module_id(&self) -> ModuleId {
self.id
}
pub fn import(&mut self, module: impl Module) -> &mut Self {
self.imports.push(Box::new(module));
self
}
pub fn imports(&mut self, modules: impl IntoModules) -> &mut Self {
self.imports.extend(modules.into_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((TypeId::of::<C>(), 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 },
}
}