diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..8b67908 --- /dev/null +++ b/.ignore @@ -0,0 +1 @@ +badges/* diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 2547fcb..0000000 --- a/TODO.md +++ /dev/null @@ -1,40 +0,0 @@ -# Important -* [ ] Get rid of the #deprecated -* [ ] Get rid of the #dead_code - -# Test Driven -* [ ] Config Load and persistance -* [ ] Config recovery -* [ ] Error testing framework - -# Doc Writing -* [x] Config -* [x] Date -* [x] Error Handling -* [ ] Ids -* [x] IO -* [ ] Modules -* [ ] Persistence -* [ ] Server -* [ ] Votes -* [ ] Watchdog - -# Examples testing -* [x] Dates -# Testing -* [ ] Thouroughly test the naivedate objects creations - -# Tasks -## Dan -* [x] Finish testing to reach 100% coverage -* [ ] Implement Resilience & Recovery -* [x] Parse date mini language -* [ ] Migrate the todo into gitea - -## Vky -* [x] Write documentation for all functions in IO.rs -* [ ] Replace the usage of print with the appropriate logging where needed -* [ ] Create all module signature for queries -* [ ] Make worker functions (dedup code) -* [ ] Create a smaller context (?) -* [ ] Have a testing preset diff --git a/src/votes.rs b/src/votes.rs index 63fec8d..97fbd4d 100644 --- a/src/votes.rs +++ b/src/votes.rs @@ -13,8 +13,12 @@ //! #![allow(dead_code, deprecated)] -use std::{collections::HashMap, sync::LazyLock}; +use std::{ + collections::HashMap, + sync::{LazyLock, Mutex}, +}; +use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -48,8 +52,9 @@ pub(crate) struct Vote { type DateDataType = String; /// The global status of the event -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Default)] pub(crate) enum EventStatus { + #[default] /// The event exists but wasn't started yet Pending, /// The event was started but the finish date wasn't reached yet @@ -63,7 +68,7 @@ pub(crate) enum EventStatus { } /// An event, wether ongoing or planned -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Default)] pub(crate) struct Event { /// The title of the even title: String, @@ -72,7 +77,7 @@ pub(crate) struct Event { /// The global status of the vote status: EventStatus, /// Date at which to autostart the vote process - launch_date: Option, + launch_date: NaiveDateTime, /// Date at which to autoclose the vote process close_date: Option, /// The inner list of votes cast @@ -91,6 +96,7 @@ pub(crate) struct PendingEvents { /// The list of pending events pending_events: EventListType, } + impl PendingEvents { /// Create a new empty list of events, called in case of a first initialization /// @@ -100,6 +106,11 @@ impl PendingEvents { pending_events: EventListType::new(), } } + + /// Run all upcomming events if the auto launch time was reached + pub fn run_upcoming(&mut self) { + self.pending_events.insert(Uuid::new_v4(), Event::default()); + } } /// The list of ongoing events, not yet closed @@ -118,12 +129,19 @@ impl OngoingEvents { ongoing_events: EventListType::new(), } } + + /// Prune all outdated votes + pub fn prune_old(&mut self) { + self.ongoing_events.clear(); + } } /// The thread safe list of pending events -static CURRENT_EVENTS: LazyLock = LazyLock::new(PendingEvents::new); +pub static PENDING_EVENTS: LazyLock> = + LazyLock::new(|| Mutex::new(PendingEvents::new())); /// The thread safe list of ongoing events -static PENDING_EVENTS: LazyLock = LazyLock::new(OngoingEvents::new); +pub static ONGOING_EVENTS: LazyLock> = + LazyLock::new(|| Mutex::new(OngoingEvents::new())); #[cfg(test)] mod tests { @@ -134,5 +152,10 @@ mod tests { fn init_test() { let _e = PendingEvents::new(); let _o = OngoingEvents::new(); + assert!(PENDING_EVENTS.lock().is_ok()); + assert!(ONGOING_EVENTS.lock().is_ok()); + + PENDING_EVENTS.lock().unwrap().run_upcoming(); + ONGOING_EVENTS.lock().unwrap().prune_old(); } } diff --git a/src/watchdog.rs b/src/watchdog.rs index db45f1c..658627e 100644 --- a/src/watchdog.rs +++ b/src/watchdog.rs @@ -1,12 +1,106 @@ -//! Event scheduler in charge of waiting out events and enabling them when times comes +//! The `scheduler` module contains the logic for managing time-based tasks and events. +//! It is responsible for running scheduled tasks and garbage collecting old events. //! -//! Features: -//! Time based garbage collector -//! Time managed events -//! +//! This module includes several components: //! +//! - **Scheduler Thread**: A background thread that runs in an infinite loop, +//! checking for upcoming events and executing them when their scheduled times are reached. +//! - **Time-based Garbage Collection**: The scheduler periodically cleans up old events +//! that have passed their scheduled execution time, ensuring that memory usage remains efficient. +//! +//! Key functions in this module include: +//! +//! - `watchdog_update`: Updates the internal state of the scheduler, +//! checks for and runs upcoming events, and performs garbage collection if necessary. + +use std::sync::{LazyLock, Mutex}; + +use chrono::{DateTime, Local, NaiveDate}; + +use crate::votes::{ONGOING_EVENTS, PENDING_EVENTS}; + +/// The main scheduler waiting and dispatch loop. +/// +/// +/// This function continuously waits for the specified time interval to elapse, +/// then spawns a blocking task to perform the `watchdog_update` function. The +/// loop continues indefinitely, allowing for continuous scheduling of the +/// `watchdog_update` task at the specified intervals. +#[cfg(not(tarpaulin_include))] // This loop is untestable instead the logic is kept to the minimal +async fn main_scheduler_loop(mut interval: tokio::time::Interval) { + loop { + interval.tick().await; + // tokio::spawn(async {watchdog_update().await;}); // For async task + tokio::task::spawn_blocking(|| watchdog_update(Local::now())); + } +} + +/// The `watchdog_update` function updates the state of the watchdog and executes the necessary tasks. +/// +/// This function takes the current time as an argument, which is used to determine whether a new day has passed +/// and to update the internal calendar state. It then lists all upcoming events that are scheduled to be run +/// and executes them. Additionally, it schedules any ongoing tasks for future execution. +/// +/// If a new day has been detected (based on the current time), it prunes old events from the list of ongoing events. +/// +fn watchdog_update(current_time: DateTime) { + // Update day and tell if a day passed + let is_new_day = update_date(current_time.date_naive()); + // List all upcoming events and run all events that should be ran + PENDING_EVENTS.lock().unwrap().run_upcoming(); + // Execute all scheduled tasks + // * Clean old events if a new day passed + if is_new_day { + ONGOING_EVENTS.lock().unwrap().prune_old(); + } +} + +/// A lazily-initialized, thread-safe storage for the previous day's date. +/// +/// This constant is used to track when a new day has started. When a new day is detected, +/// it updates this value to reflect the current date and time. +static OLD_DATE: LazyLock> = + LazyLock::new(|| Mutex::new(Local::now().date_naive())); + +/// The `update_date` function updates the internal calendar state by taking a new date and comparing it with the previous day's date. +/// +/// It returns a boolean indicating whether a new day has passed. +/// This function is critical for determining when to prune old events from the ongoing event list. +/// ## Note +/// This whole function exists only in the purpose of manually testing the autopruning and autotesting of all time-related function. +fn update_date(date: NaiveDate) -> bool { + let old = OLD_DATE.lock().unwrap().signed_duration_since(date); + + if old.num_days() < 0 { + *OLD_DATE.lock().unwrap() = date; + true + } else { + false + } +} #[cfg(test)] mod tests { - // use super::*; + use chrono::Days; + + use super::*; + + #[test] + fn test_initialisation() { + assert!(OLD_DATE.lock().is_ok()); + let date = Local::now().date_naive(); + update_date(date); + assert!(!update_date(date)); + } + + #[test] + fn test_update() { + // TODO: Fill this test as the update functions are filled + let date = Local::now(); + watchdog_update(date); + let date2 = date.checked_add_days(Days::new(12)).unwrap(); + assert!(update_date(date2.date_naive())); + let date2 = date.checked_add_days(Days::new(14)).unwrap(); + watchdog_update(date2); + } }