1use async_trait::async_trait;
7use std::collections::HashMap;
8
9use crate::core::Job;
10use crate::error::Result;
11
12pub mod activator;
13pub mod processor;
14pub mod retry;
15pub mod scheduler;
16pub mod server;
17pub mod worker;
18
19pub use activator::JobActivator;
20pub use processor::JobProcessor;
21pub use retry::{RetryPolicy, RetryStrategy};
22pub use scheduler::JobScheduler;
23pub use server::{BackgroundJobServer, ServerConfig};
24pub use worker::{WorkerConfig, WorkerContext, WorkerResult};
25
26#[async_trait]
31pub trait Worker: Send + Sync {
32 async fn execute(&self, job: &Job, context: &WorkerContext) -> Result<WorkerResult>;
42
43 fn method_name(&self) -> &str;
45
46 fn can_handle(&self, method: &str) -> bool {
48 self.method_name() == method
49 }
50}
51
52#[derive(Default)]
57pub struct WorkerRegistry {
58 workers: HashMap<String, Box<dyn Worker>>,
59}
60
61impl WorkerRegistry {
62 pub fn new() -> Self {
64 Self {
65 workers: HashMap::new(),
66 }
67 }
68
69 pub fn register<W>(&mut self, worker: W)
71 where
72 W: Worker + 'static,
73 {
74 let method_name = worker.method_name().to_string();
75 self.workers.insert(method_name, Box::new(worker));
76 }
77
78 pub fn get_worker(&self, method: &str) -> Option<&dyn Worker> {
80 self.workers.get(method).map(|w| w.as_ref())
81 }
82
83 pub fn get_methods(&self) -> Vec<&str> {
85 self.workers.keys().map(|s| s.as_str()).collect()
86 }
87
88 pub fn has_worker(&self, method: &str) -> bool {
90 self.workers.contains_key(method)
91 }
92
93 pub fn len(&self) -> usize {
95 self.workers.len()
96 }
97
98 pub fn is_empty(&self) -> bool {
100 self.workers.is_empty()
101 }
102}