Adds a way to peak into inner values of event holders and generate truly unique ids

This commit is contained in:
Dandaedre 2024-12-04 21:28:56 +01:00
parent 4cbeadaeeb
commit 9a671a16e7
6 changed files with 116 additions and 17 deletions

View File

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

View File

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

View File

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

View File

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

View File

@ -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<tokio::sync::Mutex<Option<poise::serenity_prelude::Context>>>,
}
/// 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<Self, IdleError> {
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<TypedEvent> {
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()))
})
}
}

View File

@ -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<String, EventPending> {
&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<String, EventOngoing> {
&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<String, EventClosed> {
&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)]