1mod batches;
5mod database;
6mod memory;
7
8use std::sync::Arc;
9
10pub(crate) use database::DatabaseStore;
11pub(crate) use memory::MemoryStore;
12
13use chrono::{DateTime, Utc};
14use navree_contracts::{BoxFuture, JobEnvelope};
15use navree_db::Uow;
16
17use crate::batch::{BatchRow, Finish, Finished};
18use crate::record::{
19 FailedJob, FailedSummary, NewJob, PendingJob, PendingQuery, QueueStatus, ReservedJob,
20 RetryTarget, from_millis,
21};
22use crate::{QueueError, QueueFake};
23
24pub(crate) type PrepareCallback<'a> =
26 dyn Fn(JobEnvelope, &BatchRow) -> Result<NewJob, QueueError> + Send + Sync + 'a;
27
28pub trait QueueStore: Send + Sync + 'static {
62 fn insert(&self, job: NewJob) -> BoxFuture<'_, Result<String, QueueError>>;
65
66 fn reserve<'a>(
70 &'a self,
71 queue: &'a str,
72 worker: &'a str,
73 now: i64,
74 ) -> BoxFuture<'a, Result<Option<ReservedJob>, QueueError>>;
75
76 fn complete<'a>(&'a self, job: &'a ReservedJob) -> BoxFuture<'a, Result<(), QueueError>>;
78
79 fn release<'a>(
82 &'a self,
83 job: &'a ReservedJob,
84 worker: &'a str,
85 available_at: i64,
86 ) -> BoxFuture<'a, Result<bool, QueueError>>;
87
88 fn fail<'a>(
91 &'a self,
92 job: &'a ReservedJob,
93 worker: &'a str,
94 error: &'a str,
95 now: i64,
96 ) -> BoxFuture<'a, Result<bool, QueueError>>;
97
98 fn failed(&self) -> BoxFuture<'_, Result<Vec<FailedJob>, QueueError>>;
100
101 fn failed_summary(
105 &self,
106 since: DateTime<Utc>,
107 limit: usize,
108 ) -> BoxFuture<'_, Result<FailedSummary, QueueError>> {
109 Box::pin(async move { Ok(FailedSummary::of(&self.failed().await?, since, limit)) })
110 }
111
112 fn retry<'a>(
115 &'a self,
116 target: &'a RetryTarget,
117 now: i64,
118 ) -> BoxFuture<'a, Result<u64, QueueError>>;
119
120 fn flush_failed(&self) -> BoxFuture<'_, Result<u64, QueueError>>;
122
123 fn pending_count<'a>(&'a self, queue: &'a str) -> BoxFuture<'a, Result<u64, QueueError>>;
126}
127
128pub(crate) enum Store {
130 Database(DatabaseStore),
131 Memory(MemoryStore),
132 Fake(QueueFake),
134 Custom(&'static str, Arc<dyn QueueStore>),
137}
138
139impl std::fmt::Debug for Store {
140 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141 match self {
142 Store::Database(db) => f.debug_tuple("Database").field(db).finish(),
143 Store::Memory(memory) => f.debug_tuple("Memory").field(memory).finish(),
144 Store::Fake(fake) => f.debug_tuple("Fake").field(fake).finish(),
145 Store::Custom(name, _) => f.debug_tuple("Custom").field(name).finish(),
146 }
147 }
148}
149
150impl Store {
151 pub(crate) fn name(&self) -> &'static str {
153 match self {
154 Store::Database(_) => "Database",
155 Store::Memory(_) => "Memory",
156 Store::Fake(_) => "Fake",
157 Store::Custom(name, _) => name,
158 }
159 }
160
161 pub(crate) async fn insert(&self, job: NewJob) -> Result<String, QueueError> {
164 match self {
165 Store::Database(db) => db.insert(&job).await,
166 Store::Memory(memory) => Ok(memory.insert(job)),
167 Store::Fake(fake) => {
168 let id = job.id.clone();
169 fake.record(envelope_of(job));
170 Ok(id)
171 }
172 Store::Custom(_, store) => store.insert(job).await,
173 }
174 }
175
176 pub(crate) async fn reserve(
177 &self,
178 queue: &str,
179 worker: &str,
180 now: i64,
181 ) -> Result<Option<ReservedJob>, QueueError> {
182 match self {
183 Store::Database(db) => db.reserve(queue, worker, now).await,
184 Store::Memory(memory) => Ok(memory.reserve(queue, worker, now)),
185 Store::Fake(_) => Ok(None),
186 Store::Custom(_, store) => store.reserve(queue, worker, now).await,
187 }
188 }
189
190 pub(crate) async fn complete(&self, job: &ReservedJob) -> Result<(), QueueError> {
191 match self {
192 Store::Database(db) => db.complete(&job.id).await,
193 Store::Memory(memory) => {
194 memory.complete(&job.id);
195 Ok(())
196 }
197 Store::Fake(_) => Ok(()),
198 Store::Custom(_, store) => store.complete(job).await,
199 }
200 }
201
202 pub(crate) async fn release(
205 &self,
206 job: &ReservedJob,
207 worker: &str,
208 available_at: i64,
209 ) -> Result<bool, QueueError> {
210 match self {
211 Store::Database(db) => db.release(&job.id, worker, available_at).await,
212 Store::Memory(memory) => Ok(memory.release(&job.id, worker, available_at)),
213 Store::Fake(_) => Ok(false),
214 Store::Custom(_, store) => store.release(job, worker, available_at).await,
215 }
216 }
217
218 pub(crate) async fn fail(
221 &self,
222 job: &ReservedJob,
223 worker: &str,
224 error: &str,
225 now: i64,
226 ) -> Result<bool, QueueError> {
227 match self {
228 Store::Database(db) => db.fail(job, worker, error, now).await,
229 Store::Memory(memory) => Ok(memory.fail(job, worker, error, now)),
230 Store::Fake(_) => Ok(false),
231 Store::Custom(_, store) => store.fail(job, worker, error, now).await,
232 }
233 }
234
235 pub(crate) async fn failed_summary(
236 &self,
237 since: DateTime<Utc>,
238 limit: usize,
239 ) -> Result<FailedSummary, QueueError> {
240 match self {
241 Store::Database(db) => db.failed_summary(since, limit).await,
242 Store::Memory(memory) => Ok(FailedSummary::of(&memory.failed(), since, limit)),
243 Store::Fake(_) => Ok(FailedSummary::default()),
244 Store::Custom(_, store) => store.failed_summary(since, limit).await,
245 }
246 }
247
248 pub(crate) async fn failed(&self) -> Result<Vec<FailedJob>, QueueError> {
249 match self {
250 Store::Database(db) => db.failed().await,
251 Store::Memory(memory) => Ok(memory.failed()),
252 Store::Fake(_) => Ok(Vec::new()),
253 Store::Custom(_, store) => store.failed().await,
254 }
255 }
256
257 pub(crate) async fn retry(&self, target: &RetryTarget, now: i64) -> Result<u64, QueueError> {
259 let retried = match self {
260 Store::Database(db) => db.retry(target, now).await?,
261 Store::Memory(memory) => memory.retry(target, now),
262 Store::Fake(_) => 0,
263 Store::Custom(_, store) => store.retry(target, now).await?,
264 };
265 match target {
266 RetryTarget::Id(id) if retried == 0 => {
267 Err(QueueError::FailedJobNotFound { id: id.clone() })
268 }
269 _ => Ok(retried),
270 }
271 }
272
273 pub(crate) async fn flush_failed(&self) -> Result<u64, QueueError> {
275 match self {
276 Store::Database(db) => db.flush_failed().await,
277 Store::Memory(memory) => Ok(memory.flush_failed()),
278 Store::Fake(_) => Ok(0),
279 Store::Custom(_, store) => store.flush_failed().await,
280 }
281 }
282
283 pub(crate) async fn pending_count(&self, queue: &str) -> Result<u64, QueueError> {
284 match self {
285 Store::Database(db) => db.pending_count(queue).await,
286 Store::Memory(memory) => Ok(memory.pending_count(queue)),
287 Store::Fake(fake) => Ok(fake.count_on(queue)),
288 Store::Custom(_, store) => store.pending_count(queue).await,
289 }
290 }
291
292 pub(crate) async fn status(&self, queue: &str, now: i64) -> Result<QueueStatus, QueueError> {
295 match self {
296 Store::Database(db) => db.status(queue, now).await,
297 Store::Memory(memory) => Ok(memory.status(queue, now)),
298 Store::Fake(fake) => {
299 let waiting = fake.count_on(queue);
300 Ok(QueueStatus {
301 queue: queue.to_owned(),
302 waiting,
303 delayed: 0,
304 running: 0,
305 oldest_available_at: (waiting > 0).then(|| from_millis(now)),
306 at: from_millis(now),
307 })
308 }
309 Store::Custom(_, store) => Ok(QueueStatus {
312 queue: queue.to_owned(),
313 waiting: store.pending_count(queue).await?,
314 delayed: 0,
315 running: 0,
316 oldest_available_at: None,
317 at: from_millis(now),
318 }),
319 }
320 }
321
322 pub(crate) async fn pending_jobs(
323 &self,
324 query: &PendingQuery,
325 now: i64,
326 ) -> Result<Vec<PendingJob>, QueueError> {
327 match self {
328 Store::Database(db) => db.pending_jobs(query, now).await,
329 Store::Memory(memory) => Ok(memory.pending_jobs(query, now)),
330 Store::Fake(_) | Store::Custom(..) => Ok(Vec::new()),
331 }
332 }
333
334 pub(crate) async fn pending_job(
335 &self,
336 id: &str,
337 now: i64,
338 ) -> Result<Option<PendingJob>, QueueError> {
339 match self {
340 Store::Database(db) => db.pending_job(id, now).await,
341 Store::Memory(memory) => Ok(memory.pending_job(id, now)),
342 Store::Fake(_) | Store::Custom(..) => Ok(None),
343 }
344 }
345
346 pub(crate) async fn failed_job(&self, id: &str) -> Result<Option<FailedJob>, QueueError> {
347 match self {
348 Store::Database(db) => db.failed_job(id).await,
349 Store::Memory(memory) => Ok(memory.failed_job(id)),
350 Store::Fake(_) => Ok(None),
351 Store::Custom(_, store) => {
352 Ok(store.failed().await?.into_iter().find(|job| job.id == id))
353 }
354 }
355 }
356
357 pub(crate) async fn forget(&self, id: &str) -> Result<(), QueueError> {
360 let deleted = match self {
361 Store::Database(db) => db.forget(id).await?,
362 Store::Memory(memory) => memory.forget(id),
363 Store::Fake(_) => false,
364 Store::Custom(name, _) => {
365 return Err(QueueError::Store(
366 format!("the {name} queue driver cannot forget one failed job").into(),
367 ));
368 }
369 };
370 if deleted {
371 Ok(())
372 } else {
373 Err(QueueError::FailedJobNotFound { id: id.to_owned() })
374 }
375 }
376
377 pub(crate) async fn insert_batch(
379 &self,
380 row: BatchRow,
381 jobs: Vec<NewJob>,
382 ) -> Result<(), QueueError> {
383 match self {
384 Store::Database(db) => db.insert_batch(&row, &jobs).await,
385 Store::Memory(memory) => {
386 memory.insert_batch(row, jobs);
387 Ok(())
388 }
389 Store::Fake(fake) => {
390 let (callbacks, members): (Vec<_>, Vec<_>) =
393 jobs.into_iter().partition(|job| job.membership.callback);
394 fake.record_batch(row, members.into_iter().map(envelope_of).collect());
395 for callback in callbacks {
396 fake.record(envelope_of(callback));
397 }
398 Ok(())
399 }
400 Store::Custom(name, _) => Err(no_batches(name)),
401 }
402 }
403
404 pub(crate) async fn insert_batch_in(
407 &self,
408 uow: &Uow,
409 row: &BatchRow,
410 jobs: &[NewJob],
411 ) -> Result<(), QueueError> {
412 match self {
413 Store::Database(db) => db.insert_batch_in(uow, row, jobs).await,
414 Store::Memory(_) | Store::Fake(_) => Ok(()),
415 Store::Custom(name, _) => Err(no_batches(name)),
416 }
417 }
418
419 pub(crate) async fn finish_batch_job(
422 &self,
423 job: &ReservedJob,
424 worker: &str,
425 finish: Finish,
426 error: &str,
427 now: i64,
428 prepare: &PrepareCallback<'_>,
429 ) -> Result<Finished, QueueError> {
430 match self {
431 Store::Database(db) => {
432 db.finish_batch_job(job, worker, finish, error, now, prepare)
433 .await
434 }
435 Store::Memory(memory) => {
436 memory.finish_batch_job(job, worker, finish, error, now, prepare)
437 }
438 Store::Fake(_) => Ok(Finished::Lost),
439 Store::Custom(name, _) => Err(no_batches(name)),
440 }
441 }
442
443 pub(crate) async fn find_batch(&self, id: &str) -> Result<Option<BatchRow>, QueueError> {
444 match self {
445 Store::Database(db) => db.find_batch(id).await,
446 Store::Memory(memory) => Ok(memory.find_batch(id)),
447 Store::Fake(fake) => Ok(fake.find_batch(id)),
448 Store::Custom(..) => Ok(None),
449 }
450 }
451
452 pub(crate) async fn batches(&self, limit: usize) -> Result<Vec<BatchRow>, QueueError> {
453 match self {
454 Store::Database(db) => db.batches(limit).await,
455 Store::Memory(memory) => Ok(memory.batches(limit)),
456 Store::Fake(fake) => Ok(fake.batch_rows(limit)),
457 Store::Custom(..) => Ok(Vec::new()),
458 }
459 }
460
461 pub(crate) async fn cancel_batch(
462 &self,
463 id: &str,
464 now: i64,
465 ) -> Result<Option<BatchRow>, QueueError> {
466 match self {
467 Store::Database(db) => db.cancel_batch(id, now).await,
468 Store::Memory(memory) => Ok(memory.cancel_batch(id, now)),
469 Store::Fake(fake) => Ok(fake.cancel_batch(id, now)),
470 Store::Custom(..) => Ok(None),
471 }
472 }
473
474 pub(crate) async fn prune_batches(&self, before: i64) -> Result<u64, QueueError> {
475 match self {
476 Store::Database(db) => db.prune_batches(before).await,
477 Store::Memory(memory) => Ok(memory.prune_batches(before)),
478 Store::Fake(_) | Store::Custom(..) => Ok(0),
479 }
480 }
481
482 pub(crate) async fn count_for_operation(&self, operation_id: &str) -> Result<u64, QueueError> {
484 match self {
485 Store::Database(db) => db.count_for_operation(operation_id).await,
486 Store::Memory(memory) => Ok(memory.count_for_operation(operation_id)),
487 Store::Fake(_) => Ok(0),
488 Store::Custom(..) => Ok(1),
492 }
493 }
494}
495
496fn no_batches(driver: &str) -> QueueError {
498 QueueError::Store(format!("the {driver} queue driver does not support batches").into())
499}
500
501pub(crate) fn envelope_of(job: NewJob) -> JobEnvelope {
504 let delay_ms = job.available_at.saturating_sub(job.created_at).max(0);
505 let delay_secs = u64::try_from(delay_ms.div_euclid(1000) + i64::from(delay_ms % 1000 != 0))
506 .unwrap_or_default();
507 JobEnvelope {
508 job_type: job.job_type,
509 payload: job.payload,
510 options: job.options,
511 delay_secs: (delay_secs > 0).then_some(delay_secs),
512 unique_key: job.unique_key,
513 }
514}