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
use crate::context::JobContext;
use crate::Consumer;
use actix::prelude::*;
use chrono::prelude::*;
use futures::future::BoxFuture;
use log::{debug, warn};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use tokio::sync::{oneshot, oneshot::Sender as OneshotSender};
pub trait Job:
Serialize + DeserializeOwned + MessageEncodable + MessageDecodable + Send + Unpin
{
type Result: 'static + Debug;
fn name() -> &'static str {
std::any::type_name::<Self>()
}
fn retries() -> i64 {
0
}
}
pub trait JobHandler<C>
where
C: Consumer + Actor,
Self: Job,
{
type Result: JobResponse<C, Self>;
fn handle(self, ctx: &mut JobContext<C>) -> <Self as JobHandler<C>>::Result;
}
pub trait MessageDecodable
where
Self: Sized,
{
fn decode_message(value: &Vec<u8>) -> Result<Self, &'static str>;
}
pub trait MessageEncodable
where
Self: Sized,
{
fn encode_message(&self) -> Result<Vec<u8>, &'static str>;
}
impl<T> MessageDecodable for T
where
T: DeserializeOwned,
{
fn decode_message(value: &Vec<u8>) -> Result<T, &'static str> {
rmp_serde::decode::from_slice(value).or(Err("failed to decode value with msgpack"))
}
}
impl<T: Serialize> MessageEncodable for T {
fn encode_message(&self) -> Result<Vec<u8>, &'static str> {
rmp_serde::encode::to_vec(self).or(Err("failed to encode value"))
}
}
#[derive(Debug)]
pub enum Error {
Failed,
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum JobState {
Unacked,
Acked,
Rejected,
}
#[derive(Message, Debug, Serialize, Deserialize)]
#[rtype(result = "Result<JobState, Error>")]
pub struct PushJob {
pub id: uuid::Uuid,
pub job: Vec<u8>,
state: JobState,
pub retries: i64,
}
impl Drop for PushJob {
fn drop(&mut self) {
if self.state() == &JobState::Unacked {
warn!(
"Something went wrong: Dropping unacknowledged job [{:?}]",
&self.id
);
}
}
}
#[derive(Message, Debug, Serialize, Deserialize)]
#[rtype(result = "Result<JobState, Error>")]
pub struct ScheduledJob {
pub(crate) inner: PushJob,
pub(crate) time: DateTime<Utc>,
}
impl<J: Job> From<J> for PushJob {
fn from(job: J) -> Self {
PushJob::new(uuid::Uuid::new_v4(), job)
}
}
impl PushJob {
pub fn new<J: Job>(id: uuid::Uuid, job: J) -> Self {
let job = J::encode_message(&job).unwrap();
PushJob {
id,
job,
state: JobState::Unacked,
retries: 0,
}
}
pub async fn handle<C, J>(&mut self, ctx: &mut JobContext<C>)
where
C: Consumer + Actor,
J: JobHandler<C>,
{
let (tx, rx) = oneshot::channel();
let job = J::decode_message(&self.job).unwrap();
job.handle(ctx).process(Some(tx));
match rx.await {
Ok(value) => {
self.state = JobState::Acked;
debug!("Job [{}] completed with value: {:?}", self.id, value);
}
Err(err) => {
self.state = JobState::Rejected;
warn!("Job [{}] failed with error: {:?}", self.id, err);
}
}
}
pub fn state(&self) -> &JobState {
&self.state
}
pub fn ack(&mut self) {
self.state = JobState::Acked;
}
pub fn reject(&mut self) {
self.state = JobState::Rejected;
}
}
pub trait JobResponse<C: Consumer + Actor, J: Job + JobHandler<C>> {
fn process(self, tx: Option<OneshotSender<<J as Job>::Result>>);
}
trait JobOneshot<M> {
fn send(self, msg: M);
}
pub type JobFuture<I> = BoxFuture<'static, I>;
impl<C: Consumer + Actor, J: Job<Result = R> + JobHandler<C>, R: Debug + 'static> JobResponse<C, J>
for JobFuture<R>
{
fn process(self, tx: Option<OneshotSender<R>>) {
actix_rt::spawn(async { tx.send(self.await) });
}
}
impl<C, J, R> JobResponse<C, J> for Option<R>
where
C: Consumer + Actor,
J: Job<Result = Option<R>> + JobHandler<C>,
R: Debug + 'static,
{
fn process(self, tx: Option<OneshotSender<Option<R>>>) {
tx.send(self)
}
}
impl<C, J, R, E> JobResponse<C, J> for Result<R, E>
where
C: Consumer + Actor,
J: Job<Result = Result<R, E>> + JobHandler<C>,
R: Debug + 'static,
E: Debug + 'static,
{
fn process(self, tx: Option<OneshotSender<Result<R, E>>>) {
println!("Response {:?}", self);
tx.send(self)
}
}
impl<M> JobOneshot<M> for Option<OneshotSender<M>> {
fn send(self, msg: M) {
if let Some(tx) = self {
let _ = tx.send(msg);
}
}
}
macro_rules! SIMPLE_JOB_RESULT {
($type:ty) => {
impl<C, J> JobResponse<C, J> for $type
where
C: Consumer + Actor,
J: Job<Result = $type> + JobHandler<C>,
{
fn process(self, tx: Option<OneshotSender<$type>>) {
tx.send(self)
}
}
};
}
SIMPLE_JOB_RESULT!(());
SIMPLE_JOB_RESULT!(u8);
SIMPLE_JOB_RESULT!(u16);
SIMPLE_JOB_RESULT!(u32);
SIMPLE_JOB_RESULT!(u64);
SIMPLE_JOB_RESULT!(usize);
SIMPLE_JOB_RESULT!(i8);
SIMPLE_JOB_RESULT!(i16);
SIMPLE_JOB_RESULT!(i32);
SIMPLE_JOB_RESULT!(i64);
SIMPLE_JOB_RESULT!(isize);
SIMPLE_JOB_RESULT!(f32);
SIMPLE_JOB_RESULT!(f64);
SIMPLE_JOB_RESULT!(String);
SIMPLE_JOB_RESULT!(bool);