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
#![deny(missing_docs)]

//! Docs are on the way. API is unstable, submit your ideas though Github issues.
//! Otherwise see README for API excerpt and example.
//!
//! Main struct is `Watchdog`.

extern crate tokio_timer;
extern crate futures;


use tokio_timer::Delay;
use futures::Future;
use futures::Async;

use std::sync::Arc;
use std::sync::Mutex;

use std::time::{Duration, Instant};

struct Impl {
    /// the main thing
    del : Option<Delay>,
    /// saved duration for petting and rearming
    dur : Duration,
    /// used to track pets when `del` is None (unarmed)
    ins : Instant,
}

type H = Arc<Mutex<Impl>>;
//type H = Rc<RefCell<Impl>>>;

/// The main struct. A wrapper over `tokio_timer::Delay` that has handles that can `reset` it periodically.
///
/// TODO: example
pub struct Watchdog(H);

impl Watchdog {
    /// constructor
    pub fn new(dur: Duration) -> Self {
        let ins = Instant::now() + dur;
        let del = Delay::new(ins);
        let i = Impl { del:Some(del), dur, ins };
        Watchdog(Arc::new(Mutex::new(i)))
    }
    /// Get the duration. Returns 0 on internal error.
    pub fn duration(&self) -> Duration {
        if let Ok(g) = self.0.lock() {
            g.dur
        } else {
            Duration::from_secs(0)
        }
    }
    /// Set new duration, also adjusting the timer state
    pub fn set_duration(&mut self, dur: Duration) {
        if let Ok(mut g) = self.0.lock() {
            g.ins = g.ins - g.dur + dur;
            g.dur = dur;
            let i = g.ins;
            if let Some(ref mut d) = g.del {
                d.reset(i);
            }
        }
    }
    /// Get the handle for keeping the watchdog from firing
    pub fn handle(&self) -> Pet {
        self.into()
    }
}

/// Reset/restart the watchdog, so it don't activate
#[derive(Clone)]
pub struct Pet(H);
impl Pet {
    /// Reset/restart the watchdog, so it don't activate
    ///
    /// Call it periodically from various places
    pub fn pet(&self) {
        if let Ok(mut g) = self.0.lock() {
            let i = Instant::now() + g.dur;
            g.ins = i;
            if let Some(ref mut x) = g.del {
                x.reset(i);
            }
        } else {
            // don't know what to do here
            // XXX
        }
    }
    
    /// Get how much time remains before the watchdog activates
    ///
    /// None means it is already active
    ///
    /// Some(0) is returned on internal error
    pub fn get_remaining_time(&self) -> Option<Duration> {
        if let Ok(g) = self.0.lock() {
            let now = Instant::now();
            let i = g.ins;
            if now > i {
                None
            } else {
                Some(i - now)
            }
        } else {
            Some(Duration::from_secs(0))
        }
    }
}

impl<'a> From<&'a Watchdog> for Pet {
    fn from(w : &'a Watchdog) -> Pet {
        Pet(w.0.clone())
    }
}

/// Result returned from a fired Watchdog.
///
/// Can be used to rewind (activate again) watchdog, preserving `Pet` handles pointing to it.
pub struct Rearm(H);
impl Rearm {
    /// Rearm with previously used timeout value
    pub fn rearm(self) -> Watchdog {
        Watchdog(self.0)
    }
    
    /// Rearm with new timeout value.
    pub fn rearm_with_duration(self, dur: Duration) -> Watchdog {
        let mut w = Watchdog(self.0);
        w.set_duration(dur);
        w
    }
}

impl Future for Watchdog {
    type Item = Rearm;
    /// at_capacity error may also be returned on internal Mutex problems
    type Error = tokio_timer::Error;
    
    fn poll(&mut self) -> futures::Poll<Rearm, tokio_timer::Error> {
        if let Ok(mut g) = self.0.lock() {
            if let Some(ref mut d) = g.del {
                match d.poll() {
                    Ok(Async::Ready(())) => Ok(Async::Ready(
                        Rearm(self.0.clone())
                    )),
                    Ok(Async::NotReady) => Ok(Async::NotReady),
                    Err(x) => Err(x),
                }
            } else {
                Ok(Async::Ready(Rearm(self.0.clone())))
            }
        } else {
            // unlikely to happen, just some filler
            Err(tokio_timer::Error::at_capacity())
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}