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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Timer-based event sources
//!
//! A `Timer<T>` is a general time-tracking object. It is used by setting timeouts,
//! and generates events whenever a timeout expires.
//!
//! The `Timer<T>` event source provides an handle `TimerHandle<T>`, which is used
//! to set or cancel timeouts. This handle is cloneable and can be send accross threads
//! if `T: Send`, allowing you to setup timeouts from any point of your program.

use std::cell::RefCell;
use std::collections::BinaryHeap;
use std::io;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex,
};
use std::time::{Duration, Instant};

use super::ping::{make_ping, PingSource};
use crate::{EventSource, Poll, Readiness, Token};

/// A Timer event source
///
/// It generates events of type `(T, TimerHandle<T>)`, providing you
/// an handle inside the event callback, allowing you to set new timeouts
/// as a response to a timeout being reached (for reccuring ticks for example).
pub struct Timer<T> {
    inner: Arc<Mutex<TimerInner<T>>>,
    source: TimerSource,
}

impl<T> Timer<T> {
    /// Create a new timer with default parameters
    ///
    /// Default time resolution is 100ms
    pub fn new() -> std::io::Result<Timer<T>> {
        let (scheduler, source) = TimerScheduler::new()?;
        let inner = TimerInner::new(scheduler);
        Ok(Timer {
            inner: Arc::new(Mutex::new(inner)),
            source,
        })
    }

    /// Get an handle for this timer
    pub fn handle(&self) -> TimerHandle<T> {
        TimerHandle {
            inner: self.inner.clone(),
        }
    }
}

/// An handle to a timer, used to set or cancel timeouts
///
/// This handle can be cloned, and can be sent accross thread as long
/// as `T: Send`.
pub struct TimerHandle<T> {
    inner: Arc<Mutex<TimerInner<T>>>,
}

// Manual impl of `Clone` as #[derive(Clone)] adds a `T: Clone` bound
#[cfg(not(tarpaulin_include))]
impl<T> Clone for TimerHandle<T> {
    fn clone(&self) -> TimerHandle<T> {
        TimerHandle {
            inner: self.inner.clone(),
        }
    }
}

/// An itentifier to cancel a timeout if necessary
pub struct Timeout {
    counter: u32,
}

impl<T> TimerHandle<T> {
    /// Set a new timeout
    ///
    /// The associated `data` will be given as argument to the callback.
    ///
    /// The returned `Timeout` can be used to cancel it. You can drop it if you don't
    /// plan to cancel this timeout.
    pub fn add_timeout(&self, delay_from_now: Duration, data: T) -> Timeout {
        self.inner
            .lock()
            .unwrap()
            .insert(Instant::now() + delay_from_now, data)
    }

    /// Cancel a previsouly set timeout and retrieve the associated data
    ///
    /// This method returns `None` if the timeout does not exist (it has already fired
    /// or has already been cancelled).
    pub fn cancel_timeout(&self, timeout: &Timeout) -> Option<T> {
        self.inner.lock().unwrap().cancel(timeout)
    }

    /// Cancel all planned timeouts for this timer
    ///
    /// All associated data will be dropped.
    pub fn cancel_all_timeouts(&self) {
        self.inner.lock().unwrap().cancel_all();
    }
}

impl<T: 'static> EventSource for Timer<T> {
    type Event = T;
    type Metadata = TimerHandle<T>;
    type Ret = ();

    fn process_events<C>(
        &mut self,
        readiness: Readiness,
        token: Token,
        mut callback: C,
    ) -> std::io::Result<()>
    where
        C: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
    {
        let mut handle = TimerHandle {
            inner: self.inner.clone(),
        };
        let inner = &self.inner;
        self.source.process_events(readiness, token, |(), &mut ()| {
            let mut some_expired = false;
            loop {
                let next_expired: Option<T> = {
                    let mut guard = inner.lock().unwrap();
                    guard.next_expired()
                };
                if let Some(val) = next_expired {
                    some_expired = true;
                    callback(val, &mut handle);
                } else {
                    break;
                }
            }
            // now compute the next timeout and signal if necessary
            if some_expired {
                inner.lock().unwrap().reschedule();
            }
        })
    }

    fn register(&mut self, poll: &mut Poll, token: Token) -> std::io::Result<()> {
        self.source.register(poll, token)
    }

    fn reregister(&mut self, poll: &mut Poll, token: Token) -> std::io::Result<()> {
        self.source.reregister(poll, token)
    }

    fn unregister(&mut self, poll: &mut Poll) -> std::io::Result<()> {
        self.source.unregister(poll)
    }
}

/*
 * Timer logic
 */

struct TimeoutData<T> {
    deadline: Instant,
    data: RefCell<Option<T>>,
    counter: u32,
}

struct TimerInner<T> {
    heap: BinaryHeap<TimeoutData<T>>,
    scheduler: TimerScheduler,
    counter: u32,
}

impl<T> TimerInner<T> {
    fn new(scheduler: TimerScheduler) -> TimerInner<T> {
        TimerInner {
            heap: BinaryHeap::new(),
            scheduler,
            counter: 0,
        }
    }

    fn insert(&mut self, deadline: Instant, value: T) -> Timeout {
        self.heap.push(TimeoutData {
            deadline,
            data: RefCell::new(Some(value)),
            counter: self.counter,
        });
        let ret = Timeout {
            counter: self.counter,
        };
        self.counter += 1;
        self.reschedule();
        ret
    }

    fn cancel(&mut self, timeout: &Timeout) -> Option<T> {
        for data in self.heap.iter() {
            if data.counter == timeout.counter {
                return data.data.borrow_mut().take();
            }
        }
        self.reschedule();
        None
    }

    fn cancel_all(&mut self) {
        self.heap.clear();
        self.reschedule();
    }

    fn next_expired(&mut self) -> Option<T> {
        let now = Instant::now();
        loop {
            // check if there is an expired item
            if let Some(ref data) = self.heap.peek() {
                if data.deadline > now {
                    return None;
                }
            // there is an expired timeout, continue the
            // loop body
            } else {
                return None;
            }

            // There is an item in the heap, this unwrap cannot blow
            let data = self.heap.pop().unwrap();
            if let Some(val) = data.data.into_inner() {
                return Some(val);
            }
            // otherwise this timeout was cancelled, continue looping
        }
    }

    fn reschedule(&mut self) {
        if let Some(next_deadline) = self.heap.peek().map(|data| data.deadline) {
            self.scheduler.reschedule(next_deadline);
        } else {
            self.scheduler.deschedule();
        }
    }
}

// trait implementations for TimeoutData

impl<T> std::cmp::Ord for TimeoutData<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // earlier values have priority
        self.deadline.cmp(&other.deadline).reverse()
    }
}

impl<T> std::cmp::PartialOrd for TimeoutData<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        // earlier values have priority
        Some(self.deadline.cmp(&other.deadline).reverse())
    }
}

impl<T> std::cmp::PartialEq for TimeoutData<T> {
    fn eq(&self, other: &Self) -> bool {
        // earlier values have priority
        self.deadline == other.deadline
    }
}

impl<T> std::cmp::Eq for TimeoutData<T> {}

/*
 * Scheduling
 */

struct TimerScheduler {
    current_deadline: Arc<Mutex<Option<Instant>>>,
    kill_switch: Arc<AtomicBool>,
    thread: std::thread::JoinHandle<()>,
}

type TimerSource = PingSource;

impl TimerScheduler {
    fn new() -> io::Result<(TimerScheduler, TimerSource)> {
        let current_deadline = Arc::new(Mutex::new(None::<Instant>));
        let thread_deadline = current_deadline.clone();

        let kill_switch = Arc::new(AtomicBool::new(false));
        let thread_kill = kill_switch.clone();

        let (ping, ping_source) = make_ping()?;

        let thread = std::thread::Builder::new()
            .name("calloop timer".into())
            .spawn(move || loop {
                // stop if requested
                if thread_kill.load(Ordering::Acquire) {
                    return;
                }
                // otherwise check the timeout
                let opt_deadline: Option<Instant> = {
                    // subscope to ensure the mutex does not remain locked while the thread is parked
                    let guard = thread_deadline.lock().unwrap();
                    *guard
                };
                if let Some(deadline) = opt_deadline {
                    if let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
                        // it is not yet expired, go to sleep until it
                        std::thread::park_timeout(remaining);
                    } else {
                        // it is expired, wake the event loop and go to sleep
                        ping.ping();
                        std::thread::park();
                    }
                } else {
                    // there is none, got to sleep
                    std::thread::park();
                }
            })?;

        let scheduler = TimerScheduler {
            current_deadline,
            kill_switch,
            thread,
        };
        Ok((scheduler, ping_source))
    }

    fn reschedule(&mut self, new_deadline: Instant) {
        let mut deadline_guard = self.current_deadline.lock().unwrap();
        if let Some(current_deadline) = *deadline_guard {
            if new_deadline < current_deadline || current_deadline <= Instant::now() {
                *deadline_guard = Some(new_deadline);
                self.thread.thread().unpark();
            }
        } else {
            *deadline_guard = Some(new_deadline);
            self.thread.thread().unpark();
        }
    }

    fn deschedule(&mut self) {
        *(self.current_deadline.lock().unwrap()) = None;
    }
}

impl Drop for TimerScheduler {
    fn drop(&mut self) {
        self.kill_switch.store(true, Ordering::Release);
    }
}

/*
 * Tests
 */

#[cfg(test)]
mod tests {
    use std::io;
    use std::time::Duration;

    use super::*;

    #[test]
    fn single_timer() {
        let mut event_loop = crate::EventLoop::new().unwrap();

        let evl_handle = event_loop.handle();

        let mut fired = false;

        let timer = Timer::<()>::new().unwrap();
        let timer_handle = timer.handle();
        evl_handle
            .insert_source(timer, move |(), _, f| {
                *f = true;
            })
            .map_err(Into::<io::Error>::into)
            .unwrap();

        timer_handle.add_timeout(Duration::from_millis(300), ());

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(100)), &mut fired)
            .unwrap();

        // it should not have fired yet
        assert!(!fired);

        event_loop.dispatch(None, &mut fired).unwrap();

        // it should have fired now
        assert!(fired);
    }

    #[test]
    fn multi_timout_order() {
        let mut event_loop = crate::EventLoop::new().unwrap();

        let evl_handle = event_loop.handle();

        let mut fired = Vec::new();

        let timer = Timer::<u32>::new().unwrap();
        let timer_handle = timer.handle();

        evl_handle
            .insert_source(timer, |val, _, fired: &mut Vec<u32>| {
                fired.push(val);
            })
            .map_err(Into::<io::Error>::into)
            .unwrap();

        timer_handle.add_timeout(Duration::from_millis(300), 1);
        timer_handle.add_timeout(Duration::from_millis(100), 2);
        timer_handle.add_timeout(Duration::from_millis(600), 3);

        // 3 dispatches as each returns once at least one event occured

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(200)), &mut fired)
            .unwrap();

        assert_eq!(&fired, &[2]);

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(300)), &mut fired)
            .unwrap();

        assert_eq!(&fired, &[2, 1]);

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(400)), &mut fired)
            .unwrap();

        assert_eq!(&fired, &[2, 1, 3]);
    }

    #[test]
    fn timer_cancel() {
        let mut event_loop = crate::EventLoop::new().unwrap();

        let evl_handle = event_loop.handle();

        let mut fired = Vec::new();

        let timer = Timer::<u32>::new().unwrap();
        let timer_handle = timer.handle();

        evl_handle
            .insert_source(timer, |val, _, fired: &mut Vec<u32>| fired.push(val))
            .map_err(Into::<io::Error>::into)
            .unwrap();

        let timeout1 = timer_handle.add_timeout(Duration::from_millis(300), 1);
        let timeout2 = timer_handle.add_timeout(Duration::from_millis(100), 2);
        let timeout3 = timer_handle.add_timeout(Duration::from_millis(600), 3);

        // 3 dispatches as each returns once at least one event occured
        //
        // The timeouts 1 and 3 and not cancelled right away, but still before they
        // fire

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(200)), &mut fired)
            .unwrap();

        assert_eq!(&fired, &[2]);

        // timeout2 has already fired, we cancel timeout1
        assert_eq!(timer_handle.cancel_timeout(&timeout2), None);
        assert_eq!(timer_handle.cancel_timeout(&timeout1), Some(1));

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(300)), &mut fired)
            .unwrap();

        assert_eq!(&fired, &[2]);

        // cancel timeout3
        assert_eq!(timer_handle.cancel_timeout(&timeout3), Some(3));

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(600)), &mut fired)
            .unwrap();

        assert_eq!(&fired, &[2]);
    }
}