1use sea_orm::{ConnectionTrait, DatabaseBackend, Statement};
2
3use super::{JobBox, JobError};
4
5#[derive(Debug, Clone)]
8pub struct JobBatch {
9 pub id: String,
10 pub name: String,
11 pub total_jobs: i64,
12 pub pending_jobs: i64,
13 pub failed_jobs: i64,
14 pub cancelled: bool,
15 pub created_at: i64,
16 pub finished_at: Option<i64>,
17 pub cancelled_at: Option<i64>,
18}
19
20impl JobBatch {
21 pub fn progress(&self) -> f64 {
23 if self.total_jobs == 0 {
24 return 1.0;
25 }
26 (self.total_jobs - self.pending_jobs) as f64 / self.total_jobs as f64
27 }
28
29 pub fn pending_jobs(&self) -> i64 {
30 self.pending_jobs
31 }
32
33 pub fn failed_jobs(&self) -> i64 {
34 self.failed_jobs
35 }
36
37 pub fn total_jobs(&self) -> i64 {
38 self.total_jobs
39 }
40
41 pub fn finished(&self) -> bool {
43 self.pending_jobs == 0
44 }
45
46 pub fn cancelled(&self) -> bool {
47 self.cancelled
48 }
49
50 pub async fn refresh(&self, db: &sea_orm::DatabaseConnection) -> Result<JobBatch, JobError> {
52 JobBatchStore::new(db.clone())
53 .find(&self.id)
54 .await?
55 .ok_or_else(|| JobError::Queue(format!("Batch {} not found", self.id)))
56 }
57
58 pub async fn cancel(&self, db: &sea_orm::DatabaseConnection) -> Result<(), JobError> {
61 JobBatchStore::new(db.clone()).cancel(&self.id).await
62 }
63}
64
65#[derive(Debug)]
67pub struct PendingBatch {
68 name: String,
69 jobs: Vec<JobBox>,
70}
71
72impl PendingBatch {
73 pub fn name(mut self, name: impl Into<String>) -> Self {
74 self.name = name.into();
75 self
76 }
77
78 pub fn add_job(mut self, job: JobBox) -> Self {
79 self.jobs.push(job);
80 self
81 }
82
83 pub fn add_many(mut self, jobs: Vec<JobBox>) -> Self {
84 self.jobs.extend(jobs);
85 self
86 }
87
88 pub(crate) fn name_of(&self) -> &str {
89 &self.name
90 }
91
92 pub(crate) fn jobs(&self) -> &[JobBox] {
93 &self.jobs
94 }
95}
96
97pub fn batch(jobs: Vec<JobBox>) -> PendingBatch {
100 PendingBatch {
101 name: String::new(),
102 jobs,
103 }
104}
105
106#[derive(Debug, Clone)]
108pub struct JobBatchStore {
109 db: sea_orm::DatabaseConnection,
110 table_name: String,
111}
112
113impl JobBatchStore {
114 pub fn new(db: sea_orm::DatabaseConnection) -> Self {
115 Self {
116 db,
117 table_name: "job_batches".to_string(),
118 }
119 }
120
121 pub fn with_table(mut self, table: &str) -> Self {
122 self.table_name = table.to_string();
123 self
124 }
125
126 pub fn table_name(&self) -> &str {
127 &self.table_name
128 }
129
130 pub async fn ensure_table_exists(&self) -> Result<(), JobError> {
131 let sql = format!(
132 "CREATE TABLE IF NOT EXISTS {} (
133 id TEXT PRIMARY KEY,
134 name TEXT NOT NULL DEFAULT '',
135 total_jobs INTEGER NOT NULL DEFAULT 0,
136 pending_jobs INTEGER NOT NULL DEFAULT 0,
137 failed_jobs INTEGER NOT NULL DEFAULT 0,
138 cancelled INTEGER NOT NULL DEFAULT 0,
139 created_at INTEGER NOT NULL,
140 finished_at INTEGER,
141 cancelled_at INTEGER
142 )",
143 self.table_name
144 );
145 self.db
146 .execute(Statement::from_string(DatabaseBackend::Sqlite, sql))
147 .await
148 .map_err(|e| JobError::Queue(format!("Failed to create job batches table: {}", e)))?;
149 Ok(())
150 }
151
152 pub async fn insert(&self, batch: &JobBatch) -> Result<(), JobError> {
153 let sql = format!(
154 "INSERT INTO {} (id, name, total_jobs, pending_jobs, failed_jobs, cancelled, created_at, finished_at, cancelled_at)
155 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
156 self.table_name
157 );
158 self.db
159 .execute(Statement::from_sql_and_values(
160 DatabaseBackend::Sqlite,
161 &sql,
162 [
163 batch.id.clone().into(),
164 batch.name.clone().into(),
165 batch.total_jobs.into(),
166 batch.pending_jobs.into(),
167 batch.failed_jobs.into(),
168 (batch.cancelled as i64).into(),
169 batch.created_at.into(),
170 batch
171 .finished_at
172 .map(|v| sea_orm::Value::BigInt(Some(v)))
173 .unwrap_or(sea_orm::Value::BigInt(None)),
174 batch
175 .cancelled_at
176 .map(|v| sea_orm::Value::BigInt(Some(v)))
177 .unwrap_or(sea_orm::Value::BigInt(None)),
178 ],
179 ))
180 .await
181 .map_err(|e| JobError::Queue(format!("Failed to insert batch: {}", e)))?;
182 Ok(())
183 }
184
185 pub async fn find(&self, id: &str) -> Result<Option<JobBatch>, JobError> {
186 let sql = format!(
187 "SELECT id, name, total_jobs, pending_jobs, failed_jobs, cancelled, created_at, finished_at, cancelled_at
188 FROM {} WHERE id = ?1",
189 self.table_name
190 );
191 let result = self
192 .db
193 .query_one(Statement::from_sql_and_values(
194 DatabaseBackend::Sqlite,
195 &sql,
196 [id.into()],
197 ))
198 .await
199 .map_err(|e| JobError::Queue(format!("Failed to find batch: {}", e)))?;
200
201 let Some(row) = result else {
202 return Ok(None);
203 };
204 let get = |idx: usize| row.try_get_by_index::<i64>(idx).ok();
205
206 Ok(Some(JobBatch {
207 id: row
208 .try_get_by_index::<String>(0)
209 .unwrap_or_else(|_| id.to_string()),
210 name: row.try_get_by_index::<String>(1).unwrap_or_default(),
211 total_jobs: get(2).unwrap_or(0),
212 pending_jobs: get(3).unwrap_or(0),
213 failed_jobs: get(4).unwrap_or(0),
214 cancelled: get(5).unwrap_or(0) != 0,
215 created_at: get(6).unwrap_or(0),
216 finished_at: get(7),
217 cancelled_at: get(8),
218 }))
219 }
220
221 pub async fn decrement_pending(&self, id: &str) -> Result<(), JobError> {
222 let sql = format!(
223 "UPDATE {} SET pending_jobs = MAX(pending_jobs - 1, 0) WHERE id = ?1",
224 self.table_name
225 );
226 self.db
227 .execute(Statement::from_sql_and_values(
228 DatabaseBackend::Sqlite,
229 &sql,
230 [id.into()],
231 ))
232 .await
233 .map_err(|e| JobError::Queue(format!("Failed to decrement batch pending: {}", e)))?;
234 Ok(())
235 }
236
237 pub async fn increment_failed(&self, id: &str) -> Result<(), JobError> {
238 let sql = format!(
239 "UPDATE {} SET failed_jobs = failed_jobs + 1 WHERE id = ?1",
240 self.table_name
241 );
242 self.db
243 .execute(Statement::from_sql_and_values(
244 DatabaseBackend::Sqlite,
245 &sql,
246 [id.into()],
247 ))
248 .await
249 .map_err(|e| JobError::Queue(format!("Failed to increment batch failed: {}", e)))?;
250 Ok(())
251 }
252
253 pub async fn mark_finished_if_done(&self, id: &str) -> Result<(), JobError> {
255 let now = now_unix();
256 let sql = format!(
257 "UPDATE {} SET finished_at = ?1 WHERE id = ?2 AND pending_jobs = 0 AND finished_at IS NULL",
258 self.table_name
259 );
260 self.db
261 .execute(Statement::from_sql_and_values(
262 DatabaseBackend::Sqlite,
263 &sql,
264 [now.into(), id.into()],
265 ))
266 .await
267 .map_err(|e| JobError::Queue(format!("Failed to finish batch: {}", e)))?;
268 Ok(())
269 }
270
271 pub async fn cancel(&self, id: &str) -> Result<(), JobError> {
272 let now = now_unix();
273 let sql = format!(
274 "UPDATE {} SET cancelled = 1, cancelled_at = ?1 WHERE id = ?2",
275 self.table_name
276 );
277 self.db
278 .execute(Statement::from_sql_and_values(
279 DatabaseBackend::Sqlite,
280 &sql,
281 [now.into(), id.into()],
282 ))
283 .await
284 .map_err(|e| JobError::Queue(format!("Failed to cancel batch: {}", e)))?;
285 Ok(())
286 }
287
288 pub async fn is_cancelled(&self, id: &str) -> Result<bool, JobError> {
290 let sql = format!("SELECT cancelled FROM {} WHERE id = ?1", self.table_name);
291 let result = self
292 .db
293 .query_one(Statement::from_sql_and_values(
294 DatabaseBackend::Sqlite,
295 &sql,
296 [id.into()],
297 ))
298 .await
299 .map_err(|e| JobError::Queue(format!("Failed to check batch: {}", e)))?;
300
301 match result {
302 Some(row) => Ok(row.try_get_by_index::<i64>(0).unwrap_or(0) != 0),
303 None => Ok(false),
304 }
305 }
306}
307
308fn now_unix() -> i64 {
309 std::time::SystemTime::now()
310 .duration_since(std::time::UNIX_EPOCH)
311 .unwrap()
312 .as_secs() as i64
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318 use crate::queue::{DatabaseQueue, JobResolver, Queue, QueueWorker, ShouldQueue};
319 use std::sync::atomic::{AtomicUsize, Ordering};
320 use std::sync::Arc;
321
322 #[derive(Debug)]
323 struct TestJob {
324 name: String,
325 counter: Arc<AtomicUsize>,
326 fail: bool,
327 }
328
329 #[async_trait::async_trait]
330 impl ShouldQueue for TestJob {
331 async fn handle(&self) -> Result<(), JobError> {
332 if self.fail {
333 return Err(JobError::Failed("boom".into()));
334 }
335 self.counter.fetch_add(1, Ordering::SeqCst);
336 Ok(())
337 }
338 fn name(&self) -> &str {
339 &self.name
340 }
341 fn max_attempts(&self) -> Option<u64> {
342 Some(1)
343 }
344 }
345
346 async fn setup(name: &str) -> (DatabaseQueue, Arc<AtomicUsize>, Arc<AtomicUsize>) {
347 let ok_counter = Arc::new(AtomicUsize::new(0));
348 let fail_counter = Arc::new(AtomicUsize::new(0));
349 let ok = ok_counter.clone();
350 let fail = fail_counter.clone();
351 let resolver: JobResolver = Arc::new(move |class, _payload| -> Option<super::JobBox> {
352 match class {
353 "ok" => Some(Box::new(TestJob {
354 name: "ok".into(),
355 counter: ok.clone(),
356 fail: false,
357 })),
358 "bad" => Some(Box::new(TestJob {
359 name: "bad".into(),
360 counter: fail.clone(),
361 fail: true,
362 })),
363 _ => None,
364 }
365 });
366 let db = sea_orm::Database::connect("sqlite::memory:").await.unwrap();
367 (
368 DatabaseQueue::new(name, db, resolver),
369 ok_counter,
370 fail_counter,
371 )
372 }
373
374 #[tokio::test]
375 async fn batch_tracks_progress_to_finished() {
376 let (queue, counter, _) = setup("default").await;
377 queue.ensure_table_exists().await.unwrap();
378
379 let b = batch(vec![Box::new(TestJob {
380 name: "ok".into(),
381 counter: counter.clone(),
382 fail: false,
383 })])
384 .add_job(Box::new(TestJob {
385 name: "ok".into(),
386 counter: counter.clone(),
387 fail: false,
388 }));
389
390 let batch = queue.dispatch_batch(&b.name("import")).await.unwrap();
391 assert_eq!(batch.total_jobs(), 2);
392 assert_eq!(batch.pending_jobs(), 2);
393 assert!(!batch.finished());
394 assert_eq!(batch.progress(), 0.0);
395
396 let worker = QueueWorker::new(Arc::new(queue.clone()));
397 assert!(worker.process_next_job().await.unwrap().is_ok());
398 let found = queue.batch(&batch.id).await.unwrap().unwrap();
399 assert_eq!(found.pending_jobs(), 1);
400 assert_eq!(found.progress(), 0.5);
401
402 assert!(worker.process_next_job().await.unwrap().is_ok());
403 let found = queue.batch(&batch.id).await.unwrap().unwrap();
404 assert_eq!(found.pending_jobs(), 0);
405 assert!(found.finished());
406 assert!(found.finished_at.is_some());
407 assert_eq!(counter.load(Ordering::SeqCst), 2);
408 }
409
410 #[tokio::test]
411 async fn batch_records_failed_jobs() {
412 let (queue, _, fail_counter) = setup("default").await;
413 queue.ensure_table_exists().await.unwrap();
414 queue.ensure_failed_table_exists().await.unwrap();
415
416 let batch = queue
417 .dispatch_batch(&batch(vec![
418 Box::new(TestJob {
419 name: "bad".into(),
420 counter: fail_counter.clone(),
421 fail: true,
422 }),
423 Box::new(TestJob {
424 name: "ok".into(),
425 counter: fail_counter.clone(),
426 fail: false,
427 }),
428 ]))
429 .await
430 .unwrap();
431
432 let worker = QueueWorker::new(Arc::new(queue.clone()));
433 let _ = worker.process_next_job().await.unwrap();
434 let _ = worker.process_next_job().await.unwrap();
435
436 let found = queue.batch(&batch.id).await.unwrap().unwrap();
437 assert_eq!(found.failed_jobs(), 1);
438 assert_eq!(found.pending_jobs(), 0);
439 assert!(found.finished());
440 assert!(found.finished_at.is_some());
441 }
442
443 #[tokio::test]
444 async fn cancelled_batch_jobs_are_skipped() {
445 let (queue, counter, _) = setup("default").await;
446 queue.ensure_table_exists().await.unwrap();
447
448 let batch = queue
449 .dispatch_batch(&batch(vec![Box::new(TestJob {
450 name: "ok".into(),
451 counter: counter.clone(),
452 fail: false,
453 })]))
454 .await
455 .unwrap();
456
457 queue.cancel_batch(&batch.id).await.unwrap();
458 let found = queue.batch(&batch.id).await.unwrap().unwrap();
459 assert!(found.cancelled());
460 assert!(found.cancelled_at.is_some());
461
462 assert!(queue.pop().await.is_none());
463 assert_eq!(queue.count().await, 0);
464 assert_eq!(counter.load(Ordering::SeqCst), 0);
465 }
466
467 #[tokio::test]
468 async fn batch_refresh_and_cancel_via_instance() {
469 let (queue, counter, _) = setup("default").await;
470 queue.ensure_table_exists().await.unwrap();
471
472 let batch = queue
473 .dispatch_batch(&batch(vec![Box::new(TestJob {
474 name: "ok".into(),
475 counter: counter.clone(),
476 fail: false,
477 })]))
478 .await
479 .unwrap();
480
481 queue.cancel_batch(&batch.id).await.unwrap();
482 let refreshed = queue.batch(&batch.id).await.unwrap().unwrap();
483 assert!(refreshed.cancelled());
484 }
485}