1use std::collections::HashMap;
2use std::sync::Arc;
3
4use crate::handler::TaskHandler;
5use crate::TaskConfig;
6
7#[derive(Clone)]
12pub struct HandlerRegistry {
13 handlers: HashMap<i16, (Arc<dyn TaskHandler>, TaskConfig)>,
15}
16
17impl HandlerRegistry {
18 pub fn new() -> Self {
20 Self {
21 handlers: HashMap::new(),
22 }
23 }
24
25 pub fn register(
27 &mut self,
28 handler: impl TaskHandler + 'static,
29 config: TaskConfig,
30 ) -> &mut Self {
31 let task_type = handler.task_type();
32 if task_type != config.task_type {
33 tracing::warn!(
34 "Handler task_type ({}) 与 config.task_type ({}) 不一致,将使用 config 中的值",
35 task_type, config.task_type
36 );
37 }
38 self.handlers
39 .insert(config.task_type, (Arc::new(handler), config));
40 self
41 }
42
43 pub fn from_discovered(&mut self) -> &mut Self {
48 for entry in crate::TASK_HANDLERS {
49 let handler = (entry.handler_fn)();
50 let config = (entry.config_fn)();
51 self.handlers
52 .insert(entry.task_type, (Arc::from(handler), config));
53 }
54 self
55 }
56
57 pub fn get(&self, task_type: i16) -> Option<(Arc<dyn TaskHandler>, &TaskConfig)> {
59 self.handlers
60 .get(&task_type)
61 .map(|(h, c)| (Arc::clone(h), c))
62 }
63
64 pub fn task_types(&self) -> Vec<i16> {
66 self.handlers.keys().copied().collect()
67 }
68
69 pub fn get_config(&self, task_type: i16) -> Option<&TaskConfig> {
71 self.handlers.get(&task_type).map(|(_, c)| c)
72 }
73
74 pub fn len(&self) -> usize {
76 self.handlers.len()
77 }
78
79 pub fn is_empty(&self) -> bool {
81 self.handlers.is_empty()
82 }
83}
84
85impl Default for HandlerRegistry {
86 fn default() -> Self {
87 Self::new()
88 }
89}