limon-core 0.3.3

limon core library
Documentation
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
//! A module for managing scheduled items that can be periodically polled.
//!
//! The `schedule` module provides structures and traits to manage objects
//! that need to be executed, updated, or checked at regular intervals.
//! Each item must implement the `Schedulable` trait, which defines a unique
//! identifier and an associated interval.
//!
//! The `Schedule` struct maintains:
//! - A mapping of item `id` to the items themselves for fast lookup.
//! - A mapping of `interval` to sets of item `id`, allowing efficient
//!   retrieval of all items that should be polled at a given interval.
//!
//! # Example
//!
//! ```rust
//! use std::collections::HashSet;
//!
//! use limon_core::schedule::{Schedule, Schedulable};
//!
//! struct Task {
//!     id: i64,
//!     interval: i64,
//! }
//!
//! impl Schedulable for Task {
//!     type Id = i64;
//!     type Interval = i64;
//!
//!     fn get_id(&self) -> Self::Id { self.id }
//!     fn get_interval(&self) -> Self::Interval { self.interval }
//! }
//!
//! let schedule: Schedule<Task> = Schedule::new();
//!
//! # tokio_test::block_on(async {
//! schedule.insert(Task { id: 1, interval: 30 }).await;
//! schedule.insert(Task { id: 2, interval: 60 }).await;
//!
//! assert_eq!(schedule.get_due(0, 90).await.len(), 2);
//! # })
//! ```

use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::sync::Arc;

use tokio::sync::RwLock;

/// A trait for items that can be scheduled.
///
/// This trait defines the necessary requirements for an item to be
/// stored and managed by a [Schedule]. Each item must have a unique
/// identifier `id` and an associated `interval`. Both types must
/// support hashing and equality checks, and be convertible to `i64`.
pub trait Schedulable {
  /// The unique identifier for the item.
  type Id: Eq + Hash + Into<i64> + Copy;

  /// The interval associated with the item.
  type Interval: Eq + Hash + Into<i64> + Copy;

  /// Returns the unique identifier of the item.
  fn get_id(&self) -> Self::Id;

  /// Returns the interval of the item.
  fn get_interval(&self) -> Self::Interval;
}

/// A schedule for managing [Schedulable] items.
///
/// The [Schedule] structure stores items indexed by their unique
/// identifiers and groups item `id` by their `interval`. This allows
/// efficient lookup of items by `id` and retrieval of all `id` in a
/// given interval.
///
/// | Operation | Time complexity |
/// |-----------|-----------------|
/// | Get       | O(1)            |
/// | Get due   | O(m)            |
/// | Insert    | O(1)            |
/// | Remove    | O(1)            |
///
/// **m** - it's amount of unique intervals.
pub struct Schedule<Item: Schedulable> {
  items: RwLock<HashMap<Item::Id, Arc<Item>>>,
  intervals: RwLock<HashMap<Item::Interval, HashSet<Item::Id>>>,
}

impl<Item: Schedulable> Schedule<Item> {
  /// Create a new schedule.
  pub fn new() -> Self {
    Self {
      items: RwLock::new(HashMap::new()),
      intervals: RwLock::new(HashMap::new()),
    }
  }

  /// Returns `true` if the [Schedule] doesn't contain elements.
  pub async fn is_empty(&self) -> bool {
    self.items.read().await.is_empty() && self.intervals.read().await.is_empty()
  }

  /// Get an item by `id`.
  pub async fn get(&self, id: Item::Id) -> Option<Arc<Item>> {
    self.items.read().await.get(&id).cloned()
  }

  /// Get items that are included in the interval `from` and `to`.
  ///
  /// An element is included in the interval if there is at least
  /// one value between `from` and `to` that is divisible by
  /// the item's [interval](Schedulable::Interval) without a remainder.
  ///
  /// `from` and `to` should be > 0 and `from` should be <= `to`.
  pub async fn get_due(&self, from: i64, to: i64) -> Vec<Arc<Item>> {
    let mut result = Vec::new();
    let intervals = self.intervals.read().await;

    for (interval, ids) in intervals.iter() {
      let interval = (*interval).into();
      let next_check = ((from + interval - 1) / interval) * interval;

      if next_check <= to {
        let guard = self.items.read().await;

        for id in ids {
          if let Some(item) = guard.get(id) {
            result.push(item.clone());
          }
        }
      }
    }

    result
  }

  /// Insert an item into schedule.
  ///
  /// If an item with this `id` is already in the schedule, it will be replaced.
  pub async fn insert(&self, item: Item) {
    let id = item.get_id();
    let interval = item.get_interval();

    {
      let mut intervals = self.intervals.write().await;

      if let Some(ids_set) = intervals.get_mut(&interval) {
        ids_set.insert(id);
      } else {
        let mut set = HashSet::new();
        set.insert(id);

        intervals.insert(interval, set);
      }
    }

    {
      let mut items = self.items.write().await;

      items.insert(id, Arc::new(item));
    }
  }

  /// Remove an item by `id` from the schedule if it exists.
  pub async fn remove(&self, id: Item::Id) {
    if let Some(item) = self.items.write().await.remove(&id) {
      let interval = item.get_interval();
      let mut intervals = self.intervals.write().await;

      if let Some(set) = intervals.get_mut(&interval) {
        if set.remove(&id) && set.is_empty() {
          intervals.remove(&interval);
        }
      }
    }
  }

  /// Clears the schedule, removing all items. Keeps the allocated
  /// memory for reuse.
  pub async fn clear(&self) {
    self.items.write().await.clear();
    self.intervals.write().await.clear();
  }
}

#[cfg(test)]
mod tests {
  use tokio::sync::RwLockReadGuard;

  use super::*;

  #[derive(Debug, PartialEq)]
  struct Task {
    id: i64,
    interval: i64,
    updated: bool,
  }

  impl<Item: Schedulable> Schedule<Item> {
    pub async fn items_ref(&self) -> RwLockReadGuard<'_, HashMap<Item::Id, Arc<Item>>> {
      self.items.read().await
    }

    pub async fn intervals_ref(
      &self,
    ) -> RwLockReadGuard<'_, HashMap<Item::Interval, HashSet<Item::Id>>> {
      self.intervals.read().await
    }
  }

  impl From<(i64, i64)> for Task {
    fn from(args: (i64, i64)) -> Self {
      Task {
        id: args.0,
        interval: args.1,
        updated: false,
      }
    }
  }

  impl Schedulable for Task {
    type Id = i64;
    type Interval = i64;

    fn get_id(&self) -> Self::Id {
      self.id
    }

    fn get_interval(&self) -> Self::Interval {
      self.interval
    }
  }

  #[tokio::test]
  async fn empty_schedule() {
    let schedule: Schedule<Task> = Schedule::new();

    assert!(
      schedule.items_ref().await.is_empty(),
      "schedule items shouldn't be empty"
    );
    assert!(
      schedule.intervals_ref().await.is_empty(),
      "schedule intervals shouldn't be empty"
    );
  }

  #[tokio::test]
  async fn test_empty_schedule() {
    let schedule: Schedule<Task> = Schedule::new();

    assert!(
      schedule.get_due(1, 100).await.is_empty(),
      "empty schedule shouldn't return due items"
    );
  }

  #[tokio::test]
  async fn get_due_on_boundary() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 10))).await;

    assert_eq!(
      schedule.get_due(1, 10).await.len(),
      1,
      "schedule should return item on boundary"
    );
    assert_eq!(
      schedule.get_due(10, 10).await.len(),
      1,
      "schedule should return item on boundary equals"
    );
  }

  #[tokio::test]
  async fn get_due_before_boundary() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 10))).await;

    assert!(
      schedule.get_due(1, 9).await.is_empty(),
      "schedule shouldn't return due items before boundary"
    );
  }

  #[tokio::test]
  async fn test_multiple_intervals() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 5))).await;
    schedule.insert(Task::from((2, 10))).await;

    let ids: Vec<i64> = schedule.get_due(1, 10).await.iter().map(|t| t.id).collect();

    assert!(
      ids.contains(&1),
      "schedule should return item with interval 5"
    );
    assert!(
      ids.contains(&2),
      "schedule should return item with interval 10"
    );
  }

  #[tokio::test]
  async fn test_skip_multiple_intervals() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 10))).await;

    assert_eq!(
      schedule.get_due(1, 35).await.len(),
      1,
      "schedule should return due item even if multiple intervals were passed"
    );
  }

  #[tokio::test]
  async fn insert_single_item_into_schedule() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 30))).await;

    assert!(
      schedule.items_ref().await.contains_key(&1),
      "schedule items should contain entry"
    );
    assert!(
      schedule.intervals_ref().await.contains_key(&30),
      "schedule intervals should contain entry"
    );
    assert_eq!(
      schedule.get(1).await,
      Some(Arc::new(Task::from((1, 30)))),
      "schedule should return entry by id"
    );
  }

  #[tokio::test]
  async fn insert_multiple_items_into_schedule() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 30))).await;
    schedule.insert(Task::from((2, 30))).await;

    assert!(
      schedule.items_ref().await.contains_key(&1),
      "schedule items should contain entry"
    );
    assert!(
      schedule.items_ref().await.contains_key(&2),
      "schedule items should contain entry"
    );
    assert!(
      schedule.intervals_ref().await.contains_key(&30),
      "schedule intervals should contain entry"
    );
    assert_eq!(
      schedule.get(1).await,
      Some(Arc::new(Task::from((1, 30)))),
      "schedule should return entry by id"
    );
    assert_eq!(
      schedule.get(2).await,
      Some(Arc::new(Task::from((2, 30)))),
      "schedule should return entry by id"
    );
  }

  #[tokio::test]
  async fn insert_the_sane_item_twice() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 30))).await;
    schedule.insert(Task::from((1, 30))).await;

    assert_eq!(
      schedule.items_ref().await.len(),
      1,
      "schedule items shouldn't be empty"
    );
    assert_eq!(
      schedule.intervals_ref().await.len(),
      1,
      "schedule intervals shouldn't be empty"
    );
  }

  #[tokio::test]
  async fn remove_item_from_schedule() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 30))).await;
    schedule.remove(1).await;

    assert!(
      schedule.items_ref().await.is_empty(),
      "schedule items should be empty"
    );
    assert!(
      schedule.intervals_ref().await.is_empty(),
      "schedule intervals should be empty"
    );
  }

  #[tokio::test]
  async fn clear() {
    let schedule: Schedule<Task> = Schedule::new();

    schedule.insert(Task::from((1, 10))).await;
    schedule.insert(Task::from((2, 20))).await;

    assert!(!schedule.is_empty().await, "schedule shouldn't be empty");

    schedule.clear().await;
    assert!(schedule.is_empty().await, "schedule should be empty");
  }
}