From 72bf7ea3bb3bb435c2f1cf37ec280881850e6f56 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 5 Nov 2024 18:10:13 +0100 Subject: [PATCH 1/3] Adds some logic on the votes and watchdog --- Cargo.toml | 3 +++ README.md | 2 +- badges/coverage.svg | 1 + badges/release.svg | 1 - badges/test.svg | 2 +- badges/test_cov.svg | 1 - badges/version.svg | 1 + src/date/date_tools.rs | 24 +++++++++++------- src/votes.rs | 55 ++++++++++++++++++++++++++++++++++++------ src/watchdog.rs | 28 ++++++++++++++++----- 10 files changed, 92 insertions(+), 26 deletions(-) create mode 100644 badges/coverage.svg delete mode 100644 badges/release.svg delete mode 100644 badges/test_cov.svg create mode 100644 badges/version.svg diff --git a/Cargo.toml b/Cargo.toml index e29711f..540c7d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,9 @@ simplelog = { version = "0.12.2", features = ["paris"] } log = { version = "0.4.22", features = ["std"] } nom = "7.1.3" criterion = "0.5" +serde_json = { version = "1.0.132", features = ["alloc"] } +postcard = { version = "1.0.10", features = ["alloc"] } +ron = "0.8.1" [profile.dev] debug = 0 diff --git a/README.md b/README.md index 982fec7..5a86b23 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # idlefox -![code coverage](badges/test_cov.svg) ![version](badges/release.svg) ![code coverage](badges/test.svg) +![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) IdleFox is a feature-rich Discord bot designed to streamline the process of finding meeting dates, organizing events, and making decisions among multiple options. With its user-friendly commands and robust command system, IdleFox helps facilitate effective communication within server communities. diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..5bcb4dd --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 68%test-coverage68% diff --git a/badges/release.svg b/badges/release.svg deleted file mode 100644 index 99d9d9d..0000000 --- a/badges/release.svg +++ /dev/null @@ -1 +0,0 @@ -release: v0.1.0releasev0.1.0 diff --git a/badges/test.svg b/badges/test.svg index a34aaf8..a7859aa 100644 --- a/badges/test.svg +++ b/badges/test.svg @@ -1 +1 @@ -build: passingbuildpassing +test: passingtestpassing diff --git a/badges/test_cov.svg b/badges/test_cov.svg deleted file mode 100644 index f21e8b5..0000000 --- a/badges/test_cov.svg +++ /dev/null @@ -1 +0,0 @@ -test-coverage: 100%test-coverage100% diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..c28c459 --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.1.0version0.1.0 diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs index 616e595..bafa332 100644 --- a/src/date/date_tools.rs +++ b/src/date/date_tools.rs @@ -2,6 +2,7 @@ use crate::error_handling::IdleError; use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday}; +use serde::{Deserialize, Serialize}; use super::{ date_parse::{DateObject, DatePoint}, @@ -134,7 +135,7 @@ impl DatePoint { } /// An enum representing either a single [NaiveDate] or a date range between two [NaiveDate]. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] // #[cfg_attr(test, derive(PartialEq))] pub enum NaiveDateObject { /// A range between two dates, inclusive at both ends. @@ -153,11 +154,8 @@ pub enum NaiveDateObject { /// This struct provides an abstraction over a list of date objects, enabling both sequential iteration /// over the dates in order or direct access to any date by its index. The structure is designed to handle /// different sources of date information, allowing for flexible data manipulation based on the provided dates. -/// -/// # Example -/// - -#[cfg_attr(test, derive(PartialEq, Debug))] +#[derive(Debug, Default, Serialize, Deserialize)] +#[cfg_attr(test, derive(PartialEq))] pub struct NaiveDateList { /// The inner vector inner: Vec, @@ -320,10 +318,8 @@ pub fn parse_date_list( #[cfg(test)] pub(crate) mod tests { - - use crate::date::date_parse::DateRange; - use super::*; + use crate::date::date_parse::DateRange; #[test] fn test_relative_days() { @@ -475,4 +471,14 @@ pub(crate) mod tests { assert_eq!(list.unparsed, None); assert_eq!(list.len(), 2); } + #[test] + fn test_serialisation() { + let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fri and some other text"; + let context = NaiveDate::from_ymd_opt(2023, 10, 1); + let list = parse_date_list(input, context).unwrap(); + + let s = ron::to_string(&list).unwrap(); + // Simple roundtrip assertion + assert_eq!(list, ron::from_str(&s).unwrap()); + } } diff --git a/src/votes.rs b/src/votes.rs index 97fbd4d..c5a90ab 100644 --- a/src/votes.rs +++ b/src/votes.rs @@ -22,6 +22,8 @@ use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; use uuid::Uuid; +use crate::date::date_tools::NaiveDateList; + /// Placeholder datatype /// /// Links to an event, active or planned @@ -79,11 +81,11 @@ pub(crate) struct Event { /// Date at which to autostart the vote process launch_date: NaiveDateTime, /// Date at which to autoclose the vote process - close_date: Option, + close_date: Option, /// The inner list of votes cast votes: Vec, /// The list of values to vote for, this list all the valid dates to vote for - vote_values: Vec, + vote_values: NaiveDateList, } // This split in two differents structs conceptually represents @@ -107,9 +109,30 @@ impl PendingEvents { } } - /// Run all upcomming events if the auto launch time was reached - pub fn run_upcoming(&mut self) { + /// Process and activate all upcomming events if the auto launch time was reached + /// TODO: Test & doc + pub fn process_upcoming(&mut self, current_time: NaiveDateTime) { self.pending_events.insert(Uuid::new_v4(), Event::default()); + let upcomming = self.find_upcomming(current_time); + + for uuid in upcomming { + let event = self.pending_events.remove(&uuid).unwrap(); + ONGOING_EVENTS.lock().unwrap().add_event(uuid, event); + } + } + + // fn launch(&self, event: Event) -> Result<(), IdleError> { + // todo!() + // } + + /// Find all event that are bound to be launched + /// TODO: Test & doc + fn find_upcomming(&self, current_time: NaiveDateTime) -> Vec { + self.pending_events + .iter() + .filter(|&(_, e)| e.launch_date > current_time) + .map(|(k, _v)| (*k)) + .collect() } } @@ -131,8 +154,17 @@ impl OngoingEvents { } /// Prune all outdated votes - pub fn prune_old(&mut self) { + /// + /// TODO: Test & doc + pub fn prune_old(&mut self, current_time: NaiveDateTime) { self.ongoing_events.clear(); + unimplemented!() + } + + /// Add a new event + /// TODO: Test & doc + pub(crate) fn add_event(&mut self, id: Uuid, event: Event) { + self.ongoing_events.insert(id, event); } } @@ -145,17 +177,26 @@ pub static ONGOING_EVENTS: LazyLock> = #[cfg(test)] mod tests { + use chrono::Local; + use super::*; // Test all structs can be safely initialized #[test] + #[ignore] 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(); + PENDING_EVENTS + .lock() + .unwrap() + .process_upcoming(Local::now().naive_local()); + ONGOING_EVENTS + .lock() + .unwrap() + .prune_old(Local::now().naive_local()); } } diff --git a/src/watchdog.rs b/src/watchdog.rs index 658627e..037fd93 100644 --- a/src/watchdog.rs +++ b/src/watchdog.rs @@ -42,17 +42,25 @@ async fn main_scheduler_loop(mut interval: tokio::time::Interval) { /// 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) { // 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(); + PENDING_EVENTS + .lock() + .unwrap() + .process_upcoming(current_time.naive_local()); // Execute all scheduled tasks // * Clean old events if a new day passed if is_new_day { - ONGOING_EVENTS.lock().unwrap().prune_old(); + ONGOING_EVENTS + .lock() + .unwrap() + .prune_old(current_time.naive_local()); } + + // TODO: Save global state } /// A lazily-initialized, thread-safe storage for the previous day's date. @@ -86,7 +94,7 @@ mod tests { use super::*; #[test] - fn test_initialisation() { + fn initialisation() { assert!(OLD_DATE.lock().is_ok()); let date = Local::now().date_naive(); update_date(date); @@ -94,13 +102,21 @@ mod tests { } #[test] - fn test_update() { - // TODO: Fill this test as the update functions are filled + #[ignore] + 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); + + todo!("Fill this test as the update functions are filled") + } + + #[test] + #[ignore] + fn watchdog_autosave() { + unimplemented!() } } -- 2.45.1 From 7761751eae8e73f08c2be8ea8a893eaef3dc1878 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 6 Nov 2024 02:15:10 +0100 Subject: [PATCH 2/3] Adds a lot of test and docs and some of the votes/watchdog implementations --- badges/coverage.svg | 2 +- src/error_handling.rs | 16 +++++ src/votes.rs | 163 ++++++++++++++++++++++++++++++++---------- src/watchdog.rs | 40 +++++++++-- 4 files changed, 177 insertions(+), 44 deletions(-) diff --git a/badges/coverage.svg b/badges/coverage.svg index 5bcb4dd..d0fe343 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 68%test-coverage68% +test-coverage: 78%test-coverage78% diff --git a/src/error_handling.rs b/src/error_handling.rs index 9e4c343..bd0ff6f 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -9,6 +9,7 @@ use chrono::Month; use log::SetLoggerError; use poise::serenity_prelude; use thiserror::Error; +use uuid::Uuid; // // Since the errors themselves are very verbose, this seemed like complete overkill // #[allow(clippy::missing_docs_in_private_items)] @@ -51,6 +52,21 @@ pub enum IdleError { /// It may indicate that the file reader is read-only, and manual intervention will be required to resolve the problem. #[error("An error occurred while initializing the logger: {0}")] LoggerInitFailure(#[from] SetLoggerError), + + /// Indicates an event couldn't be launched + /// + /// Raised when there's an issue launching an event usually indicates something went wrong with bookeeping. + /// Note that while a UUID is given, it may no longer exist in memory and might only be found in logs. + #[error("An event couldn't be launched (Id: {0})")] + EventLaunch(Uuid), + + /// Error indicating multiple events couldn't be pruned + /// + /// Raised when one or more events cannot be removed from the ongoing events list. + /// This usually indicates a problem with managing and updating the list of ongoing events. + /// Note that while a UUID is given, it may no longer exist in memory and might only be found in logs. + #[error("One or more events couldn't be removed from the ongoing events list (Id(s): {0:?})")] + EventPrune(Vec), } impl From>> for IdleError { diff --git a/src/votes.rs b/src/votes.rs index c5a90ab..ac00e19 100644 --- a/src/votes.rs +++ b/src/votes.rs @@ -18,11 +18,11 @@ use std::{ sync::{LazyLock, Mutex}, }; -use chrono::NaiveDateTime; +use chrono::{Months, NaiveDateTime, TimeDelta}; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use crate::date::date_tools::NaiveDateList; +use crate::{date::date_tools::NaiveDateList, error_handling::IdleError}; /// Placeholder datatype /// @@ -71,7 +71,7 @@ pub(crate) enum EventStatus { /// An event, wether ongoing or planned #[derive(Serialize, Deserialize, Default)] -pub(crate) struct Event { +pub(crate) struct MockEvent { /// The title of the even title: String, /// Description of the event @@ -81,18 +81,32 @@ pub(crate) struct Event { /// Date at which to autostart the vote process launch_date: NaiveDateTime, /// Date at which to autoclose the vote process + // TODO: this option is useless, we need a time to close the votes anyway, just fill it to launch+12months or something smarter close_date: Option, /// The inner list of votes cast votes: Vec, /// The list of values to vote for, this list all the valid dates to vote for vote_values: NaiveDateList, } +impl MockEvent { + /// All the logic behind a vote becoming live + fn launch(&mut self, id: Uuid) -> Result<(), IdleError> { + let _ = id; + // TODO: Define this + self.status = EventStatus::Started; + // Maybe send a message ? the bot will need the Uuid of the event to be able to add reaction + // TODO: This is a vkypoint, as this method will need an IO interaction + Ok(()) + } +} // This split in two differents structs conceptually represents // the fact that very differents actions will be performed for each struct -type EventListType = HashMap; +type EventListType = HashMap; -/// The list of pending events, not yet started +// The list of pending events, not yet started +/// +/// This struct represents the collection of events that have been scheduled but have not yet begun. #[derive(Serialize, Deserialize)] pub(crate) struct PendingEvents { /// The list of pending events @@ -100,34 +114,52 @@ pub(crate) struct PendingEvents { } impl PendingEvents { - /// Create a new empty list of events, called in case of a first initialization + /// Create a new empty list of events, called in case of a first initialization. /// - /// However a deserialization will always be performed if possible + /// However, a deserialization will always be performed if possible. fn new() -> Self { Self { pending_events: EventListType::new(), } } - /// Process and activate all upcomming events if the auto launch time was reached - /// TODO: Test & doc - pub fn process_upcoming(&mut self, current_time: NaiveDateTime) { - self.pending_events.insert(Uuid::new_v4(), Event::default()); - let upcomming = self.find_upcomming(current_time); - - for uuid in upcomming { - let event = self.pending_events.remove(&uuid).unwrap(); - ONGOING_EVENTS.lock().unwrap().add_event(uuid, event); - } + /// Add a new event to the list of upcoming events. + /// + /// This function generates a new UUID for the event before adding it to the list. + fn add_future_event(&mut self, event: MockEvent) { + self.pending_events.insert(Uuid::new_v4(), event); } - // fn launch(&self, event: Event) -> Result<(), IdleError> { - // todo!() - // } + /// Process and activate all upcoming events if the auto-launch time has been reached. + /// + /// Returns an `IdleError` if there's an issue launching any event or adding it to the ongoing list. + pub fn process_upcoming(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> { + self.pending_events + .insert(Uuid::new_v4(), MockEvent::default()); + self.find_upcoming(current_time) + .iter() + .try_for_each(|uuid| { + self.launch(*uuid)?; + Ok(()) + }) + } - /// Find all event that are bound to be launched - /// TODO: Test & doc - fn find_upcomming(&self, current_time: NaiveDateTime) -> Vec { + /// Launch the specified event by moving it from pending events to ongoing events. + /// + /// Returns an `IdleError` if the event cannot be found in pending events. + fn launch(&mut self, uuid: Uuid) -> Result<(), IdleError> { + let event = self + .pending_events + .remove(&uuid) + .ok_or(IdleError::EventLaunch(uuid))?; + ONGOING_EVENTS.lock().unwrap().add_event(uuid, event)?; + Ok(()) + } + + /// Find all events that are scheduled to start before the given current time. + /// + /// Returns a vector of UUIDs corresponding to the upcoming events. + fn find_upcoming(&self, current_time: NaiveDateTime) -> Vec { self.pending_events .iter() .filter(|&(_, e)| e.launch_date > current_time) @@ -137,6 +169,8 @@ impl PendingEvents { } /// The list of ongoing events, not yet closed +/// +/// This struct represents the collection of events that have been initiated but have not yet concluded. #[derive(Serialize, Deserialize)] pub(crate) struct OngoingEvents { /// The list of ongoing events @@ -144,27 +178,60 @@ pub(crate) struct OngoingEvents { } impl OngoingEvents { - /// Create a new empty list of ongoing events, called in case of a first initialization + /// Create a new empty list of ongoing events, called in case of a first initialization. /// - /// However a deserialisation will always be performed if possible + /// However, a deserialization will always be performed if possible. fn new() -> Self { Self { ongoing_events: EventListType::new(), } } - /// Prune all outdated votes + /// Remove all outdated votes for the current user /// - /// TODO: Test & doc - pub fn prune_old(&mut self, current_time: NaiveDateTime) { - self.ongoing_events.clear(); - unimplemented!() + /// This function is expected to be called periodically by the watchdog. + pub(crate) fn prune_old(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> { + let mut failure = Vec::new(); + for uuid in self.find_old(current_time) { + if self.ongoing_events.remove(&uuid).is_none() { + failure.push(uuid); + } + } + match failure.is_empty() { + true => Ok(()), + false => Err(IdleError::EventPrune(failure)), + } + // self.find_old(current_time).iter().try_for_each(|uuid| { + // self.ongoing_events + // .remove(uuid) + // .ok_or(IdleError::EventLaunch(*uuid))?; + // Ok(()) + // }) } - /// Add a new event - /// TODO: Test & doc - pub(crate) fn add_event(&mut self, id: Uuid, event: Event) { + /// Find all events that are scheduled to start more than 3 days ago from the given current time. + /// + /// Returns a vector of UUIDs corresponding to the old events. + fn find_old(&mut self, current_time: NaiveDateTime) -> Vec { + self.ongoing_events + .iter() + .filter(|(_, e)| { + e.close_date + .unwrap_or(e.launch_date.checked_add_months(Months::new(12)).unwrap()) + .signed_duration_since(current_time) + > TimeDelta::days(3) + }) + .map(|(k, _)| *k) + .collect() + } + + /// Add a new event to the list of ongoing events. + /// + /// This function also launch the event based and adds a callback with the Uuid of the original caller. + pub(crate) fn add_event(&mut self, id: Uuid, mut event: MockEvent) -> Result<(), IdleError> { + event.launch(id)?; self.ongoing_events.insert(id, event); + Ok(()) } } @@ -190,13 +257,35 @@ mod tests { assert!(PENDING_EVENTS.lock().is_ok()); assert!(ONGOING_EVENTS.lock().is_ok()); - PENDING_EVENTS + assert!(PENDING_EVENTS .lock() .unwrap() - .process_upcoming(Local::now().naive_local()); - ONGOING_EVENTS + .process_upcoming(Local::now().naive_local()) + .is_ok()); + assert!(ONGOING_EVENTS .lock() .unwrap() - .prune_old(Local::now().naive_local()); + .prune_old(Local::now().naive_local()) + .is_ok()); + } + + #[test] + #[ignore] + fn test_launch() { + assert!(MockEvent::default().launch(Uuid::new_v4()).is_ok()); + } + + #[test] + #[ignore] + fn test_upcomming_events() { + let e = MockEvent::default(); + // e.launch_date = NaiveDateTime + // ; PENDING_EVENTS.lock().unwrap().add_future_event(e) + } + + #[test] + #[ignore] + fn test_ongoing_events() { + unimplemented!() } } diff --git a/src/watchdog.rs b/src/watchdog.rs index 037fd93..176a9d4 100644 --- a/src/watchdog.rs +++ b/src/watchdog.rs @@ -47,17 +47,29 @@ 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 + if let Err(e) = PENDING_EVENTS .lock() .unwrap() - .process_upcoming(current_time.naive_local()); + .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 { - ONGOING_EVENTS + if let Err(e) = ONGOING_EVENTS .lock() .unwrap() - .prune_old(current_time.naive_local()); + .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 @@ -102,7 +114,6 @@ mod tests { } #[test] - #[ignore] fn test_watchdog_update() { let date = Local::now(); watchdog_update(date); @@ -110,13 +121,30 @@ mod tests { assert!(update_date(date2.date_naive())); let date2 = date.checked_add_days(Days::new(14)).unwrap(); watchdog_update(date2); + } - todo!("Fill this test as the update functions are filled") + #[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!() } } -- 2.45.1 From 5f996b26e3154cb3ad8187f7fb3bf9d4ad86a112 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 6 Nov 2024 18:17:06 +0100 Subject: [PATCH 3/3] Adds a lot of testing and examples --- badges/coverage.svg | 2 +- src/date/date_tools.rs | 2 +- src/error_handling.rs | 21 +++ src/lib.rs | 9 +- src/main.rs | 12 +- src/votes.rs | 312 ++++++++++++++++++++++++++++++++++++----- src/watchdog.rs | 2 +- tests/generic.rs | 9 +- 8 files changed, 322 insertions(+), 47 deletions(-) diff --git a/badges/coverage.svg b/badges/coverage.svg index d0fe343..2dcfcbe 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 78%test-coverage78% +test-coverage: 93%test-coverage93% diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs index bafa332..3f81999 100644 --- a/src/date/date_tools.rs +++ b/src/date/date_tools.rs @@ -155,7 +155,7 @@ pub enum NaiveDateObject { /// over the dates in order or direct access to any date by its index. The structure is designed to handle /// different sources of date information, allowing for flexible data manipulation based on the provided dates. #[derive(Debug, Default, Serialize, Deserialize)] -#[cfg_attr(test, derive(PartialEq))] +#[cfg_attr(test, derive(PartialEq, Clone))] pub struct NaiveDateList { /// The inner vector inner: Vec, diff --git a/src/error_handling.rs b/src/error_handling.rs index bd0ff6f..04010cc 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -67,6 +67,27 @@ pub enum IdleError { /// Note that while a UUID is given, it may no longer exist in memory and might only be found in logs. #[error("One or more events couldn't be removed from the ongoing events list (Id(s): {0:?})")] EventPrune(Vec), + + /// Error indicating an event could not be deleted + /// + /// This error is raised when attempting to delete an event fails, + /// either due to a problem with bookkeping or because the specified UUID + /// does not correspond to any existing events anymore. + #[error("An event couldn't be deleted (Id: {0})")] + DeleteEvent(Uuid), + + /// Error indicating that an ongoing event launch couldn't be performed + /// + /// This error was likely raised as a launch operation for an event was already underway. + /// Launching multiple times for the same event may lead to inconsistent states or data corruption. + #[error("Couldn't launch event (Id: {0})")] + LaunchingEvent(Uuid), + + /// Error indicating a mutex was poisoned or couldn't be acquired + /// + /// This is likely due to a thread being terminated but could also arise from a deadlock or a subtle race condition + #[error("An error happened while trying to acquire a mutex")] + MutexError, } impl From>> for IdleError { diff --git a/src/lib.rs b/src/lib.rs index f04cbe3..7294c63 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,7 +16,12 @@ pub mod io; // Maybe in lib mod modules; // Maybe in lib mod persistence; // Likely in lib mod server; // Maybe in lib -mod votes; // Likely in lib +pub mod votes; // Likely in lib mod watchdog; // Definitely in lib -// TODO: Make sensible module re-export +// // Re export +// pub use votes::add_future_event; +// pub use votes::launch_future_event; +// +pub use error_handling::IdleError; +pub use watchdog::main_scheduler_loop; diff --git a/src/main.rs b/src/main.rs index 7a6d7a1..1d6afc1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,13 +7,19 @@ use idlefox::config::init_logger; use idlefox::io::discord_main_loop; +use idlefox::main_scheduler_loop; +use tokio::time; // The main loop is untestable #[cfg(not(tarpaulin_include))] #[tokio::main] async fn main() { + use tokio::task; + init_logger().unwrap(); - discord_main_loop().await; - // use date_parse::test_parsing; - // test_parsing(); + // TODO: Check that this is actually what we want + task::spawn(discord_main_loop()); + task::spawn(main_scheduler_loop(time::interval( + time::Duration::from_secs(60 * 10), + ))); } diff --git a/src/votes.rs b/src/votes.rs index ac00e19..37c96d6 100644 --- a/src/votes.rs +++ b/src/votes.rs @@ -9,21 +9,164 @@ //! Note: //! - The types `UserDataType`, `VoteValueType`, and some fields are marked as deprecated and should not be used. //! They are placeholders for the actual data structures which need to be defined correctly. -//! - Some code is commented out, such as test cases, which are currently unused. -//! -#![allow(dead_code, deprecated)] +#![allow(deprecated)] use std::{ collections::HashMap, + fmt::Display, sync::{LazyLock, Mutex}, }; -use chrono::{Months, NaiveDateTime, TimeDelta}; +use chrono::{NaiveDateTime, TimeDelta}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::{date::date_tools::NaiveDateList, error_handling::IdleError}; +// Helper functions, user facing +// Helper functions, user facing + +/// Adds a parsed vote to the list of planned events. +/// +/// This function will use the `PendingEvents` instance to store the provided event. +/// The structure of the input parameter `event` is expected to be a correctly formatted parsed vote. +/// +/// ## Parameters: +/// - `event`: A `ParsedVote` struct representing the details of the event to be scheduled. +/// +/// ## Example: +/// ```rust +/// # use idlefox::votes::{add_pending_event, ParsedVote}; +/// let parsed_vote = ParsedVote::default(); +/// +/// let id = add_pending_event(parsed_vote).unwrap(); +/// ``` +pub fn add_pending_event(event: ParsedVote) -> Result { + PENDING_EVENTS + .lock() + .unwrap() + // .map_err(|_| IdleError::MutexError)? + .add_pending_event(event) +} + +/// Launches a pending event by transferring it from the pending to ongoing events list. +/// +/// This function identifies an event by its UUID and moves it from the planned (pending) events to the ongoing events. If the event is successfully launched, it returns `Ok(())`. Otherwise, it returns an error of type `IdleError`. +/// +/// ## Parameters: +/// - `uuid`: A `Uuid` that uniquely identifies the event to be launched. +/// +/// ## Example: +/// ```rust +/// # use idlefox::votes::{add_pending_event, make_into_ongoing_event, ParsedVote}; +/// let id = add_pending_event(ParsedVote::default()).unwrap(); +/// +/// make_into_ongoing_event(id).unwrap() +/// ``` +pub fn make_into_ongoing_event(uuid: Uuid) -> Result<(), IdleError> { + PENDING_EVENTS + .lock() + .unwrap() + // .map_err(|_| IdleError::MutexError)? + .launch(uuid) +} + +/// Manually adds an ongoing event. +/// +/// This function is intended for internal use and directly adds an event +/// to the list of ongoing events. It expects a UUID and a parsed vote as inputs, +/// using which it updates the `OngoingEvents` instance. +/// +/// ## Parameters: +/// - `uuid`: A `Uuid` that uniquely identifies the event to be added. +/// - `event`: A `ParsedVote` struct representing the details of the ongoing event to be added. +/// +/// ## Example: +/// ```rust +/// # use uuid::Uuid; +/// # use idlefox::votes::{add_ongoing_event, ParsedVote}; +/// let uuid = Uuid::new_v4(); // A new id +/// let parsed_vote = ParsedVote::default(); // A very legit event +/// +/// add_ongoing_event(uuid, parsed_vote).unwrap(); +/// ``` +pub fn add_ongoing_event(uuid: Uuid, event: ParsedVote) -> Result<(), IdleError> { + ONGOING_EVENTS + .lock() + .unwrap() + // .map_err(|_| IdleError::MutexError)? + .add_event(uuid, event)?; + Ok(()) +} + +/// Destroy an event without closing it and officially ending it +/// +/// This function removes an ongoing event from the list of ongoing events. +/// It expects a UUID as input and returns a `Result` containing either a `ParsedVote` +/// struct representing the details of the removed event or an `IdleError`. +/// +/// ## Example: +/// ```rust +/// # use idlefox::votes::{ +/// # add_pending_event, del_ongoing_event, make_into_ongoing_event, ParsedVote, +/// # }; +/// let id = add_pending_event(ParsedVote::default()).unwrap(); +/// make_into_ongoing_event(id).unwrap(); +/// +/// del_ongoing_event(id).unwrap(); +/// ``` +pub fn del_ongoing_event(uuid: Uuid) -> Result { + ONGOING_EVENTS + .lock() + .unwrap() + // .map_err(|_| IdleError::MutexError)? + .del_event(uuid) +} + +/// Destroy a pending event without closing it +/// +/// This function removes a pending event from the list of pending events. +/// It expects a UUID as input and returns a `Result` containing either a `ParsedVote` +/// struct representing the details of the removed event or an `IdleError`. +/// +/// ## Example: +/// ```rust +/// # use idlefox::votes::{ +/// # add_pending_event, del_pending_event, make_into_ongoing_event, ParsedVote, +/// # }; +/// let id = add_pending_event(ParsedVote::default()).unwrap(); +/// del_pending_event(id).unwrap(); +/// ``` +pub fn del_pending_event(uuid: Uuid) -> Result { + PENDING_EVENTS + .lock() + .unwrap() + // .map_err(|_| IdleError::MutexError)? + .del_event(uuid) +} + +/// This function is used to close an ongoing event and return the parsed vote associated with it. If the closure is successful, the owned event is returned for post-treatment. +/// # Arguments +/// +/// * `uuid` - A Uuid representing the identifier of the event that is to be closed. +/// +/// ## Example: +/// ```rust +/// # use idlefox::votes::{ +/// # add_pending_event, close_ongoing_event, make_into_ongoing_event, ParsedVote, +/// # }; +/// let id = add_pending_event(ParsedVote::default()).unwrap(); +/// make_into_ongoing_event(id).unwrap(); +/// close_ongoing_event(id).unwrap(); +/// ``` +pub fn close_ongoing_event(uuid: Uuid) -> Result { + ONGOING_EVENTS + .lock() + .unwrap() + // .map_err(|_| IdleError::MutexError)? + .close_event(uuid) +} + /// Placeholder datatype /// /// Links to an event, active or planned @@ -36,12 +179,13 @@ type EventDataType = Uuid; type UserDataType = String; /// What an user voted for -#[deprecated(note = "This is an incorrect type to define a vote")] +#[deprecated(note = "This is an incorrect type to define a voting ballot")] type VoteValueType = String; /// A vote, represents a user interraction towards an event -#[derive(Serialize, Deserialize)] -pub(crate) struct Vote { +#[derive(Serialize, Deserialize, Debug)] +#[cfg_attr(test, derive(Clone))] +pub(crate) struct Ballot { /// The event the vote refers to linked_event: EventDataType, /// The user casting the vote @@ -50,11 +194,8 @@ pub(crate) struct Vote { vote_value: VoteValueType, } -/// Data type representing a date -type DateDataType = String; - /// The global status of the event -#[derive(Serialize, Deserialize, Default)] +#[derive(Serialize, Deserialize, Default, Debug, Clone, Copy)] pub(crate) enum EventStatus { #[default] /// The event exists but wasn't started yet @@ -70,8 +211,9 @@ pub(crate) enum EventStatus { } /// An event, wether ongoing or planned -#[derive(Serialize, Deserialize, Default)] -pub(crate) struct MockEvent { +#[derive(Debug, Serialize, Deserialize, Default)] +#[cfg_attr(test, derive(Clone))] +pub struct ParsedVote { /// The title of the even title: String, /// Description of the event @@ -81,14 +223,29 @@ pub(crate) struct MockEvent { /// Date at which to autostart the vote process launch_date: NaiveDateTime, /// Date at which to autoclose the vote process - // TODO: this option is useless, we need a time to close the votes anyway, just fill it to launch+12months or something smarter - close_date: Option, + close_date: NaiveDateTime, /// The inner list of votes cast - votes: Vec, + votes: Vec, /// The list of values to vote for, this list all the valid dates to vote for - vote_values: NaiveDateList, + list_candidates: NaiveDateList, + // / The vote type } -impl MockEvent { + +impl ParsedVote { + // #[allow(dead_code, unused_variables)] + // pub(crate) fn new( + // title: String, + // description: String, + // status: EventStatus, + // launch_date: NaiveDateTime, + // close_date: NaiveDateTime, + // // ballots: Vec, + // list_candidates: NaiveDateList, + // ) -> Self { + // // Have a rather smart close date if not specified + // todo!() + // } + /// All the logic behind a vote becoming live fn launch(&mut self, id: Uuid) -> Result<(), IdleError> { let _ = id; @@ -100,15 +257,29 @@ impl MockEvent { } } +// impl From for ParsedVote { +// fn from(value: VoteContainer) -> Self { +// todo!() +// } +// } + +impl Display for ParsedVote { + /// A display for a vote, it is exactly what the discord bot will send + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // TODO: Complete this (vky) + write!(f, "{:?}", self) + } +} + // This split in two differents structs conceptually represents // the fact that very differents actions will be performed for each struct -type EventListType = HashMap; +type EventListType = HashMap; // The list of pending events, not yet started /// /// This struct represents the collection of events that have been scheduled but have not yet begun. #[derive(Serialize, Deserialize)] -pub(crate) struct PendingEvents { +pub struct PendingEvents { /// The list of pending events pending_events: EventListType, } @@ -126,8 +297,10 @@ impl PendingEvents { /// Add a new event to the list of upcoming events. /// /// This function generates a new UUID for the event before adding it to the list. - fn add_future_event(&mut self, event: MockEvent) { - self.pending_events.insert(Uuid::new_v4(), event); + fn add_pending_event(&mut self, event: ParsedVote) -> Result { + let id = Uuid::new_v4(); + self.pending_events.insert(id, event); + Ok(id) } /// Process and activate all upcoming events if the auto-launch time has been reached. @@ -135,7 +308,7 @@ impl PendingEvents { /// Returns an `IdleError` if there's an issue launching any event or adding it to the ongoing list. pub fn process_upcoming(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> { self.pending_events - .insert(Uuid::new_v4(), MockEvent::default()); + .insert(Uuid::new_v4(), ParsedVote::default()); self.find_upcoming(current_time) .iter() .try_for_each(|uuid| { @@ -152,7 +325,8 @@ impl PendingEvents { .pending_events .remove(&uuid) .ok_or(IdleError::EventLaunch(uuid))?; - ONGOING_EVENTS.lock().unwrap().add_event(uuid, event)?; + add_ongoing_event(uuid, event)?; + // make_into_ongoing_event(uuid)?; Ok(()) } @@ -166,17 +340,24 @@ impl PendingEvents { .map(|(k, _v)| (*k)) .collect() } + /// delete the event without launching it + pub fn del_event(&mut self, uuid: Uuid) -> Result { + self.pending_events + .remove(&uuid) + .ok_or(IdleError::DeleteEvent(uuid)) + } } /// The list of ongoing events, not yet closed /// /// This struct represents the collection of events that have been initiated but have not yet concluded. #[derive(Serialize, Deserialize)] -pub(crate) struct OngoingEvents { +pub struct OngoingEvents { /// The list of ongoing events ongoing_events: EventListType, } +#[allow(dead_code, unused_variables)] impl OngoingEvents { /// Create a new empty list of ongoing events, called in case of a first initialization. /// @@ -215,12 +396,7 @@ impl OngoingEvents { fn find_old(&mut self, current_time: NaiveDateTime) -> Vec { self.ongoing_events .iter() - .filter(|(_, e)| { - e.close_date - .unwrap_or(e.launch_date.checked_add_months(Months::new(12)).unwrap()) - .signed_duration_since(current_time) - > TimeDelta::days(3) - }) + .filter(|(_, e)| e.close_date.signed_duration_since(current_time) > TimeDelta::days(3)) .map(|(k, _)| *k) .collect() } @@ -228,11 +404,29 @@ impl OngoingEvents { /// Add a new event to the list of ongoing events. /// /// This function also launch the event based and adds a callback with the Uuid of the original caller. - pub(crate) fn add_event(&mut self, id: Uuid, mut event: MockEvent) -> Result<(), IdleError> { + pub(crate) fn add_event(&mut self, id: Uuid, mut event: ParsedVote) -> Result<(), IdleError> { event.launch(id)?; self.ongoing_events.insert(id, event); Ok(()) } + /// delete the event without launching it + pub fn del_event(&mut self, uuid: Uuid) -> Result { + self.ongoing_events + .remove(&uuid) + .ok_or(IdleError::DeleteEvent(uuid)) + } + + /// Close an event removing it from the ongoing event list + pub fn close_event(&mut self, uuid: Uuid) -> Result { + // TODO: Another vkypoint, as we cant continue without knowing how to send a message + let event = self + .ongoing_events + .remove(&uuid) + .ok_or(IdleError::LaunchingEvent(uuid))?; + let str_event = event.to_string(); + // TODO: Do something with this string + Ok(event) + } } /// The thread safe list of pending events @@ -250,7 +444,6 @@ mod tests { // Test all structs can be safely initialized #[test] - #[ignore] fn init_test() { let _e = PendingEvents::new(); let _o = OngoingEvents::new(); @@ -270,17 +463,60 @@ mod tests { } #[test] - #[ignore] - fn test_launch() { - assert!(MockEvent::default().launch(Uuid::new_v4()).is_ok()); + fn test_base_vote_handling() { + // assert!(ParsedVote::default().launch(Uuid::new_v4()).is_ok()); + let ev = ParsedVote::default(); + + // Can we add a vote ? + let id = add_pending_event(ev.clone()).unwrap(); + assert!(PENDING_EVENTS + .lock() + .unwrap() + .pending_events + .contains_key(&id)); // Is the vote present ? + del_pending_event(id).unwrap(); + assert!(!PENDING_EVENTS + .lock() + .unwrap() + .pending_events + .contains_key(&id)); // Is the vote now deleted + + let id = add_pending_event(ev.clone()).unwrap(); + make_into_ongoing_event(id).unwrap(); // Launching this event + assert!(!PENDING_EVENTS + .lock() + .unwrap() + .pending_events + .contains_key(&id)); // Is the vote now not pending + assert!(ONGOING_EVENTS + .lock() + .unwrap() + .ongoing_events + .contains_key(&id)); // Is the vote now ongoing + + close_ongoing_event(id).unwrap(); + assert!(!ONGOING_EVENTS + .lock() + .unwrap() + .ongoing_events + .contains_key(&id)); // Is the vote now not ongoing + + let id = add_pending_event(ev.clone()).unwrap(); + make_into_ongoing_event(id).unwrap(); // Launching this event + del_ongoing_event(id).unwrap(); + assert!(!ONGOING_EVENTS + .lock() + .unwrap() + .ongoing_events + .contains_key(&id)); // Is the vote now not ongoing } #[test] #[ignore] fn test_upcomming_events() { - let e = MockEvent::default(); + let _e = ParsedVote::default(); // e.launch_date = NaiveDateTime - // ; PENDING_EVENTS.lock().unwrap().add_future_event(e) + // ; PENDING_EVENTS.lock().unwrap().add_pending_event(e) } #[test] diff --git a/src/watchdog.rs b/src/watchdog.rs index 176a9d4..c10fa6a 100644 --- a/src/watchdog.rs +++ b/src/watchdog.rs @@ -27,7 +27,7 @@ use crate::votes::{ONGOING_EVENTS, PENDING_EVENTS}; /// 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) { +pub async fn main_scheduler_loop(mut interval: tokio::time::Interval) { loop { interval.tick().await; // tokio::spawn(async {watchdog_update().await;}); // For async task diff --git a/tests/generic.rs b/tests/generic.rs index 06eec6e..3de57d5 100644 --- a/tests/generic.rs +++ b/tests/generic.rs @@ -1,6 +1,13 @@ #[cfg(test)] mod tests { + use idlefox::votes::{ + add_pending_event, close_ongoing_event, make_into_ongoing_event, ParsedVote, + }; #[test] - fn generic_integration_test() {} + fn generic_integration_test() { + let id = add_pending_event(ParsedVote::default()).unwrap(); + make_into_ongoing_event(id).unwrap(); + close_ongoing_event(id).unwrap(); + } } -- 2.45.1