From e1796201137c63b248227f482cc77b918cc0cabc Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 1 Dec 2024 18:42:52 +0100 Subject: [PATCH 1/5] Adds a mock of (untested) persistence --- badges/coverage.svg | 2 +- src/error_handling.rs | 6 +++++ src/persistence.rs | 30 +++++++++++++++++++++ src/server.rs | 4 +++ src/votes/helper_functions.rs | 51 ++++++++++++++++++++++++++++++++--- src/votes/holders.rs | 3 +++ 6 files changed, 91 insertions(+), 5 deletions(-) diff --git a/badges/coverage.svg b/badges/coverage.svg index ead59f4..b1445c0 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 84%test-coverage84% +test-coverage: 75%test-coverage75% diff --git a/src/error_handling.rs b/src/error_handling.rs index df41160..db3828c 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -103,6 +103,12 @@ pub enum IdleError { /// This error will happen when an incorrect string is sent to a command invocation #[error("An error occured while trying to parse a Discord command")] DiscordContainerParse, + /// Indicate a backup coouldn't be done, usually means the file descriptor is busy or permission are incorrect + #[error("An error occured while trying to save file {0}")] + BackupError(std::io::Error), + /// Indicate a value couldn't be serialized + #[error("An error occured while trying to serialize data {0}")] + SerdeError(serde_json::Error), } impl From>> for IdleError { diff --git a/src/persistence.rs b/src/persistence.rs index 9604417..1590d73 100644 --- a/src/persistence.rs +++ b/src/persistence.rs @@ -6,6 +6,36 @@ //! //! +use crate::IdleError; +use serde::{de::DeserializeOwned, Serialize}; +use std::{fs::File, io::Write, path::Path}; + +/// Tries to load the list of pending events from disk or return a default (empty) list +pub(crate) fn load_from_disk(path: &str) -> T +where + T: Default + DeserializeOwned, +{ + match File::open(&path) { + Ok(f) => serde_json::from_reader(f).unwrap_or_default(), + Err(_) => T::default(), + } +} + +/// Tries to save the list to disk and return an error on failure +pub(crate) fn save_to_disk(data: T, path: &str) -> Result<(), IdleError> +where + T: Serialize, +{ + let mut f = File::create(path).map_err(IdleError::BackupError)?; + f.write( + serde_json::to_string_pretty(&data) + .map_err(IdleError::SerdeError)? + .as_bytes(), + ) + .map_err(IdleError::BackupError)?; + Ok(()) +} + #[cfg(test)] mod tests { // use super::*; diff --git a/src/server.rs b/src/server.rs index c037574..11b3f4a 100644 --- a/src/server.rs +++ b/src/server.rs @@ -4,6 +4,10 @@ //! Show all votes (pending and happening) //! Allow vote closing //! +// warp for creating the API +// Tokio to run an asynchronous server +// Serde to help serialize incoming JSON +// parking_lot to create a ReadWriteLock for your local storage #[cfg(test)] mod tests { diff --git a/src/votes/helper_functions.rs b/src/votes/helper_functions.rs index 9153bd6..fb5486d 100644 --- a/src/votes/helper_functions.rs +++ b/src/votes/helper_functions.rs @@ -1,16 +1,21 @@ //! Submodule including all helper functions to handle vote creation and evolution //! -use std::sync::Arc; - use chrono::NaiveDate; - -use crate::{ids::EventIdType, IdleError}; +use std::{ + ops::{Deref, DerefMut}, + sync::Arc, +}; use super::{ events::{EventOngoing, EventPending}, holders::ListClosedEvents, ListOngoingEvents, ListPendingEvents, }; +use crate::{ + ids::EventIdType, + persistence::{load_from_disk, save_to_disk}, + IdleError, +}; /// Adds a parsed vote to the list of planned events. /// @@ -206,3 +211,41 @@ pub struct EventHolder { /// The newly created discord context pub discord_ctx: Arc>>, } + +impl EventHolder { + pub fn try_load_from_disk() -> Result { + Ok(Self { + pending_events: Arc::new(std::sync::Mutex::new(load_from_disk::( + "data/pending_events.json", + ))), + ongoing_events: Arc::new(std::sync::Mutex::new(load_from_disk::( + "data/ongoin_events.json", + ))), + closed_events: Arc::new(std::sync::Mutex::new(load_from_disk::( + "data/ongoin_events.json", + ))), + old_date: Arc::new(std::sync::Mutex::new(load_from_disk::( + "data/old_date.json", + ))), + ..Default::default() + }) + } + + pub fn try_save_to_disk(holder: EventHolder) -> Result<(), IdleError> { + save_to_disk::<&ListPendingEvents>( + &holder.pending_events.lock().unwrap(), + "data/pending_events.json", + )?; + save_to_disk::<&ListOngoingEvents>( + &holder.ongoing_events.lock().unwrap(), + "data/ongoing_events.json", + )?; + save_to_disk::<&ListPendingEvents>( + &holder.pending_events.lock().unwrap(), + "data/pending_events.json", + )?; + + save_to_disk::<&NaiveDate>(&holder.old_date.lock().unwrap(), "data/old_date.json")?; + Ok(()) + } +} diff --git a/src/votes/holders.rs b/src/votes/holders.rs index 0ba236b..108cc05 100644 --- a/src/votes/holders.rs +++ b/src/votes/holders.rs @@ -11,7 +11,10 @@ //! The module aims to provide a robust framework for managing event lifecycles within an //! application, ensuring separation between pending and ongoing events and supporting //! actions such as adding, launching, processing, and autoclosing events. +use std::{fs::File, io::Write}; + use chrono::NaiveDateTime; +use nom::AsBytes; use serde::{Deserialize, Serialize}; use crate::{ -- 2.45.1 From 53b8f1df3e03805c5a6132b19c125dbffea39a81 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 3 Dec 2024 05:46:59 -0600 Subject: [PATCH 2/5] Adds more persistence tests --- .gitignore | 1 + README.md | 2 +- src/date/date_tools.rs | 2 +- src/error_handling.rs | 9 ++- src/io.rs | 3 +- src/persistence.rs | 102 ++++++++++++++++++++++++++++------ src/votes/ballots.rs | 2 +- src/votes/events.rs | 6 +- src/votes/helper_functions.rs | 56 ++++++++----------- src/votes/holders.rs | 21 ++++--- 10 files changed, 135 insertions(+), 69 deletions(-) diff --git a/.gitignore b/.gitignore index 9dd9bc9..4d3429a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ # will have compiled files and executables debug/ target/ +test/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html diff --git a/README.md b/README.md index 5a86b23..5ce631a 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ IdleFox is a feature-rich Discord bot designed to streamline the process of find - `votes.rs`: Manages event and vote data structures, enabling voting functionality within Discord servers. - `persistence.rs`: Ensures data persistence and integrity between bot runs. - `server.rs`: Provides server-related functionalities, such as displaying votes and closing ongoing votes. -- `modules.rs`: Aggregates various voting logic functions into a single module for easier management and use within the application. This includes decision-making features beyond simple vote counting. +- `modules.rs`: Aggregates various voting logic functions into a single module for easier management and use within the application. This includes decision-making features beyond simple vote counting. - `error_handling.rs`: Handles error reporting and logging, ensuring that any issues encountered by the bot are appropriately recorded and reported. A great emphasis is put on organizing the votes themselves, delaying posting them and editing the answers as time goes. diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs index eeff275..3920ae9 100644 --- a/src/date/date_tools.rs +++ b/src/date/date_tools.rs @@ -149,7 +149,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, Clone))] +#[cfg_attr(test, derive(PartialEq, Eq, Clone))] pub struct NaiveDateList { /// The inner vector inner: Vec, diff --git a/src/error_handling.rs b/src/error_handling.rs index db3828c..0dc55ed 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -103,9 +103,12 @@ pub enum IdleError { /// This error will happen when an incorrect string is sent to a command invocation #[error("An error occured while trying to parse a Discord command")] DiscordContainerParse, - /// Indicate a backup coouldn't be done, usually means the file descriptor is busy or permission are incorrect - #[error("An error occured while trying to save file {0}")] - BackupError(std::io::Error), + /// Indicate a backup write couldn't be done, usually means the file descriptor is busy or permission are incorrect + #[error("An error occured while trying to write file {0}")] + BackupWriteError(std::io::Error), + /// Indicate a backup read couldn't be done, usually means the file descriptor is busy or permission are incorrect + #[error("An error occured while trying to read file {0}")] + BackupReadError(std::io::Error), /// Indicate a value couldn't be serialized #[error("An error occured while trying to serialize data {0}")] SerdeError(serde_json::Error), diff --git a/src/io.rs b/src/io.rs index b607dbe..0817149 100644 --- a/src/io.rs +++ b/src/io.rs @@ -26,7 +26,6 @@ use crate::modules::handler; use crate::votes::EventHolder; use distance::levenshtein; use poise::serenity_prelude::{self as serenity}; - use poise::Modal as _; use crate::error_handling::IdleError; @@ -92,7 +91,7 @@ pub enum VoteTypeIdentifier { WeeklyVote, /// Represents a short-term vote, that can be of any length and can be cast at any time without any form or plan. ShortVote, - /// Represents a long-term vote, where the list of days voted upon extends beyond a week. + /// Represents a long-term vote, where the list of days voted upon extends beyond a week. LongVote, /// Indicates that the vote type has not been set yet, should only be used by default and is not a valid value. #[default] diff --git a/src/persistence.rs b/src/persistence.rs index 1590d73..4c7f877 100644 --- a/src/persistence.rs +++ b/src/persistence.rs @@ -8,35 +8,103 @@ use crate::IdleError; use serde::{de::DeserializeOwned, Serialize}; -use std::{fs::File, io::Write, path::Path}; +use std::io::{Read, Write}; /// Tries to load the list of pending events from disk or return a default (empty) list -pub(crate) fn load_from_disk(path: &str) -> T +pub(crate) fn load_from_reader(rdr: Reader) -> Data where - T: Default + DeserializeOwned, + Data: Default + DeserializeOwned, + Reader: Read + Sized, { - match File::open(&path) { - Ok(f) => serde_json::from_reader(f).unwrap_or_default(), - Err(_) => T::default(), - } + serde_json::from_reader(rdr).unwrap_or_default() +} + +/// Load a struct into an Arc Mutex, mapping errors into BackupError +/// +/// This macro is direct sugarcoating of the load_from_disk macro +#[macro_export] +macro_rules! load_it { + ($r_type:ident, $path:expr) => { + Arc::new(std::sync::Mutex::new(load_from_reader::<$r_type, File>( + File::open($path).map_err(IdleError::BackupReadError)?, + ))) + }; } /// Tries to save the list to disk and return an error on failure -pub(crate) fn save_to_disk(data: T, path: &str) -> Result<(), IdleError> +pub(crate) fn save_to_writer(data: Data, mut writer: Writer) -> Result<(), IdleError> where - T: Serialize, + Data: Serialize, + Writer: Write + Sized, { - let mut f = File::create(path).map_err(IdleError::BackupError)?; - f.write( - serde_json::to_string_pretty(&data) - .map_err(IdleError::SerdeError)? - .as_bytes(), - ) - .map_err(IdleError::BackupError)?; + // let mut f = File::create(wrtr).map_err(IdleError::BackupError)?; + writer + .write( + serde_json::to_string_pretty(&data) + .map_err(IdleError::SerdeError)? + .as_bytes(), + ) + .map_err(IdleError::BackupWriteError)?; Ok(()) } +/// Save a struct behind an Arc Mutex into a file, mapping errors into BackupError +/// +/// This macro is direct sugarcoating of the save_to_writer function +/// +/// # Usage +/// +/// save_it!() +#[macro_export] +macro_rules! save_it { + ($value:expr, $r_type:ident, $path:expr) => { + save_to_writer::<&$r_type, File>( + &$value.lock().unwrap(), + File::create($path).map_err(IdleError::BackupWriteError)?, + )?; + }; +} + #[cfg(test)] mod tests { - // use super::*; + use super::*; + use crate::votes::{EventPending, ListOngoingEvents, ListPendingEvents}; + use std::fs::{create_dir, remove_dir_all, File}; + use std::io::BufWriter; + use std::sync::{Arc, Mutex}; + + #[test] + fn test_serialisation() { + let event_og = ListOngoingEvents::default(); + let mut buffer = BufWriter::new(Vec::new()); + let serialisation = save_to_writer(&event_og, &mut buffer); + assert!(serialisation.is_ok()); + let deserialized_data: ListOngoingEvents = load_from_reader(buffer.buffer()); + assert_eq!(event_og, deserialized_data); + } + + #[test] + fn test_macro_caller() { + test_macros().unwrap() + } + + fn test_macros() -> Result<(), IdleError> { + let event_og = Arc::new(Mutex::new(ListPendingEvents::default())); + { + let mut e = event_og.lock().unwrap(); + println!(" Here {:?}", event_og); + for _ in 0..10 { + e.add_pending_event(EventPending::default())?; + } + } + let _ = remove_dir_all("test"); + let _ = create_dir("test"); + save_it!(&event_og, ListPendingEvents, "test/testwrite.json"); + let event_new = load_it!(ListPendingEvents, "test/testwrite.json"); + assert_eq!( + event_og.lock().unwrap().to_owned(), + event_new.lock().unwrap().to_owned() + ); + Ok(()) + } } diff --git a/src/votes/ballots.rs b/src/votes/ballots.rs index 41b7980..6275c5f 100644 --- a/src/votes/ballots.rs +++ b/src/votes/ballots.rs @@ -11,7 +11,7 @@ use super::{BallotValueType, EventIdType, UserDataType}; /// A `Ballot` represents a user interaction towards an event. This struct is used to record the details of a vote, /// including which user casted it, which event it pertains to, and what value or option was voted for. #[derive(Serialize, Deserialize, Debug)] -#[cfg_attr(test, derive(Clone))] +#[cfg_attr(test, derive(Clone, Eq, PartialEq))] pub struct Ballot { /// The event the vote refers to linked_event: EventIdType, diff --git a/src/votes/events.rs b/src/votes/events.rs index 9eddd6d..84fc634 100644 --- a/src/votes/events.rs +++ b/src/votes/events.rs @@ -28,7 +28,7 @@ use super::Ballot; /// A pending event, waiting to be opened. In this state the even can be safely modified /// and either manual input or the autostart date will start the vote. #[derive(Serialize, Deserialize, Default)] -#[cfg_attr(test, derive(Clone))] +#[cfg_attr(test, derive(Clone, Debug, PartialEq, Eq))] pub struct EventPending { /// The parsed representation of the vote associated with this event. /// It holds the details required for the voting process. @@ -44,7 +44,7 @@ impl EventPending { } #[derive(Serialize, Deserialize)] -#[cfg_attr(test, derive(Clone))] +#[cfg_attr(test, derive(Debug, PartialEq, Clone))] // An ongoing event, waiting to be closed thus allowing the ballots to be counted. pub struct EventOngoing { /// The parsed representation of the vote associated with this event. @@ -87,7 +87,7 @@ pub struct EventClosed { /// ongoing and planned voting events, providing a clear and organized way to manage their /// data throughout their lifecycle. #[derive(Debug, Serialize, Deserialize, Default)] -#[cfg_attr(test, derive(Clone))] +#[cfg_attr(test, derive(Clone, Eq, PartialEq))] pub(super) struct ParsedVote { /// The title of the even pub(super) title: String, diff --git a/src/votes/helper_functions.rs b/src/votes/helper_functions.rs index fb5486d..dbdc0c1 100644 --- a/src/votes/helper_functions.rs +++ b/src/votes/helper_functions.rs @@ -1,10 +1,7 @@ //! Submodule including all helper functions to handle vote creation and evolution //! use chrono::NaiveDate; -use std::{ - ops::{Deref, DerefMut}, - sync::Arc, -}; +use std::{fs::File, sync::Arc}; use super::{ events::{EventOngoing, EventPending}, @@ -13,8 +10,9 @@ use super::{ }; use crate::{ ids::EventIdType, - persistence::{load_from_disk, save_to_disk}, - IdleError, + load_it, + persistence::{load_from_reader, save_to_writer}, + save_it, IdleError, }; /// Adds a parsed vote to the list of planned events. @@ -215,37 +213,31 @@ pub struct EventHolder { impl EventHolder { pub fn try_load_from_disk() -> Result { Ok(Self { - pending_events: Arc::new(std::sync::Mutex::new(load_from_disk::( - "data/pending_events.json", - ))), - ongoing_events: Arc::new(std::sync::Mutex::new(load_from_disk::( - "data/ongoin_events.json", - ))), - closed_events: Arc::new(std::sync::Mutex::new(load_from_disk::( - "data/ongoin_events.json", - ))), - old_date: Arc::new(std::sync::Mutex::new(load_from_disk::( - "data/old_date.json", - ))), + pending_events: load_it!(ListPendingEvents, "data/pending_events.json"), + ongoing_events: load_it!(ListOngoingEvents, "data/ongoin_events.json"), + closed_events: load_it!(ListClosedEvents, "data/closed_events.json"), + old_date: load_it!(NaiveDate, "data/old_date.json"), ..Default::default() }) } pub fn try_save_to_disk(holder: EventHolder) -> Result<(), IdleError> { - save_to_disk::<&ListPendingEvents>( - &holder.pending_events.lock().unwrap(), - "data/pending_events.json", - )?; - save_to_disk::<&ListOngoingEvents>( - &holder.ongoing_events.lock().unwrap(), - "data/ongoing_events.json", - )?; - save_to_disk::<&ListPendingEvents>( - &holder.pending_events.lock().unwrap(), - "data/pending_events.json", - )?; - - save_to_disk::<&NaiveDate>(&holder.old_date.lock().unwrap(), "data/old_date.json")?; + save_it!( + holder.pending_events, + ListPendingEvents, + "data/pending_events.json" + ); + save_it!( + holder.ongoing_events, + ListOngoingEvents, + "data/ongoing_events.json" + ); + save_it!( + holder.closed_events, + ListClosedEvents, + "data/closed_events.json" + ); + save_it!(&holder.old_date, NaiveDate, "data/old_date.json"); Ok(()) } } diff --git a/src/votes/holders.rs b/src/votes/holders.rs index 108cc05..f20b426 100644 --- a/src/votes/holders.rs +++ b/src/votes/holders.rs @@ -11,10 +11,8 @@ //! The module aims to provide a robust framework for managing event lifecycles within an //! application, ensuring separation between pending and ongoing events and supporting //! actions such as adding, launching, processing, and autoclosing events. -use std::{fs::File, io::Write}; use chrono::NaiveDateTime; -use nom::AsBytes; use serde::{Deserialize, Serialize}; use crate::{ @@ -30,8 +28,9 @@ use super::{ /// The list of pending events, not yet started /// -/// This struct represents the collection of events that have been scheduled but have not yet begun. +/// This struct represents the collection of events that have been scheduled but have not yet begun. #[derive(Serialize, Deserialize, Default)] +#[cfg_attr(test, derive(Debug, PartialEq, Clone))] pub struct ListPendingEvents { /// The list of pending events pending_events: PendingHashmap, @@ -41,18 +40,15 @@ impl ListPendingEvents { /// Add a new event to the list of upcoming events. /// /// This function generates a new HUID for the event before adding it to the list. - pub(super) fn add_pending_event( - &mut self, - event: EventPending, - ) -> Result { + pub fn add_pending_event(&mut self, event: EventPending) -> Result { let id = generate_id(); self.pending_events.insert(id.clone(), event); Ok(id) } - /// Process and activate all upcoming events if the auto-launch time has been reached. + /// 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. + /// 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, @@ -108,6 +104,7 @@ impl ListPendingEvents { /// /// This struct represents the collection of events that have been initiated but have not yet concluded. #[derive(Serialize, Deserialize, Default)] +#[cfg_attr(test, derive(Debug, PartialEq, Clone))] pub struct ListOngoingEvents { /// The list of ongoing events ongoing_events: OngoingHashmap, @@ -368,4 +365,10 @@ mod tests { // TODO: Check the status at several points } + + #[ignore] + #[test] + fn serialisation_check() { + todo!() + } } -- 2.45.1 From 4cbeadaeeb74ee34d6712e82e901e22bc4d55c98 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 4 Dec 2024 08:15:45 -0600 Subject: [PATCH 3/5] Changes names for import's sake --- src/persistence.rs | 8 ++++---- src/votes/helper_functions.rs | 20 ++++++++++---------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/persistence.rs b/src/persistence.rs index 4c7f877..d278473 100644 --- a/src/persistence.rs +++ b/src/persistence.rs @@ -23,7 +23,7 @@ where /// /// This macro is direct sugarcoating of the load_from_disk macro #[macro_export] -macro_rules! load_it { +macro_rules! load_from_reader { ($r_type:ident, $path:expr) => { Arc::new(std::sync::Mutex::new(load_from_reader::<$r_type, File>( File::open($path).map_err(IdleError::BackupReadError)?, @@ -56,7 +56,7 @@ where /// /// save_it!() #[macro_export] -macro_rules! save_it { +macro_rules! save_to_writer { ($value:expr, $r_type:ident, $path:expr) => { save_to_writer::<&$r_type, File>( &$value.lock().unwrap(), @@ -99,8 +99,8 @@ mod tests { } let _ = remove_dir_all("test"); let _ = create_dir("test"); - save_it!(&event_og, ListPendingEvents, "test/testwrite.json"); - let event_new = load_it!(ListPendingEvents, "test/testwrite.json"); + save_to_writer!(&event_og, ListPendingEvents, "test/testwrite.json"); + let event_new = load_from_reader!(ListPendingEvents, "test/testwrite.json"); assert_eq!( event_og.lock().unwrap().to_owned(), event_new.lock().unwrap().to_owned() diff --git a/src/votes/helper_functions.rs b/src/votes/helper_functions.rs index dbdc0c1..fafc1e0 100644 --- a/src/votes/helper_functions.rs +++ b/src/votes/helper_functions.rs @@ -10,9 +10,9 @@ use super::{ }; use crate::{ ids::EventIdType, - load_it, + load_from_reader, persistence::{load_from_reader, save_to_writer}, - save_it, IdleError, + save_to_writer, IdleError, }; /// Adds a parsed vote to the list of planned events. @@ -213,31 +213,31 @@ pub struct EventHolder { impl EventHolder { pub fn try_load_from_disk() -> Result { Ok(Self { - pending_events: load_it!(ListPendingEvents, "data/pending_events.json"), - ongoing_events: load_it!(ListOngoingEvents, "data/ongoin_events.json"), - closed_events: load_it!(ListClosedEvents, "data/closed_events.json"), - old_date: load_it!(NaiveDate, "data/old_date.json"), + pending_events: load_from_reader!(ListPendingEvents, "data/pending_events.json"), + ongoing_events: load_from_reader!(ListOngoingEvents, "data/ongoin_events.json"), + closed_events: load_from_reader!(ListClosedEvents, "data/closed_events.json"), + old_date: load_from_reader!(NaiveDate, "data/old_date.json"), ..Default::default() }) } pub fn try_save_to_disk(holder: EventHolder) -> Result<(), IdleError> { - save_it!( + save_to_writer!( holder.pending_events, ListPendingEvents, "data/pending_events.json" ); - save_it!( + save_to_writer!( holder.ongoing_events, ListOngoingEvents, "data/ongoing_events.json" ); - save_it!( + save_to_writer!( holder.closed_events, ListClosedEvents, "data/closed_events.json" ); - save_it!(&holder.old_date, NaiveDate, "data/old_date.json"); + save_to_writer!(&holder.old_date, NaiveDate, "data/old_date.json"); Ok(()) } } -- 2.45.1 From 9a671a16e7eec1f24c363f036d61583e554fa3e1 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 4 Dec 2024 21:28:56 +0100 Subject: [PATCH 4/5] Adds a way to peak into inner values of event holders and generate truly unique ids --- src/date/date_tools.rs | 4 ++-- src/ids.rs | 30 ++++++++++++++++++++++++- src/votes/ballots.rs | 4 ++-- src/votes/events.rs | 16 +++++++------- src/votes/helper_functions.rs | 41 ++++++++++++++++++++++++++++++++++- src/votes/holders.rs | 38 +++++++++++++++++++++++++++++--- 6 files changed, 116 insertions(+), 17 deletions(-) diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs index 3920ae9..7636c04 100644 --- a/src/date/date_tools.rs +++ b/src/date/date_tools.rs @@ -148,8 +148,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. -#[derive(Debug, Default, Serialize, Deserialize)] -#[cfg_attr(test, derive(PartialEq, Eq, Clone))] +#[derive(Debug, Default, Serialize, Deserialize, Clone)] +#[cfg_attr(test, derive(PartialEq, Eq))] pub struct NaiveDateList { /// The inner vector inner: Vec, diff --git a/src/ids.rs b/src/ids.rs index 4913eb8..9ed2f23 100644 --- a/src/ids.rs +++ b/src/ids.rs @@ -1,18 +1,46 @@ -//! Handle all Ids functionalities +//! This module contains utilities for generating event ids. //! //! Features: //! Generating a human readable ID for a HUID //! Finding the HUID from an ID //! Removing ID as needed +use crate::votes::EventHolder; + /// Generic type representing an ID pub type EventIdType = String; /// Generate an id +/// +/// # Examples +/// +/// ``` +/// use idlefox::ids::generate_id; +/// let id: String = generate_id(); +/// println!("Generated id: {}", id); +/// ``` pub fn generate_id() -> String { human_ids::generate(None) } +/// Generate a unique id, slower in timing but insure zero collision at runtime +/// +/// # Examples +/// +/// ``` +/// use idlefox::ids::generate_unique_id; +/// # use idlefox::votes::EventHolder; +/// let holder = EventHolder::default(); +/// let id: String = generate_unique_id(&holder); +/// println!("Generated id: {}", id); +pub fn generate_unique_id(holder: &EventHolder) -> String { + let id = generate_id(); + match holder.contains_event(&id) { + true => generate_unique_id(holder), + false => id, + } +} + #[cfg(test)] mod test { use super::generate_id; diff --git a/src/votes/ballots.rs b/src/votes/ballots.rs index 6275c5f..ab1c599 100644 --- a/src/votes/ballots.rs +++ b/src/votes/ballots.rs @@ -10,8 +10,8 @@ use super::{BallotValueType, EventIdType, UserDataType}; /// A `Ballot` represents a user interaction towards an event. This struct is used to record the details of a vote, /// including which user casted it, which event it pertains to, and what value or option was voted for. -#[derive(Serialize, Deserialize, Debug)] -#[cfg_attr(test, derive(Clone, Eq, PartialEq))] +#[derive(Serialize, Deserialize, Debug, Clone)] +#[cfg_attr(test, derive(Eq, PartialEq))] pub struct Ballot { /// The event the vote refers to linked_event: EventIdType, diff --git a/src/votes/events.rs b/src/votes/events.rs index 84fc634..65034b7 100644 --- a/src/votes/events.rs +++ b/src/votes/events.rs @@ -27,8 +27,8 @@ use super::Ballot; /// A pending event, waiting to be opened. In this state the even can be safely modified /// and either manual input or the autostart date will start the vote. -#[derive(Serialize, Deserialize, Default)] -#[cfg_attr(test, derive(Clone, Debug, PartialEq, Eq))] +#[derive(Serialize, Deserialize, Default, Clone)] +#[cfg_attr(test, derive(Debug, PartialEq, Eq))] pub struct EventPending { /// The parsed representation of the vote associated with this event. /// It holds the details required for the voting process. @@ -43,8 +43,8 @@ impl EventPending { } } -#[derive(Serialize, Deserialize)] -#[cfg_attr(test, derive(Debug, PartialEq, Clone))] +#[derive(Serialize, Deserialize, Clone)] +#[cfg_attr(test, derive(Debug, PartialEq))] // An ongoing event, waiting to be closed thus allowing the ballots to be counted. pub struct EventOngoing { /// The parsed representation of the vote associated with this event. @@ -66,8 +66,8 @@ impl EventOngoing { } } -#[derive(Serialize, Deserialize)] -#[cfg_attr(test, derive(Clone))] +#[derive(Serialize, Deserialize, Clone)] +// #[cfg_attr(test, derive(Clone))] /// A closed event, while the users cannot interract with it in this state, /// this event can still be reopened and it's results can be read. /// All events have an expiry date and in this state the event will be cleaned @@ -86,8 +86,8 @@ pub struct EventClosed { /// This structure is specifically used within the application to encapsulate both /// ongoing and planned voting events, providing a clear and organized way to manage their /// data throughout their lifecycle. -#[derive(Debug, Serialize, Deserialize, Default)] -#[cfg_attr(test, derive(Clone, Eq, PartialEq))] +#[derive(Debug, Serialize, Deserialize, Default, Clone)] +#[cfg_attr(test, derive(Eq, PartialEq))] pub(super) struct ParsedVote { /// The title of the even pub(super) title: String, diff --git a/src/votes/helper_functions.rs b/src/votes/helper_functions.rs index fafc1e0..f4f0d60 100644 --- a/src/votes/helper_functions.rs +++ b/src/votes/helper_functions.rs @@ -5,7 +5,7 @@ use std::{fs::File, sync::Arc}; use super::{ events::{EventOngoing, EventPending}, - holders::ListClosedEvents, + holders::{ListClosedEvents, TypedEvent}, ListOngoingEvents, ListPendingEvents, }; use crate::{ @@ -210,6 +210,15 @@ pub struct EventHolder { pub discord_ctx: Arc>>, } +/// Access the inner value by borrowing the inner wrapper +/// +/// A macro is better than a trait and polymorphic code at this scale +macro_rules! inner { + ($value:expr) => { + $value.lock().unwrap().borrow_inner() + }; +} + impl EventHolder { pub fn try_load_from_disk() -> Result { Ok(Self { @@ -240,4 +249,34 @@ impl EventHolder { save_to_writer!(&holder.old_date, NaiveDate, "data/old_date.json"); Ok(()) } + + /// Check wether the holder contains an event + /// + /// This is a low level plumbing tool, mostly used to check for collisions + pub(crate) fn contains_event(&self, id: &String) -> bool { + inner!(self.pending_events).contains_key(id) + || inner!(self.pending_events).contains_key(id) + || inner!(self.pending_events).contains_key(id) + } + + /// Try to find an even by it's id, returns a TypedEvent to keep track of the location of the event + /// + /// Note that this function is useless right now as it clones the event making it very impractical + #[deprecated] + #[allow(dead_code)] + pub(crate) fn find_event(&self, id: &String) -> Option { + inner!(self.pending_events) + .get(id) + .map(|e| TypedEvent::Pending(e.clone())) + .or_else(|| { + inner!(self.ongoing_events) + .get(id) + .map(|e| TypedEvent::Ongoing(e.clone())) + }) + .or_else(|| { + inner!(self.closed_events) + .get(id) + .map(|e| TypedEvent::Closed(e.clone())) + }) + } } diff --git a/src/votes/holders.rs b/src/votes/holders.rs index f20b426..48dfb3a 100644 --- a/src/votes/holders.rs +++ b/src/votes/holders.rs @@ -12,6 +12,8 @@ //! application, ensuring separation between pending and ongoing events and supporting //! actions such as adding, launching, processing, and autoclosing events. +use std::collections::HashMap; + use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; @@ -98,13 +100,22 @@ impl ListPendingEvents { } // TODO: maybe add an update_upcoming(date) ? + // /// + // pub fn contains_event(&self, id: &str) -> bool { + // self.pending_events.contains_key(id) + // } + + /// Borrow the inner pending events + pub fn borrow_inner(&self) -> &HashMap { + &self.pending_events + } } /// 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, Default)] -#[cfg_attr(test, derive(Debug, PartialEq, Clone))] +#[derive(Serialize, Deserialize, Default, Clone)] +#[cfg_attr(test, derive(Debug, PartialEq))] pub struct ListOngoingEvents { /// The list of ongoing events ongoing_events: OngoingHashmap, @@ -183,7 +194,11 @@ impl ListOngoingEvents { .map(|(k, _)| k.clone()) .collect() } - // TODO: maybe add an update_ongoing(date) ? + + /// Borrow the inner ongoing events + pub fn borrow_inner(&self) -> &HashMap { + &self.ongoing_events + } } /// The list of closed events @@ -232,6 +247,23 @@ impl ListClosedEvents { false => Err(IdleError::EventPrune(failure)), } } + + /// Borrow the inner ongoing events + pub fn borrow_inner(&self) -> &HashMap { + &self.closed_events + } +} + +/// A generic event, holding an event and his type as variants, +/// doing so is the easiest way to pass an event around outside of the event lists +#[allow(dead_code)] +pub enum TypedEvent { + /// Event that is ongoing. + Ongoing(EventOngoing), + /// Event that has yet to be resolved. + Pending(EventPending), + /// Event that has been resolved and is pending deletion. + Closed(EventClosed), } #[cfg(test)] -- 2.45.1 From 0e3a7fb3ad0fb8631c856b806b22ee8ee6548908 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 5 Dec 2024 04:56:59 -0600 Subject: [PATCH 5/5] Adds a blanket implementation and a trait for Borrowable inner dictionnary --- src/votes/helper_functions.rs | 1 + src/votes/holders.rs | 23 ++----------- src/votes/mod.rs | 1 + src/votes/traits.rs | 63 +++++++++++++++++++++++++++++++++++ 4 files changed, 68 insertions(+), 20 deletions(-) create mode 100644 src/votes/traits.rs diff --git a/src/votes/helper_functions.rs b/src/votes/helper_functions.rs index f4f0d60..ffd962d 100644 --- a/src/votes/helper_functions.rs +++ b/src/votes/helper_functions.rs @@ -1,5 +1,6 @@ //! Submodule including all helper functions to handle vote creation and evolution //! +use crate::votes::traits::BorrowInner; use chrono::NaiveDate; use std::{fs::File, sync::Arc}; diff --git a/src/votes/holders.rs b/src/votes/holders.rs index 48dfb3a..0059a62 100644 --- a/src/votes/holders.rs +++ b/src/votes/holders.rs @@ -12,8 +12,6 @@ //! application, ensuring separation between pending and ongoing events and supporting //! actions such as adding, launching, processing, and autoclosing events. -use std::collections::HashMap; - use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; @@ -35,7 +33,7 @@ use super::{ #[cfg_attr(test, derive(Debug, PartialEq, Clone))] pub struct ListPendingEvents { /// The list of pending events - pending_events: PendingHashmap, + pub(super) pending_events: PendingHashmap, } impl ListPendingEvents { @@ -104,11 +102,6 @@ impl ListPendingEvents { // pub fn contains_event(&self, id: &str) -> bool { // self.pending_events.contains_key(id) // } - - /// Borrow the inner pending events - pub fn borrow_inner(&self) -> &HashMap { - &self.pending_events - } } /// The list of ongoing events, not yet closed @@ -118,7 +111,7 @@ impl ListPendingEvents { #[cfg_attr(test, derive(Debug, PartialEq))] pub struct ListOngoingEvents { /// The list of ongoing events - ongoing_events: OngoingHashmap, + pub(super) ongoing_events: OngoingHashmap, } impl ListOngoingEvents { @@ -194,11 +187,6 @@ impl ListOngoingEvents { .map(|(k, _)| k.clone()) .collect() } - - /// Borrow the inner ongoing events - pub fn borrow_inner(&self) -> &HashMap { - &self.ongoing_events - } } /// The list of closed events @@ -208,7 +196,7 @@ impl ListOngoingEvents { #[derive(Serialize, Deserialize, Default)] pub struct ListClosedEvents { /// The list of closed events - closed_events: ClosedHashmap, + pub(super) closed_events: ClosedHashmap, } impl ListClosedEvents { @@ -247,11 +235,6 @@ impl ListClosedEvents { false => Err(IdleError::EventPrune(failure)), } } - - /// Borrow the inner ongoing events - pub fn borrow_inner(&self) -> &HashMap { - &self.closed_events - } } /// A generic event, holding an event and his type as variants, diff --git a/src/votes/mod.rs b/src/votes/mod.rs index 31f6954..f7408c1 100644 --- a/src/votes/mod.rs +++ b/src/votes/mod.rs @@ -19,6 +19,7 @@ mod ballots; mod events; mod helper_functions; mod holders; +mod traits; // Republish pub use ballots::Ballot; diff --git a/src/votes/traits.rs b/src/votes/traits.rs new file mode 100644 index 0000000..a2f3857 --- /dev/null +++ b/src/votes/traits.rs @@ -0,0 +1,63 @@ +//! Module holding all inner voting traits +#![allow(dead_code)] + +use std::collections::HashMap; + +use super::{ + holders::ListClosedEvents, EventClosed, EventOngoing, EventPending, ListOngoingEvents, + ListPendingEvents, +}; + +/// Signals that the object will let you borrow an inner dictionnary +/// +/// Doing so will allow blanket implementations great for generic dictionnary handling +pub(crate) trait BorrowInner { + /// Borrow the inner ongoing events + fn borrow_inner(&self) -> &HashMap; +} + +impl BorrowInner for ListClosedEvents { + /// Borrow the inner ongoing events + fn borrow_inner(&self) -> &HashMap { + &self.closed_events + } +} + +impl BorrowInner for ListOngoingEvents { + /// Borrow the inner ongoing events + fn borrow_inner(&self) -> &HashMap { + &self.ongoing_events + } +} + +impl BorrowInner for ListPendingEvents { + /// Borrow the inner ongoing events + fn borrow_inner(&self) -> &HashMap { + &self.pending_events + } +} + +/// Signals that the object will let you mutably borrow an inner dictionnary +/// +/// Doing so will allow blanket implementations great for generic dictionnary handling +pub(crate) trait BorrowMutInner { + /// Borrow the inner ongoing events + fn borrow_inner(&self) -> &HashMap; +} + +/// Blanket inner dictionnary implementation +/// +/// This trait is meant to allow for inner dictionnary manipulation +pub(crate) trait EventManipulation { + /// get the inner value + fn get_attr(&self, s: &str) -> Option<&R>; +} + +impl EventManipulation for T +where + T: BorrowInner, +{ + fn get_attr(&self, s: &str) -> Option<&R> { + self.borrow_inner().get(s) + } +} -- 2.45.1