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
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
//
use async_std::prelude::*;
use async_std::sync::Mutex;
use async_std::task;
use async_trait::async_trait;
use flume::{bounded, Receiver, RecvError, Sender};
use std::cmp::Ordering as ComparisonOrdering;
use std::collections::BinaryHeap;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::sync::{Arc, Weak};
use std::time::{Duration, Instant};
use zenoh_core::zconfigurable;

zconfigurable! {
    static ref TIMER_EVENTS_CHANNEL_SIZE: usize = 1;
}

#[async_trait]
pub trait Timed {
    async fn run(&mut self);
}

type TimedFuture = Arc<dyn Timed + Send + Sync>;

#[derive(Clone)]
pub struct TimedHandle(Weak<AtomicBool>);

impl TimedHandle {
    pub fn defuse(self) {
        if let Some(arc) = self.0.upgrade() {
            arc.store(false, AtomicOrdering::Release);
        }
    }
}

#[derive(Clone)]
pub struct TimedEvent {
    when: Instant,
    period: Option<Duration>,
    future: TimedFuture,
    fused: Arc<AtomicBool>,
}

impl TimedEvent {
    pub fn once(when: Instant, event: impl Timed + Send + Sync + 'static) -> TimedEvent {
        TimedEvent {
            when,
            period: None,
            future: Arc::new(event),
            fused: Arc::new(AtomicBool::new(true)),
        }
    }

    pub fn periodic(interval: Duration, event: impl Timed + Send + Sync + 'static) -> TimedEvent {
        TimedEvent {
            when: Instant::now() + interval,
            period: Some(interval),
            future: Arc::new(event),
            fused: Arc::new(AtomicBool::new(true)),
        }
    }

    pub fn is_fused(&self) -> bool {
        self.fused.load(AtomicOrdering::Acquire)
    }

    pub fn get_handle(&self) -> TimedHandle {
        TimedHandle(Arc::downgrade(&self.fused))
    }
}

impl Eq for TimedEvent {}

impl Ord for TimedEvent {
    fn cmp(&self, other: &Self) -> ComparisonOrdering {
        // The usual cmp is defined as: self.when.cmp(&other.when)
        // This would make the events odered from largets to the smallest in the heap.
        // However, we want the events to be ordered from the smallets to the largest.
        // As a consequence of this, we swap the comparison terms, converting the heap
        // from a max-heap into a min-heap.
        other.when.cmp(&self.when)
    }
}

impl PartialOrd for TimedEvent {
    fn partial_cmp(&self, other: &Self) -> Option<ComparisonOrdering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for TimedEvent {
    fn eq(&self, other: &Self) -> bool {
        self.when == other.when
    }
}

async fn timer_task(
    events: Arc<Mutex<BinaryHeap<TimedEvent>>>,
    new_event: Receiver<(bool, TimedEvent)>,
) -> Result<(), RecvError> {
    // Error message
    let e = "Timer has been dropped. Unable to run timed events.";

    // Acquire the lock
    let mut events = events.lock().await;

    loop {
        // Fuuture for adding new events
        let new = new_event.recv_async();

        match events.peek() {
            Some(next) => {
                // Future for waiting an event timing
                let wait = async {
                    let next = next.clone();
                    let now = Instant::now();
                    if next.when > now {
                        task::sleep(next.when - now).await;
                    }
                    Ok((false, next))
                };

                match new.race(wait).await {
                    Ok((is_new, mut ev)) => {
                        if is_new {
                            // A new event has just been added: push it onto the heap
                            events.push(ev);
                            continue;
                        }

                        // We are ready to serve the event, remove it from the heap
                        let _ = events.pop();

                        // Execute the future if the event is fused
                        if ev.is_fused() {
                            // Now there is only one Arc pointing to the event future
                            // It is safe to access and execute to the inner future as mutable
                            Arc::get_mut(&mut ev.future).unwrap().run().await;

                            // Check if the event is periodic
                            if let Some(interval) = ev.period {
                                ev.when = Instant::now() + interval;
                                events.push(ev);
                            }
                        }
                    }
                    Err(_) => {
                        // Channel error
                        log::trace!("{}", e);
                        return Ok(());
                    }
                }
            }
            None => match new.await {
                Ok((_, ev)) => {
                    events.push(ev);
                    continue;
                }
                Err(_) => {
                    // Channel error
                    log::trace!("{}", e);
                    return Ok(());
                }
            },
        }
    }
}

#[derive(Clone)]
pub struct Timer {
    events: Arc<Mutex<BinaryHeap<TimedEvent>>>,
    sl_sender: Option<Sender<()>>,
    ev_sender: Option<Sender<(bool, TimedEvent)>>,
}

impl Timer {
    pub fn new(spawn_blocking: bool) -> Timer {
        // Create the channels
        let (ev_sender, ev_receiver) = bounded::<(bool, TimedEvent)>(*TIMER_EVENTS_CHANNEL_SIZE);
        let (sl_sender, sl_receiver) = bounded::<()>(1);

        // Create the timer object
        let timer = Timer {
            events: Arc::new(Mutex::new(BinaryHeap::new())),
            sl_sender: Some(sl_sender),
            ev_sender: Some(ev_sender),
        };

        // Start the timer task
        let c_e = timer.events.clone();
        let fut = async move {
            let _ = sl_receiver
                .recv_async()
                .race(timer_task(c_e, ev_receiver))
                .await;
            log::trace!("A - Timer task no longer running...");
        };
        if spawn_blocking {
            task::spawn_blocking(|| task::block_on(fut));
        } else {
            task::spawn(fut);
        }

        // Return the timer object
        timer
    }

    pub fn start(&mut self, spawn_blocking: bool) {
        if self.sl_sender.is_none() {
            // Create the channels
            let (ev_sender, ev_receiver) =
                bounded::<(bool, TimedEvent)>(*TIMER_EVENTS_CHANNEL_SIZE);
            let (sl_sender, sl_receiver) = bounded::<()>(1);

            // Store the channels handlers
            self.sl_sender = Some(sl_sender);
            self.ev_sender = Some(ev_sender);

            // Start the timer task
            let c_e = self.events.clone();
            let fut = async move {
                let _ = sl_receiver
                    .recv_async()
                    .race(timer_task(c_e, ev_receiver))
                    .await;
                log::trace!("A - Timer task no longer running...");
            };
            if spawn_blocking {
                task::spawn_blocking(|| task::block_on(fut));
            } else {
                task::spawn(fut);
            }
        }
    }

    #[inline]
    pub async fn start_async(&mut self, spawn_blocking: bool) {
        self.start(spawn_blocking)
    }

    pub fn stop(&mut self) {
        if let Some(sl_sender) = &self.sl_sender {
            // Stop the timer task
            let _ = sl_sender.send(());

            log::trace!("Stopping timer...");
            // Remove the channels handlers
            self.sl_sender = None;
            self.ev_sender = None;
        }
    }

    pub async fn stop_async(&mut self) {
        if let Some(sl_sender) = &self.sl_sender {
            // Stop the timer task
            let _ = sl_sender.send_async(()).await;

            log::trace!("Stopping timer...");
            // Remove the channels handlers
            self.sl_sender = None;
            self.ev_sender = None;
        }
    }

    pub fn add(&self, event: TimedEvent) {
        if let Some(ev_sender) = &self.ev_sender {
            let _ = ev_sender.send((true, event));
        }
    }

    pub async fn add_async(&self, event: TimedEvent) {
        if let Some(ev_sender) = &self.ev_sender {
            let _ = ev_sender.send_async((true, event)).await;
        }
    }
}

impl Default for Timer {
    fn default() -> Self {
        Self::new(false)
    }
}

mod tests {
    #[test]
    fn timer() {
        use super::{Timed, TimedEvent, Timer};
        use async_std::task;
        use async_trait::async_trait;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;
        use std::time::{Duration, Instant};

        #[derive(Clone)]
        struct MyEvent {
            counter: Arc<AtomicUsize>,
        }

        #[async_trait]
        impl Timed for MyEvent {
            async fn run(&mut self) {
                self.counter.fetch_add(1, Ordering::SeqCst);
            }
        }

        async fn run() {
            // Create the timer
            let mut timer = Timer::new(false);

            // Counter for testing
            let counter = Arc::new(AtomicUsize::new(0));

            // Create my custom event
            let myev = MyEvent {
                counter: counter.clone(),
            };

            // Default testing interval: 1 s
            let interval = Duration::from_secs(1);

            /* [1] */
            println!("Timer [1]: Once event and run");
            // Fire a once timed event
            let now = Instant::now();
            let event = TimedEvent::once(now + (2 * interval), myev.clone());

            // Add the event to the timer
            timer.add_async(event).await;

            // Wait for the event to occur
            task::sleep(3 * interval).await;

            // Load and reset the counter value
            let value = counter.swap(0, Ordering::SeqCst);
            assert_eq!(value, 1);

            /* [2] */
            println!("Timer [2]: Once event and defuse");
            // Fire a once timed event and defuse it before it is executed
            let now = Instant::now();
            let event = TimedEvent::once(now + (2 * interval), myev.clone());
            let handle = event.get_handle();

            // Add the event to the timer
            timer.add_async(event).await;
            //
            handle.defuse();

            // Wait for the event to occur
            task::sleep(3 * interval).await;

            // Load and reset the counter value
            let value = counter.swap(0, Ordering::SeqCst);
            assert_eq!(value, 0);

            /* [3] */
            println!("Timer [3]: Periodic event run and defuse");
            // Number of events to occur
            let amount: usize = 3;

            // Half the waiting interval for granularity reasons
            let to_elapse = (2 * amount as u32) * interval;

            // Fire a periodic event
            let event = TimedEvent::periodic(2 * interval, myev.clone());
            let handle = event.get_handle();

            // Add the event to the timer
            timer.add_async(event).await;

            // Wait for the events to occur
            task::sleep(to_elapse + interval).await;

            // Load and reset the counter value
            let value = counter.swap(0, Ordering::SeqCst);
            assert_eq!(value, amount);

            // Defuse the event (check if twice defusing don't cause troubles)
            handle.clone().defuse();
            handle.defuse();

            // Wait a bit more to verify that not more events have been fired
            task::sleep(to_elapse).await;

            // Load and reset the counter value
            let value = counter.swap(0, Ordering::SeqCst);
            assert_eq!(value, 0);

            /* [4] */
            println!("Timer [4]: Periodic event and stop/start timer");
            // Fire a periodic event
            let event = TimedEvent::periodic(2 * interval, myev);

            // Add the event to the timer
            timer.add_async(event).await;

            // Wait for the events to occur
            task::sleep(to_elapse + interval).await;

            // Load and reset the counter value
            let value = counter.swap(0, Ordering::SeqCst);
            assert_eq!(value, amount);

            // Stop the timer
            timer.stop_async().await;

            // Wait some time
            task::sleep(to_elapse).await;

            // Load and reset the counter value
            let value = counter.swap(0, Ordering::SeqCst);
            assert_eq!(value, 0);

            // Restart the timer
            timer.start_async(false).await;

            // Wait for the events to occur
            task::sleep(to_elapse).await;

            // Load and reset the counter value
            let value = counter.swap(0, Ordering::SeqCst);
            assert_eq!(value, amount);
        }

        task::block_on(run());
    }
}