Skip to main content

larastvel_core/queue/
database.rs

1use std::sync::{Arc, Mutex};
2
3use async_trait::async_trait;
4
5use super::{
6    batches::{JobBatch, PendingBatch},
7    JobBox, JobError, Queue,
8};
9
10pub type JobResolver = Arc<dyn Fn(&str, &str) -> Option<JobBox> + Send + Sync>;
11
12type Reserved = Option<(i64, Option<String>)>;
13
14pub struct DatabaseQueue {
15    name: String,
16    table_name: String,
17    db: sea_orm::DatabaseConnection,
18    resolver: JobResolver,
19    last_reserved: Arc<Mutex<Reserved>>,
20    failed_table_name: String,
21    batch_table_name: String,
22}
23
24impl std::fmt::Debug for DatabaseQueue {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        f.debug_struct("DatabaseQueue")
27            .field("name", &self.name)
28            .field("table_name", &self.table_name)
29            .field("db", &self.db)
30            .field("resolver", &"<closure>")
31            .finish()
32    }
33}
34
35impl Clone for DatabaseQueue {
36    fn clone(&self) -> Self {
37        Self {
38            name: self.name.clone(),
39            table_name: self.table_name.clone(),
40            db: self.db.clone(),
41            resolver: self.resolver.clone(),
42            last_reserved: self.last_reserved.clone(),
43            failed_table_name: self.failed_table_name.clone(),
44            batch_table_name: self.batch_table_name.clone(),
45        }
46    }
47}
48
49impl DatabaseQueue {
50    pub fn new(name: &str, db: sea_orm::DatabaseConnection, resolver: JobResolver) -> Self {
51        Self {
52            name: name.to_string(),
53            table_name: "jobs".to_string(),
54            db,
55            resolver,
56            last_reserved: Arc::new(Mutex::new(None)),
57            failed_table_name: "failed_jobs".to_string(),
58            batch_table_name: "job_batches".to_string(),
59        }
60    }
61
62    pub fn with_table(mut self, table: &str) -> Self {
63        self.table_name = table.to_string();
64        self
65    }
66
67    /// Set the name of the `failed_jobs` table used to record permanent
68    /// failures.
69    pub fn with_failed_table(mut self, table: &str) -> Self {
70        self.failed_table_name = table.to_string();
71        self
72    }
73
74    pub async fn ensure_table_exists(&self) -> Result<(), JobError> {
75        let sql = format!(
76            "CREATE TABLE IF NOT EXISTS {} (
77                id INTEGER PRIMARY KEY AUTOINCREMENT,
78                queue TEXT NOT NULL DEFAULT 'default',
79                payload TEXT NOT NULL,
80                class TEXT NOT NULL DEFAULT '',
81                attempts INTEGER NOT NULL DEFAULT 0,
82                max_attempts INTEGER NOT NULL DEFAULT 3,
83                reserved_at INTEGER,
84                available_at INTEGER NOT NULL,
85                created_at INTEGER NOT NULL
86            )",
87            self.table_name
88        );
89        use sea_orm::ConnectionTrait;
90        self.db
91            .execute(sea_orm::Statement::from_string(
92                sea_orm::DatabaseBackend::Sqlite,
93                sql,
94            ))
95            .await
96            .map_err(|e| JobError::Queue(format!("Failed to create jobs table: {}", e)))?;
97        Ok(())
98    }
99
100    /// Ensure the `failed_jobs` table exists (used by [`Queue::fail`]).
101    pub async fn ensure_failed_table_exists(&self) -> Result<(), JobError> {
102        super::FailedJobStore::new(self.db.clone())
103            .with_table(&self.failed_table_name)
104            .ensure_table_exists()
105            .await
106    }
107
108    /// Set the name of the `job_batches` table used to track batches.
109    pub fn with_batches_table(mut self, table: &str) -> Self {
110        self.batch_table_name = table.to_string();
111        self
112    }
113
114    /// Ensure the `job_batches` table exists.
115    pub async fn ensure_batches_table_exists(&self) -> Result<(), JobError> {
116        super::JobBatchStore::new(self.db.clone())
117            .with_table(&self.batch_table_name)
118            .ensure_table_exists()
119            .await
120    }
121
122    /// Dispatch a pending batch (Laravel's `Bus::batch([...])->dispatch()`).
123    pub async fn dispatch_batch(&self, pending: &PendingBatch) -> Result<JobBatch, JobError> {
124        self.ensure_batches_table_exists().await?;
125
126        let now = now_unix();
127        let id = uuid::Uuid::new_v4().to_string();
128        let total = pending.jobs().len() as i64;
129        let batch = JobBatch {
130            id,
131            name: pending.name_of().to_string(),
132            total_jobs: total,
133            pending_jobs: total,
134            failed_jobs: 0,
135            cancelled: false,
136            created_at: now,
137            finished_at: None,
138            cancelled_at: None,
139        };
140
141        super::JobBatchStore::new(self.db.clone())
142            .with_table(&self.batch_table_name)
143            .insert(&batch)
144            .await?;
145
146        for job in pending.jobs() {
147            let payload = serde_json::to_string(&serde_json::json!({
148                "name": job.name(),
149                "batch_id": batch.id,
150            }))
151            .map_err(|e| JobError::Queue(format!("Serialization error: {}", e)))?;
152
153            let max_attempts = job.max_attempts().unwrap_or(3);
154            let sql = format!(
155                "INSERT INTO {} (queue, payload, class, attempts, max_attempts, available_at, created_at)
156                 VALUES (?1, ?2, ?3, 0, ?4, ?5, ?5)",
157                self.table_name
158            );
159            use sea_orm::ConnectionTrait;
160            self.db
161                .execute(sea_orm::Statement::from_sql_and_values(
162                    sea_orm::DatabaseBackend::Sqlite,
163                    &sql,
164                    [
165                        self.name.clone().into(),
166                        payload.into(),
167                        job.name().to_string().into(),
168                        (max_attempts as i64).into(),
169                        now.into(),
170                    ],
171                ))
172                .await
173                .map_err(|e| JobError::Queue(format!("Failed to push batch job: {}", e)))?;
174        }
175
176        Ok(batch)
177    }
178
179    /// Look up a batch by its id.
180    pub async fn batch(&self, id: &str) -> Result<Option<JobBatch>, JobError> {
181        super::JobBatchStore::new(self.db.clone())
182            .with_table(&self.batch_table_name)
183            .find(id)
184            .await
185    }
186
187    /// Cancel a batch by its id. Reserved jobs finish; the rest are skipped
188    /// by the worker.
189    pub async fn cancel_batch(&self, id: &str) -> Result<(), JobError> {
190        super::JobBatchStore::new(self.db.clone())
191            .with_table(&self.batch_table_name)
192            .cancel(id)
193            .await
194    }
195
196    /// Record the last reserved job as failed in the `failed_jobs` table and
197    /// remove it from the jobs table. If no job was reserved, falls back to
198    /// exhausting its attempts.
199    async fn record_failure(&self, job: JobBox, exception: String) -> Result<(), JobError> {
200        let reserved = self.last_reserved.lock().unwrap().clone();
201        let Some((job_id, batch_id)) = reserved else {
202            return Ok(());
203        };
204
205        if let Some(batch_id) = &batch_id {
206            let store =
207                super::JobBatchStore::new(self.db.clone()).with_table(&self.batch_table_name);
208            store.increment_failed(batch_id).await?;
209            store.decrement_pending(batch_id).await?;
210            store.mark_finished_if_done(batch_id).await?;
211        }
212
213        let store = super::FailedJobStore::new(self.db.clone()).with_table(&self.failed_table_name);
214        store.ensure_table_exists().await?;
215
216        let class = job.name().to_string();
217        let payload = super::failed::job_payload(job.as_ref());
218
219        store
220            .log(&self.name, &self.name, &class, &payload, &exception)
221            .await?;
222
223        let sql = format!("DELETE FROM {} WHERE id = ?1", self.table_name);
224        use sea_orm::ConnectionTrait;
225        self.db
226            .execute(sea_orm::Statement::from_sql_and_values(
227                sea_orm::DatabaseBackend::Sqlite,
228                &sql,
229                [job_id.into()],
230            ))
231            .await
232            .map_err(|e| JobError::Queue(format!("Failed to remove failed job row: {}", e)))?;
233        Ok(())
234    }
235}
236
237#[async_trait]
238impl Queue for DatabaseQueue {
239    async fn push(&self, job: JobBox) -> Result<(), JobError> {
240        let payload = serde_json::to_string(&serde_json::json!({
241            "name": job.name(),
242        }))
243        .map_err(|e| JobError::Queue(format!("Serialization error: {}", e)))?;
244
245        let class = job.name().to_string();
246        let max_attempts = job.max_attempts().unwrap_or(3);
247        let now = std::time::SystemTime::now()
248            .duration_since(std::time::UNIX_EPOCH)
249            .unwrap()
250            .as_secs() as i64;
251
252        let sql = format!(
253            "INSERT INTO {} (queue, payload, class, attempts, max_attempts, available_at, created_at)
254             VALUES (?1, ?2, ?3, 0, ?4, ?5, ?5)",
255            self.table_name
256        );
257        use sea_orm::ConnectionTrait;
258        self.db
259            .execute(sea_orm::Statement::from_sql_and_values(
260                sea_orm::DatabaseBackend::Sqlite,
261                &sql,
262                [
263                    self.name.clone().into(),
264                    payload.into(),
265                    class.into(),
266                    (max_attempts as i64).into(),
267                    now.into(),
268                ],
269            ))
270            .await
271            .map_err(|e| JobError::Queue(format!("Failed to push job: {}", e)))?;
272        Ok(())
273    }
274
275    async fn pop(&self) -> Option<(JobBox, u64)> {
276        let now = now_unix();
277        let store = super::JobBatchStore::new(self.db.clone()).with_table(&self.batch_table_name);
278
279        loop {
280            let sql = format!(
281                "SELECT id, payload, class, attempts FROM {}
282                 WHERE queue = ?1 AND (reserved_at IS NULL OR reserved_at < ?2)
283                 AND attempts < max_attempts
284                 AND available_at <= ?2
285                 ORDER BY id ASC LIMIT 1",
286                self.table_name
287            );
288            use sea_orm::{ConnectionTrait, QueryResult};
289            let result: Vec<QueryResult> = self
290                .db
291                .query_all(sea_orm::Statement::from_sql_and_values(
292                    sea_orm::DatabaseBackend::Sqlite,
293                    &sql,
294                    [self.name.clone().into(), now.into(), now.into()],
295                ))
296                .await
297                .ok()?;
298
299            let row = result.into_iter().next()?;
300
301            let class: String = row.try_get_by_index::<String>(2).ok()?;
302            let payload: String = row.try_get_by_index::<String>(1).ok()?;
303            let id: Option<i64> = row.try_get_by_index::<i64>(0).ok();
304            let batch_id: Option<String> =
305                serde_json::from_str(&payload)
306                    .ok()
307                    .and_then(|v: serde_json::Value| {
308                        v.get("batch_id").and_then(|b| b.as_str()).map(String::from)
309                    });
310
311            if let Some(batch_id) = &batch_id {
312                if store.is_cancelled(batch_id).await.unwrap_or(false) {
313                    if let Some(job_id) = id {
314                        let delete_sql = format!("DELETE FROM {} WHERE id = ?1", self.table_name);
315                        let _ = self
316                            .db
317                            .execute(sea_orm::Statement::from_sql_and_values(
318                                sea_orm::DatabaseBackend::Sqlite,
319                                &delete_sql,
320                                [job_id.into()],
321                            ))
322                            .await;
323                    }
324                    continue;
325                }
326            }
327
328            let resolver = self.resolver.clone();
329            let job = resolver(&class, &payload)?;
330
331            let attempts: i64 = row.try_get_by_index::<i64>(3).unwrap_or(0);
332            if let Some(job_id) = id {
333                let update_sql = format!(
334                    "UPDATE {} SET reserved_at = ?1, attempts = attempts + 1 WHERE id = ?2",
335                    self.table_name
336                );
337                let _ = self
338                    .db
339                    .execute(sea_orm::Statement::from_sql_and_values(
340                        sea_orm::DatabaseBackend::Sqlite,
341                        &update_sql,
342                        [now.into(), job_id.into()],
343                    ))
344                    .await;
345
346                let mut last = self.last_reserved.lock().unwrap();
347                *last = Some((job_id, batch_id));
348            }
349
350            return Some((job, (attempts + 1) as u64));
351        }
352    }
353
354    /// Release the last reserved row back to the queue with a delay, keeping
355    /// its attempt count. Assumes a single worker per queue instance.
356    async fn release(
357        &self,
358        job: JobBox,
359        attempts: u64,
360        delay_seconds: u64,
361    ) -> Result<(), JobError> {
362        let _ = (job, attempts);
363        let id = {
364            let last = self.last_reserved.lock().unwrap();
365            last.as_ref().map(|(job_id, _)| *job_id)
366        };
367        let Some(job_id) = id else {
368            return Ok(());
369        };
370        let now = std::time::SystemTime::now()
371            .duration_since(std::time::UNIX_EPOCH)
372            .unwrap()
373            .as_secs() as i64;
374
375        let sql = format!(
376            "UPDATE {} SET reserved_at = NULL, available_at = ?1 WHERE id = ?2",
377            self.table_name
378        );
379        use sea_orm::ConnectionTrait;
380        self.db
381            .execute(sea_orm::Statement::from_sql_and_values(
382                sea_orm::DatabaseBackend::Sqlite,
383                &sql,
384                [(now + delay_seconds as i64).into(), job_id.into()],
385            ))
386            .await
387            .map_err(|e| JobError::Queue(format!("Failed to release job: {}", e)))?;
388        Ok(())
389    }
390
391    /// Permanently fail the last reserved row by recording it in the
392    /// `failed_jobs` table and removing it from the jobs table.
393    async fn fail(&self, job: JobBox, exception: String) -> Result<(), JobError> {
394        self.record_failure(job, exception).await
395    }
396
397    /// Called by the worker after a job finishes successfully: decrements the
398    /// pending count of the job's batch (if any) and marks it finished.
399    async fn job_succeeded(&self, job: JobBox) -> Result<(), JobError> {
400        let reserved = self.last_reserved.lock().unwrap().clone();
401        let _ = job;
402
403        let Some((_, Some(batch_id))) = reserved else {
404            return Ok(());
405        };
406
407        let store = super::JobBatchStore::new(self.db.clone()).with_table(&self.batch_table_name);
408        store.decrement_pending(&batch_id).await?;
409        store.mark_finished_if_done(&batch_id).await?;
410        Ok(())
411    }
412
413    async fn count(&self) -> usize {
414        let sql = format!(
415            "SELECT COUNT(*) as cnt FROM {} WHERE queue = ?1 AND attempts < max_attempts",
416            self.table_name
417        );
418        use sea_orm::ConnectionTrait;
419        let result = self
420            .db
421            .query_one(sea_orm::Statement::from_sql_and_values(
422                sea_orm::DatabaseBackend::Sqlite,
423                &sql,
424                [self.name.clone().into()],
425            ))
426            .await;
427
428        match result {
429            Ok(Some(row)) => {
430                let cnt: Option<i64> = row.try_get_by_index(0).ok();
431                cnt.unwrap_or(0) as usize
432            }
433            _ => 0,
434        }
435    }
436
437    fn name(&self) -> &str {
438        &self.name
439    }
440}
441
442fn now_unix() -> i64 {
443    std::time::SystemTime::now()
444        .duration_since(std::time::UNIX_EPOCH)
445        .unwrap()
446        .as_secs() as i64
447}