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
//! Thread safe scheduler
use crate::queue::Notifier;
use crate::NotificationId;
use crossbeam_queue::SegQueue;
use std::cmp::Ordering as CmpOrdering;
use std::collections::{BTreeSet, HashSet};
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::ops::{Add, Sub};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, RwLock};
use std::thread::JoinHandle;
use std::{
    fmt, thread,
    time::{Duration, Instant},
};

/// Schedules notification deliveries
#[derive(Debug)]
pub struct NotificationScheduler {
    notifier: Arc<dyn Notifier>,
    scheduler: Arc<Scheduler>,
}

impl NotificationScheduler {
    /// Creates a new scheduler that uses the provided notifier to deliver notifications
    pub fn new(notifier: Arc<dyn Notifier>, scheduler: Arc<Scheduler>) -> NotificationScheduler {
        NotificationScheduler {
            notifier,
            scheduler,
        }
    }

    /// Schedules recurring notification deliveries with fixed intervals
    pub fn notify_with_fixed_interval<I: Into<Option<Duration>>>(
        &self,
        id: NotificationId,
        interval: Duration,
        initial_delay: I,
        name: Option<String>,
    ) -> ScheduleEntryId
    where
        I: Into<Option<Duration>>,
    {
        let notifier = Arc::clone(&self.notifier);
        let entry = ScheduleEntry::with_interval(interval, initial_delay, name, move || {
            let _ = notifier.notify(id);
        });
        let id = entry.id;
        self.scheduler.schedule(entry);
        id
    }

    /// Schedules a one-time notification delivery
    pub fn notify_once_after_delay(
        &self,
        id: NotificationId,
        delay: Duration,
        name: Option<String>,
    ) -> ScheduleEntryId {
        let notifier = Arc::clone(&self.notifier);
        let entry = ScheduleEntry::one_time(delay, name, move || {
            let _ = notifier.notify(id);
        });
        let id = entry.id;
        self.scheduler.schedule(entry);
        id
    }

    /// Cancels future notification(s)
    pub fn cancel(&self, id: ScheduleEntryId) {
        self.scheduler.cancel(id);
    }
}

type Callback = dyn Fn() + Send + Sync + 'static;

/// Entry associated with callback
#[derive(Clone)]
pub struct ScheduleEntry {
    start: Instant,
    /// The interval with which to run the callback. No interval means only one-time run
    interval: Option<Duration>,
    callback: Arc<Callback>,
    /// The assigned name of the entry for debugging purposes
    pub name: Option<String>,
    /// Entry Id
    pub id: ScheduleEntryId,
}

impl ScheduleEntry {
    /// Creates an entry to run the callback repeatedly with a fixed delay
    pub fn with_interval<I, F>(
        interval: Duration,
        initial_delay: I,
        name: Option<String>,
        callback: F,
    ) -> ScheduleEntry
    where
        I: Into<Option<Duration>>,
        F: Fn() + Send + Sync + 'static,
    {
        let now = Instant::now();
        ScheduleEntry {
            start: initial_delay.into().map(|d| now.add(d)).unwrap_or(now),
            interval: Some(interval),
            callback: Arc::new(callback),
            name,
            id: ScheduleEntryId::gen_next(),
        }
    }

    /// Creates an entry to run the callback only once after a given delay
    pub fn one_time<F>(delay: Duration, name: Option<String>, callback: F) -> ScheduleEntry
    where
        F: Fn() + Send + Sync + 'static,
    {
        ScheduleEntry {
            start: Instant::now().add(delay),
            interval: None,
            callback: Arc::new(callback),
            name,
            id: ScheduleEntryId::gen_next(),
        }
    }
}

impl fmt::Debug for ScheduleEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScheduleEntry")
            .field("start", &self.start)
            .field("interval", &self.interval)
            .field("name", &self.name)
            .field("id", &self.id)
            .finish()
    }
}

impl Hash for ScheduleEntry {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.start.hash(hasher);
        self.id.hash(hasher);
    }
}

impl Eq for ScheduleEntry {}

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

impl Ord for ScheduleEntry {
    fn cmp(&self, other: &Self) -> CmpOrdering {
        self.start.cmp(&other.start).then(self.id.cmp(&other.id))
    }
}

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

static NEXT_SCHEDULE_ENTRY_ID: AtomicU32 = AtomicU32::new(1);

/// Id associated with an entry
#[derive(Copy, Clone, Debug, PartialEq, Ord, PartialOrd, Eq, Hash)]
pub struct ScheduleEntryId(u32);

impl ScheduleEntryId {
    /// Generates next `ScheduleEntryId`, which is guaranteed to be unique
    pub fn gen_next() -> ScheduleEntryId {
        let id = NEXT_SCHEDULE_ENTRY_ID.fetch_add(1, Ordering::SeqCst);
        ScheduleEntryId(id)
    }

    /// Returns id
    pub fn id(&self) -> u32 {
        self.0
    }
}

/// Scheduler Status
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SchedulerStatus {
    /// Currently executing an entry
    Active,
    /// Waiting for new entries to be scheduled
    Parked,
    /// Waiting to execute entries in the queue at the scheduled intervals
    ParkedTimeout,
}

/// Single-threaded scheduler that prioritizes "cancels" over schedule executions, hence multiple queues
#[derive(Debug)]
pub struct Scheduler {
    shutdown: Arc<AtomicBool>,
    thread_handle: JoinHandle<()>,
    schedule_queue: Arc<SegQueue<ScheduleEntry>>,
    cancel_queue: Arc<SegQueue<ScheduleEntryId>>,
    name: String,
    status: Arc<RwLock<SchedulerStatus>>,
    entry_count: Arc<AtomicU32>,
}

impl Default for Scheduler {
    fn default() -> Scheduler {
        Scheduler::new(None)
    }
}

// Helps distinguish different scheduler creations
static SCHEDULER_THREAD_ID: AtomicU32 = AtomicU32::new(1);

impl Scheduler {
    /// Returns the name of the scheduler
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Schedules entry for execution(s)
    pub fn schedule(&self, entry: ScheduleEntry) {
        self.schedule_queue.push(entry);
        self.thread_handle.thread().unpark();
    }

    /// Cancels future execution(s)
    pub fn cancel(&self, id: ScheduleEntryId) {
        self.cancel_queue.push(id);
        self.thread_handle.thread().unpark();
    }

    /// Returns the scheduler's current status
    pub fn status(&self) -> SchedulerStatus {
        *(self.status.read().unwrap())
    }

    /// Number of current entries
    pub fn entry_count(&self) -> u32 {
        self.entry_count.load(Ordering::SeqCst)
    }

    /// Creates a scheduler
    pub fn new(name: Option<String>) -> Scheduler {
        let t_id = SCHEDULER_THREAD_ID.fetch_add(1, Ordering::SeqCst);
        let name_prefix = "mio-misc-scheduler";
        let name = name
            .map(|n| format!("{}-{}-{}", name_prefix, n, t_id))
            .unwrap_or_else(|| format!("{}-{}", name_prefix, t_id));
        let name_clone = name.clone();

        let shut_down = Arc::new(AtomicBool::new(false));
        let shutdown_clone = Arc::clone(&shut_down);
        let entry_count = Arc::new(AtomicU32::new(0));
        let entry_count_clone = Arc::clone(&entry_count);
        let schedule_queue = Arc::new(SegQueue::new());
        let schedule_queue_clone = Arc::clone(&schedule_queue);
        let cancel_queue = Arc::new(SegQueue::new());
        let cancel_queue_clone = Arc::clone(&cancel_queue);
        let status = Arc::new(RwLock::new(SchedulerStatus::Active));
        let status_clone = Arc::clone(&status);
        let thread_handle = thread::Builder::new()
            .name(name.clone())
            .spawn(move || {
                let mut entries: BTreeSet<ScheduleEntry> = BTreeSet::new();
                let mut entries_to_cancel: HashSet<ScheduleEntryId> = HashSet::new();
                while !shut_down.load(Ordering::SeqCst) {
                    // cancel requests take precedence
                    while let Some(entry_id) = cancel_queue.pop() {
                        trace!(
                            "{}: cancelling scheduler entry with id {:?};",
                            name,
                            entry_id
                        );
                        let _ = entries_to_cancel.insert(entry_id);
                    }
                    if let Some(entry) = schedule_queue.pop() {
                        trace!("{}: scheduling entry; {:?};", name, entry);
                        if entries.insert(entry) {
                            entry_count.fetch_add(1, Ordering::SeqCst);
                        }
                    }
                    if let Some(entry) = entries.iter().cloned().next() {
                        let now = Instant::now();
                        // time to execute a callback ?
                        if now.ge(&entry.start) {
                            entries.remove(&entry);
                            // entry still relevant ?
                            if !entries_to_cancel.contains(&entry.id) {
                                trace!("{}: executing scheduler entry; {:?}", name, entry);
                                let cb = Arc::clone(&entry.callback);
                                cb();
                                if let Some(interval) = entry.interval {
                                    // add back
                                    let updated_entry = ScheduleEntry {
                                        start: Instant::now().add(interval),
                                        interval: entry.interval,
                                        callback: entry.callback,
                                        name: entry.name,
                                        id: entry.id,
                                    };
                                    entries.insert(updated_entry);
                                }
                            } else {
                                // not executing and not scheduling a new entry
                                trace!("{}: cancelling scheduler entry; {:?}", name, entry);

                                if entries_to_cancel.remove(&entry.id) {
                                    entry_count.fetch_sub(1, Ordering::SeqCst);
                                }
                            }
                        } else {
                            // park until the nearest time when we need to execute a function
                            let timeout_dur = entry.start.sub(now);
                            trace!("{}: parking scheduler for {:?}", name, timeout_dur);
                            *status.write().unwrap() = SchedulerStatus::ParkedTimeout;
                            thread::park_timeout(timeout_dur);
                            *status.write().unwrap() = SchedulerStatus::Active;
                        }
                    } else {
                        // there's no function to execute, so park indefinitely instead of spinning idly
                        trace!("{}: parking scheduler until being un-parked", name);
                        *status.write().unwrap() = SchedulerStatus::Parked;
                        thread::park();
                        *status.write().unwrap() = SchedulerStatus::Active;
                    }
                }
            })
            .unwrap();
        Scheduler {
            shutdown: shutdown_clone,
            thread_handle,
            schedule_queue: schedule_queue_clone,
            cancel_queue: cancel_queue_clone,
            name: name_clone,
            status: status_clone,
            entry_count: entry_count_clone,
        }
    }
}

impl Drop for Scheduler {
    fn drop(&mut self) {
        self.shutdown.store(true, Ordering::SeqCst);
        self.thread_handle.thread().unpark();
    }
}