1mod 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
32pub const OPERATION_UPDATED_EVENT: &str = "operation.updated";
35
36pub fn operation_topic(id: Uuid) -> String {
41 format!("operation.{id}")
42}
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
46#[serde(rename_all = "snake_case")]
47#[non_exhaustive]
48pub enum OperationStatus {
49 Pending,
51 Running,
53 Succeeded,
55 Failed,
57 Cancelled,
59}
60
61impl OperationStatus {
62 pub fn is_finished(self) -> bool {
65 matches!(
66 self,
67 OperationStatus::Succeeded | OperationStatus::Failed | OperationStatus::Cancelled
68 )
69 }
70
71 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#[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 pub fn new(kind: impl Into<String>) -> Self {
116 Self {
117 kind: kind.into(),
118 ..Self::default()
119 }
120 }
121
122 pub fn owner(mut self, user_id: Uuid) -> Self {
124 self.owner_id = Some(user_id);
125 self
126 }
127
128 pub fn workspace(mut self, workspace_id: Uuid) -> Self {
131 self.workspace_id = Some(workspace_id);
132 self
133 }
134
135 pub fn total(mut self, total: u64) -> Self {
137 self.total = total;
138 self
139 }
140
141 pub fn note(mut self, note: impl Into<String>) -> Self {
143 self.note = note.into();
144 self
145 }
146
147 pub fn idempotent(mut self) -> Self {
152 self.idempotent = true;
153 self
154 }
155}
156
157#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
159pub struct OperationProgress {
160 pub done: u64,
162 pub total: u64,
164 pub percent: u8,
166 pub note: String,
168}
169
170#[derive(Clone, Debug, PartialEq, Serialize, ToSchema)]
174pub struct OperationRecord {
175 pub id: Uuid,
177 pub kind: String,
179 pub status: OperationStatus,
181 pub progress: OperationProgress,
183 pub result: Option<Value>,
185 pub error: Option<String>,
187 pub owner_id: Option<Uuid>,
189 pub workspace_id: Option<Uuid>,
191 pub batch_id: Option<String>,
193 pub created_at: DateTime<Utc>,
195 pub started_at: Option<DateTime<Utc>>,
197 pub heartbeat_at: Option<DateTime<Utc>>,
199 pub finished_at: Option<DateTime<Utc>>,
201 pub updated_at: DateTime<Utc>,
203 #[serde(skip)]
205 pub(crate) version: i64,
206 #[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 pub fn is_finished(&self) -> bool {
218 self.status.is_finished()
219 }
220
221 pub fn channel(&self) -> String {
224 channel_name(self.id)
225 }
226}
227
228pub(crate) fn channel_name(id: Uuid) -> String {
230 format!("private-operations.{id}")
231}
232
233#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
235pub struct SweepReport {
236 pub failed: u64,
238 pub redispatched: u64,
240 pub finished: u64,
242}
243
244pub struct Operations {
281 db: Option<Db>,
282 queue: Queue,
283 options: OperationsOptions,
284 changes: broadcast::Sender<Uuid>,
285 app: Option<WeakAppContext>,
286}
287
288const 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 pub fn options(&self) -> &OperationsOptions {
311 &self.options
312 }
313
314 fn db(&self) -> Result<&Db, QueueError> {
317 self.db.as_ref().ok_or(QueueError::NoDatabase)
318 }
319
320 fn writer(&self) -> Result<&dyn Executor, QueueError> {
323 let db = self.db()?;
324 Ok(db.pool())
325 }
326
327 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 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 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 pub async fn find(&self, id: Uuid) -> Result<Option<OperationRecord>, QueueError> {
392 sql::find(self.writer()?, id).await
393 }
394
395 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 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, ¬e.into(), now);
416 self.update(id, stmt).await
417 }
418
419 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 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 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 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 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 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 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 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 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 pub(crate) fn subscribe(&self) -> broadcast::Receiver<Uuid> {
599 self.changes.subscribe()
600 }
601
602 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 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 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 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 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 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 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 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 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 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
745struct Announcer {
747 changes: broadcast::Sender<Uuid>,
748 app: Option<WeakAppContext>,
749}
750
751impl Announcer {
752 async fn announce(&self, record: &OperationRecord) {
753 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 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
804pub const STALLED_MESSAGE: &str = "The operation stopped responding.";
806
807pub 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}