Skip to main content

tako_rs_core/queue/
builder.rs

1//! Builder for configuring a [`Queue`].
2
3use std::collections::VecDeque;
4use std::sync::Arc;
5use std::sync::atomic::AtomicBool;
6use std::sync::atomic::AtomicU64;
7
8use parking_lot::Mutex;
9use scc::HashMap as SccHashMap;
10use tokio::sync::Notify;
11
12use super::RetryPolicy;
13use super::runtime::Queue;
14use super::runtime::QueueInner;
15
16/// Builder for configuring a [`Queue`].
17pub struct QueueBuilder {
18  pub(crate) workers: usize,
19  pub(crate) retry: RetryPolicy,
20}
21
22impl QueueBuilder {
23  /// Set the number of worker tasks (default: 4).
24  pub fn workers(mut self, n: usize) -> Self {
25    self.workers = n.max(1);
26    self
27  }
28
29  /// Set the retry policy for failed jobs.
30  pub fn retry(mut self, policy: RetryPolicy) -> Self {
31    self.retry = policy;
32    self
33  }
34
35  /// Build the queue. Call [`Queue::start()`] to begin processing.
36  pub fn build(self) -> Queue {
37    Queue {
38      inner: Arc::new(QueueInner {
39        pending: Mutex::new(VecDeque::new()),
40        handlers: SccHashMap::new(),
41        dead_letters: Mutex::new(Vec::new()),
42        notify: Notify::new(),
43        next_id: AtomicU64::new(1),
44        num_workers: self.workers,
45        retry_policy: self.retry,
46        shutdown: AtomicBool::new(false),
47        inflight: AtomicU64::new(0),
48        drain_notify: Notify::new(),
49      }),
50    }
51  }
52}