idlefox/src/watchdog.rs

151 lines
5.7 KiB
Rust

//! 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.
//!
//! 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
pub 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.
// TODO: Thouroughly test
fn watchdog_update(current_time: DateTime<Local>) {
// 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
if let Err(e) = PENDING_EVENTS
.lock()
.unwrap()
.process_upcoming(current_time.naive_local())
{
// Process the error, log it and try to recover, this error can only happen during a difficult
// to reproduce data race where a task would be edited or externally deleted just as it is about to be launched
#[cfg(not(tarpaulin_include))]
log::error!("{}:{} {:?}", file!(), line!(), e);
}
// Execute all scheduled tasks
// * Clean old events if a new day passed
if is_new_day {
if let Err(e) = ONGOING_EVENTS
.lock()
.unwrap()
.prune_old(current_time.naive_local())
{
// Process the error, log it and try to recover, this error can only happen during a difficult
// to reproduce data race where a task would be edited or externally deleted just as it is about to be deleted
#[cfg(not(tarpaulin_include))]
log::error!("{}:{} {:?}", file!(), line!(), e);
}
}
// TODO: Save global state
}
/// 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<Mutex<NaiveDate>> =
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 chrono::Days;
use super::*;
#[test]
fn initialisation() {
assert!(OLD_DATE.lock().is_ok());
let date = Local::now().date_naive();
update_date(date);
assert!(!update_date(date));
}
#[test]
fn test_watchdog_update() {
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);
}
#[test]
#[ignore]
fn test_watchdog_pruning() {
// Add an event for a date
// Check that the watchdog erased it now that it is passed
// Check that if is set long in the past the event isn't launched as it is not valid and is instead destroyed immediately
// Check that an event cannot stay in memory if it is invalid or wont be launched
unimplemented!()
}
#[test]
#[ignore]
fn test_watchdog_launching() {
// Add an event for a date
// Check that the watchdog launched it
unimplemented!()
}
#[test]
#[ignore]
fn watchdog_autosave() {
// Check that every update of the watchdog saves the votes
unimplemented!()
}
}