mytheclipse_queue/
worker.rs1use 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
13pub type JobFuture = Pin<Box<dyn std::future::Future<Output = Result<(), JobError>> + Send>>;
15
16pub 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#[derive(Debug, Clone)]
33pub struct WorkerConfig {
34 pub concurrency: usize,
36 pub max_retries: u32,
38 pub retry_base_delay: Duration,
40 pub retry_max_delay: Duration,
42 pub retry_factor: f64,
44 pub visibility_timeout: Duration,
46 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
64pub 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 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 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 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
151pub 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}