1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*!
This crate provides a persisted job queue backed by PostgreSQL with a simple to use interface.
Its written as an easy to use async job queue library without macros or generics shenanigans.
Usage boils down to 3 points:
1. Implement `Handler` trait
2. Initialize the queue with a `PgPool` and start it
3. Insert jobs
Default configurations for jobs and queues are.. defaults, so make sure to read through appropriate Job and SimpleQueue documentation.
## Features
- Simple handler interface
- Job scheduling and rescheduling
- Job retry support
- Job crash handling
- Job cancellation
- Job fingerprinting (soft identifier)
- Existing jobs deduplication (unique key with noop on job reinsert - only for live jobs)
- Configurable global and per-queue backoff strategy (linear and exponential provided, custom supported)
- 3 tiered job permits (global permit, per queue permit, handler owned limit)
- Stalled job recovery (heartbeat)
- Archive and DLQ (requires `janitor` feature)
- Poison job detection (`reaper`)
## Usage
### Handler Implementation
```no_run
// handlers.rs
use simple_queue::prelude::*;
struct MyHandler {
counter: std::sync::atomic::AtomicUsize,
};
impl Handler for MyHandler {
const QUEUE: &'static str = "my-queue";
async fn process(&self, queue: &SimpleQueue, job: &Job) -> Result<JobResult, BoxDynError> {
self.counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(JobResult::Success)
}
}
```
### Queue Initialization
```no_run
// main.rs
# use sqlx::PgPool;
# use std::sync::Arc;
# use serde_json::json;
use simple_queue::prelude::*;
# struct MyHandler { counter: std::sync::atomic::AtomicUsize }
# impl Handler for MyHandler {
# const QUEUE: &'static str = "my-queue";
#
# async fn process(&self, queue: &SimpleQueue, job: &Job) -> Result<JobResult, BoxDynError> {
# self.counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
# Ok(JobResult::Success)
# }
# }
#[tokio::main]
async fn main() {
# let PG_URL = "postgres://user:password@localhost:5432/dbname";
let pool: PgPool = PgPool::connect(PG_URL).await.unwrap();
let queue = Arc::new(SimpleQueue::new(pool));
let handler = MyHandler { counter: std::sync::atomic::AtomicUsize::new(0) };
// Deosn't have to happen before `simple_queue::start`
queue.register_handler(handler);
// Keep clone for insertion
simple_queue::start(queue.clone()).await;
let job = Job::new("my-queue", json!({}));
queue.insert_job(job).await;
}
```
## Thread Structure
```text
┌─────────────┐
│ Entry Point │
└──────┬──────┘
│ spawns
┌─────────────────────┼──────────────────────┐
▼ ▼ ▼
┌────────────────┐ ┌────────────────┐ ┌────────────────┐
│Queue Processor │ │ Janitor │ │ Reaper │
│ / Poller │ └────────────────┘ └────────────────┘
└───────┬────────┘
│
│ wait global permit
▼
┌─────────┐
│ run() │
└────┬────┘
│ job obtained
│
├──────────────────────┐
│ │ spawn first
│ ▼
│ ┌───────────────┐
│ │ Heartbeat │
│ │ Thread │
│ └───────┬───────┘
│ │ ownership
▼ │
wait queue permit │
│ │
▼ │
┌──────────────────────┐ │
│ Job Thread │◄───┘ heartbeat passed in
│ │ (drop job == drop heartbeat)
│ wait handler permit │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Process │ │
│ │ Job │ │
│ └─────────────┘ │
└──────────────────────┘
```
## Future Work
- Distributed Semaphores using PostgreSQL
- Temporary store on connection loss
- Job templates
- Queue interactor interface
- PG Listener (to decrease job-to-queue latency)
- Job Queue partitioning (dead tuples accumulation prevention)
## Decisions
- JSON for job data for inspectability of DLQ/Archive
- Poll mechanism / non-distributed semaphores as a good enough (for now)
*/
use Arc;
use PgPool;
use Semaphore;
pub
/// Any error that can be returned by a job handler.
pub type BoxDynError = ;
pub use *;
/// Sets up the queue schema in the database.
///
/// It's recommended to run this once during application startup.
///
/// Note: Separation from the main database is recommended but not required.
pub async
/// Sets up the queue schema in the database using a PostgreSQL URL.
pub async
/// Queue starting function.
///
/// It starts:
/// - A reaper task that reclaims stalled jobs
/// - A janitor task that periodically checks the queue, archives old jobs and moves errored jobs to a dead queue
///
/// It returns a [`tokio::task::JoinSet`] that can be used to wait for the tasks to complete,
/// and it does so only AFTER the queue has started polling.
pub async
pub async
/// Starts the queue without a janitor task.
///
/// For cases when you don't need a janitor task, i.e. completed and error queues should stay in the same table.
/// Useful for development and testing.
///
/// It returns a [`tokio::task::JoinSet`] that can be used to wait for the tasks to complete,
/// and it does so only AFTER the queue has started polling.
pub async