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
//! This module contains useful tasks that you can attach to an `Actor`.

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};
use tokio::sync::watch;

/// Contorls the `HeartBeat` parameters.
pub struct HeartBeatHandle {
    duration: watch::Sender<Duration>,
}

impl HeartBeatHandle {
    /// Creates a new `HeartBeat` handle.
    pub fn new(duration: Duration) -> Self {
        let (tx, _rx) = watch::channel(duration);
        Self { duration: tx }
    }
    /// Change the `Duration` of the `HeartBeat`.
    pub fn update(&mut self, duration: Duration) -> Result<(), Error> {
        self.duration.send(duration)?;
        Ok(())
    }
}

/// The lite task that sends ticks to a `Recipient`.
#[derive(Debug)]
pub struct HeartBeat {
    duration: watch::Receiver<Duration>,
    recipient: Box<dyn ActionRecipient<Tick>>,
}

impl HeartBeat {
    /// Creates a new `HeartBeat` lite task.
    pub fn new<T>(duration: Duration, address: Address<T>) -> Self
    where
        T: Actor + ActionHandler<Tick>,
    {
        let handle = HeartBeatHandle::new(duration);
        Self::new_with_handle(&handle, address)
    }

    /// Creates a new `HeartBeat` lite task.
    /// With `HeartBeatHandle` to change `duration` on the fly.
    pub fn new_with_handle<T>(handle: &HeartBeatHandle, address: Address<T>) -> Self
    where
        T: Actor + ActionHandler<Tick>,
    {
        let rx = handle.duration.subscribe();
        Self {
            duration: rx,
            recipient: Box::new(address),
        }
    }
}

/// `Tick` value that sent by `HeartBeat` lite task.
#[derive(Debug)]
pub struct Tick(pub Instant);

impl Action for Tick {}

#[async_trait]
impl LiteTask for HeartBeat {
    type Output = ();

    fn log_target(&self) -> &str {
        "HeartBeat"
    }

    async fn repeatable_routine(&mut self) -> Result<Option<Self::Output>, Error> {
        // IMPORTANT: Don't use `schedule` to avoid late beats: when the task was canceled,
        // but teh scheduled messages still remained in the actor's queue.
        let tick = Tick(Instant::now());
        self.recipient.act(tick)?;
        // StopSender can be used to interrupt it
        Ok(None)
    }

    async fn routine_wait(&mut self, _last_attempt: Instant, _succeed: bool) {
        use tokio::time::{sleep_until, timeout_at};
        let now = Instant::now();
        loop {
            let duration = *self.duration.borrow();
            let instant = (now + duration).into();
            let res = timeout_at(instant, self.duration.changed()).await;
            match res {
                Ok(Ok(())) => {
                    // Changed. Double check the duration.
                    continue;
                }
                Ok(Err(_)) => {
                    // No sender that can change the duration. Just waiting.
                    sleep_until(instant).await;
                    break;
                }
                Err(_elapsed) => {
                    // Time elapsed. Repeat `routine` again
                    break;
                }
            }
        }
    }
}

/// Handler of heartbeat events and a task
#[async_trait]
pub trait OnTick: Actor {
    /// Called when tick received.
    ///
    /// Also `tick` will be called after lite task initialization.
    async fn tick(&mut self, tick: Tick, ctx: &mut Context<Self>) -> Result<(), Error>;
    /// Called when the heartbeat task finished or interrupted.
    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
    }
}

// TODO: Support custom tags.
#[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
    }
}