use std::any::{Any, TypeId, type_name};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::{Arc, RwLock};
use shaku::{HasComponent, HasProvider, Interface, ModuleInterface};
use crate::Error;
use crate::sync::{read, write};
pub(crate) type Erased = Box<dyn Any + Send + Sync>;
type Resolver<I> = Box<dyn Fn() -> Result<Arc<I>, Error> + Send + Sync>;
type Callback<I> = Arc<dyn Fn(&Arc<I>, &Application) + Send + Sync>;
pub(crate) fn erase<I: ?Sized + Interface>(instance: Arc<I>) -> Erased {
Box::new(instance)
}
pub(crate) fn unerase<I: ?Sized + Interface>(erased: &Erased) -> Arc<I> {
Arc::clone(
erased
.downcast_ref::<Arc<I>>()
.expect("laravel-facade: erased value has an unexpected type"),
)
}
pub struct Application {
bindings: BTreeMap<TypeId, Erased>,
instances: RwLock<BTreeMap<TypeId, Erased>>,
resolved: RwLock<BTreeSet<TypeId>>,
after_resolving: RwLock<BTreeMap<TypeId, Vec<Erased>>>,
}
impl Application {
pub fn builder<M: ModuleInterface>(module: M) -> ApplicationBuilder<M> {
ApplicationBuilder {
module: Arc::new(module),
bindings: BTreeMap::new(),
}
}
pub fn bound<I: ?Sized + Interface>(&self) -> bool {
let id = TypeId::of::<I>();
self.bindings.contains_key(&id) || read(&self.instances).contains_key(&id)
}
pub fn resolved<I: ?Sized + Interface>(&self) -> bool {
let id = TypeId::of::<I>();
read(&self.resolved).contains(&id) || read(&self.instances).contains_key(&id)
}
pub fn make<I: ?Sized + Interface>(&self) -> Result<Arc<I>, Error> {
let id = TypeId::of::<I>();
if let Some(instance) = read(&self.instances).get(&id) {
return Ok(unerase(instance));
}
let resolver = self
.bindings
.get(&id)
.and_then(|erased| erased.downcast_ref::<Resolver<I>>())
.ok_or(Error::NotInstantiable {
accessor: type_name::<I>(),
})?;
let instance = resolver()?;
write(&self.resolved).insert(id);
let callbacks: Vec<Callback<I>> = read(&self.after_resolving)
.get(&id)
.into_iter()
.flatten()
.filter_map(|erased| erased.downcast_ref::<Callback<I>>().cloned())
.collect();
for callback in callbacks {
callback(&instance, self);
}
Ok(instance)
}
pub fn instance<I: ?Sized + Interface>(&self, instance: Arc<I>) -> Arc<I> {
let previous = write(&self.instances).insert(TypeId::of::<I>(), erase(Arc::clone(&instance)));
drop(previous); instance
}
pub fn forget_instance<I: ?Sized + Interface>(&self) {
let previous = write(&self.instances).remove(&TypeId::of::<I>());
drop(previous);
}
pub fn after_resolving<I: ?Sized + Interface>(
&self,
callback: impl Fn(&Arc<I>, &Application) + Send + Sync + 'static,
) {
let callback: Callback<I> = Arc::new(callback);
write(&self.after_resolving)
.entry(TypeId::of::<I>())
.or_default()
.push(Box::new(callback));
}
}
impl fmt::Debug for Application {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Application")
.field("bindings", &self.bindings.len())
.field("instances", &read(&self.instances).len())
.field("resolved", &read(&self.resolved).len())
.finish_non_exhaustive()
}
}
pub struct ApplicationBuilder<M> {
module: Arc<M>,
bindings: BTreeMap<TypeId, Erased>,
}
impl<M: ModuleInterface> ApplicationBuilder<M> {
pub fn bind<I: ?Sized + Interface>(self) -> Self
where
M: HasComponent<I>,
{
let module = Arc::clone(&self.module);
self.insert::<I>(Box::new(move || Ok(HasComponent::<I>::resolve(&*module))))
}
pub fn bind_provider<I: ?Sized + Interface>(self) -> Self
where
M: HasProvider<I>,
{
let module = Arc::clone(&self.module);
self.insert::<I>(Box::new(move || {
HasProvider::<I>::provide(&*module)
.map(Arc::from)
.map_err(|e| Error::Provider {
accessor: type_name::<I>(),
message: e.to_string(),
})
}))
}
pub fn build(self) -> Arc<Application> {
Arc::new(Application {
bindings: self.bindings,
instances: RwLock::default(),
resolved: RwLock::default(),
after_resolving: RwLock::default(),
})
}
fn insert<I: ?Sized + Interface>(mut self, resolver: Resolver<I>) -> Self {
self.bindings.insert(TypeId::of::<I>(), Box::new(resolver));
self
}
}
impl<M> fmt::Debug for ApplicationBuilder<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApplicationBuilder")
.field("module", &type_name::<M>())
.field("bindings", &self.bindings.len())
.finish()
}
}