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
use crate::actor_runtime::{Actor, Context};
use crate::handlers::{Action, ActionHandler, TaskEliminated};
use crate::ids::IdOf;
use crate::linkage::{ActionRecipient, Address};
use crate::lite_runtime::LiteTask;
use crate::lite_runtime::TaskError;
use anyhow::Error;
use async_trait::async_trait;
use std::fmt::Debug;
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct HeartBeat {
duration: Duration,
recipient: Box<dyn ActionRecipient<Tick>>,
}
impl HeartBeat {
pub fn new<T>(duration: Duration, address: Address<T>) -> Self
where
T: Actor + ActionHandler<Tick>,
{
Self {
duration,
recipient: Box::new(address),
}
}
}
#[derive(Debug)]
pub struct Tick(pub Instant);
impl Action for Tick {}
#[async_trait]
impl LiteTask for HeartBeat {
type Output = ();
async fn repeatable_routine(&mut self) -> Result<Option<Self::Output>, Error> {
let tick = Tick(Instant::now());
self.recipient.act(tick).await?;
Ok(None)
}
fn retry_delay(&self, _last_attempt: Instant) -> Duration {
self.duration
}
}
#[async_trait]
pub trait OnTick: Actor {
async fn tick(&mut self, tick: Tick, ctx: &mut Context<Self>) -> Result<(), Error>;
async fn done(&mut self, ctx: &mut Context<Self>) -> Result<(), Error>;
}
#[async_trait]
impl<T> ActionHandler<Tick> for T
where
T: OnTick,
{
async fn handle(&mut self, tick: Tick, ctx: &mut Context<Self>) -> Result<(), Error> {
OnTick::tick(self, tick, ctx).await
}
}
#[async_trait]
impl<T> TaskEliminated<HeartBeat, ()> for T
where
T: OnTick,
{
async fn handle(
&mut self,
_id: IdOf<HeartBeat>,
_tag: (),
_result: Result<(), TaskError>,
ctx: &mut Context<Self>,
) -> Result<(), Error> {
OnTick::done(self, ctx).await
}
}