use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use super::waiters::{fail_cause, hnil_in, lock};
use crate::failure::Never;
use crate::failure::{Cause, Exit};
use crate::kernel::{Effect, ExitKind, sleep, succeed, suspend, yield_fiber};
use crate::runtime::FiberHandle;
use crate::scope::Scope;
#[derive(Clone, Debug)]
pub struct RestartIntensity {
max_restarts: u32,
within: Duration,
events: VecDeque<Instant>,
}
impl RestartIntensity {
pub fn new(max_restarts: u32, within: Duration) -> Self {
Self {
max_restarts,
within,
events: VecDeque::new(),
}
}
pub fn note(&mut self, now: Instant) -> bool {
self.events.push_back(now);
let window_start = now.checked_sub(self.within).unwrap_or(now);
while self.events.front().is_some_and(|t| *t < window_start) {
self.events.pop_front();
}
self.events.len() <= self.max_restarts as usize
}
pub fn max_restarts(&self) -> u32 {
self.max_restarts
}
pub fn within(&self) -> Duration {
self.within
}
}
#[derive(Clone, Debug)]
pub enum SupervisorPolicy<A = ()> {
Terminate,
Restart {
delay: Duration,
},
RestartWithLimit {
limit: u64,
delay: Duration,
},
Escalate,
Ignore {
recover: A,
},
}
type Make<A, E, R> = Arc<Mutex<dyn FnMut() -> Effect<A, E, R> + Send>>;
pub fn supervised<A, E, R, F>(policy: SupervisorPolicy<A>, make: F) -> Effect<A, E, R>
where
A: Clone + Send + Sync + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
F: FnMut() -> Effect<A, E, R> + Send + 'static,
{
attempt(Arc::new(policy), Arc::new(Mutex::new(make)), 0, None)
}
fn attempt<A, E, R>(
policy: Arc<SupervisorPolicy<A>>,
make: Make<A, E, R>,
used: u64,
acc: Option<Cause<E>>,
) -> Effect<A, E, R>
where
A: Clone + Send + Sync + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
suspend(move || {
let eff = (*lock(&make))();
eff.exit::<E>().flat_map(move |exit| match exit {
Exit::Success(a) => succeed(a),
Exit::Failure(c) => on_failure(policy, make, used, acc, c),
})
})
}
fn pause<E: Send + 'static, R: Send + Sync + 'static>(d: Duration) -> Effect<(), E, R> {
if d.is_zero() { yield_fiber() } else { sleep(d) }
}
fn on_failure<A, E, R>(
policy: Arc<SupervisorPolicy<A>>,
make: Make<A, E, R>,
used: u64,
acc: Option<Cause<E>>,
cause: Cause<E>,
) -> Effect<A, E, R>
where
A: Clone + Send + Sync + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
if ExitKind::of_cause(&cause) == ExitKind::Interrupt {
return fail_cause(cause);
}
match &*policy {
SupervisorPolicy::Terminate | SupervisorPolicy::Escalate => fail_cause(cause),
SupervisorPolicy::Ignore { recover } => succeed(recover.clone()),
SupervisorPolicy::Restart { delay } => {
let d = *delay;
pause(d).then(attempt(policy, make, used, acc))
}
SupervisorPolicy::RestartWithLimit { limit, delay } => {
let all = match acc {
None => cause,
Some(prev) => Cause::then(prev, cause),
};
if used >= *limit {
return fail_cause(all);
}
let d = *delay;
pause(d).then(attempt(policy, make, used + 1, Some(all)))
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Supervisor {
scope: Scope,
}
impl Supervisor {
pub fn new() -> Self {
Self {
scope: Scope::new(),
}
}
pub fn scope(&self) -> &Scope {
&self.scope
}
pub fn is_shutdown(&self) -> bool {
self.scope.is_closed()
}
pub fn fork<A, E, R>(&self, eff: Effect<A, E, R>) -> Effect<FiberHandle<A, E>, Never, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
self.scope.fork_in(eff)
}
pub fn spawn<A, E, R, F>(
&self,
policy: SupervisorPolicy<A>,
make: F,
) -> Effect<FiberHandle<A, E>, Never, R>
where
A: Clone + Send + Sync + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
F: FnMut() -> Effect<A, E, R> + Send + 'static,
{
self.fork(supervised(policy, make))
}
pub fn shutdown<E, R>(&self) -> Effect<(), E, R>
where
E: Send + 'static,
R: Send + Sync + 'static,
{
hnil_in(self.scope.close(ExitKind::Interrupt).widen())
}
pub fn attach_to<E, R>(&self, parent: &Scope) -> Effect<(), E, R>
where
E: Send + 'static,
R: Send + Sync + 'static,
{
parent.add_finalizer(self.scope.close(ExitKind::Interrupt))
}
}