use std::collections::HashMap;
use crate::actor::ActorId;
use crate::supervision::strategy::RestartStrategy;
use crate::supervision::child::ChildSpec;
pub struct Supervisor {
id: ActorId,
strategy: RestartStrategy,
children: Vec<ChildSpec>,
restart_counts: HashMap<ActorId, usize>,
}
impl Supervisor {
pub fn new(id: ActorId, strategy: RestartStrategy) -> Self {
Self {
id,
strategy,
children: Vec::new(),
restart_counts: HashMap::new(),
}
}
pub fn child(&mut self, spec: ChildSpec) -> &mut Self {
self.children.push(spec);
self
}
pub fn id(&self) -> ActorId {
self.id
}
pub fn strategy(&self) -> &RestartStrategy {
&self.strategy
}
pub fn children(&self) -> &[ChildSpec] {
&self.children
}
pub fn handle_child_failure(&mut self, child_id: ActorId) -> bool {
let count = self.restart_counts.entry(child_id).or_insert(0);
*count += 1;
match &self.strategy {
RestartStrategy::OneForOne { max_restarts, .. } => {
if *count > *max_restarts {
tracing::error!(
child_id = %child_id,
restart_count = *count,
"Too many restarts, escalating"
);
false
} else {
tracing::warn!(
child_id = %child_id,
restart_count = *count,
"Restarting actor"
);
true
}
}
}
}
}