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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use super::Client;
use crate::Error;
use crate::JobOptions;
use crate::job::{Job, JobDetails};
use serde_json::json;
use sqlx::types::Json;
use std::borrow::Borrow;
use uuid::Uuid;
impl Client {
/// Enqueue a job.
///
/// Will return [`Error::Conflict`] in case a job with this ID already exist,
/// which happen if you are providing the ID yourself.
///
/// If the queue does not exist, [`Error::DoesNotExist`] will be returned.
///
/// In case the system throttles the job (see [`Job::singleton_key`]), [`Error::Throttled`]
/// will be returned.
pub async fn send_job<'a, J>(&self, job: J) -> Result<Uuid, Error>
where
J: Borrow<Job<'a>>,
{
let job = job.borrow();
sqlx::query_scalar(&self.stmt.create_job)
.bind(job.id)
.bind(job.queue_name)
.bind(Json(&job.data))
.bind(Json(&job.opts()))
.fetch_one(&self.pool)
.await
.map_err(|e| {
if let sqlx::Error::RowNotFound = e {
return Error::DoesNotExist {
msg: "queue does not exist",
};
}
if let Some(db_error) = e.as_database_error() {
if let Some(constraint) = db_error.constraint() {
if constraint.starts_with('j') {
if constraint.ends_with("_pkey") {
return Error::Conflict {
msg: "job with this id already exists",
};
}
if constraint.ends_with("_i1") {
return Error::Throttled {
msg: "policy 'short' is applied to jobs with state 'created'",
};
}
if constraint.ends_with("_i2") {
return Error::Throttled {
msg: "policy 'singleton' is applied to jobs with state 'active'",
};
}
if constraint.ends_with("_i3") {
return Error::Throttled {
msg: "policy 'stately' is applied to jobs with state 'created', 'retry' or 'active'",
};
}
if constraint.ends_with("_i4") {
return Error::Throttled {
msg: "singleton policy applied to jobs with 'singleton_on' property and state not 'cancelled'",
};
}
if constraint.ends_with("_i6") {
return Error::Throttled {
msg: "explusive policy applied",
};
}
}
if constraint == "dlq_fkey" {
return Error::DoesNotExist {
msg: "dead letter queue does not exist",
};
}
if constraint == "q_fkey" {
return Error::DoesNotExist {
msg: "queue does not exist",
};
}
}
}
Error::Sqlx(e)
})
}
/// Create and enqueue a job.
pub async fn send_data<Q, D>(&self, queue_name: Q, data: D) -> Result<Uuid, Error>
where
Q: AsRef<str>,
D: Borrow<serde_json::Value>,
{
sqlx::query_scalar(&self.stmt.create_job)
.bind(Option::<Uuid>::None)
.bind(queue_name.as_ref())
.bind(Json(data.borrow()))
.bind(Json(JobOptions::default()))
.fetch_optional(&self.pool)
.await?
.ok_or(Error::DoesNotExist {
msg: "queue does not exist",
})
}
/// Fetch a job from a queue.
pub async fn fetch_job<Q>(&self, queue_name: Q) -> Result<Option<JobDetails>, Error>
where
Q: AsRef<str>,
{
let maybe_job: Option<JobDetails> = sqlx::query_as(&self.stmt.fetch_jobs)
.bind(queue_name.as_ref())
.bind(1f64)
.fetch_optional(&self.pool)
.await?;
Ok(maybe_job)
}
/// Get this job's details including metadata.
///
/// Unlike [`Client::fetch_job`] _will not consume_ a job from the queue,
/// rather will only get this job's details. Useful for monitoring, analyzing
/// the execution progress, e.g. how many times this job has been retried or what
/// `output` has been written to this jobs.
pub async fn get_job<Q>(&self, queue_name: Q, job_id: Uuid) -> Result<Option<JobDetails>, Error>
where
Q: AsRef<str>,
{
let maybe_job: Option<JobDetails> = sqlx::query_as(&self.stmt.get_job_info)
.bind(queue_name.as_ref())
.bind(job_id)
.fetch_optional(&self.pool)
.await?;
Ok(maybe_job)
}
/// Fetch a batch of jobs.
pub async fn fetch_jobs<Q>(
&self,
queue_name: Q,
batch_size: u64,
) -> Result<Vec<JobDetails>, Error>
where
Q: AsRef<str>,
{
let maybe_job: Vec<JobDetails> = sqlx::query_as(&self.stmt.fetch_jobs)
.bind(queue_name.as_ref())
.bind(batch_size as f64)
.fetch_all(&self.pool)
.await?;
Ok(maybe_job)
}
/// Delete a job from a queue.
///
/// In a happy path, returns `false`, if the specified queue or the job with this ID does not exist,
/// otherwise returns `true`.
///
/// To delete numerous jobs from a queue, use [Client::delete_jobs].
pub async fn delete_job<Q>(&self, queue_name: Q, job_id: Uuid) -> Result<bool, Error>
where
Q: AsRef<str>,
{
let count = self.delete_jobs(queue_name, [job_id]).await?;
Ok(count == 1)
}
/// Delete numerous jobs from a queue.
///
/// In a happy path, returns the number of deleted records, where `0` means
/// either the specified queue does not exist, or there are no jobs with
/// these ids in the queue.
pub async fn delete_jobs<Q, J>(&self, queue_name: Q, job_ids: J) -> Result<usize, Error>
where
Q: AsRef<str>,
J: IntoIterator<Item = Uuid>,
{
let count: (i64,) = sqlx::query_as(&self.stmt.delete_jobs)
.bind(queue_name.as_ref())
.bind(job_ids.into_iter().collect::<Vec<Uuid>>())
.fetch_one(&self.pool)
.await?;
Ok(count.0 as usize)
}
/// Mark a job as `failed`.
pub async fn fail_job<Q>(&self, queue_name: Q, job_id: Uuid) -> Result<bool, Error>
where
Q: AsRef<str>,
{
let count = self
.update_jobs_returning_affected_count(
queue_name,
[job_id],
Some(json!({})),
&self.stmt.fail_jobs_by_jids,
)
.await?;
Ok(count == 1)
}
/// Mark a job as `failed` leaving details in the jobs' `output`.
pub async fn fail_job_with_details<Q, O>(
&self,
queue_name: Q,
job_id: Uuid,
details: O,
) -> Result<bool, Error>
where
Q: AsRef<str>,
O: Into<serde_json::Value>,
{
let count = self
.fail_jobs_with_details(queue_name, [job_id], details)
.await?;
Ok(count == 1)
}
/// Mark numerous jobs as `failed` leaving details in the jobs' `output`.
///
/// In a happy path, returns the number of jobs marked as `failed`,
/// where `0` means there are no jobs with these ids in the queue or
/// no such queue.
pub async fn fail_jobs_with_details<Q, I, O>(
&self,
queue_name: Q,
job_ids: I,
details: O,
) -> Result<usize, Error>
where
Q: AsRef<str>,
I: IntoIterator<Item = Uuid>,
O: Into<serde_json::Value>,
{
self.update_jobs_returning_affected_count(
queue_name,
job_ids,
Some(details.into()),
&self.stmt.fail_jobs_by_jids,
)
.await
}
/// Mark numerous jobs as `failed`.
pub async fn fail_jobs<Q, I>(&self, queue_name: Q, job_ids: I) -> Result<usize, Error>
where
Q: AsRef<str>,
I: IntoIterator<Item = Uuid>,
{
self.update_jobs_returning_affected_count(
queue_name,
job_ids,
Some(json!({})),
&self.stmt.fail_jobs_by_jids,
)
.await
}
/// Mark a job as completed.
///
/// Will call [`Client::complete_jobs`] internally.
pub async fn complete_job<Q, O>(
&self,
queue_name: Q,
job_id: Uuid,
details: O,
) -> Result<bool, Error>
where
Q: AsRef<str>,
O: Into<serde_json::Value>,
{
let count = self.complete_jobs(queue_name, [job_id], details).await?;
Ok(count == 1)
}
/// Mark numerous jobs as `completed`.
///
/// In a happy path, returns the number of jobs marked as `completed`,
/// where `0` means there are no jobs with these ids in the queue or
/// no such queue.
pub async fn complete_jobs<Q, I, O>(
&self,
queue_name: Q,
job_ids: I,
details: O,
) -> Result<usize, Error>
where
Q: AsRef<str>,
I: IntoIterator<Item = Uuid>,
O: Into<serde_json::Value>,
{
self.update_jobs_returning_affected_count(
queue_name,
job_ids,
Some(details.into()),
&self.stmt.complete_jobs,
)
.await
}
/// Mark a job as `cancelled`.
///
/// Will call [`Client::cancel_jobs`] internally.
pub async fn cancel_job<Q>(&self, queue_name: Q, job_id: Uuid) -> Result<bool, Error>
where
Q: AsRef<str>,
{
let count = self.cancel_jobs(queue_name, [job_id]).await?;
Ok(count == 1)
}
/// Mark numerous jobs as `cancelled`.
///
/// In a happy path, returns the number of jobs marked as `cancelled`,
/// where `0` means there are no jobs with these ids in the queue or
/// no such queue.
pub async fn cancel_jobs<Q, I>(&self, queue_name: Q, job_ids: I) -> Result<usize, Error>
where
Q: AsRef<str>,
I: IntoIterator<Item = Uuid>,
{
self.update_jobs_returning_affected_count(queue_name, job_ids, None, &self.stmt.cancel_jobs)
.await
}
/// Mark a cancelled job (See [`Client::cancel_job`]) as `created` again.
///
/// Will call [`Client::resume_jobs`] internally.
pub async fn resume_job<Q>(&self, queue_name: Q, job_id: Uuid) -> Result<bool, Error>
where
Q: AsRef<str>,
{
let count = self.resume_jobs(queue_name, [job_id]).await?;
Ok(count == 1)
}
/// Mark numerous cancelled jobs as `created` again.
///
/// In a happy path, returns the number of jobs marked as `created`,
/// where `0` means there are no jobs with these ids in the queue or
/// no such queue.
pub async fn resume_jobs<Q, I>(&self, queue_name: Q, job_ids: I) -> Result<usize, Error>
where
Q: AsRef<str>,
I: IntoIterator<Item = Uuid>,
{
self.update_jobs_returning_affected_count(queue_name, job_ids, None, &self.stmt.resume_jobs)
.await
}
async fn update_jobs_returning_affected_count<Q, I>(
&self,
queue_name: Q,
job_ids: I,
details: Option<serde_json::Value>,
q: &str,
) -> Result<usize, Error>
where
Q: AsRef<str>,
I: IntoIterator<Item = Uuid>,
{
let q = sqlx::query_as(q)
.bind(queue_name.as_ref())
.bind(job_ids.into_iter().collect::<Vec<Uuid>>());
let q = match details {
Some(d) => q.bind(d),
None => q,
};
let count: (i64,) = q.fetch_one(&self.pool).await?;
Ok(count.0 as usize)
}
}