Skip to main content

mytheclipse_queue/
worker.rs

1//! Worker pool for processing queued jobs with retry, backoff, and graceful shutdown.
2
3use std::pin::Pin;
4use std::sync::Arc;
5use std::time::Duration;
6
7use tokio::sync::Semaphore;
8
9use crate::error::JobError;
10use crate::job::Job;
11use crate::traits::Queue;
12
13/// A future returned by a job handler.
14pub type JobFuture = Pin<Box<dyn std::future::Future<Output = Result<(), JobError>> + Send>>;
15
16/// A handler for processing a single job.
17pub trait JobHandler: Send + Sync {
18    fn handle(&self, job: Job) -> JobFuture;
19}
20
21impl<F, Fut> JobHandler for F
22where
23    F: Fn(Job) -> Fut + Send + Sync,
24    Fut: std::future::Future<Output = Result<(), JobError>> + Send + 'static,
25{
26    fn handle(&self, job: Job) -> JobFuture {
27        Box::pin((self)(job))
28    }
29}
30
31/// Configuration for the worker pool.
32#[derive(Debug, Clone)]
33pub struct WorkerConfig {
34    /// Maximum concurrent job handlers.
35    pub concurrency: usize,
36    /// Maximum number of retry attempts (0 = no retries).
37    pub max_retries: u32,
38    /// Base delay for exponential backoff between retries.
39    pub retry_base_delay: Duration,
40    /// Maximum delay cap for retry backoff.
41    pub retry_max_delay: Duration,
42    /// Backoff multiplier.
43    pub retry_factor: f64,
44    /// Visibility timeout for in-progress jobs.
45    pub visibility_timeout: Duration,
46    /// Polling interval when a queue is empty.
47    pub poll_interval: Duration,
48}
49
50impl Default for WorkerConfig {
51    fn default() -> Self {
52        Self {
53            concurrency: 4,
54            max_retries: 3,
55            retry_base_delay: Duration::from_millis(500),
56            retry_max_delay: Duration::from_secs(10),
57            retry_factor: 2.0,
58            visibility_timeout: Duration::from_secs(30),
59            poll_interval: Duration::from_millis(100),
60        }
61    }
62}
63
64/// A pool of workers consuming jobs from a `Queue`.
65pub struct WorkerPool<Q: Queue + 'static> {
66    queue: Arc<Q>,
67    config: WorkerConfig,
68    semaphore: Arc<Semaphore>,
69}
70
71impl<Q: Queue + 'static> WorkerPool<Q> {
72    /// Creates a new worker pool with the given concurrency.
73    pub fn new(queue: Q, concurrency: usize) -> Self {
74        Self::with_config(
75            queue,
76            WorkerConfig {
77                concurrency,
78                ..Default::default()
79            },
80        )
81    }
82
83    /// Creates a new worker pool with explicit configuration.
84    pub fn with_config(queue: Q, config: WorkerConfig) -> Self {
85        let sem = Arc::new(Semaphore::new(config.concurrency.max(1)));
86        Self {
87            queue: Arc::new(queue),
88            config,
89            semaphore: sem,
90        }
91    }
92
93    /// Starts `concurrency` workers consuming from `topic`.
94    pub fn start<H>(&self, topic: &str, handler: H)
95    where
96        H: JobHandler + 'static,
97    {
98        let queue = Arc::clone(&self.queue);
99        let config = self.config.clone();
100        let semaphore = Arc::clone(&self.semaphore);
101        let handler: Arc<dyn JobHandler> = Arc::new(handler);
102        let topic_owned = topic.to_string();
103
104        for _ in 0..config.concurrency {
105            let q = Arc::clone(&queue);
106            let sem = Arc::clone(&semaphore);
107            let h = Arc::clone(&handler);
108            let cfg = config.clone();
109            let topic_inner = topic_owned.clone();
110
111            tokio::spawn(async move {
112                loop {
113                    match q.dequeue(&topic_inner, cfg.poll_interval).await {
114                        Ok(Some(job)) => {
115                            let _permit = sem.clone().acquire_owned().await;
116                            let q2 = Arc::clone(&q);
117                            let h2 = Arc::clone(&h);
118                            let cfg2 = cfg.clone();
119                            let t2 = topic_inner.clone();
120                            let j2 = job.clone();
121
122                            tokio::spawn(async move {
123                                let fut = h2.handle(j2.clone());
124                                match fut.await {
125                                    Ok(()) => {
126                                        let _ = q2.ack(&j2).await;
127                                    }
128                                    Err(_) => {
129                                        if j2.attempt < cfg2.max_retries {
130                                            let _ = q2.nack(&j2, true).await;
131                                        } else {
132                                            let _ = q2.dlq_move(&t2, j2.clone()).await;
133                                            let _ = q2.nack(&j2, false).await;
134                                        }
135                                    }
136                                }
137                            });
138                        }
139                        Ok(None) => {}
140                        Err(e) => {
141                            tracing::error!("queue error: {e}");
142                            tokio::time::sleep(cfg.poll_interval).await;
143                        }
144                    }
145                }
146            });
147        }
148    }
149}
150
151/// Computes the (capped) exponential backoff delay.
152pub fn retry_delay(config: &WorkerConfig, attempt: u32) -> Duration {
153    let exponent = attempt as f64;
154    let computed =
155        config.retry_base_delay.as_millis() as f64 * config.retry_factor.powf(exponent.max(0.0));
156    let capped = computed.min(config.retry_max_delay.as_millis() as f64);
157    Duration::from_millis(capped as u64)
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn retry_delay_bounded() {
166        let config = WorkerConfig::default();
167        let d = retry_delay(&config, 0);
168        assert!(d <= config.retry_max_delay);
169    }
170}