use chrono::{DateTime, Utc};
use navree_contracts::JobOptions;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, navree_orm::Model)]
#[model(table = "failed_jobs")]
pub struct FailedJob {
pub id: String,
pub queue: String,
pub job_type: String,
#[model(cast = navree_orm::cast::JsonText)]
pub payload: Value,
#[model(cast = navree_orm::cast::JsonText)]
pub options: JobOptions,
pub error: String,
pub attempts: u32,
#[model(cast = "unix_timestamp_ms")]
pub failed_at: DateTime<Utc>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct FailedJobBrief {
pub id: String,
pub queue: String,
pub job_type: String,
pub error: String,
pub attempts: u32,
pub max_attempts: u32,
pub failed_at: DateTime<Utc>,
}
impl From<&FailedJob> for FailedJobBrief {
fn from(job: &FailedJob) -> FailedJobBrief {
FailedJobBrief {
id: job.id.clone(),
queue: job.queue.clone(),
job_type: job.job_type.clone(),
error: job.error.clone(),
attempts: job.attempts,
max_attempts: job.options.max_attempts,
failed_at: job.failed_at,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct FailedSummary {
pub total: u64,
pub since: u64,
pub newest: Vec<FailedJobBrief>,
}
impl FailedSummary {
pub(crate) fn of(failed: &[FailedJob], since: DateTime<Utc>, limit: usize) -> FailedSummary {
FailedSummary {
total: failed.len() as u64,
since: failed.iter().filter(|job| job.failed_at >= since).count() as u64,
newest: failed.iter().take(limit).map(Into::into).collect(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PendingState {
Waiting,
Delayed,
Running,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PendingJob {
pub id: String,
pub queue: String,
pub job_type: String,
pub payload: Value,
pub options: JobOptions,
pub attempts: u32,
pub state: PendingState,
pub available_at: DateTime<Utc>,
pub reserved_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PendingQuery {
pub queue: Option<String>,
pub search: Option<String>,
pub limit: Option<u64>,
}
impl PendingQuery {
pub const DEFAULT_LIMIT: u64 = 500;
pub(crate) fn limit(&self) -> u64 {
self.limit.unwrap_or(Self::DEFAULT_LIMIT)
}
pub(crate) fn needle(&self) -> Option<String> {
self.search
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_lowercase)
}
pub(crate) fn matches(&self, queue: &str, job_type: &str) -> bool {
if self.queue.as_deref().is_some_and(|q| q != queue) {
return false;
}
match self.needle() {
Some(needle) => {
queue.to_lowercase().contains(&needle) || job_type.to_lowercase().contains(&needle)
}
None => true,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct QueueStatus {
pub queue: String,
pub waiting: u64,
pub delayed: u64,
pub running: u64,
pub oldest_available_at: Option<DateTime<Utc>>,
pub at: DateTime<Utc>,
}
impl QueueStatus {
pub fn pending(&self) -> u64 {
self.waiting + self.delayed + self.running
}
pub fn oldest_wait(&self) -> std::time::Duration {
self.oldest_available_at
.and_then(|since| (self.at - since).to_std().ok())
.unwrap_or_default()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RetryTarget {
All,
Id(String),
}
impl From<&str> for RetryTarget {
fn from(value: &str) -> Self {
if value == "all" {
RetryTarget::All
} else {
RetryTarget::Id(value.to_owned())
}
}
}
impl From<String> for RetryTarget {
fn from(value: String) -> Self {
RetryTarget::from(value.as_str())
}
}
impl FailedJob {
pub(crate) fn of(job: &ReservedJob, error: &str, now: i64) -> FailedJob {
FailedJob {
id: job.id.clone(),
queue: job.queue.clone(),
job_type: job.job_type.clone(),
payload: job.payload.clone(),
options: job.options.clone(),
error: error.to_owned(),
attempts: job.attempts,
failed_at: from_millis(now),
}
}
pub fn requeued(&self, now: i64) -> NewJob {
NewJob {
id: self.id.clone(),
queue: self.queue.clone(),
job_type: self.job_type.clone(),
payload: self.payload.clone(),
options: self.options.clone(),
available_at: now,
created_at: now,
unique_key: None,
unique_for_ms: None,
trace_parent: None,
membership: Membership::default(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Membership {
pub batch_id: Option<String>,
pub callback: bool,
pub operation_id: Option<String>,
}
impl Membership {
pub(crate) fn batch_job(batch_id: &str, operation_id: Option<&str>) -> Self {
Self {
batch_id: Some(batch_id.to_owned()),
callback: false,
operation_id: operation_id.map(str::to_owned),
}
}
pub(crate) fn batch_callback(batch_id: &str, operation_id: Option<&str>) -> Self {
Self {
batch_id: Some(batch_id.to_owned()),
callback: true,
operation_id: operation_id.map(str::to_owned),
}
}
pub(crate) fn in_batch(&self) -> Option<&str> {
match (&self.batch_id, self.callback) {
(Some(batch), false) => Some(batch),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NewJob {
pub id: String,
pub queue: String,
pub job_type: String,
pub payload: Value,
pub options: JobOptions,
pub available_at: i64,
pub created_at: i64,
pub unique_key: Option<String>,
pub unique_for_ms: Option<i64>,
pub trace_parent: Option<String>,
#[serde(default)]
pub membership: Membership,
}
impl NewJob {
pub fn blocked_by(&self, created_at: i64) -> bool {
self.unique_for_ms
.is_none_or(|window| self.created_at < created_at.saturating_add(window))
}
pub fn stale_after_ms(&self) -> i64 {
stale_after_ms(&self.options)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReservedJob {
pub id: String,
pub queue: String,
pub job_type: String,
pub payload: Value,
pub options: JobOptions,
pub attempts: u32,
pub trace_parent: Option<String>,
#[serde(default)]
pub membership: Membership,
}
pub(crate) const UNLIMITED_RESERVATION_SECS: u64 = 86_400;
pub(crate) fn stale_after_ms(options: &JobOptions) -> i64 {
let timeout = match options.timeout_secs {
0 => UNLIMITED_RESERVATION_SECS,
secs => secs,
};
let secs = timeout.saturating_add(crate::STALE_RESERVATION_GRACE_SECS);
i64::try_from(secs.saturating_mul(1000)).unwrap_or(i64::MAX)
}
pub(crate) fn from_millis(ms: i64) -> DateTime<Utc> {
DateTime::from_timestamp_millis(ms).unwrap_or_default()
}