use std::convert::Infallible;
use std::marker::PhantomData;
use std::panic::Location;
use std::sync::Arc;
use std::time::Duration;
use crate::binding::factory::{
Factory, ShutdownFactory, erase_check, erase_destroy_hook, erase_init_hook, erase_signalled_hook,
};
use crate::binding::{AlsoAs, BindingRecord, Qualifier, ReadyRecord, coercion};
use crate::dependency::Dependencies;
use crate::hooks::{HookFn, HookKind, HookRecord};
use crate::key::Key;
use crate::scope::HookCapable;
use crate::timer::{BoxError, Bound};
pub enum Open {}
pub enum Set {}
pub struct Binding<S, B>(Infallible, PhantomData<(S, B)>);
pub struct Contribution<S, B>(Infallible, PhantomData<(S, B)>);
pub struct ReadyItem<W, A>(Infallible, PhantomData<(W, A)>);
pub struct HookItem<B>(Infallible, PhantomData<B>);
mod sealed {
use crate::binding::BindingRecord;
use crate::timer::Bound;
pub trait State {
fn write(record: &mut BindingRecord, bound: Bound);
fn write_unbounded(record: &mut BindingRecord) {
Self::write(record, Bound::Unbounded);
}
}
}
impl<S, B> sealed::State for Binding<S, B> {
fn write(record: &mut BindingRecord, bound: Bound) {
record.construct_bound = bound;
}
}
impl<S, B> sealed::State for Contribution<S, B> {
fn write(record: &mut BindingRecord, bound: Bound) {
record.construct_bound = bound;
}
}
impl<W, A> sealed::State for ReadyItem<W, A> {
fn write(record: &mut BindingRecord, bound: Bound) {
if let Some(ready) = record.ready.as_mut() {
ready.whole = bound;
if ready.attempt == Bound::Default {
ready.attempt = Bound::Unbounded;
}
}
}
fn write_unbounded(record: &mut BindingRecord) {
if let Some(ready) = record.ready.as_mut() {
ready.whole = Bound::Unbounded;
ready.attempt = Bound::Unbounded;
}
}
}
impl<B> sealed::State for HookItem<B> {
fn write(record: &mut BindingRecord, bound: Bound) {
if let Some(hook) = record.hooks.last_mut() {
hook.bound = bound;
}
}
}
pub trait Timeout<C>: sealed::State {
type Next;
type Construction;
}
impl<S> Timeout<Binding<S, Open>> for Binding<S, Open> {
type Next = Binding<S, Set>;
type Construction = Binding<S, Set>;
}
impl<S> Timeout<Contribution<S, Open>> for Contribution<S, Open> {
type Next = Contribution<S, Set>;
type Construction = Contribution<S, Set>;
}
impl<C> Timeout<C> for HookItem<Open> {
type Next = HookItem<Set>;
type Construction = C;
}
impl<A, C> Timeout<C> for ReadyItem<Open, A> {
type Next = ReadyItem<Set, A>;
type Construction = C;
}
pub trait Unbounded<C>: sealed::State {
type Next;
type Construction;
}
impl<S> Unbounded<Binding<S, Open>> for Binding<S, Open> {
type Next = Binding<S, Set>;
type Construction = Binding<S, Set>;
}
impl<S> Unbounded<Contribution<S, Open>> for Contribution<S, Open> {
type Next = Contribution<S, Set>;
type Construction = Contribution<S, Set>;
}
impl<C> Unbounded<C> for HookItem<Open> {
type Next = HookItem<Set>;
type Construction = C;
}
impl<C> Unbounded<C> for ReadyItem<Open, Open> {
type Next = ReadyItem<Set, Set>;
type Construction = C;
}
pub trait AttemptTimeout: sealed::State {
type Next;
}
impl<W> AttemptTimeout for ReadyItem<W, Open> {
type Next = ReadyItem<W, Set>;
}
pub trait SingleBinding: sealed::State {}
impl<S, B> SingleBinding for Binding<S, B> {}
#[diagnostic::on_unimplemented(
message = "closure hooks and readiness checks exist on singleton handles only",
label = "this binding is execution-scoped or transient",
note = "register the factory with `singleton(..)`, or move the hook to a singleton"
)]
pub trait HookHost: sealed::State {}
impl<S: HookCapable, B> HookHost for Binding<S, B> {}
impl<S: HookCapable, B> HookHost for Contribution<S, B> {}
pub struct Handle<'m, T: ?Sized, K, C = K> {
record: &'m mut BindingRecord,
_s: PhantomData<fn() -> (PhantomData<T>, K, C)>,
}
impl<'m, T: ?Sized, K, C> Handle<'m, T, K, C> {
pub(crate) fn new(record: &'m mut BindingRecord) -> Self {
Handle { record, _s: PhantomData }
}
fn to<K2, C2>(self) -> Handle<'m, T, K2, C2> {
Handle { record: self.record, _s: PhantomData }
}
fn push_hook<K2>(
self,
kind: HookKind,
run: HookFn,
dependencies: Dependencies,
location: &'static Location<'static>,
) -> Handle<'m, T, K2, C> {
self.record.hooks.push(HookRecord { kind, bound: Bound::Default, run, dependencies, location });
self.to()
}
}
impl<'m, T: ?Sized + Send + Sync + 'static, K, C: SingleBinding> Handle<'m, T, K, C> {
#[track_caller]
pub fn also_as<U: ?Sized + Send + Sync + 'static>(
self,
coerce: impl Fn(Arc<T>) -> Arc<U> + Send + Sync + 'static,
) -> Handle<'m, T, C, C> {
let location = Location::caller();
self.record.also.push(AlsoAs { key: Key::of::<U, ()>(), coerce: coercion::<T, U, _>(coerce), location });
self.to()
}
pub fn qualified<Q: 'static>(self) -> Handle<'m, T, C, C> {
self.record.qualifier = Qualifier::of::<Q>();
self.to()
}
}
impl<'m, T: ?Sized, K, C: HookHost> Handle<'m, T, K, C> {
#[track_caller]
pub fn ready<Args, F, E>(self, check: F) -> Handle<'m, T, ReadyItem<Open, Open>, C>
where
F: Factory<Args, Output = Result<(), E>>,
E: Into<BoxError> + Send + 'static,
{
let location = Location::caller();
let mut dependencies = Dependencies::default();
<F as Factory<Args>>::dependencies(&mut dependencies);
let ready = ReadyRecord {
check: erase_check::<Args, F, E>(check),
dependencies,
retries: 0,
backoff: Duration::ZERO,
backoff_location: None,
whole: Bound::Default,
attempt: Bound::Default,
location,
};
if let Some(replaced) = self.record.ready.replace(ready) {
self.record.replaced_ready.push(replaced.location);
}
self.to()
}
#[track_caller]
pub fn on_init<Args, F, E>(self, hook: F) -> Handle<'m, T, HookItem<Open>, C>
where
F: Factory<Args, Output = Result<(), E>>,
E: Into<BoxError> + Send + 'static,
{
let location = Location::caller();
let mut dependencies = Dependencies::default();
<F as Factory<Args>>::dependencies(&mut dependencies);
self.push_hook(HookKind::OnModuleInit, erase_init_hook::<Args, F, E>(hook), dependencies, location)
}
#[track_caller]
pub fn on_destroy<Args, F>(self, hook: F) -> Handle<'m, T, HookItem<Open>, C>
where
F: Factory<Args, Output = ()>,
{
let location = Location::caller();
let mut dependencies = Dependencies::default();
<F as Factory<Args>>::dependencies(&mut dependencies);
self.push_hook(HookKind::OnModuleDestroy, erase_destroy_hook::<Args, F>(hook), dependencies, location)
}
#[track_caller]
pub fn before_shutdown<Args, F>(self, hook: F) -> Handle<'m, T, HookItem<Open>, C>
where
F: ShutdownFactory<Args>,
{
let location = Location::caller();
let mut dependencies = Dependencies::default();
<F as ShutdownFactory<Args>>::dependencies(&mut dependencies);
self.push_hook(HookKind::BeforeApplicationShutdown, erase_signalled_hook::<Args, F>(hook), dependencies, location)
}
#[track_caller]
pub fn on_shutdown<Args, F>(self, hook: F) -> Handle<'m, T, HookItem<Open>, C>
where
F: ShutdownFactory<Args>,
{
let location = Location::caller();
let mut dependencies = Dependencies::default();
<F as ShutdownFactory<Args>>::dependencies(&mut dependencies);
self.push_hook(HookKind::OnApplicationShutdown, erase_signalled_hook::<Args, F>(hook), dependencies, location)
}
}
impl<'m, T: ?Sized, K: Timeout<C>, C> Handle<'m, T, K, C> {
pub fn timeout(self, d: Duration) -> Handle<'m, T, K::Next, K::Construction> {
<K as sealed::State>::write(&mut *self.record, Bound::After(d));
self.to()
}
}
impl<'m, T: ?Sized, K: Unbounded<C>, C> Handle<'m, T, K, C> {
pub fn unbounded(self) -> Handle<'m, T, K::Next, K::Construction> {
<K as sealed::State>::write_unbounded(&mut *self.record);
self.to()
}
}
impl<'m, T: ?Sized, K: AttemptTimeout, C> Handle<'m, T, K, C> {
pub fn attempt_timeout(self, d: Duration) -> Handle<'m, T, K::Next, C> {
if let Some(ready) = self.record.ready.as_mut() {
ready.attempt = Bound::After(d);
}
self.to()
}
}
impl<'m, T: ?Sized, W, A, C> Handle<'m, T, ReadyItem<W, A>, C> {
pub fn retries(self, n: u32) -> Self {
if let Some(ready) = self.record.ready.as_mut() {
ready.retries = n;
}
self
}
#[track_caller]
pub fn backoff(self, d: Duration) -> Self {
let location = Location::caller();
if let Some(ready) = self.record.ready.as_mut() {
ready.backoff = d;
ready.backoff_location = Some(location);
}
self
}
}