diff --git a/badges/coverage.svg b/badges/coverage.svg
index 5bcb4dd..d0fe343 100644
--- a/badges/coverage.svg
+++ b/badges/coverage.svg
@@ -1 +1 @@
-
+
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!()
}
}