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
use actix::prelude::*;
use async_trait::async_trait;
use std::marker::PhantomData;
use crate::{messages::{Pop, Push}, queue::{TaskQueue}};
#[derive(Debug)]
pub enum WorkerExecuteError {
Retryable,
NonRetryable
}
#[async_trait]
pub trait QueueConsumer<T: Default + Sized + Unpin + 'static, W> {
async fn execute(&self, task: T) -> Result<W, WorkerExecuteError>;
fn get_queue(&self) -> Addr<TaskQueue<T>>;
fn retry(&self, task: T) -> T;
fn drop(&self, task: T);
fn result(&self, result: W);
}
pub struct TaskWorker<T: Default + Sized + Unpin + 'static, W: Send + Sized + Unpin + 'static> {
task: PhantomData<T>,
result: PhantomData<W>
}
impl<T: Default + Sized + Unpin + 'static, W: Send + Sized + Unpin + 'static> Actor for TaskWorker<T, W> {
type Context = Context<Self>;
}
impl<T: Copy + Default + Sized + Unpin + Send + 'static, W: Send + Sized + Unpin + 'static> TaskWorker<T, W> where Self: QueueConsumer<T, W> {
pub fn new() -> TaskWorker<T, W> {
TaskWorker {
task: PhantomData,
result: PhantomData
}
}
pub async fn next(&self) {
let queue = self.get_queue();
if let Ok(ret) = queue.send(Pop::new()).await {
match ret {
Ok(task) => {
let execute_result = self.execute(task).await;
match execute_result {
Ok(result) => {
self.result(result);
},
Err(err) => {
match err {
WorkerExecuteError::Retryable => queue.do_send(Push::new(self.retry(task))),
WorkerExecuteError::NonRetryable => self.drop(task)
}
}
}
}
Err(error) => println!("{:?}", error)
}
}
}
}