use std::collections::HashMap;
use std::sync::Arc;
use crate::handler::TaskHandler;
use crate::TaskConfig;
#[derive(Clone)]
pub struct HandlerRegistry {
handlers: HashMap<i16, (Arc<dyn TaskHandler>, TaskConfig)>,
}
impl HandlerRegistry {
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
}
}
pub fn register(
&mut self,
handler: impl TaskHandler + 'static,
config: TaskConfig,
) -> &mut Self {
let task_type = handler.task_type();
if task_type != config.task_type {
tracing::warn!(
"Handler task_type ({}) 与 config.task_type ({}) 不一致,将使用 config 中的值",
task_type, config.task_type
);
}
self.handlers
.insert(config.task_type, (Arc::new(handler), config));
self
}
pub fn from_discovered(&mut self) -> &mut Self {
for entry in crate::TASK_HANDLERS {
let handler = (entry.handler_fn)();
let config = (entry.config_fn)();
self.handlers
.insert(entry.task_type, (Arc::from(handler), config));
}
self
}
pub fn get(&self, task_type: i16) -> Option<(Arc<dyn TaskHandler>, &TaskConfig)> {
self.handlers
.get(&task_type)
.map(|(h, c)| (Arc::clone(h), c))
}
pub fn task_types(&self) -> Vec<i16> {
self.handlers.keys().copied().collect()
}
pub fn get_config(&self, task_type: i16) -> Option<&TaskConfig> {
self.handlers.get(&task_type).map(|(_, c)| c)
}
pub fn len(&self) -> usize {
self.handlers.len()
}
pub fn is_empty(&self) -> bool {
self.handlers.is_empty()
}
}
impl Default for HandlerRegistry {
fn default() -> Self {
Self::new()
}
}