idlefox/src/watchdog.rs

175 lines
6.8 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 crate::votes::EventHolder;
use chrono::{DateTime, Local, NaiveDate};
/// 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, ev_ctx: EventHolder) {
loop {
fk_around(&ev_ctx);
interval.tick().await;
// tokio::spawn(async {watchdog_update().await;}); // For async task
let ev = ev_ctx.clone();
tokio::task::spawn_blocking(move || watchdog_update(Local::now(), ev));
}
}
/// Close to finding out
fn fk_around(ev_ctx: &EventHolder) {
println!(
"In the fk_around function ({}):",
Local::now() // &ev_ctx
);
if let Some(discord_ctx) = ev_ctx.discord_ctx.lock().unwrap().as_mut() {
println!("Fking around : {:#?}", discord_ctx);
}
}
/// 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>, ev_ctx: EventHolder) {
// Update day and tell if a day passed
let is_new_day = update_date(current_time.date_naive(), &ev_ctx);
// List all upcoming events and run all events that should be ran
if let Err(e) = ev_ctx
.pending_events
.lock()
.unwrap()
.process_upcoming(current_time.naive_local(), &ev_ctx)
{
// 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) = ev_ctx
.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);
}
if let Err(e) = ev_ctx
.ongoing_events
.lock()
.unwrap()
.autoclose(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 closed
#[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, ev_ctx: &EventHolder) -> bool {
let old = ev_ctx.old_date.lock().unwrap().signed_duration_since(date);
if old.num_days() < 0 {
*ev_ctx.old_date.lock().unwrap() = date;
true
} else {
false
}
}
#[cfg(test)]
mod tests {
use chrono::Days;
use super::*;
#[test]
fn initialisation() {
let ev_ctx = EventHolder::default();
assert!(ev_ctx.old_date.lock().is_ok());
let date = Local::now().date_naive();
update_date(date, &ev_ctx);
assert!(!update_date(date, &ev_ctx));
}
#[test]
fn test_watchdog_update() {
let ctx = EventHolder::default();
let date = Local::now();
watchdog_update(date, ctx.clone());
let date2 = date.checked_add_days(Days::new(12)).unwrap();
assert!(update_date(date2.date_naive(), &ctx));
let date2 = date.checked_add_days(Days::new(14)).unwrap();
watchdog_update(date2, ctx.clone());
}
#[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!()
}
}