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
use crate::actor_runtime::{Actor, Status};
use crate::compat::watch;
use crate::handlers::{Operation, TaskEliminated};
use crate::ids::{Id, IdOf};
use crate::lifecycle::{LifecycleNotifier, TaskDone};
use crate::linkage::Address;
use anyhow::Error;
use async_trait::async_trait;
use futures::{
future::{select, Either, FusedFuture},
Future, FutureExt,
};
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
use uuid::Uuid;
pub trait Tag: Send + 'static {}
impl Tag for () {}
#[async_trait]
pub trait LiteTask: Sized + Send + 'static {
type Output: Send;
fn name(&self) -> String {
let uuid = Uuid::new_v4();
format!("Task:{}({})", std::any::type_name::<Self>(), uuid)
}
async fn routine(self, mut stop: StopReceiver) -> Result<Self::Output, Error> {
stop.or(self.interruptable_routine())
.await
.map_err(Error::from)
.and_then(std::convert::identity)
}
async fn interruptable_routine(mut self) -> Result<Self::Output, Error> {
self.pre_repeatable_routine().await?;
loop {
let last_attempt = Instant::now();
let routine_result = self.repeatable_routine().await;
let instant = {
match routine_result {
Ok(Some(output)) => {
break Ok(output);
}
Ok(None) => {
self.retry_at(last_attempt, true)
}
Err(err) => {
log::error!("Routine {} failed: {}", self.name(), err);
self.retry_at(last_attempt, false)
}
}
};
crate::compat::delay_until(instant).await;
}
}
async fn pre_repeatable_routine(&mut self) -> Result<(), Error> {
Ok(())
}
async fn repeatable_routine(&mut self) -> Result<Option<Self::Output>, Error> {
Ok(None)
}
fn retry_at(&mut self, _last_attempt: Instant, succeed: bool) -> Instant {
Instant::now() + self.retry_delay(_last_attempt, succeed)
}
fn retry_delay(&mut self, _last_attempt: Instant, _succeed: bool) -> Duration {
Duration::from_secs(5)
}
}
pub(crate) fn spawn<T, S, M>(
task: T,
tag: M,
supervisor: Option<Address<S>>,
custom_name: Option<String>,
) -> TaskAddress<T>
where
T: LiteTask,
S: Actor + TaskEliminated<T, M>,
M: Tag,
{
let task_name = custom_name.unwrap_or_else(|| task.name());
let id = Id::new(task_name);
let (stop_sender, stop_receiver) = make_stop_channel(id.clone());
let id_of = IdOf::<T>::new(id.clone());
let done_notifier = {
match supervisor {
None => <dyn LifecycleNotifier<_>>::ignore(),
Some(super_addr) => {
let op = Operation::Done { id };
<dyn LifecycleNotifier<_>>::once(super_addr, op)
}
}
};
let runtime = LiteRuntime {
id: id_of,
task,
done_notifier,
stop_receiver,
tag,
};
crate::compat::spawn_async(runtime.entrypoint());
stop_sender
}
pub trait StopSignal: Future<Output = ()> + FusedFuture + Send {}
impl<T> StopSignal for T where T: Future<Output = ()> + FusedFuture + Send {}
#[derive(Debug, Error)]
#[error("task interrupted by a signal")]
pub struct TaskStopped;
fn make_stop_channel<T>(id: Id) -> (TaskAddress<T>, StopReceiver) {
let (tx, rx) = watch::channel(Status::Alive);
let sender = TaskAddress {
id: IdOf::new(id),
tx: Arc::new(tx),
};
let receiver = StopReceiver { status: rx };
(sender, receiver)
}
#[derive(Debug)]
pub struct TaskAddress<T> {
id: IdOf<T>,
tx: Arc<watch::Sender<Status>>,
}
impl<T> Clone for TaskAddress<T> {
fn clone(&self) -> Self {
Self {
id: self.id(),
tx: Arc::clone(&self.tx),
}
}
}
impl<T> TaskAddress<T> {
pub fn id(&self) -> IdOf<T> {
self.id.clone()
}
pub fn stop(&self) -> Result<(), Error> {
self.tx.send(Status::Stop).map_err(Error::from)
}
}
impl<T: LiteTask> PartialEq for TaskAddress<T> {
fn eq(&self, other: &Self) -> bool {
self.id.eq(&other.id)
}
}
impl<T: LiteTask> Eq for TaskAddress<T> {}
impl<T: LiteTask> Hash for TaskAddress<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
#[derive(Debug, Clone)]
pub struct StopReceiver {
status: watch::Receiver<Status>,
}
impl StopReceiver {
pub fn is_alive(&self) -> bool {
*self.status.borrow() == Status::Alive
}
pub fn into_future(self) -> Pin<Box<dyn StopSignal>> {
Box::pin(just_done(self.status).fuse())
}
pub async fn or<Fut>(&mut self, fut: Fut) -> Result<Fut::Output, TaskStopped>
where
Fut: Future,
{
let fut = Box::pin(fut);
let either = select(self.clone().into_future(), fut).await;
match either {
Either::Left((_done, _rem_fut)) => Err(TaskStopped),
Either::Right((output, _rem_fut)) => Ok(output),
}
}
}
async fn just_done(mut status: watch::Receiver<Status>) {
while status.changed().await.is_ok() {
if status.borrow().is_done() {
break;
}
}
}
#[derive(Debug, Error)]
pub enum TaskError {
#[error("task was interrupted")]
Interrupted,
#[error("task failed: {0}")]
Other(Error),
}
impl TaskError {
pub fn is_interrupted(&self) -> bool {
matches!(self, Self::Interrupted)
}
pub fn into_other(self) -> Option<Error> {
match self {
Self::Interrupted => None,
Self::Other(err) => Some(err),
}
}
#[deprecated(since = "0.86.2", note = "Use ordinary `match` for checking.")]
pub fn swap<T>(result: Result<T, Self>) -> Result<Option<T>, Error> {
match result {
Ok(value) => Ok(Some(value)),
Err(Self::Interrupted) => Ok(None),
Err(Self::Other(err)) => Err(err),
}
}
}
impl From<Error> for TaskError {
fn from(error: Error) -> Self {
match error.downcast::<TaskStopped>() {
Ok(_stopped) => Self::Interrupted,
Err(other) => Self::Other(other),
}
}
}
struct LiteRuntime<T: LiteTask, M: Tag> {
id: IdOf<T>,
task: T,
done_notifier: Box<dyn LifecycleNotifier<TaskDone<T, M>>>,
stop_receiver: StopReceiver,
tag: M,
}
impl<T: LiteTask, M: Tag> LiteRuntime<T, M> {
async fn entrypoint(mut self) {
log::info!("Task started: {:?}", self.id);
let res = self
.task
.routine(self.stop_receiver)
.await
.map_err(TaskError::from);
if let Err(err) = res.as_ref() {
if !err.is_interrupted() {
log::error!("Task failed: {:?}: {}", self.id, err);
}
}
log::info!("Task finished: {:?}", self.id);
let task_done = TaskDone::new(self.id.clone(), self.tag, res);
if let Err(err) = self.done_notifier.notify(task_done) {
log::error!(
"Can't send done notification from the task {:?}: {}",
self.id,
err
);
}
}
}