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
use std::error::Error;
use std::fmt::Debug;
use std::future::Future;
use std::ops::Deref;
use futures::Stream;
use url::Url;
#[cfg(feature = "rabbitmq")]
mod amqp;
#[cfg(feature = "rabbitmq")]
pub use amqp::*;
#[cfg(feature = "local")]
mod local;
#[cfg(feature = "local")]
pub use local::*;
#[async_trait::async_trait]
pub trait JobQueue: Send + Sync {
type Err: Debug;
type Handle: JobHandle<Err = Self::Err>;
type Consumer: Consumer<Err = Self::Err>;
async fn put_job<D>(&self, job: D) -> Result<(), Self::Err>
where
D: AsRef<[u8]> + Send;
async fn get_job(&self) -> Result<JobResult<Self::Handle>, Self::Err>;
async fn consumer(&self) -> Self::Consumer;
async fn close(&self) -> Result<(), Self::Err> {
Ok(())
}
}
#[async_trait::async_trait]
pub trait MakeJobQueue: Send + Sync {
type Queue: JobQueue<Err = Self::Err>;
type Err: Error + Send + Sync;
async fn make_job_queue(&self, name: &str, url: Url) -> Result<Self::Queue, Self::Err>;
}
#[async_trait::async_trait]
pub trait JobHandle: Send + Sync + 'static {
type Err: Debug;
async fn ack_job(&self) -> Result<(), Self::Err>;
async fn nack_job(&self) -> Result<(), Self::Err>;
}
pub trait Consumer: Stream<Item = Result<JobResult<Self::Handle>, Self::Err>> {
type Err: Debug;
type Handle: JobHandle<Err = Self::Err>;
}
pub struct JobResult<H>
where
H: JobHandle + 'static,
{
handle: Option<H>,
job: Vec<u8>,
}
impl<H> JobResult<H>
where
H: JobHandle,
{
pub fn new(job: Vec<u8>, handle: H) -> Self {
Self {
handle: handle.into(),
job,
}
}
async fn run_with_handle<F>(&mut self, f: impl FnOnce(H) -> F) -> Result<(), H::Err>
where
F: Future<Output = Result<(), H::Err>>,
{
if let Some(handle) = self.handle.take() {
(f)(handle).await
} else {
Ok(())
}
}
pub fn job(&self) -> &Vec<u8> {
&self.job
}
pub fn split(self) -> (Option<H>, Vec<u8>) {
(self.handle, self.job)
}
pub async fn nack_job(&mut self) -> Result<(), H::Err> {
self.run_with_handle(|h| async move { h.nack_job().await })
.await
}
pub async fn ack_job(&mut self) -> Result<(), H::Err> {
self.run_with_handle(|h| async move { h.ack_job().await })
.await
}
}
impl<H> PartialEq for JobResult<H>
where
H: JobHandle,
{
fn eq(&self, other: &Self) -> bool {
self.job == other.job
}
}
impl<H> Deref for JobResult<H>
where
H: JobHandle + Send + Sync + 'static,
{
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
&self.job
}
}