Skip to main content

tablo_jobs/
worker.rs

1//! Claiming and running jobs.
2
3use std::{
4    collections::{HashMap, HashSet},
5    sync::Arc,
6    time::{Duration, Instant},
7};
8
9use jiff::{SignedDuration, Timestamp};
10use serde::{Deserialize, Serialize};
11use tablo_core::PanelHandle;
12use toasty::Db;
13use tokio::{
14    sync::watch,
15    task::{JoinError, JoinSet},
16};
17use topcoat::context::Cx;
18use tracing::Instrument;
19
20use crate::{
21    AuthMailQueue, Job, JobState, QueuedJob,
22    job::{Kind, kind_of},
23    mail::SendAuthMail,
24    schedule::Schedule,
25};
26
27/// How long a lock outlives its kind's timeout, so no live run is taken over.
28const LOCK_MARGIN: Duration = Duration::from_mins(1);
29/// How many jobs one worker runs at once.
30const BATCH: usize = 16;
31/// How long a worker waits before it asks again, when no run of its own ends first.
32const IDLE: Duration = Duration::from_secs(1);
33/// How often a worker sweeps for lapsed locks and due schedules, however busy it is.
34const SWEEP: Duration = Duration::from_secs(15);
35const BACKOFF_BASE_SECONDS: i64 = 30;
36const BACKOFF_CAP_SECONDS: i64 = 60 * 60;
37/// How long a succeeded job stays by default.
38const KEEP_SUCCEEDED: Duration = Duration::from_hours(14 * 24);
39/// How often the queue deletes the succeeded jobs past their keep.
40const PRUNE_EVERY: Duration = Duration::from_hours(24);
41
42/// Runs a panel's queued jobs: claims the due ones, runs each with a timeout against the panel's
43/// [`context`](PanelHandle::context), and retries a failure with backoff.
44///
45/// ```rust,no_run
46/// # use serde::{Deserialize, Serialize};
47/// # use std::time::Duration;
48/// # use tablo_core::PanelHandle;
49/// # use tablo_jobs::{AuthMailQueue, Job, Worker};
50/// # #[derive(Clone, Serialize, Deserialize)]
51/// # struct ReconcileBilling;
52/// # impl Job for ReconcileBilling {
53/// #     const KIND: &'static str = "reconcile-billing";
54/// #     async fn run(self, _: &topcoat::context::Cx) -> topcoat::Result<()> { Ok(()) }
55/// # }
56/// # #[derive(Clone)] struct Stripe;
57/// # async fn start(panel: &PanelHandle, mail: AuthMailQueue, stripe: Stripe) -> topcoat::Result<()> {
58/// let (stop, stopped) = tokio::sync::watch::channel(false);
59/// let worker = Worker::new(panel)?
60///     .every(Duration::from_hours(6), ReconcileBilling)
61///     .auth_mail(&mail)
62///     .context(move |cx| cx.with(stripe.clone()));
63/// let running = tokio::spawn(worker.run(stopped));
64/// // On a shutdown signal:
65/// stop.send(true).ok();
66/// running.await.ok();
67/// # Ok(())
68/// # }
69/// ```
70///
71/// - Delivery is at least once. A worker that stops mid-run leaves the job's lock to lapse, a
72///   minute past its kind's [`TIMEOUT`](Job::TIMEOUT), and the job runs again after its backoff.
73/// - A run that fails, or outlasts its [`TIMEOUT`](Job::TIMEOUT), waits from 30 seconds, doubling
74///   up to an hour, with up to a quarter more drawn from the job's id. A job out of attempts turns
75///   [`Dead`](JobState::Dead) and stays until someone queues it again.
76/// - A worker claims only the kinds it [`register`](Self::register)s, so workers may split the
77///   kinds between them. A job of a kind no worker registers, such as one a newer release queued,
78///   waits for a worker that does.
79/// - Any number of workers share one queue. A claim is a version-checked update, so each job runs
80///   once per claim, and the running job of a [`lane`](Job::lane) holds the lane in a unique
81///   column, so the database refuses a second.
82/// - Every day it deletes the jobs that succeeded more than
83///   [`keep_succeeded`](Self::keep_succeeded) ago, fourteen days by default. A dead job stays.
84#[derive(Clone)]
85pub struct Worker {
86    inner: Arc<Inner>,
87}
88
89#[derive(Clone)]
90struct Inner {
91    db: Db,
92    panel: PanelHandle,
93    kinds: HashMap<&'static str, Kind>,
94    schedules: Vec<Schedule>,
95    context: Arc<dyn Fn(Cx) -> Cx + Send + Sync>,
96    mail: Option<AuthMailQueue>,
97}
98
99impl Worker {
100    /// A worker running jobs in `panel`'s database, against `panel`'s context.
101    ///
102    /// # Errors
103    ///
104    /// When `panel`'s context holds no database, which a handle from
105    /// [`Panel::handle`](tablo_core::Panel::handle) or a router always does.
106    pub fn new(panel: &PanelHandle) -> topcoat::Result<Self> {
107        let db = tablo_core::db::db(&panel.context())?;
108        let worker = Self {
109            inner: Arc::new(Inner {
110                db,
111                panel: panel.clone(),
112                kinds: HashMap::new(),
113                schedules: Vec::new(),
114                context: Arc::new(|cx| cx),
115                mail: None,
116            }),
117        };
118        Ok(worker.keep_succeeded(KEEP_SUCCEEDED))
119    }
120
121    fn inner_mut(&mut self) -> &mut Inner {
122        Arc::make_mut(&mut self.inner)
123    }
124
125    /// Runs the jobs of kind `J`. Registering a kind again changes nothing.
126    #[must_use]
127    pub fn register<J: Job>(mut self) -> Self {
128        self.inner_mut().kinds.insert(J::KIND, kind_of::<J>());
129        self
130    }
131
132    /// Registers `J` and enqueues `job` every `every`, the first run one interval after any
133    /// worker first sees the schedule. However many workers run, each period enqueues once, and
134    /// a run that has not started absorbs the next. Scheduling a kind again replaces its schedule.
135    #[must_use]
136    pub fn every<J: Job + Clone>(mut self, every: Duration, job: J) -> Self {
137        let inner = self.inner_mut();
138        inner
139            .schedules
140            .retain(|schedule| schedule.kind() != J::KIND);
141        inner.schedules.push(Schedule::new(every, job));
142        self.register::<J>()
143    }
144
145    /// Adds to each run's context what its jobs read beyond the panel's: a mail transport, an API
146    /// client. `extend` receives the panel's context and returns it with its additions. Each run
147    /// gets a context of its own, since a context memoizes what it loads. Calling it again
148    /// replaces the previous `extend`.
149    #[must_use]
150    pub fn context(mut self, extend: impl Fn(Cx) -> Cx + Send + Sync + 'static) -> Self {
151        self.inner_mut().context = Arc::new(extend);
152        self
153    }
154
155    /// Sends the letters `queue` queues, through the [`Mailer`](topcoat::mail::Mailer) the
156    /// [`context`](Self::context) adds. See [`AuthMailQueue`].
157    #[must_use]
158    pub fn auth_mail(mut self, queue: &AuthMailQueue) -> Self {
159        self.inner_mut().mail = Some(queue.clone());
160        self.register::<SendAuthMail>()
161    }
162
163    /// Keeps a succeeded job for `age` before the daily prune deletes it.
164    #[must_use]
165    pub fn keep_succeeded(self, age: Duration) -> Self {
166        self.every(
167            PRUNE_EVERY,
168            PruneJobs {
169                keep_seconds: age.as_secs(),
170            },
171        )
172    }
173
174    /// Polls for due jobs until `shutdown` holds `true` or its sender drops, then lets the runs
175    /// in hand finish. A slot a run frees takes the next due job at once, and the sweep keeps its
176    /// pace under any load.
177    pub async fn run(self, mut shutdown: watch::Receiver<bool>) {
178        let mut runs = JoinSet::new();
179        let mut swept: Option<Instant> = None;
180        while !*shutdown.borrow() {
181            if swept.is_none_or(|at| at.elapsed() >= SWEEP) {
182                swept = Some(Instant::now());
183                self.sweep().await;
184            }
185            let free = BATCH - runs.len();
186            if free > 0 {
187                match self.claim(free).await {
188                    Ok(claimed) => {
189                        for job in claimed {
190                            self.spawn(&mut runs, job);
191                        }
192                    }
193                    Err(error) => {
194                        tracing::error!(error = %format!("{error:#}"), "claiming jobs failed");
195                    }
196                }
197            }
198            tokio::select! {
199                () = tokio::time::sleep(IDLE) => {}
200                Some(run) = runs.join_next(), if !runs.is_empty() => ended(run),
201                changed = shutdown.changed() => if changed.is_err() { break },
202            }
203        }
204        while let Some(run) = runs.join_next().await {
205            ended(run);
206        }
207    }
208
209    /// Requeues the jobs whose lock lapsed and enqueues the due schedules, then runs every due
210    /// job until none is left: what a test calls to say "the worker ran".
211    ///
212    /// # Errors
213    ///
214    /// When the driver fails to claim jobs.
215    pub async fn drain(&self) -> topcoat::Result<()> {
216        self.sweep().await;
217        while self.drain_once().await? > 0 {}
218        Ok(())
219    }
220
221    /// Claims up to a batch of due jobs, runs them to their end, and answers how many it claimed.
222    ///
223    /// # Errors
224    ///
225    /// When the driver fails to claim jobs. A job's own failure is recorded on its row instead.
226    pub async fn drain_once(&self) -> topcoat::Result<usize> {
227        let claimed = self.claim(BATCH).await?;
228        let count = claimed.len();
229        let mut runs = JoinSet::new();
230        for job in claimed {
231            self.spawn(&mut runs, job);
232        }
233        while let Some(run) = runs.join_next().await {
234            ended(run);
235        }
236        Ok(count)
237    }
238
239    fn spawn(&self, runs: &mut JoinSet<()>, job: QueuedJob) {
240        let worker = self.clone();
241        let span = tracing::info_span!(
242            "job",
243            kind = %job.kind,
244            id = %job.id,
245            attempt = job.attempts
246        );
247        runs.spawn(async move { worker.execute(job).await }.instrument(span));
248    }
249
250    /// Requeues lapsed locks and enqueues due schedules. A failure waits for the next sweep.
251    async fn sweep(&self) {
252        if let Err(error) = self.recover().await {
253            tracing::error!(error = %format!("{error:#}"), "recovering lapsed jobs failed");
254        }
255        for schedule in &self.inner.schedules {
256            if let Err(error) = schedule.tick(&self.inner.db).await {
257                tracing::error!(
258                    kind = schedule.kind(),
259                    error = %format!("{error:#}"),
260                    "a schedule failed"
261                );
262            }
263        }
264    }
265
266    /// Up to `limit` due jobs of the registered kinds, each now held by this worker.
267    async fn claim(&self, limit: usize) -> topcoat::Result<Vec<QueuedJob>> {
268        let mut db = self.inner.db.clone();
269        let now = Timestamp::now();
270        let fields = QueuedJob::fields();
271        // Leaves out the jobs of busy lanes, so they do not fill the batch and hold back the rest.
272        // Exclusion itself is the unique `running_lane`: this read is stale once another worker
273        // claims.
274        let mut busy: HashSet<String> = QueuedJob::filter(fields.state().eq(JobState::Running))
275            .exec(&mut db)
276            .await?
277            .into_iter()
278            .filter_map(|job| job.running_lane)
279            .collect();
280        let kinds: Vec<String> = self.inner.kinds.keys().map(ToString::to_string).collect();
281        let mut due = fields
282            .state()
283            .eq(JobState::Queued)
284            .and(fields.run_at().le(now))
285            .and(fields.kind().in_list(kinds));
286        if !busy.is_empty() {
287            let lanes: Vec<Option<String>> = busy.iter().cloned().map(Some).collect();
288            due = due.and(
289                fields
290                    .lane()
291                    .is_none()
292                    .or(fields.lane().in_list(lanes).not()),
293            );
294        }
295        let due = QueuedJob::filter(due)
296            .order_by(fields.run_at().asc())
297            .limit(limit)
298            .exec(&mut db)
299            .await?;
300        let mut claimed = Vec::with_capacity(due.len());
301        for mut job in due {
302            if job.lane.as_ref().is_some_and(|lane| busy.contains(lane)) {
303                continue;
304            }
305            let Some(kind) = self.inner.kinds.get(job.kind.as_str()) else {
306                continue;
307            };
308            let locked_until = now.checked_add(SignedDuration::try_from(
309                kind.timeout.saturating_add(LOCK_MARGIN),
310            )?)?;
311            let free_key = job.id.to_string();
312            let attempts = job.attempts + 1;
313            let lane = job.lane.clone();
314            // Lost to the version check when another worker claimed this job, and to the unique
315            // `running_lane` when another worker claimed a job of its lane.
316            let update = job
317                .update()
318                .state(JobState::Running)
319                .running_lane(lane.clone())
320                .attempts(attempts)
321                .locked_until(Some(locked_until))
322                .dedupe_key(free_key)
323                .exec(&mut db)
324                .await;
325            match update {
326                Ok(()) => {
327                    busy.extend(lane);
328                    claimed.push(job);
329                }
330                Err(error) if lost_race(&error) => {}
331                // The jobs claimed so far still run; the rest wait for the next claim.
332                Err(error) if !claimed.is_empty() => {
333                    tracing::error!(%error, "claiming a job failed");
334                    break;
335                }
336                Err(error) => return Err(error.into()),
337            }
338        }
339        Ok(claimed)
340    }
341
342    /// Runs `job` and records how it ended.
343    async fn execute(&self, job: QueuedJob) {
344        // A claim takes only registered kinds.
345        let Some(kind) = self.inner.kinds.get(job.kind.as_str()) else {
346            return;
347        };
348        let cx = self.run_context();
349        let outcome = tokio::time::timeout(kind.timeout, (kind.run)(&job.payload, &cx))
350            .await
351            .unwrap_or_else(|_| {
352                Err(topcoat::Error::msg(format!(
353                    "timed out after {:?}",
354                    kind.timeout
355                )))
356            });
357        if let Err(error) = self.record(job, outcome).await {
358            // The lock lapses and the job runs again, which an idempotent job survives.
359            tracing::error!(error = %format!("{error:#}"), "recording a job's outcome failed");
360        }
361    }
362
363    /// The context one run reads.
364    fn run_context(&self) -> Cx {
365        let cx = (self.inner.context)(self.inner.panel.context());
366        match &self.inner.mail {
367            Some(mail) => cx.with(mail.clone()),
368            None => cx,
369        }
370    }
371
372    async fn record(
373        &self,
374        mut job: QueuedJob,
375        outcome: topcoat::Result<()>,
376    ) -> topcoat::Result<()> {
377        let mut db = self.inner.db.clone();
378        let now = Timestamp::now();
379        let Err(error) = outcome else {
380            job.update()
381                .state(JobState::Succeeded)
382                .running_lane(None)
383                .locked_until(None)
384                .finished_at(Some(now))
385                .exec(&mut db)
386                .await?;
387            return Ok(());
388        };
389        let message = format!("{error:#}");
390        if job.attempts >= job.max_attempts {
391            tracing::error!(error = %message, "a job is dead");
392            job.update()
393                .state(JobState::Dead)
394                .running_lane(None)
395                .locked_until(None)
396                .finished_at(Some(now))
397                .last_error(Some(message))
398                .exec(&mut db)
399                .await?;
400        } else {
401            tracing::warn!(error = %message, "a job will retry");
402            let run_at = now.checked_add(backoff(job.attempts, job.id))?;
403            job.update()
404                .state(JobState::Queued)
405                .running_lane(None)
406                .locked_until(None)
407                .run_at(run_at)
408                .last_error(Some(message))
409                .exec(&mut db)
410                .await?;
411        }
412        Ok(())
413    }
414
415    /// Requeues the running jobs whose lock lapsed: their worker stopped.
416    async fn recover(&self) -> topcoat::Result<()> {
417        let mut db = self.inner.db.clone();
418        let fields = QueuedJob::fields();
419        let lapsed = QueuedJob::filter(
420            fields
421                .state()
422                .eq(JobState::Running)
423                .and(fields.locked_until().le(Timestamp::now())),
424        )
425        .exec(&mut db)
426        .await?;
427        let now = Timestamp::now();
428        for mut job in lapsed {
429            tracing::warn!(kind = %job.kind, id = %job.id, "a job's lock lapsed");
430            let message = Some("the worker running it stopped".to_string());
431            // Spent like a failed run: dead when out of attempts, else retried after its backoff.
432            let update = if job.attempts >= job.max_attempts {
433                job.update()
434                    .state(JobState::Dead)
435                    .running_lane(None)
436                    .locked_until(None)
437                    .finished_at(Some(now))
438                    .last_error(message)
439                    .exec(&mut db)
440                    .await
441            } else {
442                let run_at = now.checked_add(backoff(job.attempts, job.id))?;
443                job.update()
444                    .state(JobState::Queued)
445                    .running_lane(None)
446                    .locked_until(None)
447                    .run_at(run_at)
448                    .last_error(message)
449                    .exec(&mut db)
450                    .await
451            };
452            match update {
453                Ok(()) => {}
454                // Another worker recovered it first.
455                Err(error) if lost_race(&error) => {}
456                Err(error) => return Err(error.into()),
457            }
458        }
459        Ok(())
460    }
461}
462
463/// Reports a run's task that ended abnormally.
464fn ended(run: Result<(), JoinError>) {
465    if let Err(error) = run {
466        // A panicking job keeps its lock until it lapses, then runs again.
467        tracing::error!(%error, "a job's task ended abnormally");
468    }
469}
470
471/// Whether `error` is a write another worker won: the version check or a unique index refused
472/// it. A lost connection is the driver failing instead.
473pub(crate) fn lost_race(error: &toasty::Error) -> bool {
474    !(error.is_connection_lost() || error.is_connection_pool() || error.is_transaction_timeout())
475}
476
477/// How long the run after `attempt` waits: doubling from 30 seconds to an hour, with up to a
478/// quarter more drawn from the job's id, so a burst of failures does not retry as one.
479fn backoff(attempt: u64, id: uuid::Uuid) -> SignedDuration {
480    let exponent = u32::try_from(attempt.saturating_sub(1))
481        .unwrap_or(u32::MAX)
482        .min(16);
483    let seconds = BACKOFF_BASE_SECONDS
484        .saturating_mul(1 << exponent)
485        .min(BACKOFF_CAP_SECONDS);
486    let spread = i64::from(id.as_bytes()[15]) * seconds / (4 * 255);
487    SignedDuration::from_secs(seconds + spread)
488}
489
490/// Deletes the jobs that succeeded more than `keep_seconds` ago.
491#[derive(Clone, Serialize, Deserialize)]
492struct PruneJobs {
493    keep_seconds: u64,
494}
495
496impl Job for PruneJobs {
497    const KIND: &'static str = "tablo-prune-jobs";
498
499    async fn run(self, cx: &Cx) -> topcoat::Result<()> {
500        let keep = SignedDuration::try_from(Duration::from_secs(self.keep_seconds))?;
501        let cutoff = Timestamp::now().checked_sub(keep)?;
502        let fields = QueuedJob::fields();
503        QueuedJob::filter(
504            fields
505                .state()
506                .eq(JobState::Succeeded)
507                .and(fields.finished_at().le(cutoff)),
508        )
509        .delete()
510        .exec(&mut tablo_core::db::db(cx)?)
511        .await?;
512        Ok(())
513    }
514}
515
516#[cfg(test)]
517mod tests;