From 6780a56abed55f2cb85b1a4c05eb30d9cef0d88c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 6 Nov 2024 18:17:06 +0100 Subject: [PATCH] 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(); + } }