aboutsummaryrefslogtreecommitdiffstats
path: root/src/timer.rs
blob: 7db3b2ec713cdbf663d9447cf452b79daf41c111 (plain) (blame)
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
use consts::TIMER_RESOLUTION;
use futures::{Future, Stream, Sink, Poll, unsync};
use std::time::Duration;
use tokio_core::reactor::Handle;
use tokio_timer;
use interface::SharedPeer;

#[derive(Debug)]
pub enum TimerMessage {
    PersistentKeepAlive(SharedPeer, u32),
    PassiveKeepAlive(SharedPeer, u32),
    Rekey(SharedPeer, u32),
    Wipe(SharedPeer),
}

pub struct Timer {
    handle: Handle,
    timer: tokio_timer::Timer,
    tx: unsync::mpsc::Sender<TimerMessage>,
    rx: unsync::mpsc::Receiver<TimerMessage>,
}

impl Timer {
    pub fn new(handle: Handle) -> Self {
        let (tx, rx) = unsync::mpsc::channel::<TimerMessage>(1024);
        let timer = tokio_timer::wheel()
            .tick_duration(*TIMER_RESOLUTION)
            .num_slots(1 << 14)
            .build();
        Self { handle, timer, tx, rx }
    }

    pub fn spawn_delayed(&mut self, delay: Duration, message: TimerMessage) {
        trace!("queuing timer message {:?}", &message);
        let timer = self.timer.sleep(delay + (*TIMER_RESOLUTION * 2));
        let future = timer.and_then({
            let tx = self.tx.clone();
            move |_| {
                tx.clone().send(message).then(|_| Ok(()))
            }
        }).then(|_| Ok(()));
        self.handle.spawn(future);
    }

    pub fn spawn_immediately(&mut self, message: TimerMessage) {
       self.handle.spawn(self.tx.clone().send(message).then(|_| Ok(())));
    }
}

impl Stream for Timer {
    type Item = TimerMessage;
    type Error = ();

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        self.rx.poll()
    }
}