tablo_jobs/queue.rs
1//! Putting work on the queue.
2
3use std::time::Duration;
4
5use jiff::{SignedDuration, Timestamp};
6
7use crate::{Job, JobState, QueuedJob};
8
9/// A job on its way to the queue, from [`enqueue`]: set its delay or its dedupe key, then
10/// [`exec`](Self::exec) it.
11#[must_use = "an `Enqueue` writes nothing until `exec`"]
12pub struct Enqueue<'a, J> {
13 job: &'a J,
14 delay: Duration,
15 dedupe_key: Option<String>,
16}
17
18/// Queues `job`, once [`exec`](Enqueue::exec) writes it.
19///
20/// ```rust,no_run
21/// # use serde::{Deserialize, Serialize};
22/// # use tablo_jobs::{Job, enqueue};
23/// # #[derive(Serialize, Deserialize)]
24/// # struct SyncSeats { team: u64 }
25/// # impl Job for SyncSeats {
26/// # const KIND: &'static str = "sync-seats";
27/// # async fn run(self, _: &topcoat::context::Cx) -> topcoat::Result<()> { Ok(()) }
28/// # }
29/// # async fn seat_added(tx: &mut dyn toasty::Executor) -> topcoat::Result<()> {
30/// enqueue(&SyncSeats { team: 7 })
31/// .dedupe("sync-seats:7")
32/// .exec(tx)
33/// .await?;
34/// # Ok(())
35/// # }
36/// ```
37pub fn enqueue<J: Job>(job: &J) -> Enqueue<'_, J> {
38 Enqueue {
39 job,
40 delay: Duration::ZERO,
41 dedupe_key: None,
42 }
43}
44
45impl<J: Job> Enqueue<'_, J> {
46 /// Runs it no sooner than `delay` from now.
47 pub fn delay(mut self, delay: Duration) -> Self {
48 self.delay = delay;
49 self
50 }
51
52 /// While a job of this kind with `key` waits for its first run, adds nothing: a burst of ten
53 /// enqueues makes one run. A claim frees the key for good, so work arriving during the run,
54 /// or while a failed run waits for its retry, queues a job of its own. Keys of different
55 /// kinds never meet.
56 pub fn dedupe(mut self, key: impl Into<String>) -> Self {
57 self.dedupe_key = Some(key.into());
58 self
59 }
60
61 /// Writes the job through `ex`. Pass the transaction of the write that implies the job, so
62 /// the two commit together or not at all.
63 ///
64 /// # Errors
65 ///
66 /// When the job does not serialize, or the driver fails to write it.
67 pub async fn exec(self, ex: &mut dyn toasty::Executor) -> topcoat::Result<()> {
68 let id = uuid::Uuid::now_v7();
69 let now = Timestamp::now();
70 let run_at = now.checked_add(SignedDuration::try_from(self.delay)?)?;
71 let payload = serde_json::to_string(self.job)?;
72 let create = |key: String| {
73 QueuedJob::create()
74 .id(id)
75 .kind(J::KIND.to_string())
76 .payload(payload.clone())
77 .state(JobState::Queued)
78 .lane(self.job.lane())
79 .dedupe_key(key)
80 .attempts(0)
81 .max_attempts(u64::from(J::MAX_ATTEMPTS))
82 .run_at(run_at)
83 .created_at(now)
84 };
85 let Some(key) = self
86 .dedupe_key
87 .as_ref()
88 .map(|key| format!("{}:{key}", J::KIND))
89 else {
90 // A fresh key meets no other: a plain insert, on every driver.
91 create(id.to_string()).exec(ex).await?;
92 return Ok(());
93 };
94 let upserted = QueuedJob::upsert_by_dedupe_key(key.clone())
95 .on_create(|row| {
96 row.id(id)
97 .kind(J::KIND.to_string())
98 .payload(payload.clone())
99 .state(JobState::Queued)
100 .lane(self.job.lane())
101 .attempts(0)
102 .max_attempts(u64::from(J::MAX_ATTEMPTS))
103 .run_at(run_at)
104 .created_at(now)
105 })
106 .or_ignore()
107 .exec(ex)
108 .await;
109 match upserted {
110 Ok(_) => Ok(()),
111 // MySQL has no targeted upsert, and Toasty refuses it before any SQL runs.
112 Err(error) if error.is_unsupported_feature() => {
113 if waiting(ex, &key).await? {
114 return Ok(());
115 }
116 match create(key.clone()).exec(ex).await {
117 Ok(_) => Ok(()),
118 // A racing enqueue committed the key first. MySQL rolls back the statement,
119 // not the transaction, so the caller's write goes on.
120 Err(error) if held(&error) => Ok(()),
121 Err(error) => Err(error.into()),
122 }
123 }
124 Err(error) => Err(error.into()),
125 }
126 }
127}
128
129/// Whether `error` is MySQL refusing a second row under a dedupe key. A look-up cannot tell: in
130/// a transaction it reads a snapshot that may predate the row holding the key.
131fn held(error: &toasty::Error) -> bool {
132 let message = error.to_string();
133 message.contains("1062") && message.contains("_by_dedupe_key")
134}
135
136/// Whether a job holding `key` waits in the queue.
137async fn waiting(ex: &mut dyn toasty::Executor, key: &str) -> topcoat::Result<bool> {
138 Ok(QueuedJob::filter_by_dedupe_key(key)
139 .first()
140 .exec(ex)
141 .await?
142 .is_some())
143}