Skip to main content

navree_queue/operations/
mod.rs

1//! Operations: user-visible long work (an import, an export, a bulk
2//! update) with an owner, a workspace, a status, progress, a result and a
3//! heartbeat, stored in `operations`.
4
5mod controller;
6mod hooks;
7mod sql;
8
9use std::fmt;
10use std::time::Duration;
11
12use chrono::{DateTime, Utc};
13use navree_contracts::{BoxError, Broadcaster, Job, JobEnvelope, Principal, permitted};
14use navree_db::{Db, Executor, Statement, Uow};
15use navree_kernel::{AppContext, WeakAppContext};
16use navree_openapi::ToSchema;
17use navree_realtime::{NUDGE_EVENT, Topic};
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use tokio::sync::broadcast;
21use uuid::Uuid;
22
23pub(crate) use controller::authorize_channel;
24#[cfg(feature = "ui")]
25pub(crate) use controller::visible;
26pub use controller::{OPERATION_EVENT, OperationsController};
27pub(crate) use hooks::{QueueMonitor, RunningJobs, batch_settled, job_finished, skips};
28
29use crate::batch::{Batch, JobBatch};
30use crate::{OperationsOptions, Queue, QueueError};
31
32/// The realtime event every change of an operation is broadcast as, on the
33/// private channel `operations.{id}`.
34pub const OPERATION_UPDATED_EVENT: &str = "operation.updated";
35
36/// The topic of the live hub a page hears an operation change on: `operation.{id}`, told to the
37/// operation's owner and, when it has one, to the members of its workspace (see
38/// [`RealtimeModule`](navree_realtime::RealtimeModule)). A nudge carries nothing; the page
39/// fetches the operation again.
40pub fn operation_topic(id: Uuid) -> String {
41    format!("operation.{id}")
42}
43
44/// Where an operation is.
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
46#[serde(rename_all = "snake_case")]
47#[non_exhaustive]
48pub enum OperationStatus {
49    /// Started, waiting for its work to begin.
50    Pending,
51    /// Its work is running.
52    Running,
53    /// It finished; `result` may hold what it produced.
54    Succeeded,
55    /// It failed; `error` says why.
56    Failed,
57    /// It was cancelled.
58    Cancelled,
59}
60
61impl OperationStatus {
62    /// Whether the operation has finished (succeeded, failed or was
63    /// cancelled): it never changes again.
64    pub fn is_finished(self) -> bool {
65        matches!(
66            self,
67            OperationStatus::Succeeded | OperationStatus::Failed | OperationStatus::Cancelled
68        )
69    }
70
71    /// The stored name (`running`).
72    pub fn as_str(self) -> &'static str {
73        match self {
74            OperationStatus::Pending => "pending",
75            OperationStatus::Running => "running",
76            OperationStatus::Succeeded => "succeeded",
77            OperationStatus::Failed => "failed",
78            OperationStatus::Cancelled => "cancelled",
79        }
80    }
81
82    pub(crate) fn parse(name: &str) -> Option<Self> {
83        Some(match name {
84            "pending" => OperationStatus::Pending,
85            "running" => OperationStatus::Running,
86            "succeeded" => OperationStatus::Succeeded,
87            "failed" => OperationStatus::Failed,
88            "cancelled" => OperationStatus::Cancelled,
89            _ => return None,
90        })
91    }
92}
93
94impl fmt::Display for OperationStatus {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(self.as_str())
97    }
98}
99
100/// An operation to start with [`Operations::start`]:
101/// `Operation::new("export").owner(user_id).workspace(workspace_id)`.
102#[derive(Clone, Debug, Default, PartialEq, Eq)]
103pub struct Operation {
104    pub(crate) kind: String,
105    pub(crate) owner_id: Option<Uuid>,
106    pub(crate) workspace_id: Option<Uuid>,
107    pub(crate) total: u64,
108    pub(crate) note: String,
109    pub(crate) idempotent: bool,
110}
111
112impl Operation {
113    /// An operation of kind `kind` (`export`, `recipients.import`), for
114    /// people and front ends to tell operations apart.
115    pub fn new(kind: impl Into<String>) -> Self {
116        Self {
117            kind: kind.into(),
118            ..Self::default()
119        }
120    }
121
122    /// The user who started it: they may always see and cancel it.
123    pub fn owner(mut self, user_id: Uuid) -> Self {
124        self.owner_id = Some(user_id);
125        self
126    }
127
128    /// The workspace it belongs to: members whose role there grants
129    /// `operations.view` may see it (`operations.cancel` to cancel it).
130    pub fn workspace(mut self, workspace_id: Uuid) -> Self {
131        self.workspace_id = Some(workspace_id);
132        self
133    }
134
135    /// The units of work, when known up front (rows to import).
136    pub fn total(mut self, total: u64) -> Self {
137        self.total = total;
138        self
139    }
140
141    /// The first progress note (`"Waiting for a worker"`).
142    pub fn note(mut self, note: impl Into<String>) -> Self {
143        self.note = note.into();
144        self
145    }
146
147    /// Its job may safely run again from the start: when the operation
148    /// stops responding and no job of it is left in the queue, the
149    /// watchdog dispatches the job again (up to
150    /// `queue.operations.max_redispatches` times) instead of failing it.
151    pub fn idempotent(mut self) -> Self {
152        self.idempotent = true;
153        self
154    }
155}
156
157/// How far an operation got.
158#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
159pub struct OperationProgress {
160    /// Units done.
161    pub done: u64,
162    /// Units in all (0 when unknown).
163    pub total: u64,
164    /// `done` as a whole percentage of `total` (0 when `total` is 0).
165    pub percent: u8,
166    /// What the operation is doing, for people.
167    pub note: String,
168}
169
170/// A stored operation: what [`Operations`] returns, `GET
171/// /api/operations/{id}` answers, the SSE stream sends and
172/// `operation.updated` broadcasts.
173#[derive(Clone, Debug, PartialEq, Serialize, ToSchema)]
174pub struct OperationRecord {
175    /// The operation id.
176    pub id: Uuid,
177    /// Its kind (`export`).
178    pub kind: String,
179    /// Where it is.
180    pub status: OperationStatus,
181    /// How far it got.
182    pub progress: OperationProgress,
183    /// What it produced (set by [`Operations::complete`]).
184    pub result: Option<Value>,
185    /// Why it failed.
186    pub error: Option<String>,
187    /// The user who started it.
188    pub owner_id: Option<Uuid>,
189    /// The workspace it belongs to.
190    pub workspace_id: Option<Uuid>,
191    /// The batch doing its work.
192    pub batch_id: Option<String>,
193    /// When it was started.
194    pub created_at: DateTime<Utc>,
195    /// When its work began.
196    pub started_at: Option<DateTime<Utc>>,
197    /// When its work last showed signs of life.
198    pub heartbeat_at: Option<DateTime<Utc>>,
199    /// When it finished.
200    pub finished_at: Option<DateTime<Utc>>,
201    /// When it last changed.
202    pub updated_at: DateTime<Utc>,
203    /// Bumped on every change (the SSE stream's event id).
204    #[serde(skip)]
205    pub(crate) version: i64,
206    /// The job to dispatch again when an idempotent operation stalls.
207    #[serde(skip)]
208    pub(crate) job: Option<Value>,
209    #[serde(skip)]
210    pub(crate) idempotent: bool,
211    #[serde(skip)]
212    pub(crate) redispatches: u32,
213}
214
215impl OperationRecord {
216    /// Whether the operation has finished.
217    pub fn is_finished(&self) -> bool {
218        self.status.is_finished()
219    }
220
221    /// The private realtime channel its changes are broadcast on,
222    /// `private-operations.{id}`.
223    pub fn channel(&self) -> String {
224        channel_name(self.id)
225    }
226}
227
228/// `private-operations.{id}`.
229pub(crate) fn channel_name(id: Uuid) -> String {
230    format!("private-operations.{id}")
231}
232
233/// What one [`Operations::sweep`] did.
234#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
235pub struct SweepReport {
236    /// Operations that stopped responding and were marked failed.
237    pub failed: u64,
238    /// Idempotent operations whose job was dispatched again.
239    pub redispatched: u64,
240    /// Operations whose batch had finished, now finished too.
241    pub finished: u64,
242}
243
244/// User-visible long work: provided and exported by
245/// [`QueueModule`](crate::QueueModule) (it needs `DatabaseModule`).
246///
247/// ```no_run
248/// # use navree_contracts::{BoxError, Job, JobContext};
249/// # use serde::{Deserialize, Serialize};
250/// # #[derive(Serialize, Deserialize)] struct ExportDeals { operation: uuid::Uuid }
251/// # impl Job for ExportDeals { const NAME: &'static str = "deals.export"; async fn handle(self, _: JobContext) -> Result<(), BoxError> { Ok(()) } }
252/// use navree_queue::{Operation, Operations};
253///
254/// # async fn example(operations: &Operations, uow: &navree_db::Uow, user: uuid::Uuid) -> Result<(), navree_queue::QueueError> {
255/// let op = operations
256///     .start(uow, Operation::new("deals.export").owner(user))
257///     .await?;
258/// operations
259///     .dispatch(uow, &op, ExportDeals { operation: op.id })
260///     .await?;
261/// // The client follows GET /api/operations/{op.id}/events.
262/// # Ok(())
263/// # }
264/// ```
265///
266/// - [`start`](Operations::start) stores it `pending`;
267///   [`dispatch`](Operations::dispatch) and
268///   [`dispatch_batch`](Operations::dispatch_batch) queue its work.
269/// - Its job's `ctx.progress(done, total, note)` makes it `running` and
270///   records the progress; while the job runs the worker beats its
271///   heartbeat every `queue.operations.heartbeat_secs`.
272/// - It finishes when its job ends: `succeeded` (keeping any result set
273///   with [`complete`](Operations::complete)), `failed`, or `cancelled`.
274///   With a batch it finishes once the batch and its callbacks have run.
275/// - [`cancel`](Operations::cancel) is cooperative: jobs not started are
276///   skipped, running ones get `JobCancelled` from their next
277///   `ctx.progress`.
278/// - Every change is broadcast as `operation.updated` on
279///   `private-operations.{id}` (when the app has a `dyn Broadcaster`).
280pub struct Operations {
281    db: Option<Db>,
282    queue: Queue,
283    options: OperationsOptions,
284    changes: broadcast::Sender<Uuid>,
285    app: Option<WeakAppContext>,
286}
287
288/// How many change notices the SSE streams may fall behind before they
289/// reload.
290const CHANGE_BUFFER: usize = 1024;
291
292impl Operations {
293    pub(crate) fn new(
294        db: Option<Db>,
295        queue: Queue,
296        options: OperationsOptions,
297        app: Option<WeakAppContext>,
298    ) -> Self {
299        let (changes, _) = broadcast::channel(CHANGE_BUFFER);
300        Self {
301            db,
302            queue,
303            options,
304            changes,
305            app,
306        }
307    }
308
309    /// The options operations run with (`queue.operations`).
310    pub fn options(&self) -> &OperationsOptions {
311        &self.options
312    }
313
314    /// The app database; [`QueueError::NoDatabase`] in an app without
315    /// `DatabaseModule`.
316    fn db(&self) -> Result<&Db, QueueError> {
317        self.db.as_ref().ok_or(QueueError::NoDatabase)
318    }
319
320    /// What the operations' statements run on outside a unit of work: the
321    /// writer's pool (or the connection itself when it has no pool).
322    fn writer(&self) -> Result<&dyn Executor, QueueError> {
323        let db = self.db()?;
324        Ok(db.pool())
325    }
326
327    /// Stores `operation` as `pending`, as part of `uow`; returns it.
328    pub async fn start(
329        &self,
330        uow: &Uow,
331        operation: Operation,
332    ) -> Result<OperationRecord, QueueError> {
333        let now = self.queue.now_ms();
334        let record = sql::new_record(Uuid::now_v7(), &operation, now);
335        uow.execute(&sql::insert(&record)?).await?;
336        Ok(record)
337    }
338
339    /// Queues `job` as the work of `operation`, as part of `uow`; returns
340    /// the job id. The job's progress reports go to the operation, and the
341    /// operation finishes when the job ends. For an
342    /// [`idempotent`](Operation::idempotent) operation the job is kept so
343    /// the watchdog can dispatch it again.
344    pub async fn dispatch<J: Job>(
345        &self,
346        uow: &Uow,
347        operation: &OperationRecord,
348        job: J,
349    ) -> Result<String, QueueError> {
350        let envelope = JobEnvelope {
351            job_type: J::NAME.to_owned(),
352            payload: serde_json::to_value(&job).map_err(QueueError::Payload)?,
353            options: J::options(),
354            delay_secs: None,
355            unique_key: None,
356        };
357        if operation.idempotent {
358            uow.execute(&sql::set_job(operation.id, &envelope)?).await?;
359        }
360        self.queue
361            .push_for_operation_in(uow, envelope, operation.id)
362            .await
363    }
364
365    /// Dispatches `batch` as the work of `operation`, as part of `uow`
366    /// (see [`Batch::operation`]): the operation's progress follows the
367    /// batch's finished jobs, and it finishes once the batch and its
368    /// callbacks have run.
369    pub async fn dispatch_batch(
370        &self,
371        uow: &Uow,
372        operation: &OperationRecord,
373        batch: Batch,
374    ) -> Result<JobBatch, QueueError> {
375        let total = batch.len() as u64;
376        let batch = self
377            .queue
378            .dispatch_batch_in(uow, batch.operation(operation.id))
379            .await?;
380        uow.execute(&sql::set_batch(
381            operation.id,
382            &batch.id,
383            total,
384            self.queue.now_ms(),
385        ))
386        .await?;
387        Ok(batch)
388    }
389
390    /// The operation `id`.
391    pub async fn find(&self, id: Uuid) -> Result<Option<OperationRecord>, QueueError> {
392        sql::find(self.writer()?, id).await
393    }
394
395    /// The operations `owner` started, newest first, at most `limit`.
396    pub async fn for_owner(
397        &self,
398        owner: Uuid,
399        limit: usize,
400    ) -> Result<Vec<OperationRecord>, QueueError> {
401        sql::for_owner(self.writer()?, owner, limit).await
402    }
403
404    /// Records progress: the operation becomes `running` with `done` of
405    /// `total` and `note`, and its heartbeat is renewed. A finished
406    /// operation does not change. Returns the operation afterwards.
407    pub async fn progress(
408        &self,
409        id: Uuid,
410        done: u64,
411        total: u64,
412        note: impl Into<String>,
413    ) -> Result<Option<OperationRecord>, QueueError> {
414        let now = self.queue.now_ms();
415        let stmt = sql::progress(id, done, total, &note.into(), now);
416        self.update(id, stmt).await
417    }
418
419    /// Renews the heartbeat of a pending or running operation (work that
420    /// runs outside the queue calls this to show it is alive).
421    pub async fn heartbeat(&self, id: Uuid) -> Result<(), QueueError> {
422        let stmt = sql::heartbeat(id, self.queue.now_ms());
423        self.execute(stmt).await.map(|_| ())
424    }
425
426    /// Finishes the operation as `succeeded` with `result` (what a front
427    /// end needs: a download URL, counts). A finished operation does not
428    /// change. Returns the operation afterwards.
429    pub async fn complete(
430        &self,
431        id: Uuid,
432        result: impl Serialize,
433    ) -> Result<Option<OperationRecord>, QueueError> {
434        let result = serde_json::to_value(result).map_err(QueueError::Payload)?;
435        let now = self.queue.now_ms();
436        let stmt = sql::finish(id, OperationStatus::Succeeded, Some(&result), None, now)?;
437        self.update(id, stmt).await
438    }
439
440    /// Finishes the operation as `failed` with `error`, a message for
441    /// people. A finished operation does not change.
442    pub async fn fail(
443        &self,
444        id: Uuid,
445        error: impl Into<String>,
446    ) -> Result<Option<OperationRecord>, QueueError> {
447        let now = self.queue.now_ms();
448        let error = error.into();
449        let stmt = sql::finish(id, OperationStatus::Failed, None, Some(&error), now)?;
450        self.update(id, stmt).await
451    }
452
453    /// Cancels the operation: it becomes `cancelled` at once, its batch is
454    /// cancelled, its jobs that have not started are skipped, and running
455    /// ones stop at their next `ctx.progress` (cooperative). A finished
456    /// operation does not change. Returns the operation afterwards (`None`
457    /// when there is none).
458    pub async fn cancel(&self, id: Uuid) -> Result<Option<OperationRecord>, QueueError> {
459        let now = self.queue.now_ms();
460        let stmt = sql::finish(id, OperationStatus::Cancelled, None, None, now)?;
461        let record = self.update(id, stmt).await?;
462        if let Some(record) = &record
463            && record.status == OperationStatus::Cancelled
464            && let Some(batch_id) = &record.batch_id
465        {
466            self.queue.cancel_batch(batch_id).await?;
467        }
468        Ok(record)
469    }
470
471    /// The watchdog (command `queue:watchdog`; schedule it every minute).
472    /// For each pending or running operation without a heartbeat for
473    /// `queue.operations.stale_after_secs`:
474    ///
475    /// - a job of it still in the queue means the queue still owns the
476    ///   work (a crashed worker's reservation is taken over by another):
477    ///   left alone;
478    /// - its batch finished: it finishes the way the batch did;
479    /// - [`idempotent`](Operation::idempotent) with a job: the job is
480    ///   dispatched again (at most `max_redispatches` times);
481    /// - otherwise: `failed`, "The operation stopped responding.".
482    ///
483    /// Each step first claims the operation on its row (it must still be
484    /// stale), so sweeps that overlap (two nodes, or the schedule and a
485    /// manual `queue:watchdog`) restart or fail an operation once, and a
486    /// heartbeat that arrives during the sweep keeps it alive.
487    pub async fn sweep(&self) -> Result<SweepReport, QueueError> {
488        let now = self.queue.now_ms();
489        let stale_ms =
490            i64::try_from(self.options.stale_after_secs.saturating_mul(1000)).unwrap_or(i64::MAX);
491        let before = now.saturating_sub(stale_ms);
492        let stale = sql::stale(self.writer()?, before).await?;
493        let mut report = SweepReport::default();
494        for record in stale {
495            let id = record.id.to_string();
496            if self.queue.inner.store.count_for_operation(&id).await? > 0 {
497                continue;
498            }
499            if let Some(batch_id) = &record.batch_id
500                && let Some(row) = self.queue.inner.store.find_batch(batch_id).await?
501                && row.settled()
502            {
503                let finish = self.batch_finish(record.id, &row, now)?;
504                if self.apply(record.id, finish).await?.0 {
505                    report.finished += 1;
506                }
507                continue;
508            }
509            if record.idempotent
510                && let Some(job) = record
511                    .job
512                    .clone()
513                    .and_then(|job| serde_json::from_value::<JobEnvelope>(job).ok())
514                && record.redispatches < self.options.max_redispatches
515            {
516                let claim = sql::redispatched(record.id, before, now);
517                if !self.apply(record.id, claim).await?.0 {
518                    // Another sweep restarted it, or it came back to life.
519                    continue;
520                }
521                self.queue.push_for_operation(job, record.id).await?;
522                tracing::warn!(
523                    target: "navree::job",
524                    operation_id = %record.id,
525                    kind = %record.kind,
526                    redispatches = record.redispatches + 1,
527                    "operation stopped responding; its job was dispatched again"
528                );
529                report.redispatched += 1;
530                continue;
531            }
532            let stalled = sql::stalled(record.id, STALLED_MESSAGE, before, now);
533            if !self.apply(record.id, stalled).await?.0 {
534                continue;
535            }
536            tracing::warn!(
537                target: "navree::job",
538                operation_id = %record.id,
539                kind = %record.kind,
540                "operation stopped responding; marked failed"
541            );
542            report.failed += 1;
543        }
544        Ok(report)
545    }
546
547    /// Deletes the operations that finished more than `older_than` ago;
548    /// returns how many.
549    pub async fn prune(&self, older_than: Duration) -> Result<u64, QueueError> {
550        let before = self
551            .queue
552            .now_ms()
553            .saturating_sub(i64::try_from(older_than.as_millis()).unwrap_or(i64::MAX));
554        let stmt = sql::prune(before);
555        Ok(self.writer()?.execute(&stmt).await?.rows_affected)
556    }
557
558    /// Whether `principal` may see `operation`: its owner, or a holder of
559    /// `queue.operations.view_permission` (`operations.view`) app-wide or
560    /// in the operation's workspace.
561    pub async fn can_view(
562        &self,
563        principal: &Principal,
564        operation: &OperationRecord,
565    ) -> Result<bool, BoxError> {
566        self.allowed(principal, operation, &self.options.view_permission)
567            .await
568    }
569
570    /// Whether `principal` may cancel `operation`: its owner, or a holder
571    /// of `queue.operations.cancel_permission` (`operations.cancel`)
572    /// app-wide or in the operation's workspace.
573    pub async fn can_cancel(
574        &self,
575        principal: &Principal,
576        operation: &OperationRecord,
577    ) -> Result<bool, BoxError> {
578        self.allowed(principal, operation, &self.options.cancel_permission)
579            .await
580    }
581
582    async fn allowed(
583        &self,
584        principal: &Principal,
585        operation: &OperationRecord,
586        permission: &str,
587    ) -> Result<bool, BoxError> {
588        if operation.owner_id == Some(principal.user_id) {
589            return Ok(true);
590        }
591        let Some(app) = self.app() else {
592            return Ok(false);
593        };
594        permitted(&app, principal, permission, operation.workspace_id).await
595    }
596
597    /// A receiver of the ids of operations that changed in this process.
598    pub(crate) fn subscribe(&self) -> broadcast::Receiver<Uuid> {
599        self.changes.subscribe()
600    }
601
602    /// Finishes the operation the way its settled batch went.
603    pub(crate) async fn finish_from_batch(
604        &self,
605        id: Uuid,
606        row: &crate::batch::BatchRow,
607    ) -> Result<Option<OperationRecord>, QueueError> {
608        let stmt = self.batch_finish(id, row, self.queue.now_ms())?;
609        self.update(id, stmt).await
610    }
611
612    /// The statement that finishes operation `id` the way its settled batch
613    /// `row` went.
614    fn batch_finish(
615        &self,
616        id: Uuid,
617        row: &crate::batch::BatchRow,
618        now: i64,
619    ) -> Result<Statement, QueueError> {
620        if row.cancelled_at.is_some() && row.failed_jobs == 0 {
621            sql::finish(id, OperationStatus::Cancelled, None, None, now)
622        } else if row.failed_jobs > 0 && !row.allow_failures {
623            let error = format!("{} of {} jobs failed.", row.failed_jobs, row.total_jobs);
624            sql::finish(id, OperationStatus::Failed, None, Some(&error), now)
625        } else if row.callbacks_failed > 0 {
626            let error = "A follow-up job of the batch failed.";
627            sql::finish(id, OperationStatus::Failed, None, Some(error), now)
628        } else {
629            sql::finish(id, OperationStatus::Succeeded, None, None, now)
630        }
631    }
632
633    /// Records a batch's finished jobs as the operation's progress.
634    pub(crate) async fn batch_progress(
635        &self,
636        id: Uuid,
637        row: &crate::batch::BatchRow,
638    ) -> Result<Option<OperationRecord>, QueueError> {
639        let now = self.queue.now_ms();
640        let done = row.total_jobs.saturating_sub(row.pending_jobs);
641        let stmt = sql::counts(id, done, row.total_jobs, now);
642        self.update(id, stmt).await
643    }
644
645    /// Records a progress note (and renews the heartbeat) without
646    /// changing the counts: what a batch job's `ctx.progress` does.
647    pub(crate) async fn note(
648        &self,
649        id: Uuid,
650        note: &str,
651    ) -> Result<Option<OperationRecord>, QueueError> {
652        let stmt = sql::note(id, note, self.queue.now_ms());
653        self.update(id, stmt).await
654    }
655
656    /// Finishes the operation as `succeeded` (its own job succeeded),
657    /// keeping a result already set.
658    pub(crate) async fn job_succeeded(
659        &self,
660        id: Uuid,
661    ) -> Result<Option<OperationRecord>, QueueError> {
662        let now = self.queue.now_ms();
663        let stmt = sql::finish(id, OperationStatus::Succeeded, None, None, now)?;
664        self.update(id, stmt).await
665    }
666
667    /// Marks the operation running (its job started).
668    pub(crate) async fn mark_running(
669        &self,
670        id: Uuid,
671    ) -> Result<Option<OperationRecord>, QueueError> {
672        let stmt = sql::running(id, self.queue.now_ms());
673        self.update(id, stmt).await
674    }
675
676    /// The status of operation `id`.
677    pub(crate) async fn status(&self, id: Uuid) -> Result<Option<OperationStatus>, QueueError> {
678        sql::status(self.writer()?, id).await
679    }
680
681    fn app(&self) -> Option<AppContext> {
682        self.app.as_ref().and_then(WeakAppContext::upgrade)
683    }
684
685    /// Runs `stmt` in the current unit of work when there is an
686    /// unfinished one, else on its own; returns the rows it changed.
687    async fn execute(&self, stmt: Statement) -> Result<u64, QueueError> {
688        if let Some(uow) = Uow::current()
689            && !uow.is_finished().await
690        {
691            return Ok(uow.execute(&stmt).await?.rows_affected);
692        }
693        Ok(self.writer()?.execute(&stmt).await?.rows_affected)
694    }
695
696    /// Runs an update of operation `id` (in the current unit of work when
697    /// there is an unfinished one) and returns the operation afterwards.
698    /// When it changed, the change is announced: to this process's SSE
699    /// streams and as `operation.updated` on its channel, after the commit
700    /// of the unit of work it joined.
701    async fn update(
702        &self,
703        id: Uuid,
704        stmt: Statement,
705    ) -> Result<Option<OperationRecord>, QueueError> {
706        Ok(self.apply(id, stmt).await?.1)
707    }
708
709    /// [`update`](Operations::update), also telling whether `stmt` changed
710    /// the operation.
711    async fn apply(
712        &self,
713        id: Uuid,
714        stmt: Statement,
715    ) -> Result<(bool, Option<OperationRecord>), QueueError> {
716        if let Some(uow) = Uow::current()
717            && !uow.is_finished().await
718        {
719            let changed = uow.execute(&stmt).await?.rows_affected > 0;
720            let record = sql::find(&uow, id).await?;
721            if changed && let Some(record) = record.clone() {
722                let announcer = self.announcer();
723                uow.after_commit(move || {
724                    Box::pin(async move { announcer.announce(&record).await })
725                });
726            }
727            return Ok((changed, record));
728        }
729        let changed = self.writer()?.execute(&stmt).await?.rows_affected > 0;
730        let record = self.find(id).await?;
731        if changed && let Some(record) = &record {
732            self.announcer().announce(record).await;
733        }
734        Ok((changed, record))
735    }
736
737    fn announcer(&self) -> Announcer {
738        Announcer {
739            changes: self.changes.clone(),
740            app: self.app.clone(),
741        }
742    }
743}
744
745/// Announces changed operations.
746struct Announcer {
747    changes: broadcast::Sender<Uuid>,
748    app: Option<WeakAppContext>,
749}
750
751impl Announcer {
752    async fn announce(&self, record: &OperationRecord) {
753        // No receiver is not an error.
754        let _ = self.changes.send(record.id);
755        let Some(app) = self.app.as_ref().and_then(WeakAppContext::upgrade) else {
756            return;
757        };
758        let Some(broadcaster) = app.try_get::<dyn Broadcaster>().await else {
759            return;
760        };
761        let data = match serde_json::to_value(record) {
762            Ok(data) => data,
763            Err(error) => {
764                tracing::warn!(target: "navree::job", %error, "cannot serialize an operation");
765                return;
766            }
767        };
768        if let Err(error) = broadcaster
769            .broadcast(
770                vec![channel_name(record.id)],
771                OPERATION_UPDATED_EVENT.to_owned(),
772                data,
773            )
774            .await
775        {
776            tracing::warn!(target: "navree::job", operation_id = %record.id, %error, "cannot broadcast an operation update");
777        }
778        // The pages that follow the operation through the live hub fetch it again. Only an app
779        // with the hub (`RealtimeModule`) has anyone to tell.
780        if app.try_get::<navree_realtime::Live>().await.is_some() {
781            let name = operation_topic(record.id);
782            let mut channels = Vec::new();
783            if let Some(owner) = record.owner_id {
784                channels.push(Topic::user(owner, name.clone()).channel());
785            }
786            if let Some(workspace) = record.workspace_id {
787                channels.push(Topic::workspace(workspace, name).channel());
788            }
789            if !channels.is_empty()
790                && let Err(error) = broadcaster
791                    .broadcast(
792                        channels,
793                        NUDGE_EVENT.to_owned(),
794                        Value::Object(serde_json::Map::new()),
795                    )
796                    .await
797            {
798                tracing::warn!(target: "navree::job", operation_id = %record.id, %error, "cannot tell the live hub an operation changed");
799            }
800        }
801    }
802}
803
804/// The error of an operation the watchdog found stalled.
805pub const STALLED_MESSAGE: &str = "The operation stopped responding.";
806
807/// The error of an operation whose job failed.
808pub const FAILED_MESSAGE: &str = "The operation failed.";
809
810impl fmt::Debug for Operations {
811    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
812        f.debug_struct("Operations")
813            .field("options", &self.options)
814            .finish_non_exhaustive()
815    }
816}