mod controller;
mod hooks;
mod sql;
use std::fmt;
use std::time::Duration;
use chrono::{DateTime, Utc};
use navree_contracts::{BoxError, Broadcaster, Job, JobEnvelope, Principal, permitted};
use navree_db::{Db, Executor, Statement, Uow};
use navree_kernel::{AppContext, WeakAppContext};
use navree_openapi::ToSchema;
use navree_realtime::{NUDGE_EVENT, Topic};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::broadcast;
use uuid::Uuid;
pub(crate) use controller::authorize_channel;
#[cfg(feature = "ui")]
pub(crate) use controller::visible;
pub use controller::{OPERATION_EVENT, OperationsController};
pub(crate) use hooks::{QueueMonitor, RunningJobs, batch_settled, job_finished, skips};
use crate::batch::{Batch, JobBatch};
use crate::{OperationsOptions, Queue, QueueError};
pub const OPERATION_UPDATED_EVENT: &str = "operation.updated";
pub fn operation_topic(id: Uuid) -> String {
format!("operation.{id}")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum OperationStatus {
Pending,
Running,
Succeeded,
Failed,
Cancelled,
}
impl OperationStatus {
pub fn is_finished(self) -> bool {
matches!(
self,
OperationStatus::Succeeded | OperationStatus::Failed | OperationStatus::Cancelled
)
}
pub fn as_str(self) -> &'static str {
match self {
OperationStatus::Pending => "pending",
OperationStatus::Running => "running",
OperationStatus::Succeeded => "succeeded",
OperationStatus::Failed => "failed",
OperationStatus::Cancelled => "cancelled",
}
}
pub(crate) fn parse(name: &str) -> Option<Self> {
Some(match name {
"pending" => OperationStatus::Pending,
"running" => OperationStatus::Running,
"succeeded" => OperationStatus::Succeeded,
"failed" => OperationStatus::Failed,
"cancelled" => OperationStatus::Cancelled,
_ => return None,
})
}
}
impl fmt::Display for OperationStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Operation {
pub(crate) kind: String,
pub(crate) owner_id: Option<Uuid>,
pub(crate) workspace_id: Option<Uuid>,
pub(crate) total: u64,
pub(crate) note: String,
pub(crate) idempotent: bool,
}
impl Operation {
pub fn new(kind: impl Into<String>) -> Self {
Self {
kind: kind.into(),
..Self::default()
}
}
pub fn owner(mut self, user_id: Uuid) -> Self {
self.owner_id = Some(user_id);
self
}
pub fn workspace(mut self, workspace_id: Uuid) -> Self {
self.workspace_id = Some(workspace_id);
self
}
pub fn total(mut self, total: u64) -> Self {
self.total = total;
self
}
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = note.into();
self
}
pub fn idempotent(mut self) -> Self {
self.idempotent = true;
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct OperationProgress {
pub done: u64,
pub total: u64,
pub percent: u8,
pub note: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, ToSchema)]
pub struct OperationRecord {
pub id: Uuid,
pub kind: String,
pub status: OperationStatus,
pub progress: OperationProgress,
pub result: Option<Value>,
pub error: Option<String>,
pub owner_id: Option<Uuid>,
pub workspace_id: Option<Uuid>,
pub batch_id: Option<String>,
pub created_at: DateTime<Utc>,
pub started_at: Option<DateTime<Utc>>,
pub heartbeat_at: Option<DateTime<Utc>>,
pub finished_at: Option<DateTime<Utc>>,
pub updated_at: DateTime<Utc>,
#[serde(skip)]
pub(crate) version: i64,
#[serde(skip)]
pub(crate) job: Option<Value>,
#[serde(skip)]
pub(crate) idempotent: bool,
#[serde(skip)]
pub(crate) redispatches: u32,
}
impl OperationRecord {
pub fn is_finished(&self) -> bool {
self.status.is_finished()
}
pub fn channel(&self) -> String {
channel_name(self.id)
}
}
pub(crate) fn channel_name(id: Uuid) -> String {
format!("private-operations.{id}")
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub struct SweepReport {
pub failed: u64,
pub redispatched: u64,
pub finished: u64,
}
pub struct Operations {
db: Option<Db>,
queue: Queue,
options: OperationsOptions,
changes: broadcast::Sender<Uuid>,
app: Option<WeakAppContext>,
}
const CHANGE_BUFFER: usize = 1024;
impl Operations {
pub(crate) fn new(
db: Option<Db>,
queue: Queue,
options: OperationsOptions,
app: Option<WeakAppContext>,
) -> Self {
let (changes, _) = broadcast::channel(CHANGE_BUFFER);
Self {
db,
queue,
options,
changes,
app,
}
}
pub fn options(&self) -> &OperationsOptions {
&self.options
}
fn db(&self) -> Result<&Db, QueueError> {
self.db.as_ref().ok_or(QueueError::NoDatabase)
}
fn writer(&self) -> Result<&dyn Executor, QueueError> {
let db = self.db()?;
Ok(db.pool())
}
pub async fn start(
&self,
uow: &Uow,
operation: Operation,
) -> Result<OperationRecord, QueueError> {
let now = self.queue.now_ms();
let record = sql::new_record(Uuid::now_v7(), &operation, now);
uow.execute(&sql::insert(&record)?).await?;
Ok(record)
}
pub async fn dispatch<J: Job>(
&self,
uow: &Uow,
operation: &OperationRecord,
job: J,
) -> Result<String, QueueError> {
let envelope = JobEnvelope {
job_type: J::NAME.to_owned(),
payload: serde_json::to_value(&job).map_err(QueueError::Payload)?,
options: J::options(),
delay_secs: None,
unique_key: None,
};
if operation.idempotent {
uow.execute(&sql::set_job(operation.id, &envelope)?).await?;
}
self.queue
.push_for_operation_in(uow, envelope, operation.id)
.await
}
pub async fn dispatch_batch(
&self,
uow: &Uow,
operation: &OperationRecord,
batch: Batch,
) -> Result<JobBatch, QueueError> {
let total = batch.len() as u64;
let batch = self
.queue
.dispatch_batch_in(uow, batch.operation(operation.id))
.await?;
uow.execute(&sql::set_batch(
operation.id,
&batch.id,
total,
self.queue.now_ms(),
))
.await?;
Ok(batch)
}
pub async fn find(&self, id: Uuid) -> Result<Option<OperationRecord>, QueueError> {
sql::find(self.writer()?, id).await
}
pub async fn for_owner(
&self,
owner: Uuid,
limit: usize,
) -> Result<Vec<OperationRecord>, QueueError> {
sql::for_owner(self.writer()?, owner, limit).await
}
pub async fn progress(
&self,
id: Uuid,
done: u64,
total: u64,
note: impl Into<String>,
) -> Result<Option<OperationRecord>, QueueError> {
let now = self.queue.now_ms();
let stmt = sql::progress(id, done, total, ¬e.into(), now);
self.update(id, stmt).await
}
pub async fn heartbeat(&self, id: Uuid) -> Result<(), QueueError> {
let stmt = sql::heartbeat(id, self.queue.now_ms());
self.execute(stmt).await.map(|_| ())
}
pub async fn complete(
&self,
id: Uuid,
result: impl Serialize,
) -> Result<Option<OperationRecord>, QueueError> {
let result = serde_json::to_value(result).map_err(QueueError::Payload)?;
let now = self.queue.now_ms();
let stmt = sql::finish(id, OperationStatus::Succeeded, Some(&result), None, now)?;
self.update(id, stmt).await
}
pub async fn fail(
&self,
id: Uuid,
error: impl Into<String>,
) -> Result<Option<OperationRecord>, QueueError> {
let now = self.queue.now_ms();
let error = error.into();
let stmt = sql::finish(id, OperationStatus::Failed, None, Some(&error), now)?;
self.update(id, stmt).await
}
pub async fn cancel(&self, id: Uuid) -> Result<Option<OperationRecord>, QueueError> {
let now = self.queue.now_ms();
let stmt = sql::finish(id, OperationStatus::Cancelled, None, None, now)?;
let record = self.update(id, stmt).await?;
if let Some(record) = &record
&& record.status == OperationStatus::Cancelled
&& let Some(batch_id) = &record.batch_id
{
self.queue.cancel_batch(batch_id).await?;
}
Ok(record)
}
pub async fn sweep(&self) -> Result<SweepReport, QueueError> {
let now = self.queue.now_ms();
let stale_ms =
i64::try_from(self.options.stale_after_secs.saturating_mul(1000)).unwrap_or(i64::MAX);
let before = now.saturating_sub(stale_ms);
let stale = sql::stale(self.writer()?, before).await?;
let mut report = SweepReport::default();
for record in stale {
let id = record.id.to_string();
if self.queue.inner.store.count_for_operation(&id).await? > 0 {
continue;
}
if let Some(batch_id) = &record.batch_id
&& let Some(row) = self.queue.inner.store.find_batch(batch_id).await?
&& row.settled()
{
let finish = self.batch_finish(record.id, &row, now)?;
if self.apply(record.id, finish).await?.0 {
report.finished += 1;
}
continue;
}
if record.idempotent
&& let Some(job) = record
.job
.clone()
.and_then(|job| serde_json::from_value::<JobEnvelope>(job).ok())
&& record.redispatches < self.options.max_redispatches
{
let claim = sql::redispatched(record.id, before, now);
if !self.apply(record.id, claim).await?.0 {
continue;
}
self.queue.push_for_operation(job, record.id).await?;
tracing::warn!(
target: "navree::job",
operation_id = %record.id,
kind = %record.kind,
redispatches = record.redispatches + 1,
"operation stopped responding; its job was dispatched again"
);
report.redispatched += 1;
continue;
}
let stalled = sql::stalled(record.id, STALLED_MESSAGE, before, now);
if !self.apply(record.id, stalled).await?.0 {
continue;
}
tracing::warn!(
target: "navree::job",
operation_id = %record.id,
kind = %record.kind,
"operation stopped responding; marked failed"
);
report.failed += 1;
}
Ok(report)
}
pub async fn prune(&self, older_than: Duration) -> Result<u64, QueueError> {
let before = self
.queue
.now_ms()
.saturating_sub(i64::try_from(older_than.as_millis()).unwrap_or(i64::MAX));
let stmt = sql::prune(before);
Ok(self.writer()?.execute(&stmt).await?.rows_affected)
}
pub async fn can_view(
&self,
principal: &Principal,
operation: &OperationRecord,
) -> Result<bool, BoxError> {
self.allowed(principal, operation, &self.options.view_permission)
.await
}
pub async fn can_cancel(
&self,
principal: &Principal,
operation: &OperationRecord,
) -> Result<bool, BoxError> {
self.allowed(principal, operation, &self.options.cancel_permission)
.await
}
async fn allowed(
&self,
principal: &Principal,
operation: &OperationRecord,
permission: &str,
) -> Result<bool, BoxError> {
if operation.owner_id == Some(principal.user_id) {
return Ok(true);
}
let Some(app) = self.app() else {
return Ok(false);
};
permitted(&app, principal, permission, operation.workspace_id).await
}
pub(crate) fn subscribe(&self) -> broadcast::Receiver<Uuid> {
self.changes.subscribe()
}
pub(crate) async fn finish_from_batch(
&self,
id: Uuid,
row: &crate::batch::BatchRow,
) -> Result<Option<OperationRecord>, QueueError> {
let stmt = self.batch_finish(id, row, self.queue.now_ms())?;
self.update(id, stmt).await
}
fn batch_finish(
&self,
id: Uuid,
row: &crate::batch::BatchRow,
now: i64,
) -> Result<Statement, QueueError> {
if row.cancelled_at.is_some() && row.failed_jobs == 0 {
sql::finish(id, OperationStatus::Cancelled, None, None, now)
} else if row.failed_jobs > 0 && !row.allow_failures {
let error = format!("{} of {} jobs failed.", row.failed_jobs, row.total_jobs);
sql::finish(id, OperationStatus::Failed, None, Some(&error), now)
} else if row.callbacks_failed > 0 {
let error = "A follow-up job of the batch failed.";
sql::finish(id, OperationStatus::Failed, None, Some(error), now)
} else {
sql::finish(id, OperationStatus::Succeeded, None, None, now)
}
}
pub(crate) async fn batch_progress(
&self,
id: Uuid,
row: &crate::batch::BatchRow,
) -> Result<Option<OperationRecord>, QueueError> {
let now = self.queue.now_ms();
let done = row.total_jobs.saturating_sub(row.pending_jobs);
let stmt = sql::counts(id, done, row.total_jobs, now);
self.update(id, stmt).await
}
pub(crate) async fn note(
&self,
id: Uuid,
note: &str,
) -> Result<Option<OperationRecord>, QueueError> {
let stmt = sql::note(id, note, self.queue.now_ms());
self.update(id, stmt).await
}
pub(crate) async fn job_succeeded(
&self,
id: Uuid,
) -> Result<Option<OperationRecord>, QueueError> {
let now = self.queue.now_ms();
let stmt = sql::finish(id, OperationStatus::Succeeded, None, None, now)?;
self.update(id, stmt).await
}
pub(crate) async fn mark_running(
&self,
id: Uuid,
) -> Result<Option<OperationRecord>, QueueError> {
let stmt = sql::running(id, self.queue.now_ms());
self.update(id, stmt).await
}
pub(crate) async fn status(&self, id: Uuid) -> Result<Option<OperationStatus>, QueueError> {
sql::status(self.writer()?, id).await
}
fn app(&self) -> Option<AppContext> {
self.app.as_ref().and_then(WeakAppContext::upgrade)
}
async fn execute(&self, stmt: Statement) -> Result<u64, QueueError> {
if let Some(uow) = Uow::current()
&& !uow.is_finished().await
{
return Ok(uow.execute(&stmt).await?.rows_affected);
}
Ok(self.writer()?.execute(&stmt).await?.rows_affected)
}
async fn update(
&self,
id: Uuid,
stmt: Statement,
) -> Result<Option<OperationRecord>, QueueError> {
Ok(self.apply(id, stmt).await?.1)
}
async fn apply(
&self,
id: Uuid,
stmt: Statement,
) -> Result<(bool, Option<OperationRecord>), QueueError> {
if let Some(uow) = Uow::current()
&& !uow.is_finished().await
{
let changed = uow.execute(&stmt).await?.rows_affected > 0;
let record = sql::find(&uow, id).await?;
if changed && let Some(record) = record.clone() {
let announcer = self.announcer();
uow.after_commit(move || {
Box::pin(async move { announcer.announce(&record).await })
});
}
return Ok((changed, record));
}
let changed = self.writer()?.execute(&stmt).await?.rows_affected > 0;
let record = self.find(id).await?;
if changed && let Some(record) = &record {
self.announcer().announce(record).await;
}
Ok((changed, record))
}
fn announcer(&self) -> Announcer {
Announcer {
changes: self.changes.clone(),
app: self.app.clone(),
}
}
}
struct Announcer {
changes: broadcast::Sender<Uuid>,
app: Option<WeakAppContext>,
}
impl Announcer {
async fn announce(&self, record: &OperationRecord) {
let _ = self.changes.send(record.id);
let Some(app) = self.app.as_ref().and_then(WeakAppContext::upgrade) else {
return;
};
let Some(broadcaster) = app.try_get::<dyn Broadcaster>().await else {
return;
};
let data = match serde_json::to_value(record) {
Ok(data) => data,
Err(error) => {
tracing::warn!(target: "navree::job", %error, "cannot serialize an operation");
return;
}
};
if let Err(error) = broadcaster
.broadcast(
vec![channel_name(record.id)],
OPERATION_UPDATED_EVENT.to_owned(),
data,
)
.await
{
tracing::warn!(target: "navree::job", operation_id = %record.id, %error, "cannot broadcast an operation update");
}
if app.try_get::<navree_realtime::Live>().await.is_some() {
let name = operation_topic(record.id);
let mut channels = Vec::new();
if let Some(owner) = record.owner_id {
channels.push(Topic::user(owner, name.clone()).channel());
}
if let Some(workspace) = record.workspace_id {
channels.push(Topic::workspace(workspace, name).channel());
}
if !channels.is_empty()
&& let Err(error) = broadcaster
.broadcast(
channels,
NUDGE_EVENT.to_owned(),
Value::Object(serde_json::Map::new()),
)
.await
{
tracing::warn!(target: "navree::job", operation_id = %record.id, %error, "cannot tell the live hub an operation changed");
}
}
}
}
pub const STALLED_MESSAGE: &str = "The operation stopped responding.";
pub const FAILED_MESSAGE: &str = "The operation failed.";
impl fmt::Debug for Operations {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Operations")
.field("options", &self.options)
.finish_non_exhaustive()
}
}