1mod dashboard;
63mod worker;
64
65use std::collections::HashMap;
66use std::future::Future;
67use std::pin::Pin;
68use std::sync::Arc;
69use std::time::Duration;
70
71use serde::de::DeserializeOwned;
72use serde::{Deserialize, Serialize};
73use tokio::sync::Notify;
74
75pub use dashboard::{Dashboard, GATE as DASHBOARD_GATE, QueueCounts, QueueStats};
76pub use worker::Worker;
77
78use crate::db::{Db, Migration, Transaction};
79use crate::{AppState, Error, Result};
80
81pub(crate) const MIGRATIONS: &[Migration] = &[
82 crate::db::framework_migration!("queue", "00010101000100_create_jobs_table"),
83 crate::db::framework_migration!("queue", "00010101000110_add_chains_and_batches_to_jobs"),
84 crate::db::framework_migration!("queue", "00010101000120_add_callback_of_to_jobs"),
85];
86
87const SEALED: &str = "enc:";
89const UNIQUE_PREFIX: &str = "renox:unique:";
91
92pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
95 const NAME: &'static str;
97 const QUEUE: &'static str = "default";
99 const MAX_ATTEMPTS: u32 = 3;
101 const TIMEOUT: Duration = Duration::from_secs(60);
103 const ENCRYPTED: bool = false;
106 const UNIQUE_FOR: Option<Duration> = None;
110
111 fn backoff(attempt: u32) -> Duration {
113 Duration::from_secs(10 * u64::from(attempt))
114 }
115
116 fn unique_id(&self) -> String {
119 String::new()
120 }
121
122 fn middleware(&self) -> Vec<Middleware> {
125 Vec::new()
126 }
127
128 fn handle(self, ctx: JobContext) -> impl Future<Output = Result> + Send;
130
131 fn failed(self, ctx: JobContext, error: String) -> impl Future<Output = ()> + Send {
135 let _ = (ctx, error);
136 async {}
137 }
138}
139
140#[derive(Debug, Clone)]
167pub struct Middleware(MiddlewareKind);
168
169#[derive(Debug, Clone)]
170enum MiddlewareKind {
171 WithoutOverlapping {
172 key: String,
173 release_after: Duration,
174 },
175 RateLimited {
176 key: String,
177 max: u32,
178 per: Duration,
179 },
180}
181
182impl Middleware {
183 pub fn without_overlapping(key: impl Into<String>) -> Self {
186 Self(MiddlewareKind::WithoutOverlapping {
187 key: key.into(),
188 release_after: Duration::from_secs(5),
189 })
190 }
191
192 pub fn rate_limited(key: impl Into<String>, max: u32, per: Duration) -> Self {
195 Self(MiddlewareKind::RateLimited {
196 key: key.into(),
197 max,
198 per: per.max(Duration::from_secs(1)),
199 })
200 }
201
202 pub fn release_after(mut self, wait: Duration) -> Self {
204 if let MiddlewareKind::WithoutOverlapping { release_after, .. } = &mut self.0 {
205 *release_after = wait;
206 }
207 self
208 }
209}
210
211#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
215pub(crate) struct Limit {
216 max: u32,
217 per_secs: u64,
218}
219
220impl Limit {
221 pub(crate) fn new(max: u32, per: Duration) -> Self {
222 Self {
223 max,
224 per_secs: per.as_secs(),
225 }
226 }
227
228 pub(crate) fn middleware(limit: Option<Self>, key: String) -> Vec<Middleware> {
230 limit
231 .map(|l| Middleware::rate_limited(key, l.max, Duration::from_secs(l.per_secs)))
232 .into_iter()
233 .collect()
234 }
235}
236
237#[non_exhaustive]
239pub struct JobContext {
240 pub state: AppState,
242 pub attempt: u32,
244 pub id: i64,
246 pub batch_id: Option<i64>,
249}
250
251type RunFn =
252 Arc<dyn Fn(String, JobContext) -> Pin<Box<dyn Future<Output = Result> + Send>> + Send + Sync>;
253type FailedFn = Arc<
254 dyn Fn(String, JobContext, String) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
255>;
256
257#[derive(Clone)]
259pub(crate) struct JobHandler {
260 pub(crate) run: RunFn,
261 pub(crate) failed: FailedFn,
262 pub(crate) backoff: fn(u32) -> Duration,
263 pub(crate) timeout: Duration,
264 pub(crate) unique_key: fn(&str) -> Option<String>,
266 pub(crate) middleware: fn(&str) -> Vec<Middleware>,
267}
268
269pub(crate) fn handler<J: Job>() -> JobHandler {
271 JobHandler {
272 run: Arc::new(|payload, ctx| {
273 Box::pin(async move {
274 let job: J = serde_json::from_str(&payload).map_err(crate::Error::permanent)?;
276 job.handle(ctx).await
277 })
278 }),
279 failed: Arc::new(|payload, ctx, error| {
280 Box::pin(async move {
281 if let Ok(job) = serde_json::from_str::<J>(&payload) {
282 job.failed(ctx, error).await;
283 }
284 })
285 }),
286 backoff: J::backoff,
287 timeout: J::TIMEOUT,
288 unique_key: |payload| {
289 J::UNIQUE_FOR?;
290 let job: J = serde_json::from_str(payload).ok()?;
291 Some(unique_key::<J>(&job))
292 },
293 middleware: |payload| {
294 serde_json::from_str::<J>(payload)
295 .map(|job| job.middleware())
296 .unwrap_or_default()
297 },
298 }
299}
300
301fn unique_key<J: Job>(job: &J) -> String {
302 format!("{UNIQUE_PREFIX}{}:{}", J::NAME, job.unique_id())
303}
304
305pub(crate) type Handlers = Arc<HashMap<&'static str, JobHandler>>;
306
307#[derive(Debug, Clone, Serialize, Deserialize)]
309pub(crate) struct Encoded {
310 queue: String,
311 job: String,
312 payload: String,
313 max_attempts: u32,
314}
315
316#[derive(Clone)]
318pub struct Queue {
319 db: Db,
320 key: cookie::Key,
321 wake: Arc<Notify>,
322}
323
324pub(crate) fn unix_now() -> i64 {
325 crate::clock::unix_secs()
326}
327
328impl Queue {
329 pub(crate) fn new(db: Db, key: cookie::Key) -> Self {
330 Self {
331 db,
332 key,
333 wake: Arc::new(Notify::new()),
334 }
335 }
336
337 pub(crate) fn wake(&self) -> &Notify {
338 &self.wake
339 }
340
341 pub(crate) fn wake_workers(&self) {
342 self.wake.notify_waiters();
343 }
344
345 fn encode<J: Job>(&self, job: &J, queue: &str) -> Result<Encoded> {
346 let json = serde_json::to_string(job)?;
347 let payload = if J::ENCRYPTED {
348 format!("{SEALED}{}", crate::crypto::seal(&self.key, &json))
349 } else {
350 json
351 };
352 Ok(Encoded {
353 queue: queue.to_owned(),
354 job: J::NAME.to_owned(),
355 payload,
356 max_attempts: J::MAX_ATTEMPTS.max(1),
357 })
358 }
359
360 pub(crate) fn open(&self, payload: &str) -> Result<String> {
362 match payload.strip_prefix(SEALED) {
363 Some(sealed) => Ok(crate::crypto::open(&self.key, sealed).map_err(Error::permanent)?),
364 None => Ok(payload.to_owned()),
365 }
366 }
367
368 pub async fn dispatch<J: Job>(&self, job: J) -> Result<i64> {
370 self.dispatch_after(job, Duration::ZERO).await
371 }
372
373 pub async fn dispatch_after<J: Job>(&self, job: J, delay: Duration) -> Result<i64> {
375 self.push(job, J::QUEUE, delay).await
376 }
377
378 pub async fn dispatch_on<J: Job>(&self, queue: &str, job: J) -> Result<i64> {
380 self.push(job, queue, Duration::ZERO).await
381 }
382
383 async fn push<J: Job>(&self, job: J, queue: &str, delay: Duration) -> Result<i64> {
384 let encoded = self.encode(&job, queue)?;
385 let id = match J::UNIQUE_FOR {
386 None => insert(&self.db, &encoded, delay, None, None, None).await?,
387 Some(ttl) => {
388 let mut tx = self.db.begin().await?;
389 let id =
390 insert_unique(&mut tx, &unique_key::<J>(&job), ttl, &encoded, delay).await?;
391 tx.commit().await?;
392 id
393 }
394 };
395 self.wake.notify_waiters();
396 Ok(id)
397 }
398
399 pub async fn dispatch_in<J: Job>(&self, tx: &mut Transaction, job: J) -> Result<i64> {
419 let encoded = self.encode(&job, J::QUEUE)?;
420 match J::UNIQUE_FOR {
421 None => insert(tx, &encoded, Duration::ZERO, None, None, None).await,
422 Some(ttl) => {
423 insert_unique(tx, &unique_key::<J>(&job), ttl, &encoded, Duration::ZERO).await
424 }
425 }
426 }
427
428 pub fn chain(&self) -> Chain {
432 Chain {
433 queue: self.clone(),
434 jobs: Vec::new(),
435 error: None,
436 }
437 }
438
439 pub fn batch(&self, name: &str) -> Batch {
441 Batch {
442 queue: self.clone(),
443 name: name.to_owned(),
444 jobs: Vec::new(),
445 then: None,
446 catch: None,
447 finally: None,
448 allow_failures: false,
449 error: None,
450 }
451 }
452
453 pub async fn batch_status(&self, id: i64) -> Result<Option<BatchStatus>> {
455 let row = crate::db::sql(
456 "SELECT id, name, total, pending, failed, cancelled_at, finished_at, created_at \
457 FROM job_batches WHERE id = ?",
458 )
459 .bind(id)
460 .fetch_optional(&self.db)
461 .await?;
462 let Some(row) = row else {
463 return Ok(None);
464 };
465 Ok(Some(BatchStatus {
466 id: row.try_get("id")?,
467 name: row.try_get("name")?,
468 total: row.try_get("total")?,
469 pending: row.try_get("pending")?,
470 failed: row.try_get("failed")?,
471 cancelled: row.try_get::<Option<i64>>("cancelled_at")?.is_some(),
472 finished: row.try_get::<Option<i64>>("finished_at")?.is_some(),
473 created_at: crate::db::from_unix(row.try_get("created_at")?),
474 }))
475 }
476
477 pub async fn cancel_batch(&self, id: i64) -> Result<bool> {
479 Ok(crate::db::sql(
480 "UPDATE job_batches SET cancelled_at = ? WHERE id = ? AND cancelled_at IS NULL",
481 )
482 .bind(unix_now())
483 .bind(id)
484 .execute(&self.db)
485 .await?
486 == 1)
487 }
488
489 pub async fn pending(&self) -> Result<i64> {
491 Ok(crate::db::sql("SELECT COUNT(*) FROM jobs")
492 .scalar(&self.db)
493 .await?)
494 }
495
496 pub async fn failed(&self) -> Result<Vec<FailedJob>> {
498 let rows = crate::db::sql(
499 "SELECT id, queue, job, payload, error, failed_at FROM failed_jobs ORDER BY id",
500 )
501 .fetch_all(&self.db)
502 .await?;
503 rows.iter()
504 .map(|r| {
505 Ok(FailedJob {
506 id: r.try_get("id")?,
507 queue: r.try_get("queue")?,
508 job: r.try_get("job")?,
509 payload: r.try_get("payload")?,
510 error: r.try_get("error")?,
511 failed_at: crate::db::from_unix(r.try_get("failed_at")?),
512 })
513 })
514 .collect()
515 }
516
517 pub async fn retry(&self, id: i64) -> Result<bool> {
520 Ok(self.move_failed(Some(id)).await? == 1)
521 }
522
523 pub async fn retry_all(&self) -> Result<u64> {
525 self.move_failed(None).await
526 }
527
528 async fn move_failed(&self, id: Option<i64>) -> Result<u64> {
529 let mut tx = self.db.begin().await?;
530 let filter = if id.is_some() { " WHERE id = ?" } else { "" };
531 let mut batches = crate::db::sql(format!(
532 "UPDATE job_batches SET failed = failed - 1, pending = pending + 1, finished_at = NULL \
533 WHERE id IN (SELECT batch_id FROM failed_jobs{filter})"
534 ));
535 if let Some(id) = id {
536 batches = batches.bind(id);
537 }
538 batches.execute(&mut tx).await?;
539 let insert = format!(
540 "INSERT INTO jobs (queue, job, payload, max_attempts, available_at, created_at, chain, \
541 batch_id, callback_of) SELECT queue, job, payload, max_attempts, ?, ?, chain, batch_id, \
542 callback_of FROM failed_jobs{filter}"
543 );
544 let mut query = crate::db::sql(insert).bind(unix_now()).bind(unix_now());
545 if let Some(id) = id {
546 query = query.bind(id);
547 }
548 let moved = query.execute(&mut tx).await?;
549 let mut delete = crate::db::sql(format!("DELETE FROM failed_jobs{filter}"));
550 if let Some(id) = id {
551 delete = delete.bind(id);
552 }
553 delete.execute(&mut tx).await?;
554 tx.commit().await?;
555 self.wake.notify_waiters();
556 Ok(moved)
557 }
558
559 pub async fn forget_failed(&self, id: i64) -> Result<bool> {
561 Ok(crate::db::sql("DELETE FROM failed_jobs WHERE id = ?")
562 .bind(id)
563 .execute(&self.db)
564 .await?
565 == 1)
566 }
567
568 pub async fn prune_failed(&self, age: Duration) -> Result<u64> {
570 Ok(
571 crate::db::sql("DELETE FROM failed_jobs WHERE failed_at < ?")
572 .bind(unix_now() - age.as_secs() as i64)
573 .execute(&self.db)
574 .await?,
575 )
576 }
577
578 pub async fn prune_batches(&self, age: Duration) -> Result<u64> {
580 let before = unix_now() - age.as_secs() as i64;
581 Ok(crate::db::sql(
582 "DELETE FROM job_batches WHERE (finished_at IS NOT NULL AND finished_at < ?) \
583 OR (cancelled_at IS NOT NULL AND cancelled_at < ? AND pending = 0)",
584 )
585 .bind(before)
586 .bind(before)
587 .execute(&self.db)
588 .await?)
589 }
590
591 pub async fn flush_failed(&self) -> Result<u64> {
593 Ok(crate::db::sql("DELETE FROM failed_jobs")
594 .execute(&self.db)
595 .await?)
596 }
597}
598
599async fn insert<'c>(
601 db: impl crate::db::Executor<'c>,
602 job: &Encoded,
603 delay: Duration,
604 chain: Option<String>,
605 batch_id: Option<i64>,
606 callback_of: Option<i64>,
607) -> Result<i64> {
608 let now = unix_now();
609 let id: i64 = crate::db::sql(
610 "INSERT INTO jobs (queue, job, payload, max_attempts, available_at, created_at, chain, \
611 batch_id, callback_of) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
612 )
613 .bind(&job.queue)
614 .bind(&job.job)
615 .bind(&job.payload)
616 .bind(i64::from(job.max_attempts))
617 .bind(now + delay.as_secs() as i64)
618 .bind(now)
619 .bind(chain)
620 .bind(batch_id)
621 .bind(callback_of)
622 .scalar(db)
623 .await?;
624 Ok(id)
625}
626
627async fn insert_unique(
631 tx: &mut Transaction,
632 key: &str,
633 ttl: Duration,
634 job: &Encoded,
635 delay: Duration,
636) -> Result<i64> {
637 let now = unix_now();
638 let claimed = crate::db::sql(
639 "INSERT INTO cache (key, value, expires_at) VALUES (?, '0', ?) \
640 ON CONFLICT (key) DO UPDATE SET value = '0', expires_at = excluded.expires_at \
641 WHERE cache.expires_at IS NOT NULL AND cache.expires_at <= ?",
642 )
643 .bind(key)
644 .bind(now + ttl.as_secs().max(1) as i64)
645 .bind(now)
646 .execute(&mut *tx)
647 .await?;
648 if claimed == 0 {
649 let holder: String = crate::db::sql("SELECT value FROM cache WHERE key = ?")
650 .bind(key)
651 .scalar(&mut *tx)
652 .await?;
653 return Ok(holder.parse().unwrap_or_default());
654 }
655 let id = insert(&mut *tx, job, delay, None, None, None).await?;
656 crate::db::sql("UPDATE cache SET value = ? WHERE key = ?")
657 .bind(id.to_string())
658 .bind(key)
659 .execute(&mut *tx)
660 .await?;
661 Ok(id)
662}
663
664#[must_use = "a chain does nothing until dispatched"]
666pub struct Chain {
667 queue: Queue,
668 jobs: Vec<Encoded>,
669 error: Option<Error>,
670}
671
672impl Chain {
673 pub fn then<J: Job>(mut self, job: J) -> Self {
675 match self.queue.encode(&job, J::QUEUE) {
676 Ok(encoded) => self.jobs.push(encoded),
677 Err(err) => {
678 self.error.get_or_insert(err);
679 }
680 }
681 self
682 }
683
684 pub async fn dispatch(self) -> Result<i64> {
686 if let Some(err) = self.error {
687 return Err(err);
688 }
689 let mut jobs = self.jobs.into_iter();
690 let Some(first) = jobs.next() else {
691 return Ok(0);
692 };
693 let rest: Vec<Encoded> = jobs.collect();
694 let chain = (!rest.is_empty())
695 .then(|| serde_json::to_string(&rest))
696 .transpose()?;
697 let id = insert(&self.queue.db, &first, Duration::ZERO, chain, None, None).await?;
698 self.queue.wake_workers();
699 Ok(id)
700 }
701}
702
703#[must_use = "a batch does nothing until dispatched"]
707pub struct Batch {
708 queue: Queue,
709 name: String,
710 jobs: Vec<Encoded>,
711 then: Option<Encoded>,
712 catch: Option<Encoded>,
713 finally: Option<Encoded>,
714 allow_failures: bool,
715 error: Option<Error>,
716}
717
718impl Batch {
719 fn encode<J: Job>(&mut self, job: J) -> Option<Encoded> {
720 match self.queue.encode(&job, J::QUEUE) {
721 Ok(encoded) => Some(encoded),
722 Err(err) => {
723 self.error.get_or_insert(err);
724 None
725 }
726 }
727 }
728
729 pub fn push<J: Job>(mut self, job: J) -> Self {
731 if let Some(job) = self.encode(job) {
732 self.jobs.push(job);
733 }
734 self
735 }
736
737 pub fn then<J: Job>(mut self, job: J) -> Self {
739 self.then = self.encode(job);
740 self
741 }
742
743 pub fn catch<J: Job>(mut self, job: J) -> Self {
745 self.catch = self.encode(job);
746 self
747 }
748
749 pub fn finally<J: Job>(mut self, job: J) -> Self {
751 self.finally = self.encode(job);
752 self
753 }
754
755 pub fn allow_failures(mut self) -> Self {
757 self.allow_failures = true;
758 self
759 }
760
761 pub async fn dispatch(self) -> Result<i64> {
763 if let Some(err) = self.error {
764 return Err(err);
765 }
766 let json = |job: &Option<Encoded>| job.as_ref().map(serde_json::to_string).transpose();
767 let (then, catch, finally) = (json(&self.then)?, json(&self.catch)?, json(&self.finally)?);
768 let total = self.jobs.len() as i64;
769 let mut tx = self.queue.db.begin().await?;
770 let id: i64 = crate::db::sql(
771 "INSERT INTO job_batches (name, total, pending, allow_failures, then_job, catch_job, \
772 finally_job, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
773 )
774 .bind(&self.name)
775 .bind(total)
776 .bind(total)
777 .bind(self.allow_failures)
778 .bind(then)
779 .bind(catch)
780 .bind(finally)
781 .bind(unix_now())
782 .scalar(&mut tx)
783 .await?;
784 for job in &self.jobs {
785 insert(&mut tx, job, Duration::ZERO, None, Some(id), None).await?;
786 }
787 if self.jobs.is_empty() {
788 finish_batch(&mut tx, id, 0).await?;
789 }
790 tx.commit().await?;
791 self.queue.wake_workers();
792 Ok(id)
793 }
794}
795
796pub(crate) async fn batch_job_done(tx: &mut Transaction, batch_id: i64, failed: bool) -> Result {
799 let row: Option<(i64, i64, Option<String>)> = crate::db::sql(
800 "UPDATE job_batches SET pending = pending - 1, failed = failed + ?, \
801 cancelled_at = CASE WHEN ? AND NOT allow_failures THEN COALESCE(cancelled_at, ?) \
802 ELSE cancelled_at END \
803 WHERE id = ? RETURNING pending, failed, catch_job",
804 )
805 .bind(i64::from(failed))
806 .bind(failed)
807 .bind(unix_now())
808 .bind(batch_id)
809 .fetch_as(&mut *tx)
810 .await?
811 .into_iter()
812 .next();
813 let Some((pending, failures, catch)) = row else {
814 return Ok(()); };
816 if failed && failures == 1 {
817 queue_follow_up(tx, catch, batch_id).await?;
818 }
819 if pending <= 0 {
820 finish_batch(tx, batch_id, failures).await?;
821 }
822 Ok(())
823}
824
825async fn finish_batch(tx: &mut Transaction, batch_id: i64, failures: i64) -> Result {
826 let (then, finally, cancelled): (Option<String>, Option<String>, Option<i64>) = crate::db::sql(
827 "UPDATE job_batches SET finished_at = ? WHERE id = ? \
828 RETURNING then_job, finally_job, cancelled_at",
829 )
830 .bind(unix_now())
831 .bind(batch_id)
832 .fetch_as(&mut *tx)
833 .await?
834 .into_iter()
835 .next()
836 .unwrap_or_default();
837 if failures == 0 && cancelled.is_none() {
838 queue_follow_up(tx, then, batch_id).await?;
839 }
840 queue_follow_up(tx, finally, batch_id).await
841}
842
843async fn queue_follow_up(tx: &mut Transaction, job: Option<String>, batch_id: i64) -> Result {
846 if let Some(job) = job {
847 let job: Encoded = serde_json::from_str(&job)?;
848 insert(&mut *tx, &job, Duration::ZERO, None, None, Some(batch_id)).await?;
849 }
850 Ok(())
851}
852
853pub(crate) async fn continue_chain(tx: &mut Transaction, chain: &str) -> Result {
855 let rest: Vec<Encoded> = serde_json::from_str(chain)?;
856 let mut rest = rest.into_iter();
857 if let Some(next) = rest.next() {
858 let rest: Vec<Encoded> = rest.collect();
859 let chain = (!rest.is_empty())
860 .then(|| serde_json::to_string(&rest))
861 .transpose()?;
862 insert(&mut *tx, &next, Duration::ZERO, chain, None, None).await?;
863 }
864 Ok(())
865}
866
867pub(crate) async fn release_unique(tx: &mut Transaction, key: &str) -> Result {
869 crate::db::sql("DELETE FROM cache WHERE key = ?")
870 .bind(key)
871 .execute(&mut *tx)
872 .await?;
873 Ok(())
874}
875
876#[derive(Debug, Clone, Serialize)]
878#[non_exhaustive]
879pub struct BatchStatus {
880 pub id: i64,
882 pub name: String,
884 pub total: i64,
886 pub pending: i64,
888 pub failed: i64,
890 pub cancelled: bool,
892 pub finished: bool,
894 pub created_at: crate::db::DateTime,
896}
897
898impl BatchStatus {
899 pub fn progress(&self) -> u8 {
901 if self.total == 0 {
902 return 100;
903 }
904 ((self.total - self.pending) * 100 / self.total).clamp(0, 100) as u8
905 }
906}
907
908#[derive(Debug, Clone, Serialize)]
910#[non_exhaustive]
911pub struct FailedJob {
912 pub id: i64,
914 pub queue: String,
916 pub job: String,
918 pub payload: String,
920 pub error: String,
922 pub failed_at: crate::db::DateTime,
924}
925
926impl AppState {
927 pub async fn dispatch<J: Job>(&self, job: J) -> Result<i64> {
929 self.queue.dispatch(job).await
930 }
931
932 pub async fn dispatch_sync<J: Job>(&self, job: J) -> Result {
935 let ctx = JobContext {
936 state: self.clone(),
937 attempt: 1,
938 id: 0,
939 batch_id: None,
940 };
941 crate::context::scope_app(self.clone(), job.handle(ctx)).await
942 }
943}