Skip to main content

navree_queue/
worker.rs

1//! Workers: [`Queue::work`], [`WorkOptions`] and [`WorkStats`].
2
3use std::any::Any;
4use std::fmt;
5use std::future::Future;
6use std::ops::AddAssign;
7use std::panic::AssertUnwindSafe;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
10use std::time::{Duration, Instant};
11
12use futures_util::FutureExt;
13use navree_contracts::{JobCancelled, JobContext, JobRegistration};
14use navree_kernel::AppContext;
15use navree_telemetry::{EventKind, JobFailed, JobProcessed, TelemetryContext, TelemetryEvent};
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18use tokio::task::JoinSet;
19use tokio_util::sync::CancellationToken;
20use uuid::Uuid;
21
22use crate::batch::{BatchRow, Finish, Finished};
23use crate::record::ReservedJob;
24use crate::store::Store;
25use crate::{Queue, QueueError};
26
27/// A reservation older than the job's `timeout_secs` plus this many seconds
28/// is considered abandoned (its worker crashed or was killed): another
29/// worker may take the job, and that counts as a new attempt. A live worker
30/// never holds a job that long, because each attempt is cut off at its
31/// timeout.
32pub const STALE_RESERVATION_GRACE_SECS: u64 = 30;
33
34/// How a [`Queue::work`] call runs.
35#[derive(Clone, Debug, Default, PartialEq, Eq)]
36pub struct WorkOptions {
37    /// The queues to take jobs from, highest priority first (empty: the
38    /// module's [`worker_queues`](crate::QueueOptions::worker_queues)).
39    pub queues: Vec<String>,
40    /// Runs at most one job, with one worker, then returns (`--once`).
41    pub once: bool,
42    /// Returns after this many jobs (all workers together).
43    pub max_jobs: Option<u64>,
44    /// Returns as soon as no job is available, instead of polling until
45    /// the app shuts down (`--stop-when-empty`).
46    pub stop_when_empty: bool,
47}
48
49/// What a [`Queue::work`] call did.
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
51pub struct WorkStats {
52    /// Attempts run (each attempt of a retried job counts).
53    pub processed: u64,
54    /// Attempts that succeeded (the job is done).
55    pub succeeded: u64,
56    /// Failed attempts put back on the queue for another attempt.
57    pub released: u64,
58    /// Jobs moved to the failed jobs.
59    pub failed: u64,
60    /// Jobs skipped, or stopped with `JobCancelled`, because their batch or
61    /// operation was cancelled.
62    pub cancelled: u64,
63}
64
65impl AddAssign for WorkStats {
66    fn add_assign(&mut self, other: WorkStats) {
67        self.processed += other.processed;
68        self.succeeded += other.succeeded;
69        self.released += other.released;
70        self.failed += other.failed;
71        self.cancelled += other.cancelled;
72    }
73}
74
75/// How one attempt of a job ended.
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78#[non_exhaustive]
79pub enum AttemptOutcome {
80    /// The job is done.
81    Succeeded,
82    /// It failed and goes back on its queue for another attempt.
83    Released,
84    /// It failed for good and moved to the failed jobs.
85    Failed,
86    /// Skipped, or stopped with `JobCancelled`, because its batch or
87    /// operation was cancelled.
88    Cancelled,
89}
90
91impl AttemptOutcome {
92    /// The name in logs and reports: `succeeded`, `released`, `failed` or
93    /// `cancelled`.
94    pub fn as_str(self) -> &'static str {
95        match self {
96            AttemptOutcome::Succeeded => "succeeded",
97            AttemptOutcome::Released => "released",
98            AttemptOutcome::Failed => "failed",
99            AttemptOutcome::Cancelled => "cancelled",
100        }
101    }
102
103    fn stats(self) -> WorkStats {
104        let mut stats = WorkStats {
105            processed: 1,
106            ..WorkStats::default()
107        };
108        match self {
109            AttemptOutcome::Succeeded => stats.succeeded = 1,
110            AttemptOutcome::Released => stats.released = 1,
111            AttemptOutcome::Failed => stats.failed = 1,
112            AttemptOutcome::Cancelled => stats.cancelled = 1,
113        }
114        stats
115    }
116}
117
118/// One finished attempt, as a supervised worker tells its
119/// [`WorkHooks`].
120#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
121pub struct Attempt {
122    /// The job id.
123    pub job_id: String,
124    /// The queue it came from.
125    pub queue: String,
126    /// The job type.
127    pub job_type: String,
128    /// Which attempt this was (1 for the first).
129    pub attempt: u32,
130    /// How it ended.
131    pub outcome: AttemptOutcome,
132    /// How long it ran, in milliseconds.
133    pub runtime_ms: u64,
134}
135
136/// What a supervisor (navree-fleet's workers) puts around a worker: asked
137/// before every reservation, told after every attempt. Both run on the
138/// worker's task, so keep them quick.
139pub trait WorkHooks: Send + Sync + 'static {
140    /// Whether the worker may take a job now. `false` holds it (a paused
141    /// supervisor): it takes nothing and asks again after a poll interval
142    /// (a worker that stops when empty stops instead). Default: `true`.
143    fn may_reserve(&self) -> bool {
144        true
145    }
146
147    /// Told after each attempt, whatever its outcome.
148    fn attempted(&self, attempt: &Attempt) {
149        let _ = attempt;
150    }
151}
152
153/// How [`Queue::work_supervised`] runs besides its [`WorkOptions`].
154#[derive(Clone)]
155pub struct Supervision {
156    /// Concurrent workers (`None`: [`QueueOptions::workers`](crate::QueueOptions::workers)).
157    pub workers: Option<usize>,
158    /// Cancelled to stop the call as the app's shutdown would: no new job
159    /// is taken, running jobs finish.
160    pub stop: CancellationToken,
161    /// Asked before each reservation, told after each attempt.
162    pub hooks: Arc<dyn WorkHooks>,
163}
164
165impl fmt::Debug for Supervision {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_struct("Supervision")
168            .field("workers", &self.workers)
169            .field("stopped", &self.stop.is_cancelled())
170            .finish_non_exhaustive()
171    }
172}
173
174/// How a job's handler ended.
175#[derive(Clone, Debug, PartialEq, Eq)]
176enum Ran {
177    Succeeded,
178    /// It returned [`JobCancelled`].
179    Cancelled,
180    /// An error, a panic or a timeout.
181    Failed(String),
182}
183
184/// The jobs the workers of one `work` call may still take.
185struct Budget {
186    left: AtomicU64,
187    /// Whether the call has a limit, so that it ends by itself.
188    limited: bool,
189}
190
191impl Budget {
192    fn new(max_jobs: Option<u64>) -> Self {
193        Self {
194            left: AtomicU64::new(max_jobs.unwrap_or(u64::MAX)),
195            limited: max_jobs.is_some(),
196        }
197    }
198
199    /// Takes one job slot; false when none are left.
200    fn take(&self) -> bool {
201        let mut left = self.left.load(Ordering::SeqCst);
202        while left > 0 {
203            match self.left.compare_exchange_weak(
204                left,
205                left - 1,
206                Ordering::SeqCst,
207                Ordering::SeqCst,
208            ) {
209                Ok(_) => return true,
210                Err(actual) => left = actual,
211            }
212        }
213        false
214    }
215
216    /// Returns a slot that found no job.
217    fn give_back(&self) {
218        self.left.fetch_add(1, Ordering::SeqCst);
219    }
220}
221
222impl Queue {
223    /// Runs every job available now, one at a time in queue order, and
224    /// returns when none is left (jobs released for a later retry and
225    /// delayed jobs stay queued). For tests: `dispatch`, then
226    /// `run_pending`, then assert.
227    pub async fn run_pending(&self) -> Result<WorkStats, QueueError> {
228        let opts = WorkOptions {
229            stop_when_empty: true,
230            ..WorkOptions::default()
231        };
232        self.work_with(opts, 1, None).await
233    }
234
235    /// [`work`](Queue::work) under a supervisor (navree-fleet's workers):
236    /// with [`Supervision::workers`] concurrent workers, stopped by
237    /// [`Supervision::stop`] as well as by the app's shutdown, asking the
238    /// hooks before each reservation (a paused supervisor holds its
239    /// workers) and telling them every attempt.
240    pub async fn work_supervised(
241        &self,
242        opts: WorkOptions,
243        supervision: Supervision,
244    ) -> Result<WorkStats, QueueError> {
245        let workers = if opts.once {
246            1
247        } else {
248            supervision
249                .workers
250                .unwrap_or(self.inner.options.workers)
251                .max(1)
252        };
253        self.work_with(opts, workers, Some(supervision)).await
254    }
255
256    /// Runs jobs with [`workers`](crate::QueueOptions::workers) concurrent
257    /// workers (one with [`once`](WorkOptions::once)) until the app shuts
258    /// down, [`max_jobs`](WorkOptions::max_jobs) jobs ran, or, with
259    /// [`stop_when_empty`](WorkOptions::stop_when_empty) or `once`, no job
260    /// is available. A running job is always finished first.
261    ///
262    /// Each job runs with the handler registered for its type, bounded by
263    /// its `timeout_secs`; a panic counts as a failed attempt.
264    ///
265    /// Errors of the driver end the call when it would stop on an empty
266    /// queue; otherwise they are logged and the worker polls again.
267    ///
268    /// A job's outcome is stored for as long as its worker holds it, whatever
269    /// the database says for now. Past that, another worker may take the job and
270    /// it runs again: the worker logs an error naming it, and a call limited by
271    /// `once`, `stop_when_empty` or `max_jobs` returns the error, never `Ok`.
272    ///
273    /// A [`QueueFake`](crate::QueueFake) queue runs nothing and returns at once.
274    pub async fn work(&self, opts: WorkOptions) -> Result<WorkStats, QueueError> {
275        let workers = if opts.once {
276            1
277        } else {
278            self.inner.options.workers.max(1)
279        };
280        self.work_with(opts, workers, None).await
281    }
282
283    /// [`work`](Queue::work) with `workers` concurrent workers, supervised
284    /// or not.
285    async fn work_with(
286        &self,
287        opts: WorkOptions,
288        workers: usize,
289        supervision: Option<Supervision>,
290    ) -> Result<WorkStats, QueueError> {
291        if matches!(self.inner.store, Store::Fake(_)) {
292            return Ok(WorkStats::default());
293        }
294        let ctx = self.app()?;
295        let queues = if opts.queues.is_empty() {
296            self.inner.options.worker_queues()
297        } else {
298            opts.queues.clone()
299        };
300        let budget = Arc::new(Budget::new(if opts.once { Some(1) } else { opts.max_jobs }));
301        let shutdown = ctx.shutdown_token();
302        // Stops on the app's shutdown, or on the supervisor's stop.
303        let token = CancellationToken::new();
304        let hooks = supervision.as_ref().map(|s| s.hooks.clone());
305        let linked = {
306            let token = token.clone();
307            let stop = supervision.map(|s| s.stop);
308            tokio::spawn(async move {
309                let stopped = async {
310                    match stop {
311                        Some(stop) => stop.cancelled().await,
312                        None => std::future::pending().await,
313                    }
314                };
315                tokio::select! {
316                    () = shutdown.cancelled() => token.cancel(),
317                    () = stopped => token.cancel(),
318                    () = token.cancelled() => {}
319                }
320            })
321        };
322        let mut set = JoinSet::new();
323        for _ in 0..workers {
324            let worker = Worker {
325                queue: self.clone(),
326                ctx: ctx.clone(),
327                queues: queues.clone(),
328                finite: opts.once || opts.stop_when_empty,
329                budget: budget.clone(),
330                token: token.clone(),
331                hooks: hooks.clone(),
332                id: format!("worker-{}", Uuid::now_v7()),
333                busy: AtomicU32::new(0),
334            };
335            set.spawn(worker.run());
336        }
337        let result = Self::join_workers(set).await;
338        token.cancel();
339        linked.abort();
340        result
341    }
342
343    /// Waits for every worker of a `work` call; their stats summed, or the
344    /// first error.
345    async fn join_workers(
346        mut set: JoinSet<Result<WorkStats, QueueError>>,
347    ) -> Result<WorkStats, QueueError> {
348        let mut stats = WorkStats::default();
349        let mut first_error = None;
350        while let Some(joined) = set.join_next().await {
351            match joined {
352                Ok(Ok(worker_stats)) => stats += worker_stats,
353                Ok(Err(error)) => {
354                    first_error.get_or_insert(error);
355                }
356                Err(join) if join.is_panic() => std::panic::resume_unwind(join.into_panic()),
357                Err(_) => {}
358            }
359        }
360        match first_error {
361            Some(error) => Err(error),
362            None => Ok(stats),
363        }
364    }
365
366    /// Runs one reserved job in its own telemetry context (the job id, and
367    /// a span in the trace it was dispatched in, or a new trace), and
368    /// records the outcome.
369    async fn run_reserved(
370        &self,
371        ctx: &AppContext,
372        job: ReservedJob,
373        worker: &str,
374    ) -> Result<AttemptOutcome, QueueError> {
375        let mut context =
376            TelemetryContext::new(self.inner.telemetry.clone()).with_job_id(job.id.as_str());
377        if let Some(trace) = self.inner.policy.resume(job.trace_parent.as_deref()) {
378            context = context.with_trace(trace);
379        }
380        context.scope(self.run_attempt(ctx, job, worker)).await
381    }
382
383    /// Runs one reserved job and records the outcome.
384    async fn run_attempt(
385        &self,
386        ctx: &AppContext,
387        job: ReservedJob,
388        worker: &str,
389    ) -> Result<AttemptOutcome, QueueError> {
390        let started = Instant::now();
391        if job.attempts > job.options.max_attempts.max(1) {
392            let error = format!(
393                "the job was attempted too many times ({} of {}): the worker running its last attempt stopped (crashed or was killed) before it finished",
394                job.attempts, job.options.max_attempts
395            );
396            self.fail(&job, worker, &error, started).await?;
397            return Ok(AttemptOutcome::Failed);
398        }
399        let Some(registration) = self.inner.registry.get(job.job_type.as_str()) else {
400            let error = format!(
401                "no handler is registered for job type `{}`; register it with `m.job::<J>()`",
402                job.job_type
403            );
404            self.fail(&job, worker, &error, started).await?;
405            return Ok(AttemptOutcome::Failed);
406        };
407        if self.is_skipped(ctx, &job).await? {
408            self.finish(&job, worker, Finish::Skipped, "", started)
409                .await?;
410            log_cancelled(
411                &job,
412                started,
413                "the job's batch or operation was cancelled; skipped",
414            );
415            return Ok(AttemptOutcome::Cancelled);
416        }
417        let job_ctx = JobContext {
418            app: ctx.clone(),
419            job_id: job.id.clone(),
420            attempt: job.attempts,
421        };
422        let limit = Duration::from_secs(job.options.timeout_secs);
423        let running = self.begin(ctx, &job).await;
424        let ran = execute(registration, job.payload.clone(), job_ctx, limit).await;
425        self.end(running).await;
426        match ran {
427            Ran::Succeeded => {
428                self.finish(&job, worker, Finish::Succeeded, "", started)
429                    .await?;
430                self.inner.telemetry.emit_with(EventKind::JobProcessed, || {
431                    TelemetryEvent::JobProcessed(JobProcessed {
432                        queue: job.queue.clone(),
433                        job_type: job.job_type.clone(),
434                        job_id: job.id.clone(),
435                        attempt: job.attempts,
436                        duration: started.elapsed(),
437                    })
438                });
439                tracing::info!(
440                    target: "navree::job",
441                    name = %job.job_type,
442                    job_id = %job.id,
443                    queue = %job.queue,
444                    attempt = job.attempts,
445                    duration_ms = elapsed_ms(started),
446                    outcome = "succeeded",
447                    "job succeeded"
448                );
449                Ok(AttemptOutcome::Succeeded)
450            }
451            Ran::Cancelled => {
452                self.finish(&job, worker, Finish::Skipped, "", started)
453                    .await?;
454                log_cancelled(
455                    &job,
456                    started,
457                    "the job stopped: its batch or operation was cancelled",
458                );
459                Ok(AttemptOutcome::Cancelled)
460            }
461            Ran::Failed(error) if job.attempts >= job.options.max_attempts.max(1) => {
462                self.fail(&job, worker, &error, started).await?;
463                Ok(AttemptOutcome::Failed)
464            }
465            Ran::Failed(error) => {
466                self.release(&job, worker, &error, started).await?;
467                Ok(AttemptOutcome::Released)
468            }
469        }
470    }
471
472    /// Whether `job` must not run: one of a cancelled batch's jobs, or the
473    /// work of a cancelled operation.
474    async fn is_skipped(&self, ctx: &AppContext, job: &ReservedJob) -> Result<bool, QueueError> {
475        if let Some(batch_id) = job.membership.in_batch()
476            && let Some(row) = self.inner.store.find_batch(batch_id).await?
477            && row.cancelled_at.is_some()
478        {
479            return Ok(true);
480        }
481        crate::operations::skips(ctx, job).await
482    }
483
484    /// Records the end of `job`: deleted (or moved to the failed jobs), and
485    /// for a batch's job or callback, its batch updated and the callbacks
486    /// that became due queued, in one step. Then the effect on its
487    /// operation. Returns false when the worker no longer held the job.
488    async fn finish(
489        &self,
490        job: &ReservedJob,
491        worker: &str,
492        finish: Finish,
493        error: &str,
494        started: Instant,
495    ) -> Result<bool, QueueError> {
496        let now = self.now_ms();
497        let held = held_until(job, started);
498        let mut step = None;
499        if job.membership.batch_id.is_some() {
500            let prepare = |envelope, row: &BatchRow| self.prepare_callback(envelope, row);
501            match storing(held, || {
502                self.inner
503                    .store
504                    .finish_batch_job(job, worker, finish, error, now, &prepare)
505            })
506            .await?
507            {
508                Finished::Lost => return Ok(false),
509                Finished::Done(done) => step = done,
510            }
511        } else {
512            match finish {
513                Finish::Succeeded | Finish::Skipped => {
514                    storing(held, || self.inner.store.complete(job)).await?;
515                }
516                Finish::Failed => {
517                    if !storing(held, || self.inner.store.fail(job, worker, error, now)).await? {
518                        return Ok(false);
519                    }
520                }
521            }
522        }
523        if let Ok(app) = self.app() {
524            let batch = step.as_ref().map(|step| &step.batch);
525            crate::operations::job_finished(&app, job, finish, batch).await;
526        }
527        if let Some(step) = step
528            && step.settled_now
529        {
530            self.batch_settled(&step.batch).await;
531        }
532        Ok(true)
533    }
534
535    /// A batch and every callback it dispatched have finished: log it and
536    /// finish its operation.
537    async fn batch_settled(&self, row: &BatchRow) {
538        tracing::info!(
539            target: "navree::job",
540            batch_id = %row.id,
541            name = %row.name,
542            total_jobs = row.total_jobs,
543            failed_jobs = row.failed_jobs,
544            cancelled = row.cancelled_at.is_some(),
545            "batch finished"
546        );
547        if let Ok(app) = self.app() {
548            crate::operations::batch_settled(&app, row).await;
549        }
550    }
551
552    /// Puts `job` back on its queue, available after its backoff, and logs it.
553    async fn release(
554        &self,
555        job: &ReservedJob,
556        worker: &str,
557        error: &str,
558        started: Instant,
559    ) -> Result<(), QueueError> {
560        let delay = job.options.backoff.delay_for(job.attempts);
561        let delay_ms = i64::try_from(delay.as_millis()).unwrap_or(i64::MAX);
562        let available_at = self.now_ms().saturating_add(delay_ms);
563        let released = storing(held_until(job, started), || {
564            self.inner.store.release(job, worker, available_at)
565        })
566        .await?;
567        if released {
568            self.report_failure(job, error, started, true);
569            tracing::warn!(
570                target: "navree::job",
571                name = %job.job_type,
572                job_id = %job.id,
573                queue = %job.queue,
574                attempt = job.attempts,
575                duration_ms = elapsed_ms(started),
576                outcome = "released",
577                retry_in_secs = delay.as_secs(),
578                error,
579                "job attempt failed; it will be retried"
580            );
581        } else {
582            lost_reservation(job, worker);
583        }
584        Ok(())
585    }
586
587    /// Moves `job` to the failed jobs and logs it.
588    async fn fail(
589        &self,
590        job: &ReservedJob,
591        worker: &str,
592        error: &str,
593        started: Instant,
594    ) -> Result<(), QueueError> {
595        let moved = self
596            .finish(job, worker, Finish::Failed, error, started)
597            .await?;
598        if moved {
599            self.report_failure(job, error, started, false);
600            tracing::error!(
601                target: "navree::job",
602                name = %job.job_type,
603                job_id = %job.id,
604                queue = %job.queue,
605                attempt = job.attempts,
606                duration_ms = elapsed_ms(started),
607                outcome = "failed",
608                error,
609                "job failed"
610            );
611        } else {
612            lost_reservation(job, worker);
613        }
614        Ok(())
615    }
616}
617
618impl Queue {
619    /// Emits a [`JobFailed`] for a failed attempt of `job`.
620    fn report_failure(&self, job: &ReservedJob, error: &str, started: Instant, will_retry: bool) {
621        self.inner.telemetry.emit_with(EventKind::JobFailed, || {
622            TelemetryEvent::JobFailed(JobFailed {
623                queue: job.queue.clone(),
624                job_type: job.job_type.clone(),
625                job_id: job.id.clone(),
626                attempt: job.attempts,
627                duration: started.elapsed(),
628                error: error.to_owned(),
629                will_retry,
630            })
631        });
632    }
633}
634
635/// How many times a worker tries again when the database is busy, and how long
636/// it waits in between. SQLite has already waited `busy_timeout` by then.
637const BUSY_RETRIES: u32 = 5;
638const BUSY_RETRY_DELAY: Duration = Duration::from_millis(250);
639
640/// Whether `error` is the database being busy for now.
641fn is_busy(error: &QueueError) -> bool {
642    matches!(error, QueueError::Db(error) if error.is_retryable())
643}
644
645/// Until when a worker holds `job`, reserved about when `started` was taken: after
646/// that its reservation is stale and another worker may take it.
647fn held_until(job: &ReservedJob, started: Instant) -> Instant {
648    let held = Duration::from_millis(
649        u64::try_from(crate::record::stale_after_ms(&job.options)).unwrap_or(u64::MAX),
650    );
651    started.checked_add(held).unwrap_or(started)
652}
653
654/// Stores what became of a job, trying again while the database is busy and the
655/// worker still holds it (until `held`): the job has run, and if this is lost
656/// its reservation goes stale and the job runs again.
657async fn storing<T, Fut>(held: Instant, mut store: impl FnMut() -> Fut) -> Result<T, QueueError>
658where
659    Fut: Future<Output = Result<T, QueueError>>,
660{
661    loop {
662        match store().await {
663            Err(error) if is_busy(&error) && Instant::now() < held => {
664                tracing::warn!(target: "navree::job", %error, "cannot store a job's outcome; trying again");
665                tokio::time::sleep(BUSY_RETRY_DELAY).await;
666            }
667            outcome => return outcome,
668        }
669    }
670}
671
672/// One worker loop of a `work` call.
673struct Worker {
674    queue: Queue,
675    ctx: AppContext,
676    queues: Vec<String>,
677    /// Stops when no job is available.
678    finite: bool,
679    budget: Arc<Budget>,
680    token: CancellationToken,
681    /// A supervisor's hooks.
682    hooks: Option<Arc<dyn WorkHooks>>,
683    id: String,
684    /// Tries in a row that found the database busy.
685    busy: AtomicU32,
686}
687
688impl Worker {
689    async fn run(self) -> Result<WorkStats, QueueError> {
690        let mut stats = WorkStats::default();
691        while !self.token.is_cancelled() {
692            if self
693                .hooks
694                .as_ref()
695                .is_some_and(|hooks| !hooks.may_reserve())
696            {
697                // Held by the supervisor (paused).
698                if self.finite || !self.idle().await {
699                    break;
700                }
701                continue;
702            }
703            if !self.budget.take() {
704                break;
705            }
706            match self.reserve().await {
707                Ok(Some(job)) => {
708                    self.busy.store(0, Ordering::Relaxed);
709                    let started = Instant::now();
710                    let (job_id, queue, job_type, attempt) = (
711                        job.id.clone(),
712                        job.queue.clone(),
713                        job.job_type.clone(),
714                        job.attempts,
715                    );
716                    match self.queue.run_reserved(&self.ctx, job, &self.id).await {
717                        Ok(outcome) => {
718                            stats += outcome.stats();
719                            if let Some(hooks) = &self.hooks {
720                                hooks.attempted(&Attempt {
721                                    job_id,
722                                    queue,
723                                    job_type,
724                                    attempt,
725                                    outcome,
726                                    runtime_ms: elapsed_ms(started),
727                                });
728                            }
729                        }
730                        // The job ran (or was skipped) and its outcome could not be
731                        // stored while the worker held it: its reservation goes stale
732                        // and another worker runs it again. A call that ends by itself
733                        // says so, and never returns `Ok` for it.
734                        Err(error) => {
735                            tracing::error!(
736                                target: "navree::job",
737                                %error,
738                                worker = %self.id,
739                                name = %job_type,
740                                job_id = %job_id,
741                                queue = %queue,
742                                attempt,
743                                "cannot store a job's outcome; the job will run again"
744                            );
745                            if self.finite || self.budget.limited {
746                                return Err(error);
747                            }
748                            if !self.idle().await {
749                                break;
750                            }
751                        }
752                    }
753                }
754                Ok(None) => {
755                    self.budget.give_back();
756                    if self.finite || !self.idle().await {
757                        break;
758                    }
759                }
760                Err(error) => {
761                    self.budget.give_back();
762                    if !self.recover(error, "cannot reserve a job").await? {
763                        break;
764                    }
765                }
766            }
767        }
768        Ok(stats)
769    }
770
771    /// A driver error finding a job: returned when the worker stops on an empty
772    /// queue, unless it is the database being busy for now (a lock held longer
773    /// than it waits, a deadlock), which is tried again a few times; otherwise
774    /// logged, then the worker waits a poll interval. `Ok(false)` when the app
775    /// shuts down meanwhile.
776    async fn recover(&self, error: QueueError, what: &str) -> Result<bool, QueueError> {
777        if self.finite {
778            if !is_busy(&error) || self.busy.fetch_add(1, Ordering::Relaxed) >= BUSY_RETRIES {
779                return Err(error);
780            }
781            tracing::warn!(target: "navree::job", %error, worker = %self.id, "{what}; trying again");
782            tokio::time::sleep(BUSY_RETRY_DELAY).await;
783            return Ok(!self.token.is_cancelled());
784        }
785        tracing::error!(target: "navree::job", %error, worker = %self.id, "{what}");
786        Ok(self.idle().await)
787    }
788
789    /// The next available job, from the first queue that has one.
790    async fn reserve(&self) -> Result<Option<ReservedJob>, QueueError> {
791        for queue in &self.queues {
792            let now = self.queue.now_ms();
793            if let Some(job) = self.queue.inner.store.reserve(queue, &self.id, now).await? {
794                return Ok(Some(job));
795            }
796        }
797        Ok(None)
798    }
799
800    /// Waits one poll interval; false when the app shuts down meanwhile.
801    async fn idle(&self) -> bool {
802        tokio::select! {
803            () = self.token.cancelled() => false,
804            () = tokio::time::sleep(self.queue.inner.options.poll_interval()) => true,
805        }
806    }
807}
808
809/// Runs the handler, bounded by `limit` (none when zero); panics and
810/// timeouts become errors.
811async fn execute(
812    registration: &JobRegistration,
813    payload: Value,
814    ctx: JobContext,
815    limit: Duration,
816) -> Ran {
817    let run = registration.run;
818    let attempt = AssertUnwindSafe(async move { run(payload, ctx).await }).catch_unwind();
819    let result = if limit.is_zero() {
820        attempt.await
821    } else {
822        match tokio::time::timeout(limit, attempt).await {
823            Ok(result) => result,
824            Err(_) => {
825                return Ran::Failed(format!("the job timed out after {} s", limit.as_secs()));
826            }
827        }
828    };
829    match result {
830        Ok(Ok(())) => Ran::Succeeded,
831        Ok(Err(error)) if error.downcast_ref::<JobCancelled>().is_some() => Ran::Cancelled,
832        Ok(Err(error)) => Ran::Failed(error_chain(&*error)),
833        Err(panic) => Ran::Failed(format!("the job panicked: {}", panic_message(&*panic))),
834    }
835}
836
837fn log_cancelled(job: &ReservedJob, started: Instant, message: &str) {
838    tracing::info!(
839        target: "navree::job",
840        name = %job.job_type,
841        job_id = %job.id,
842        queue = %job.queue,
843        attempt = job.attempts,
844        duration_ms = elapsed_ms(started),
845        outcome = "cancelled",
846        "{message}"
847    );
848}
849
850/// `error: source: source…`.
851fn error_chain(error: &(dyn std::error::Error + 'static)) -> String {
852    let mut message = error.to_string();
853    let mut source = error.source();
854    while let Some(cause) = source {
855        let cause_text = cause.to_string();
856        if !message.ends_with(&cause_text) {
857            message.push_str(": ");
858            message.push_str(&cause_text);
859        }
860        source = cause.source();
861    }
862    message
863}
864
865fn panic_message(panic: &(dyn Any + Send)) -> String {
866    if let Some(message) = panic.downcast_ref::<&str>() {
867        (*message).to_owned()
868    } else if let Some(message) = panic.downcast_ref::<String>() {
869        message.clone()
870    } else {
871        "a non-string panic payload".to_owned()
872    }
873}
874
875fn elapsed_ms(started: Instant) -> u64 {
876    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
877}
878
879fn lost_reservation(job: &ReservedJob, worker: &str) {
880    tracing::warn!(
881        target: "navree::job",
882        name = %job.job_type,
883        job_id = %job.id,
884        worker,
885        "the job's reservation was taken over by another worker (it ran longer than its timeout); leaving it to that worker"
886    );
887}