use crate::error::types::SupervisorError;
use crate::id::types::{ChildId, SupervisorPath};
use crate::registry::entry::ChildRuntime;
use crate::tree::builder::SupervisorTree;
use std::collections::HashMap;
#[derive(Debug, Clone, Default)]
pub struct RegistryStore {
by_child_id: HashMap<ChildId, ChildRuntime>,
by_path: HashMap<String, ChildId>,
declaration_order: Vec<ChildId>,
}
impl RegistryStore {
pub fn new() -> Self {
Self::default()
}
pub fn register_tree(&mut self, tree: &SupervisorTree) -> Result<(), SupervisorError> {
for node in &tree.nodes {
self.register(ChildRuntime::new(node.child.clone(), node.path.clone()))?;
}
Ok(())
}
pub fn register(&mut self, runtime: ChildRuntime) -> Result<(), SupervisorError> {
if self.by_child_id.contains_key(&runtime.id) {
return Err(SupervisorError::fatal_config(format!(
"duplicate child id: {}",
runtime.id
)));
}
let path = runtime.path.to_string();
if self.by_path.contains_key(&path) {
return Err(SupervisorError::fatal_config(format!(
"duplicate child path: {path}"
)));
}
self.declaration_order.push(runtime.id.clone());
self.by_path.insert(path, runtime.id.clone());
self.by_child_id.insert(runtime.id.clone(), runtime);
Ok(())
}
pub fn child(&self, child_id: &ChildId) -> Option<&ChildRuntime> {
self.by_child_id.get(child_id)
}
pub fn child_mut(&mut self, child_id: &ChildId) -> Option<&mut ChildRuntime> {
self.by_child_id.get_mut(child_id)
}
pub fn child_by_path(&self, path: &SupervisorPath) -> Option<&ChildRuntime> {
self.by_path
.get(&path.to_string())
.and_then(|child_id| self.by_child_id.get(child_id))
}
pub fn declaration_order(&self) -> &[ChildId] {
&self.declaration_order
}
}