Skip to main content

larastvel_core/queue/
worker.rs

1use std::sync::{Arc, Mutex};
2use std::time::Duration;
3
4use super::{JobBox, JobError, Queue};
5
6/// Default maximum attempts for jobs that do not declare `#[tries]`.
7pub const DEFAULT_MAX_ATTEMPTS: u64 = 3;
8
9#[derive(Debug, Clone)]
10pub struct QueueWorker {
11    queue: Arc<dyn Queue>,
12    running: Arc<Mutex<bool>>,
13}
14
15impl QueueWorker {
16    pub fn new(queue: Arc<dyn Queue>) -> Self {
17        Self {
18            queue,
19            running: Arc::new(Mutex::new(true)),
20        }
21    }
22
23    pub fn queue(&self) -> &Arc<dyn Queue> {
24        &self.queue
25    }
26
27    pub fn stop(&self) {
28        let mut running = self.running.lock().unwrap();
29        *running = false;
30    }
31
32    pub fn is_running(&self) -> bool {
33        let running = self.running.lock().unwrap();
34        *running
35    }
36
37    pub async fn process_next_job(&self) -> Option<Result<(), JobError>> {
38        if let Some((job, attempts)) = self.queue.pop().await {
39            Some(self.execute(job, attempts).await)
40        } else {
41            None
42        }
43    }
44
45    pub async fn work(&self) {
46        loop {
47            let should_run = {
48                let running = self.running.lock().unwrap();
49                *running
50            };
51            if !should_run {
52                break;
53            }
54            if let Some(result) = self.process_next_job().await {
55                if let Err(e) = result {
56                    tracing::error!("[QueueWorker] Job failed permanently: {}", e);
57                }
58            } else {
59                tokio::time::sleep(Duration::from_millis(100)).await;
60            }
61        }
62    }
63
64    pub async fn work_once(&self) -> Result<(), JobError> {
65        if let Some((job, attempts)) = self.queue.pop().await {
66            self.execute(job, attempts).await
67        } else {
68            Err(JobError::Queue("No jobs in queue".to_string()))
69        }
70    }
71
72    /// Run a single job attempt, enforcing the job's declared `#[timeout]`,
73    /// `#[tries]`, `#[backoff]`, and `#[fail_on_timeout]` attributes. Failed
74    /// attempts are released back to the queue; permanent failures are marked
75    /// via `Queue::fail`.
76    async fn execute(&self, job: JobBox, attempts: u64) -> Result<(), JobError> {
77        let name = job.name().to_string();
78        let max = job.max_attempts().unwrap_or(DEFAULT_MAX_ATTEMPTS);
79        let backoff = job.backoff_seconds().unwrap_or(0);
80        let fail_on_timeout = job.fail_on_timeout();
81
82        let outcome = match job.timeout_seconds() {
83            Some(secs) => tokio::time::timeout(Duration::from_secs(secs), job.handle()).await,
84            None => Ok(job.handle().await),
85        };
86
87        match outcome {
88            Ok(Ok(())) => {
89                self.queue.job_succeeded(job).await?;
90                Ok(())
91            }
92            Ok(Err(e)) => {
93                tracing::warn!(
94                    "[QueueWorker] Job {} failed on attempt {}/{}: {}",
95                    name,
96                    attempts,
97                    max,
98                    e
99                );
100                if attempts >= max {
101                    self.queue.fail(job, e.to_string()).await?;
102                    tracing::error!(
103                        "[QueueWorker] Job {} failed permanently after {} attempts",
104                        name,
105                        attempts
106                    );
107                    Err(e)
108                } else {
109                    self.queue.release(job, attempts, backoff).await?;
110                    tracing::warn!(
111                        "[QueueWorker] Job {} released for retry (attempt {}/{})",
112                        name,
113                        attempts,
114                        max
115                    );
116                    Ok(())
117                }
118            }
119            Err(_) => {
120                tracing::warn!(
121                    "[QueueWorker] Job {} timed out on attempt {}/{}",
122                    name,
123                    attempts,
124                    max
125                );
126                if fail_on_timeout || attempts >= max {
127                    self.queue
128                        .fail(job, format!("Job {} timed out", name))
129                        .await?;
130                    tracing::error!(
131                        "[QueueWorker] Job {} timed out and failed permanently",
132                        name
133                    );
134                    Err(JobError::Failed(format!("Job {} timed out", name)))
135                } else {
136                    self.queue.release(job, attempts, backoff).await?;
137                    tracing::warn!(
138                        "[QueueWorker] Job {} released after timeout (attempt {}/{})",
139                        name,
140                        attempts,
141                        max
142                    );
143                    Ok(())
144                }
145            }
146        }
147    }
148}