use std::panic::Location;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::binding::factory::Factory;
use crate::binding::{Coercion, coercion};
use crate::dependency::Dependencies;
use crate::error::LookupError;
use crate::key::Key;
use crate::resolver::Resolver;
use crate::scope::{Auto, ExplicitScope, Scope, ScopeKind};
use crate::timer::BoxFuture;
use crate::transport::controller::{ClosureDep, EnhancerDep};
use crate::transport::{AnyErrorHandler, AnyGuard, AnyInterceptor, ErrorHandler, Guard, Interceptor, Transport};
pub struct EnhancerSpec<T: Transport> {
pub(crate) guards: Vec<Decl<AnyGuard<T>>>,
pub(crate) interceptors: Vec<Decl<AnyInterceptor<T>>>,
pub(crate) error_handlers: Vec<Decl<AnyErrorHandler<T>>>,
}
impl<T: Transport> EnhancerSpec<T> {
pub fn new() -> Self {
EnhancerSpec { guards: Vec::new(), interceptors: Vec::new(), error_handlers: Vec::new() }
}
pub fn guard<G: Guard<T>>(&mut self) -> &mut Self {
self.guards.push(Decl::by_type(widen_guard::<T, G>));
self
}
pub fn guard_value<G: Guard<T>>(&mut self, guard: G) -> &mut Self {
self.guards.push(Decl::by_value(guard, widen_guard::<T, G>));
self
}
pub fn guard_arc<G: Guard<T>>(&mut self, guard: Arc<G>) -> &mut Self {
self.guards.push(Decl::Value(widen_guard::<T, G>(guard)));
self
}
#[track_caller]
pub fn guard_with<Args, F>(&mut self, build: F) -> &mut Self
where
F: Factory<Args>,
F::Output: Guard<T>,
{
self.guards.push(Decl::by_closure::<Auto, Args, F>(build, widen_guard::<T, F::Output>, Location::caller()));
self
}
#[track_caller]
pub fn guard_with_in<S, Args, F>(&mut self, build: F) -> &mut Self
where
S: ExplicitScope,
F: Factory<Args>,
F::Output: Guard<T>,
{
self.guards.push(Decl::by_closure::<S, Args, F>(build, widen_guard::<T, F::Output>, Location::caller()));
self
}
pub fn interceptor<I: Interceptor<T>>(&mut self) -> &mut Self {
self.interceptors.push(Decl::by_type(widen_interceptor::<T, I>));
self
}
pub fn interceptor_value<I: Interceptor<T>>(&mut self, interceptor: I) -> &mut Self {
self.interceptors.push(Decl::by_value(interceptor, widen_interceptor::<T, I>));
self
}
pub fn interceptor_arc<I: Interceptor<T>>(&mut self, interceptor: Arc<I>) -> &mut Self {
self.interceptors.push(Decl::Value(widen_interceptor::<T, I>(interceptor)));
self
}
#[track_caller]
pub fn interceptor_with<Args, F>(&mut self, build: F) -> &mut Self
where
F: Factory<Args>,
F::Output: Interceptor<T>,
{
let decl = Decl::by_closure::<Auto, Args, F>(build, widen_interceptor::<T, F::Output>, Location::caller());
self.interceptors.push(decl);
self
}
#[track_caller]
pub fn interceptor_with_in<S, Args, F>(&mut self, build: F) -> &mut Self
where
S: ExplicitScope,
F: Factory<Args>,
F::Output: Interceptor<T>,
{
let decl = Decl::by_closure::<S, Args, F>(build, widen_interceptor::<T, F::Output>, Location::caller());
self.interceptors.push(decl);
self
}
pub fn error_handler<E: ErrorHandler<T>>(&mut self) -> &mut Self {
self.error_handlers.push(Decl::by_type(widen_error_handler::<T, E>));
self
}
pub fn error_handler_value<E: ErrorHandler<T>>(&mut self, handler: E) -> &mut Self {
self.error_handlers.push(Decl::by_value(handler, widen_error_handler::<T, E>));
self
}
pub fn error_handler_arc<E: ErrorHandler<T>>(&mut self, handler: Arc<E>) -> &mut Self {
self.error_handlers.push(Decl::Value(widen_error_handler::<T, E>(handler)));
self
}
#[track_caller]
pub fn error_handler_with<Args, F>(&mut self, build: F) -> &mut Self
where
F: Factory<Args>,
F::Output: ErrorHandler<T>,
{
let decl = Decl::by_closure::<Auto, Args, F>(build, widen_error_handler::<T, F::Output>, Location::caller());
self.error_handlers.push(decl);
self
}
#[track_caller]
pub fn error_handler_with_in<S, Args, F>(&mut self, build: F) -> &mut Self
where
S: ExplicitScope,
F: Factory<Args>,
F::Output: ErrorHandler<T>,
{
let decl = Decl::by_closure::<S, Args, F>(build, widen_error_handler::<T, F::Output>, Location::caller());
self.error_handlers.push(decl);
self
}
pub(crate) fn deps(&self, tier: &'static str, out: &mut Vec<EnhancerDep>) {
out.extend(deps_of(&self.guards, "guard", tier));
out.extend(deps_of(&self.interceptors, "interceptor", tier));
out.extend(deps_of(&self.error_handlers, "error handler", tier));
}
}
fn deps_of<'d, R: ?Sized + Send + Sync + 'static>(
decls: &'d [Decl<R>],
role: &'static str,
tier: &'static str,
) -> impl Iterator<Item = EnhancerDep> + 'd {
decls.iter().enumerate().filter_map(move |(index, decl)| decl.dep(role, tier, index + 1))
}
impl<T: Transport> Default for EnhancerSpec<T> {
fn default() -> Self {
EnhancerSpec::new()
}
}
impl<T: Transport> Clone for EnhancerSpec<T> {
fn clone(&self) -> Self {
EnhancerSpec {
guards: self.guards.clone(),
interceptors: self.interceptors.clone(),
error_handlers: self.error_handlers.clone(),
}
}
}
pub(crate) enum Decl<R: ?Sized> {
Type { key: Key, coerce: Coercion },
Value(Arc<R>),
Closure(Arc<ClosureDecl<R>>),
}
impl<R: ?Sized> Clone for Decl<R> {
fn clone(&self) -> Self {
match self {
Decl::Type { key, coerce } => Decl::Type { key: *key, coerce: Arc::clone(coerce) },
Decl::Value(v) => Decl::Value(Arc::clone(v)),
Decl::Closure(c) => Decl::Closure(Arc::clone(c)),
}
}
}
impl<R: ?Sized + Send + Sync + 'static> Decl<R> {
fn by_type<X: Send + Sync + 'static>(widen: fn(Arc<X>) -> Arc<R>) -> Self {
Decl::Type { key: Key::of::<X, ()>(), coerce: coercion(widen) }
}
fn by_value<X>(value: X, widen: fn(Arc<X>) -> Arc<R>) -> Self {
Decl::Value(widen(Arc::new(value)))
}
fn by_closure<S, Args, F>(build: F, widen: fn(Arc<F::Output>) -> Arc<R>, location: &'static Location<'static>) -> Self
where
S: Scope,
F: Factory<Args>,
{
let mut dependencies = Dependencies::default();
<F as Factory<Args>>::dependencies(&mut dependencies);
let factory = Arc::new(build);
let build = erase_build::<R, _>(move |r| {
let factory = Arc::clone(&factory);
let fut: BoxFuture<'_, Result<Arc<R>, LookupError>> = Box::pin(async move {
<F as Factory<Args>>::call(&*factory, r).await.map(|built| widen(Arc::new(built)))
});
fut
});
Decl::Closure(Arc::new(ClosureDecl {
id: ClosureId::next(),
scope: S::KIND,
dependencies: Arc::new(dependencies),
build,
location,
}))
}
fn dep(&self, role: &'static str, tier: &'static str, position: usize) -> Option<EnhancerDep> {
match self {
Decl::Type { key, .. } => Some(EnhancerDep::Type(*key)),
Decl::Value(_) => None,
Decl::Closure(c) => Some(EnhancerDep::Closure(ClosureDep {
id: c.id,
scope: c.scope,
dependencies: Arc::clone(&c.dependencies),
role,
tier,
position,
location: c.location,
})),
}
}
}
pub(crate) struct ClosureDecl<R: ?Sized> {
pub(crate) id: ClosureId,
pub(crate) scope: ScopeKind,
pub(crate) dependencies: Arc<Dependencies>,
pub(crate) build: Arc<dyn for<'a> Fn(&'a Resolver<'a>) -> BoxFuture<'a, Result<Arc<R>, LookupError>> + Send + Sync>,
pub(crate) location: &'static Location<'static>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ClosureId(u64);
impl ClosureId {
fn next() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
ClosureId(NEXT.fetch_add(1, Ordering::Relaxed))
}
}
fn erase_build<R, F>(f: F) -> Arc<dyn for<'a> Fn(&'a Resolver<'a>) -> BoxFuture<'a, Result<Arc<R>, LookupError>> + Send + Sync>
where
R: ?Sized + 'static,
F: for<'a> Fn(&'a Resolver<'a>) -> BoxFuture<'a, Result<Arc<R>, LookupError>> + Send + Sync + 'static,
{
Arc::new(f)
}
fn widen_guard<T: Transport, G: Guard<T>>(guard: Arc<G>) -> Arc<AnyGuard<T>> {
guard
}
fn widen_interceptor<T: Transport, I: Interceptor<T>>(interceptor: Arc<I>) -> Arc<AnyInterceptor<T>> {
interceptor
}
fn widen_error_handler<T: Transport, E: ErrorHandler<T>>(handler: Arc<E>) -> Arc<AnyErrorHandler<T>> {
handler
}