From e1796201137c63b248227f482cc77b918cc0cabc Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 1 Dec 2024 18:42:52 +0100 Subject: [PATCH] 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::{