navree_queue/record.rs
1//! The records a [`QueueStore`](crate::QueueStore) stores and returns:
2//! [`NewJob`], [`ReservedJob`] and [`FailedJob`].
3
4use chrono::{DateTime, Utc};
5use navree_contracts::JobOptions;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9/// A job that used up its attempts (or could not run at all), as kept in
10/// `failed_jobs` until it is retried or flushed.
11///
12/// It is also the navree-orm model of the database driver's `failed_jobs`
13/// table ([`FAILED_JOBS_TABLE`](crate::FAILED_JOBS_TABLE)), which the
14/// driver writes and reads through the ORM: the payload and options are
15/// stored as JSON text, the failure time as Unix milliseconds, and code
16/// queries them with typed columns (`FailedJob::query().where_(FailedJob::QUEUE.eq("mail"))`).
17/// Other drivers keep failed jobs their own way.
18#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, navree_orm::Model)]
19#[model(table = "failed_jobs")]
20pub struct FailedJob {
21 /// The job id (the id `dispatch` returned).
22 pub id: String,
23 /// The queue it was on.
24 pub queue: String,
25 /// The job type ([`Job::NAME`](navree_contracts::Job::NAME)).
26 pub job_type: String,
27 /// The job value as JSON.
28 #[model(cast = navree_orm::cast::JsonText)]
29 pub payload: Value,
30 /// The options it was dispatched with.
31 #[model(cast = navree_orm::cast::JsonText)]
32 pub options: JobOptions,
33 /// The error of the last attempt.
34 pub error: String,
35 /// How many attempts ran.
36 pub attempts: u32,
37 /// When it failed.
38 #[model(cast = "unix_timestamp_ms")]
39 pub failed_at: DateTime<Utc>,
40}
41
42/// A failed job without its payload, as an overview lists it.
43#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
44pub struct FailedJobBrief {
45 /// The job id.
46 pub id: String,
47 /// The queue it was on.
48 pub queue: String,
49 /// The job type.
50 pub job_type: String,
51 /// The error of the last attempt.
52 pub error: String,
53 /// How many attempts ran.
54 pub attempts: u32,
55 /// How many it could have.
56 pub max_attempts: u32,
57 /// When it failed.
58 pub failed_at: DateTime<Utc>,
59}
60
61impl From<&FailedJob> for FailedJobBrief {
62 fn from(job: &FailedJob) -> FailedJobBrief {
63 FailedJobBrief {
64 id: job.id.clone(),
65 queue: job.queue.clone(),
66 job_type: job.job_type.clone(),
67 error: job.error.clone(),
68 attempts: job.attempts,
69 max_attempts: job.options.max_attempts,
70 failed_at: job.failed_at,
71 }
72 }
73}
74
75/// The failed jobs in figures, and the newest of them: what a page polled every
76/// few seconds reads, however many have failed ([`Queue::failed_summary`](crate::Queue::failed_summary)).
77#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
78pub struct FailedSummary {
79 /// Every failed job.
80 pub total: u64,
81 /// The ones that failed at or after the time asked for.
82 pub since: u64,
83 /// The newest, newest first.
84 pub newest: Vec<FailedJobBrief>,
85}
86
87impl FailedSummary {
88 /// The summary of `failed` (newest first).
89 pub(crate) fn of(failed: &[FailedJob], since: DateTime<Utc>, limit: usize) -> FailedSummary {
90 FailedSummary {
91 total: failed.len() as u64,
92 since: failed.iter().filter(|job| job.failed_at >= since).count() as u64,
93 newest: failed.iter().take(limit).map(Into::into).collect(),
94 }
95 }
96}
97
98/// Where a job that is not finished yet stands ([`PendingJob::state`]).
99#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
100#[serde(rename_all = "snake_case")]
101pub enum PendingState {
102 /// Available now and waiting for a worker.
103 Waiting,
104 /// Available later: dispatched with a delay, or released for a retry
105 /// after its backoff.
106 Delayed,
107 /// Reserved by a worker (a crashed worker's reservation counts until
108 /// another worker takes the job over).
109 Running,
110}
111
112/// A job that is not finished yet, as [`Queue::pending_jobs`](crate::Queue::pending_jobs)
113/// lists it.
114#[derive(Clone, Debug, PartialEq, Serialize)]
115pub struct PendingJob {
116 /// The job id.
117 pub id: String,
118 /// The queue it is on.
119 pub queue: String,
120 /// The job type ([`Job::NAME`](navree_contracts::Job::NAME)).
121 pub job_type: String,
122 /// The job value as JSON.
123 pub payload: Value,
124 /// The options it was dispatched with.
125 pub options: JobOptions,
126 /// Attempts started so far (a running job's current one included).
127 pub attempts: u32,
128 /// Waiting, delayed or running.
129 pub state: PendingState,
130 /// When it is (or was) available to workers.
131 pub available_at: DateTime<Utc>,
132 /// When a worker reserved it, while it runs.
133 pub reserved_at: Option<DateTime<Utc>>,
134 /// When it was queued (or last retried from the failed jobs).
135 pub created_at: DateTime<Utc>,
136}
137
138/// Which pending jobs [`Queue::pending_jobs`](crate::Queue::pending_jobs)
139/// lists.
140#[derive(Clone, Debug, Default, PartialEq, Eq)]
141pub struct PendingQuery {
142 /// Only jobs of this queue.
143 pub queue: Option<String>,
144 /// Only jobs whose type or queue contains this text (case-insensitive).
145 pub search: Option<String>,
146 /// At most this many (default [`PendingQuery::DEFAULT_LIMIT`]).
147 pub limit: Option<u64>,
148}
149
150impl PendingQuery {
151 /// How many jobs a query without a limit returns.
152 pub const DEFAULT_LIMIT: u64 = 500;
153
154 /// The limit to apply.
155 pub(crate) fn limit(&self) -> u64 {
156 self.limit.unwrap_or(Self::DEFAULT_LIMIT)
157 }
158
159 /// The lowercased search text, if any.
160 pub(crate) fn needle(&self) -> Option<String> {
161 self.search
162 .as_deref()
163 .map(str::trim)
164 .filter(|s| !s.is_empty())
165 .map(str::to_lowercase)
166 }
167
168 /// Whether a job of `queue` and `job_type` matches.
169 pub(crate) fn matches(&self, queue: &str, job_type: &str) -> bool {
170 if self.queue.as_deref().is_some_and(|q| q != queue) {
171 return false;
172 }
173 match self.needle() {
174 Some(needle) => {
175 queue.to_lowercase().contains(&needle) || job_type.to_lowercase().contains(&needle)
176 }
177 None => true,
178 }
179 }
180}
181
182/// One queue's unfinished jobs at a moment, from [`Queue::status`](crate::Queue::status).
183#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
184pub struct QueueStatus {
185 /// The queue.
186 pub queue: String,
187 /// Jobs available now, waiting for a worker.
188 pub waiting: u64,
189 /// Jobs available later (delayed, or released for a retry).
190 pub delayed: u64,
191 /// Jobs reserved by a worker.
192 pub running: u64,
193 /// When the oldest waiting job became available (`None`: none waits).
194 pub oldest_available_at: Option<DateTime<Utc>>,
195 /// When the status was taken (the queue's clock).
196 pub at: DateTime<Utc>,
197}
198
199impl QueueStatus {
200 /// Every job that is not finished yet: waiting, delayed and running.
201 pub fn pending(&self) -> u64 {
202 self.waiting + self.delayed + self.running
203 }
204
205 /// How long the oldest waiting job has waited (zero when none waits).
206 pub fn oldest_wait(&self) -> std::time::Duration {
207 self.oldest_available_at
208 .and_then(|since| (self.at - since).to_std().ok())
209 .unwrap_or_default()
210 }
211}
212
213/// Which failed jobs [`Queue::retry`](crate::Queue::retry) puts back on
214/// their queues. Converts from a string: `"all"` is [`All`](RetryTarget::All),
215/// anything else a job id.
216#[derive(Clone, Debug, PartialEq, Eq)]
217pub enum RetryTarget {
218 /// Every failed job.
219 All,
220 /// The failed job with this id.
221 Id(String),
222}
223
224impl From<&str> for RetryTarget {
225 fn from(value: &str) -> Self {
226 if value == "all" {
227 RetryTarget::All
228 } else {
229 RetryTarget::Id(value.to_owned())
230 }
231 }
232}
233
234impl From<String> for RetryTarget {
235 fn from(value: String) -> Self {
236 RetryTarget::from(value.as_str())
237 }
238}
239
240impl FailedJob {
241 /// Reserved `job` as it fails at `now` (Unix milliseconds) with
242 /// `error`, after its attempts so far.
243 pub(crate) fn of(job: &ReservedJob, error: &str, now: i64) -> FailedJob {
244 FailedJob {
245 id: job.id.clone(),
246 queue: job.queue.clone(),
247 job_type: job.job_type.clone(),
248 payload: job.payload.clone(),
249 options: job.options.clone(),
250 error: error.to_owned(),
251 attempts: job.attempts,
252 failed_at: from_millis(now),
253 }
254 }
255
256 /// The job as it goes back on its queue at `now` (Unix milliseconds):
257 /// same id, attempts start over, not unique.
258 pub fn requeued(&self, now: i64) -> NewJob {
259 NewJob {
260 id: self.id.clone(),
261 queue: self.queue.clone(),
262 job_type: self.job_type.clone(),
263 payload: self.payload.clone(),
264 options: self.options.clone(),
265 available_at: now,
266 created_at: now,
267 unique_key: None,
268 unique_for_ms: None,
269 trace_parent: None,
270 membership: Membership::default(),
271 }
272 }
273}
274
275/// What a job belongs to: a batch (as one of its jobs or as one of its
276/// callbacks) and an operation. The default belongs to neither.
277#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
278#[serde(default)]
279pub struct Membership {
280 /// The batch the job belongs to.
281 pub batch_id: Option<String>,
282 /// Whether the job is a `then`, `catch` or `finally` callback of its
283 /// batch rather than one of its jobs.
284 pub callback: bool,
285 /// The operation the job does the work of.
286 pub operation_id: Option<String>,
287}
288
289impl Membership {
290 /// One of the jobs of batch `batch_id`.
291 pub(crate) fn batch_job(batch_id: &str, operation_id: Option<&str>) -> Self {
292 Self {
293 batch_id: Some(batch_id.to_owned()),
294 callback: false,
295 operation_id: operation_id.map(str::to_owned),
296 }
297 }
298
299 /// A callback of batch `batch_id`.
300 pub(crate) fn batch_callback(batch_id: &str, operation_id: Option<&str>) -> Self {
301 Self {
302 batch_id: Some(batch_id.to_owned()),
303 callback: true,
304 operation_id: operation_id.map(str::to_owned),
305 }
306 }
307
308 /// One of a batch's jobs (not a callback).
309 pub(crate) fn in_batch(&self) -> Option<&str> {
310 match (&self.batch_id, self.callback) {
311 (Some(batch), false) => Some(batch),
312 _ => None,
313 }
314 }
315}
316
317/// A job ready to be stored: what [`QueueStore::insert`](crate::QueueStore::insert)
318/// receives. Times are Unix milliseconds.
319#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
320pub struct NewJob {
321 /// The job id (a UUID v7, so ids sort in dispatch order).
322 pub id: String,
323 /// The queue.
324 pub queue: String,
325 /// The job type ([`Job::NAME`](navree_contracts::Job::NAME)).
326 pub job_type: String,
327 /// The job value as JSON.
328 pub payload: Value,
329 /// The options it was dispatched with.
330 pub options: JobOptions,
331 /// When a worker may take it first.
332 pub available_at: i64,
333 /// When it was dispatched.
334 pub created_at: i64,
335 /// Set for unique jobs: a pending job with the same key (dispatched
336 /// within [`unique_for_ms`](NewJob::unique_for_ms)) takes its place.
337 pub unique_key: Option<String>,
338 /// How long a pending unique job blocks its duplicates (`None`: while
339 /// it is pending).
340 pub unique_for_ms: Option<i64>,
341 /// The W3C `traceparent` of the span that dispatched the job, so its
342 /// attempts continue that trace.
343 pub trace_parent: Option<String>,
344 /// The batch and operation the job belongs to (none for a plain
345 /// dispatch). A driver stores it with the job and hands it back on
346 /// the [`ReservedJob`].
347 #[serde(default)]
348 pub membership: Membership,
349}
350
351impl NewJob {
352 /// Whether a pending duplicate created at `created_at` (Unix
353 /// milliseconds) still blocks this job.
354 pub fn blocked_by(&self, created_at: i64) -> bool {
355 self.unique_for_ms
356 .is_none_or(|window| self.created_at < created_at.saturating_add(window))
357 }
358
359 /// How long after a worker reserved it the job counts as abandoned, in
360 /// milliseconds: its `timeout_secs` (one day when 0) plus
361 /// [`STALE_RESERVATION_GRACE_SECS`](crate::STALE_RESERVATION_GRACE_SECS).
362 /// A store hands an abandoned reservation to the next worker.
363 pub fn stale_after_ms(&self) -> i64 {
364 stale_after_ms(&self.options)
365 }
366}
367
368/// A job a worker reserved: what [`QueueStore::reserve`](crate::QueueStore::reserve)
369/// returns.
370#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
371pub struct ReservedJob {
372 /// The job id.
373 pub id: String,
374 /// The queue.
375 pub queue: String,
376 /// The job type.
377 pub job_type: String,
378 /// The job value as JSON.
379 pub payload: Value,
380 /// The options it was dispatched with.
381 pub options: JobOptions,
382 /// How many attempts started, including the one that is starting.
383 pub attempts: u32,
384 /// The `traceparent` recorded at dispatch (see [`NewJob::trace_parent`]).
385 pub trace_parent: Option<String>,
386 /// The batch and operation the job belongs to (see
387 /// [`NewJob::membership`]).
388 #[serde(default)]
389 pub membership: Membership,
390}
391
392/// How long a reservation of a job without a time limit (`timeout_secs`
393/// 0) lasts before it counts as abandoned: one day.
394pub(crate) const UNLIMITED_RESERVATION_SECS: u64 = 86_400;
395
396/// How long after it was taken a reservation counts as abandoned, in
397/// milliseconds: the job's timeout plus
398/// [`STALE_RESERVATION_GRACE_SECS`](crate::STALE_RESERVATION_GRACE_SECS).
399pub(crate) fn stale_after_ms(options: &JobOptions) -> i64 {
400 let timeout = match options.timeout_secs {
401 0 => UNLIMITED_RESERVATION_SECS,
402 secs => secs,
403 };
404 let secs = timeout.saturating_add(crate::STALE_RESERVATION_GRACE_SECS);
405 i64::try_from(secs.saturating_mul(1000)).unwrap_or(i64::MAX)
406}
407
408/// Unix milliseconds → `DateTime<Utc>` (the epoch for out-of-range values).
409pub(crate) fn from_millis(ms: i64) -> DateTime<Utc> {
410 DateTime::from_timestamp_millis(ms).unwrap_or_default()
411}