use std::any::{Any, type_name};
use std::fmt;
use std::marker::PhantomData;
use std::panic::Location;
use std::sync::Arc;
use std::time::Duration;
use crate::binding::alias::{Alias, Input};
use crate::binding::contribute::{Contribute, Enhancer};
use crate::binding::factory::{
Factory, ShutdownFactory, erase_destroy_hook, erase_factory, erase_init_hook, erase_signalled_hook,
erase_try_factory,
};
use crate::binding::handle::{Binding, Handle, Open, Set};
use crate::binding::{BindingRecord, Qualifier, Recipe, erase_construct, instance_of};
use crate::construct::Construct;
use crate::dependency::Dependencies;
use crate::graph::register::Site;
use crate::hooks::{HookFn, HookKind, HookRecord, erase_trait_hooks};
use crate::key::{BindingKind, Key};
use crate::module::Module;
use crate::module::{ModuleIdentity, ModuleSettings};
use crate::module::meta::{Meta, MetaMap};
use crate::redact::Secret;
use crate::scope::{Auto, PerExecution, Scope, ScopeKind, Singleton, Transient};
use crate::timer::{BoxError, Bound};
use crate::transport::Role;
use crate::transport::controller::{Controller, ControllerHandle, ControllerRecord};
use crate::type_name::TypeName;
pub struct ModuleDef<'a> {
pub(crate) node: &'a mut ModuleNode,
}
impl<'a> ModuleDef<'a> {
pub(crate) fn new(node: &'a mut ModuleNode) -> Self {
ModuleDef { node }
}
#[track_caller]
pub fn import<M: Module>(&mut self, module: M) {
self.node.imports.push(ImportRecord { module: Box::new(module), at: Location::caller() });
}
pub fn global(&mut self) {
self.node.global = true;
}
#[track_caller]
pub fn export<T: ?Sized + 'static>(&mut self) {
self.push_export(Key::of::<T, ()>(), false, Location::caller());
}
#[track_caller]
pub fn export_qualified<T: ?Sized + 'static, Q: 'static>(&mut self) {
self.push_export(Key::of::<T, Q>(), false, Location::caller());
}
#[track_caller]
pub fn reexport<T: ?Sized + 'static>(&mut self) {
self.push_export(Key::of::<T, ()>(), true, Location::caller());
}
#[track_caller]
pub fn reexport_qualified<T: ?Sized + 'static, Q: 'static>(&mut self) {
self.push_export(Key::of::<T, Q>(), true, Location::caller());
}
pub fn secret<T: fmt::Display>(&mut self, secret: &Secret<T>) {
self.node.secrets.push(secret.expose().to_string());
}
pub fn meta<T: Meta>(&mut self) -> &mut T {
self.node.meta.get_or_default::<T>()
}
#[track_caller]
pub fn on_init<Args, F, E>(&mut self, hook: F) -> ModuleHook<'_>
where
F: Factory<Args, Output = Result<(), E>>,
E: Into<BoxError> + Send + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
self.push_hook(HookKind::OnModuleInit, erase_init_hook::<Args, F, E>(hook), dependencies, location)
}
#[track_caller]
pub fn on_destroy<Args, F>(&mut self, hook: F) -> ModuleHook<'_>
where
F: Factory<Args, Output = ()>,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
self.push_hook(HookKind::OnModuleDestroy, erase_destroy_hook::<Args, F>(hook), dependencies, location)
}
#[track_caller]
pub fn before_shutdown<Args, F>(&mut self, hook: F) -> ModuleHook<'_>
where
F: ShutdownFactory<Args>,
{
let location = Location::caller();
let dependencies = shutdown_dependencies::<Args, F>();
self.push_hook(HookKind::BeforeApplicationShutdown, erase_signalled_hook::<Args, F>(hook), dependencies, location)
}
#[track_caller]
pub fn on_shutdown<Args, F>(&mut self, hook: F) -> ModuleHook<'_>
where
F: ShutdownFactory<Args>,
{
let location = Location::caller();
let dependencies = shutdown_dependencies::<Args, F>();
self.push_hook(HookKind::OnApplicationShutdown, erase_signalled_hook::<Args, F>(hook), dependencies, location)
}
#[track_caller]
pub fn provide<T: Construct>(&mut self) -> Handle<'_, T, Binding<T::Scope, Set>> {
let location = Location::caller();
let mut dependencies = Dependencies::default();
T::dependencies(&mut dependencies);
let mut record = construct_record::<T>(Recipe::Construct(erase_construct::<T>()), dependencies, location);
record.construct_bound = T::CONSTRUCT_TIMEOUT;
Handle::new(self.push(record))
}
#[track_caller]
pub fn provide_with<T: Construct, Args>(
&mut self,
factory: impl Factory<Args, Output = T>,
) -> Handle<'_, T, Binding<T::Scope, Open>> {
let location = Location::caller();
let dependencies = dependencies_of::<Args, _>(&factory);
let record = construct_record::<T>(Recipe::Factory(erase_factory::<Args, _>(factory)), dependencies, location);
Handle::new(self.push(record))
}
#[track_caller]
pub fn try_provide_with<T: Construct, Args, E>(
&mut self,
factory: impl Factory<Args, Output = Result<T, E>>,
) -> Handle<'_, T, Binding<T::Scope, Open>>
where
E: Into<BoxError> + Send + 'static,
{
let location = Location::caller();
let dependencies = dependencies_of::<Args, _>(&factory);
let ctor = erase_try_factory::<Args, _, T, E>(factory);
let record = construct_record::<T>(Recipe::Factory(ctor), dependencies, location);
Handle::new(self.push(record))
}
#[track_caller]
pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> Handle<'_, T, Binding<Singleton, Set>> {
let location = Location::caller();
self.register_secret(&value);
let record = value_record::<T>(Recipe::Value(instance_of(Arc::new(value))), location);
Handle::new(self.push(record))
}
#[track_caller]
pub fn try_value<T, E>(&mut self, value: Result<T, E>) -> Handle<'_, T, Binding<Singleton, Set>>
where
T: Send + Sync + 'static,
E: Into<BoxError>,
{
let location = Location::caller();
let recipe = match value {
Ok(value) => {
self.register_secret(&value);
Recipe::Value(instance_of(Arc::new(value)))
}
Err(error) => {
self.node.failures.push(ValueFailure { error: error.into(), location });
Recipe::Failed
}
};
Handle::new(self.push(value_record::<T>(recipe, location)))
}
#[track_caller]
pub fn with<Args, F>(&mut self, factory: F) -> Handle<'_, F::Output, Binding<Auto, Open>>
where
F: Factory<Args>,
F::Output: Send + Sync + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
let ctor = erase_factory::<Args, F>(factory);
Handle::new(self.push(factory_record::<Auto, F::Output>(ctor, dependencies, location)))
}
#[track_caller]
pub fn try_with<Args, F, T, E>(&mut self, factory: F) -> Handle<'_, T, Binding<Auto, Open>>
where
F: Factory<Args, Output = Result<T, E>>,
T: Send + Sync + 'static,
E: Into<BoxError> + Send + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
let ctor = erase_try_factory::<Args, F, T, E>(factory);
Handle::new(self.push(factory_record::<Auto, T>(ctor, dependencies, location)))
}
#[track_caller]
pub fn singleton<Args, F>(&mut self, factory: F) -> Handle<'_, F::Output, Binding<Singleton, Open>>
where
F: Factory<Args>,
F::Output: Send + Sync + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
let ctor = erase_factory::<Args, F>(factory);
Handle::new(self.push(factory_record::<Singleton, F::Output>(ctor, dependencies, location)))
}
#[track_caller]
pub fn try_singleton<Args, F, T, E>(&mut self, factory: F) -> Handle<'_, T, Binding<Singleton, Open>>
where
F: Factory<Args, Output = Result<T, E>>,
T: Send + Sync + 'static,
E: Into<BoxError> + Send + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
let ctor = erase_try_factory::<Args, F, T, E>(factory);
Handle::new(self.push(factory_record::<Singleton, T>(ctor, dependencies, location)))
}
#[track_caller]
pub fn execution<Args, F>(&mut self, factory: F) -> Handle<'_, F::Output, Binding<PerExecution, Open>>
where
F: Factory<Args>,
F::Output: Send + Sync + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
let ctor = erase_factory::<Args, F>(factory);
Handle::new(self.push(factory_record::<PerExecution, F::Output>(ctor, dependencies, location)))
}
#[track_caller]
pub fn try_execution<Args, F, T, E>(&mut self, factory: F) -> Handle<'_, T, Binding<PerExecution, Open>>
where
F: Factory<Args, Output = Result<T, E>>,
T: Send + Sync + 'static,
E: Into<BoxError> + Send + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
let ctor = erase_try_factory::<Args, F, T, E>(factory);
Handle::new(self.push(factory_record::<PerExecution, T>(ctor, dependencies, location)))
}
#[track_caller]
pub fn transient<Args, F>(&mut self, factory: F) -> Handle<'_, F::Output, Binding<Transient, Open>>
where
F: Factory<Args>,
F::Output: Send + Sync + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
let ctor = erase_factory::<Args, F>(factory);
Handle::new(self.push(factory_record::<Transient, F::Output>(ctor, dependencies, location)))
}
#[track_caller]
pub fn try_transient<Args, F, T, E>(&mut self, factory: F) -> Handle<'_, T, Binding<Transient, Open>>
where
F: Factory<Args, Output = Result<T, E>>,
T: Send + Sync + 'static,
E: Into<BoxError> + Send + 'static,
{
let location = Location::caller();
let dependencies = factory_dependencies::<Args, F>();
let ctor = erase_try_factory::<Args, F, T, E>(factory);
Handle::new(self.push(factory_record::<Transient, T>(ctor, dependencies, location)))
}
pub fn contribute<U: ?Sized + Send + Sync + 'static>(&mut self) -> Contribute<'_, U> {
Contribute::new(&mut *self.node)
}
pub fn enhancer<R: Role + ?Sized>(&mut self) -> Contribute<'_, R, (), Enhancer> {
Contribute::for_role(&mut *self.node)
}
pub fn alias<T: ?Sized + Send + Sync + 'static, Q: 'static>(&mut self) -> Alias<'_, T, Q> {
Alias::new(&mut *self.node)
}
pub fn input<T: Send + Sync + 'static>(&mut self) -> Input<'_, T> {
Input::new(&mut *self.node)
}
#[track_caller]
pub fn controller<C: Controller>(&mut self) -> ControllerHandle<'_> {
let location = Location::caller();
let mut dependencies = Dependencies::default();
C::dependencies(&mut dependencies);
let mut record = construct_record::<C>(Recipe::Construct(erase_construct::<C>()), dependencies, location);
record.construct_bound = C::CONSTRUCT_TIMEOUT;
record.controller = true;
let binding = self.node.bindings.len();
self.node.bindings.push(record);
self.node.controllers.push(ControllerRecord { binding, mount: C::mount, prefix: None });
let index = self.node.controllers.len() - 1;
ControllerHandle { record: &mut self.node.controllers[index] }
}
pub(crate) fn keyed_by(&mut self, qualifier: Qualifier) {
if let Some(earlier) = self.node.keyed {
let outer = self.node.nested_keyed.map_or(earlier, |(outer, _)| outer);
self.node.nested_keyed = Some((outer, qualifier));
}
self.node.keyed = Some(qualifier);
}
pub fn qualifier(&self) -> Option<TypeName> {
self.node.keyed.or(self.node.inherited_keyed).map(|qualifier| TypeName::from_parts(qualifier.id, qualifier.name))
}
fn push(&mut self, record: BindingRecord) -> &mut BindingRecord {
let index = self.node.bindings.len();
self.node.bindings.push(record);
&mut self.node.bindings[index]
}
fn push_export(&mut self, key: Key, reexport: bool, location: &'static Location<'static>) {
self.node.exports.push(ExportRecord { key, reexport, location });
}
fn push_hook(
&mut self,
kind: HookKind,
run: HookFn,
dependencies: Dependencies,
location: &'static Location<'static>,
) -> ModuleHook<'_> {
self.node.hooks.push(HookRecord { kind, bound: Bound::Default, bound_at: None, run, dependencies, location });
ModuleHook::new(&mut *self.node)
}
fn register_secret(&mut self, value: &dyn Any) {
if let Some(secret) = value.downcast_ref::<Secret<String>>() {
self.node.secrets.push(secret.expose().clone());
} else if let Some(secret) = value.downcast_ref::<Secret<&'static str>>() {
self.node.secrets.push((*secret.expose()).to_owned());
}
}
}
fn construct_record<T: Construct>(recipe: Recipe, dependencies: Dependencies, location: &'static Location<'static>) -> BindingRecord {
let kind = <T::Scope as Scope>::KIND;
let mut record = BindingRecord::new(Key::of::<T, ()>(), type_name::<T>(), BindingKind::Single, kind, recipe, dependencies, location);
record.hooks = erase_trait_hooks::<T>(location);
record.constructs = true;
record
}
fn factory_record<S: Scope, T: 'static>(
ctor: crate::binding::ErasedCtor,
dependencies: Dependencies,
location: &'static Location<'static>,
) -> BindingRecord {
BindingRecord::new(Key::of::<T, ()>(), type_name::<T>(), BindingKind::Single, S::KIND, Recipe::Factory(ctor), dependencies, location)
}
fn value_record<T: 'static>(recipe: Recipe, location: &'static Location<'static>) -> BindingRecord {
BindingRecord::new(
Key::of::<T, ()>(),
type_name::<T>(),
BindingKind::Single,
ScopeKind::Singleton,
recipe,
Dependencies::default(),
location,
)
}
fn factory_dependencies<Args, F: Factory<Args>>() -> Dependencies {
let mut dependencies = Dependencies::default();
<F as Factory<Args>>::dependencies(&mut dependencies);
dependencies
}
fn dependencies_of<Args, F: Factory<Args>>(_factory: &F) -> Dependencies {
factory_dependencies::<Args, F>()
}
fn shutdown_dependencies<Args, F: ShutdownFactory<Args>>() -> Dependencies {
let mut dependencies = Dependencies::default();
<F as ShutdownFactory<Args>>::dependencies(&mut dependencies);
dependencies
}
pub struct ModuleHook<'m, B = Open> {
node: &'m mut ModuleNode,
_b: PhantomData<B>,
}
impl<'m> ModuleHook<'m, Open> {
pub(crate) fn new(node: &'m mut ModuleNode) -> Self {
ModuleHook { node, _b: PhantomData }
}
#[track_caller]
pub fn timeout(self, d: Duration) -> ModuleHook<'m, Set> {
self.write(Bound::After(d), Location::caller())
}
#[track_caller]
pub fn unbounded(self) -> ModuleHook<'m, Set> {
self.write(Bound::Unbounded, Location::caller())
}
fn write(self, bound: Bound, at: &'static Location<'static>) -> ModuleHook<'m, Set> {
if let Some(hook) = self.node.hooks.last_mut() {
hook.bound = bound;
hook.bound_at = Some(at);
}
ModuleHook { node: self.node, _b: PhantomData }
}
}
pub(crate) struct ModuleNode {
pub(crate) identity: ModuleIdentity,
pub(crate) global: bool,
pub(crate) keyed: Option<Qualifier>,
pub(crate) nested_keyed: Option<(Qualifier, Qualifier)>,
pub(crate) inherited_keyed: Option<Qualifier>,
pub(crate) imports: Vec<ImportRecord>,
pub(crate) bindings: Vec<BindingRecord>,
pub(crate) enhancers: Vec<usize>,
pub(crate) exports: Vec<ExportRecord>,
pub(crate) controllers: Vec<ControllerRecord>,
pub(crate) inputs: Vec<InputRecord>,
pub(crate) hooks: Vec<HookRecord>,
pub(crate) meta: MetaMap,
pub(crate) secrets: Vec<String>,
pub(crate) failures: Vec<ValueFailure>,
pub(crate) settings: ModuleSettings,
pub(crate) site: Site,
}
impl ModuleNode {
pub(crate) fn new(identity: ModuleIdentity) -> Self {
ModuleNode {
identity,
global: false,
keyed: None,
nested_keyed: None,
inherited_keyed: None,
imports: Vec::new(),
bindings: Vec::new(),
enhancers: Vec::new(),
exports: Vec::new(),
controllers: Vec::new(),
inputs: Vec::new(),
hooks: Vec::new(),
meta: MetaMap::default(),
secrets: Vec::new(),
failures: Vec::new(),
settings: ModuleSettings::new(),
site: Site::Root,
}
}
}
pub(crate) struct ImportRecord {
pub(crate) module: Box<dyn Module>,
pub(crate) at: &'static Location<'static>,
}
pub(crate) struct ExportRecord {
pub(crate) key: Key,
pub(crate) reexport: bool,
pub(crate) location: &'static Location<'static>,
}
pub(crate) struct InputRecord {
pub(crate) key: Key,
pub(crate) seeder: TypeName,
pub(crate) location: &'static Location<'static>,
}
pub(crate) struct ValueFailure {
pub(crate) error: BoxError,
pub(crate) location: &'static Location<'static>,
}