Adds some logic on the votes and watchdog #23

Merged
Dandaedre merged 3 commits from dan into dev 2024-11-06 18:17:47 +01:00
14 changed files with 532 additions and 58 deletions

View File

@ -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

View File

@ -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.

1
badges/coverage.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 93%"><title>test-coverage: 93%</title><linearGradient id="bms-20996527e2156024" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-20996527e2156024"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-20996527e2156024)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-20996527e2156024)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">93%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">93%</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="94" height="18" role="img" aria-label="release: v0.1.0"><title>release: v0.1.0</title><linearGradient id="bms-162829b957040378" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-162829b957040378"><rect width="94" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-162829b957040378)"><rect width="49" height="18" fill="#555"/><rect x="49" width="45" height="18" fill="#fe7d37"/><rect width="94" height="18" fill="url(#bms-162829b957040378)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="255" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="390">release</text><text x="255" y="130" transform="scale(.1)" fill="#fff" textLength="390">release</text><text aria-hidden="true" x="705" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="350">v0.1.0</text><text x="705" y="130" transform="scale(.1)" fill="#fff" textLength="350">v0.1.0</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="88" height="18" role="img" aria-label="build: passing"><title>build: passing</title><linearGradient id="bms-de44f1c0747536f7" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-de44f1c0747536f7"><rect width="88" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-de44f1c0747536f7)"><rect width="37" height="18" fill="#555"/><rect x="37" width="51" height="18" fill="#97ca00"/><rect width="88" height="18" fill="url(#bms-de44f1c0747536f7)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="195" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="270">build</text><text x="195" y="130" transform="scale(.1)" fill="#fff" textLength="270">build</text><text aria-hidden="true" x="615" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="615" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="130" height="18" role="img" aria-label="test-coverage: 100%"><title>test-coverage: 100%</title><linearGradient id="bms-0d308125ce4bf4b9" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-0d308125ce4bf4b9"><rect width="130" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-0d308125ce4bf4b9)"><rect width="87" height="18" fill="#555"/><rect x="87" width="43" height="18" fill="#97ca00"/><rect width="130" height="18" fill="url(#bms-0d308125ce4bf4b9)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1075" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="330">100%</text><text x="1075" y="130" transform="scale(.1)" fill="#fff" textLength="330">100%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/version.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="18" role="img" aria-label="version: 0.1.0"><title>version: 0.1.0</title><linearGradient id="bms-0431e50b7af7883f" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-0431e50b7af7883f"><rect width="90" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-0431e50b7af7883f)"><rect width="51" height="18" fill="#555"/><rect x="51" width="39" height="18" fill="#fe7d37"/><rect width="90" height="18" fill="url(#bms-0431e50b7af7883f)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="695" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="290">0.1.0</text><text x="695" y="130" transform="scale(.1)" fill="#fff" textLength="290">0.1.0</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -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, Clone))]
pub struct NaiveDateList {
/// The inner vector
inner: Vec<NaiveDateObject>,
@ -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());
}
}

View File

@ -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,42 @@ 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<Uuid>),
/// 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<nom::Err<nom::error::Error<&str>>> for IdleError {

View File

@ -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;

View File

@ -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),
)));
}

View File

@ -9,19 +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::NaiveDateTime;
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<Uuid, IdleError> {
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<ParsedVote, IdleError> {
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<ParsedVote, IdleError> {
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<ParsedVote, IdleError> {
ONGOING_EVENTS
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.close_event(uuid)
}
/// Placeholder datatype
///
/// Links to an event, active or planned
@ -34,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
@ -48,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
@ -68,8 +211,9 @@ pub(crate) enum EventStatus {
}
/// An event, wether ongoing or planned
#[derive(Serialize, Deserialize, Default)]
pub(crate) struct Event {
#[derive(Debug, Serialize, Deserialize, Default)]
#[cfg_attr(test, derive(Clone))]
pub struct ParsedVote {
/// The title of the even
title: String,
/// Description of the event
@ -79,60 +223,209 @@ 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<DateDataType>,
close_date: NaiveDateTime,
/// The inner list of votes cast
votes: Vec<Vote>,
votes: Vec<Ballot>,
/// The list of values to vote for, this list all the valid dates to vote for
vote_values: Vec<DateDataType>,
list_candidates: NaiveDateList,
// / The vote type
}
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<Ballot>,
// 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;
// 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(())
}
}
// impl From<VoteContainer> 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<Uuid, Event>;
type EventListType = HashMap<Uuid, ParsedVote>;
/// 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 {
pub struct PendingEvents {
/// The list of pending events
pending_events: EventListType,
}
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(),
}
}
/// Run all upcomming events if the auto launch time was reached
pub fn run_upcoming(&mut self) {
self.pending_events.insert(Uuid::new_v4(), Event::default());
/// 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_pending_event(&mut self, event: ParsedVote) -> Result<Uuid, IdleError> {
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.
///
/// 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(), ParsedVote::default());
self.find_upcoming(current_time)
.iter()
.try_for_each(|uuid| {
self.launch(*uuid)?;
Ok(())
})
}
/// 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))?;
add_ongoing_event(uuid, event)?;
// make_into_ongoing_event(uuid)?;
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<Uuid> {
self.pending_events
.iter()
.filter(|&(_, e)| e.launch_date > current_time)
.map(|(k, _v)| (*k))
.collect()
}
/// delete the event without launching it
pub fn del_event(&mut self, uuid: Uuid) -> Result<ParsedVote, IdleError> {
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
/// 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
pub fn prune_old(&mut self) {
self.ongoing_events.clear();
/// Remove all outdated votes for the current user
///
/// 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(())
// })
}
/// 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<Uuid> {
self.ongoing_events
.iter()
.filter(|(_, e)| e.close_date.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: 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<ParsedVote, IdleError> {
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<ParsedVote, IdleError> {
// 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)
}
}
@ -145,6 +438,8 @@ pub static ONGOING_EVENTS: LazyLock<Mutex<OngoingEvents>> =
#[cfg(test)]
mod tests {
use chrono::Local;
use super::*;
// Test all structs can be safely initialized
@ -155,7 +450,78 @@ mod tests {
assert!(PENDING_EVENTS.lock().is_ok());
assert!(ONGOING_EVENTS.lock().is_ok());
PENDING_EVENTS.lock().unwrap().run_upcoming();
ONGOING_EVENTS.lock().unwrap().prune_old();
assert!(PENDING_EVENTS
.lock()
.unwrap()
.process_upcoming(Local::now().naive_local())
.is_ok());
assert!(ONGOING_EVENTS
.lock()
.unwrap()
.prune_old(Local::now().naive_local())
.is_ok());
}
#[test]
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 = ParsedVote::default();
// e.launch_date = NaiveDateTime
// ; PENDING_EVENTS.lock().unwrap().add_pending_event(e)
}
#[test]
#[ignore]
fn test_ongoing_events() {
unimplemented!()
}
}

View File

@ -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
@ -42,17 +42,37 @@ 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<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
PENDING_EVENTS.lock().unwrap().run_upcoming();
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 {
ONGOING_EVENTS.lock().unwrap().prune_old();
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.
@ -86,7 +106,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,8 +114,7 @@ mod tests {
}
#[test]
fn test_update() {
// TODO: Fill this test as the update functions are filled
fn test_watchdog_update() {
let date = Local::now();
watchdog_update(date);
let date2 = date.checked_add_days(Days::new(12)).unwrap();
@ -103,4 +122,29 @@ mod tests {
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!()
}
}

View File

@ -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();
}
}