migrates the globals toward a shared reference #29
|
|
@ -1 +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>
|
||||
<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 After Width: | Height: | Size: 1.3 KiB |
10
src/main.rs
10
src/main.rs
|
|
@ -14,12 +14,16 @@ use tokio::time;
|
|||
#[cfg(not(tarpaulin_include))]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
use idlefox::votes::EventHolder;
|
||||
use tokio::task;
|
||||
|
||||
// TODO: Actually load them from disk
|
||||
let event_context = EventHolder::default();
|
||||
init_logger().unwrap();
|
||||
// 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),
|
||||
)));
|
||||
task::spawn(main_scheduler_loop(
|
||||
time::interval(time::Duration::from_secs(60 * 10)),
|
||||
event_context,
|
||||
));
|
||||
}
|
||||
|
|
|
|||
397
src/votes.rs
397
src/votes.rs
|
|
@ -14,17 +14,39 @@
|
|||
use std::{
|
||||
collections::HashMap,
|
||||
fmt::Display,
|
||||
sync::{LazyLock, Mutex},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use chrono::{NaiveDateTime, TimeDelta};
|
||||
use chrono::{NaiveDate, NaiveDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{date::date_tools::NaiveDateList, error_handling::IdleError};
|
||||
|
||||
// Helper functions, user facing
|
||||
// Helper functions, user facing
|
||||
/// A link to all events, to be shared between threads related to this event pool.
|
||||
///
|
||||
/// This struct serves as a central hub for managing and accessing different states of events within the
|
||||
/// system. It provides access to pending, ongoing, and potentially closed events.
|
||||
/// The use of `Arc<Mutex<>>` ensures that the events can be safely shared and modified across multiple
|
||||
/// threads without running into race conditions or other concurrency issues.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct EventHolder {
|
||||
/// A reference-counted pointer to a mutex-protected `PendingEvents` instance, managing all pending events.
|
||||
///
|
||||
/// Pending events are those that have been scheduled but not yet started
|
||||
pub pending_events: Arc<Mutex<PendingEvents>>,
|
||||
/// A reference-counted pointer to a mutex-protected `OngoingEvents` instance, managing all ongoing events.
|
||||
///
|
||||
/// Ongoing events are currently running but not yet closed.
|
||||
pub ongoing_events: Arc<Mutex<OngoingEvents>>,
|
||||
// /// A reference-counted pointer to a mutex-protected `OngoingEvents` instance, managing all closed events.
|
||||
// ///
|
||||
// /// Closed events have been voted up but havent been deleted and can therefore be watched or opened again.
|
||||
// /// These events will be autodeleted after a while
|
||||
// pub closed_events: Mutex<ClosedEvents>,
|
||||
/// A reference-counted pointer to a mutex-protected `NaiveDate` instance, representing the last date the watchdog was updated.
|
||||
pub old_date: Arc<Mutex<NaiveDate>>,
|
||||
}
|
||||
|
||||
/// Adds a parsed vote to the list of planned events.
|
||||
///
|
||||
|
|
@ -36,13 +58,14 @@ use crate::{date::date_tools::NaiveDateList, error_handling::IdleError};
|
|||
///
|
||||
/// ## Example:
|
||||
/// ```rust
|
||||
/// # use idlefox::votes::{add_pending_event, ParsedVote};
|
||||
/// # use idlefox::votes::{add_pending_event, EventHolder, ParsedVote};
|
||||
/// let ev_ctx = EventHolder::default();
|
||||
/// let parsed_vote = ParsedVote::default();
|
||||
///
|
||||
/// let id = add_pending_event(parsed_vote).unwrap();
|
||||
/// let id = add_pending_event(parsed_vote, &ev_ctx).unwrap();
|
||||
/// ```
|
||||
pub fn add_pending_event(event: ParsedVote) -> Result<Uuid, IdleError> {
|
||||
PENDING_EVENTS
|
||||
pub fn add_pending_event(event: ParsedVote, ev_ctx: &EventHolder) -> Result<Uuid, IdleError> {
|
||||
ev_ctx
|
||||
.pending_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
// .map_err(|_| IdleError::MutexError)?
|
||||
|
|
@ -58,17 +81,19 @@ pub fn add_pending_event(event: ParsedVote) -> Result<Uuid, IdleError> {
|
|||
///
|
||||
/// ## Example:
|
||||
/// ```rust
|
||||
/// # use idlefox::votes::{add_pending_event, make_into_ongoing_event, ParsedVote};
|
||||
/// let id = add_pending_event(ParsedVote::default()).unwrap();
|
||||
/// # use idlefox::votes::{add_pending_event, make_into_ongoing_event, ParsedVote, EventHolder};
|
||||
/// let ev_ctx = EventHolder::default();
|
||||
/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap();
|
||||
///
|
||||
/// make_into_ongoing_event(id).unwrap()
|
||||
/// make_into_ongoing_event(id, &ev_ctx).unwrap()
|
||||
/// ```
|
||||
pub fn make_into_ongoing_event(uuid: Uuid) -> Result<(), IdleError> {
|
||||
PENDING_EVENTS
|
||||
pub fn make_into_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> {
|
||||
ev_ctx
|
||||
.pending_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
// .map_err(|_| IdleError::MutexError)?
|
||||
.launch(uuid)
|
||||
.launch(uuid, ev_ctx)
|
||||
}
|
||||
|
||||
/// Manually adds an ongoing event.
|
||||
|
|
@ -84,14 +109,20 @@ pub fn make_into_ongoing_event(uuid: Uuid) -> Result<(), IdleError> {
|
|||
/// ## Example:
|
||||
/// ```rust
|
||||
/// # use uuid::Uuid;
|
||||
/// # use idlefox::votes::{add_ongoing_event, ParsedVote};
|
||||
/// # use idlefox::votes::{add_ongoing_event, ParsedVote, EventHolder};
|
||||
/// let ev_ctx = EventHolder::default();
|
||||
/// let uuid = Uuid::new_v4(); // A new id
|
||||
/// let parsed_vote = ParsedVote::default(); // A very legit event
|
||||
///
|
||||
/// add_ongoing_event(uuid, parsed_vote).unwrap();
|
||||
/// add_ongoing_event(uuid, parsed_vote, &ev_ctx).unwrap();
|
||||
/// ```
|
||||
pub fn add_ongoing_event(uuid: Uuid, event: ParsedVote) -> Result<(), IdleError> {
|
||||
ONGOING_EVENTS
|
||||
pub fn add_ongoing_event(
|
||||
uuid: Uuid,
|
||||
event: ParsedVote,
|
||||
ev_ctx: &EventHolder,
|
||||
) -> Result<(), IdleError> {
|
||||
ev_ctx
|
||||
.ongoing_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
// .map_err(|_| IdleError::MutexError)?
|
||||
|
|
@ -107,16 +138,18 @@ pub fn add_ongoing_event(uuid: Uuid, event: ParsedVote) -> Result<(), 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();
|
||||
/// # use idlefox::votes::{
|
||||
/// # add_pending_event, del_ongoing_event, make_into_ongoing_event, ParsedVote, EventHolder
|
||||
/// # };
|
||||
/// let ev_ctx = EventHolder::default();
|
||||
/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap();
|
||||
/// make_into_ongoing_event(id, &ev_ctx).unwrap();
|
||||
///
|
||||
/// del_ongoing_event(id).unwrap();
|
||||
/// del_ongoing_event(id, &ev_ctx).unwrap();
|
||||
/// ```
|
||||
pub fn del_ongoing_event(uuid: Uuid) -> Result<ParsedVote, IdleError> {
|
||||
ONGOING_EVENTS
|
||||
pub fn del_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<ParsedVote, IdleError> {
|
||||
ev_ctx
|
||||
.ongoing_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
// .map_err(|_| IdleError::MutexError)?
|
||||
|
|
@ -132,13 +165,15 @@ pub fn del_ongoing_event(uuid: Uuid) -> Result<ParsedVote, IdleError> {
|
|||
/// ## Example:
|
||||
/// ```rust
|
||||
/// # use idlefox::votes::{
|
||||
/// # add_pending_event, del_pending_event, make_into_ongoing_event, ParsedVote,
|
||||
/// # add_pending_event, del_pending_event, make_into_ongoing_event, ParsedVote, EventHolder
|
||||
/// # };
|
||||
/// let id = add_pending_event(ParsedVote::default()).unwrap();
|
||||
/// del_pending_event(id).unwrap();
|
||||
/// let ev_ctx = EventHolder::default();
|
||||
/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap();
|
||||
/// del_pending_event(id, &ev_ctx).unwrap();
|
||||
/// ```
|
||||
pub fn del_pending_event(uuid: Uuid) -> Result<ParsedVote, IdleError> {
|
||||
PENDING_EVENTS
|
||||
pub fn del_pending_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<ParsedVote, IdleError> {
|
||||
ev_ctx
|
||||
.pending_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
// .map_err(|_| IdleError::MutexError)?
|
||||
|
|
@ -153,14 +188,16 @@ pub fn del_pending_event(uuid: Uuid) -> Result<ParsedVote, IdleError> {
|
|||
/// ## Example:
|
||||
/// ```rust
|
||||
/// # use idlefox::votes::{
|
||||
/// # add_pending_event, close_ongoing_event, make_into_ongoing_event, ParsedVote,
|
||||
/// # add_pending_event, close_ongoing_event, make_into_ongoing_event, ParsedVote, EventHolder,
|
||||
/// # };
|
||||
/// let id = add_pending_event(ParsedVote::default()).unwrap();
|
||||
/// make_into_ongoing_event(id).unwrap();
|
||||
/// close_ongoing_event(id).unwrap();
|
||||
/// let ev_ctx = EventHolder::default();
|
||||
/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap();
|
||||
/// make_into_ongoing_event(id, &ev_ctx).unwrap();
|
||||
/// close_ongoing_event(id, &ev_ctx).unwrap();
|
||||
/// ```
|
||||
pub fn close_ongoing_event(uuid: Uuid) -> Result<ParsedVote, IdleError> {
|
||||
ONGOING_EVENTS
|
||||
pub fn close_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<ParsedVote, IdleError> {
|
||||
ev_ctx
|
||||
.ongoing_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
// .map_err(|_| IdleError::MutexError)?
|
||||
|
|
@ -224,6 +261,8 @@ pub struct ParsedVote {
|
|||
launch_date: NaiveDateTime,
|
||||
/// Date at which to autoclose the vote process
|
||||
close_date: NaiveDateTime,
|
||||
/// Date at which to autodelete the vote process
|
||||
auto_delete_date: NaiveDateTime,
|
||||
/// The inner list of votes cast
|
||||
votes: Vec<Ballot>,
|
||||
/// The list of values to vote for, this list all the valid dates to vote for
|
||||
|
|
@ -247,14 +286,18 @@ impl ParsedVote {
|
|||
// }
|
||||
|
||||
/// All the logic behind a vote becoming live
|
||||
fn launch(&mut self, id: Uuid) -> Result<(), IdleError> {
|
||||
let _ = id;
|
||||
fn launch(&mut self) -> Result<(), IdleError> {
|
||||
// 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(())
|
||||
}
|
||||
|
||||
/// Close the event
|
||||
fn close(&mut self) {
|
||||
self.status = EventStatus::Closed;
|
||||
}
|
||||
}
|
||||
|
||||
// impl From<VoteContainer> for ParsedVote {
|
||||
|
|
@ -278,21 +321,21 @@ type EventListType = HashMap<Uuid, ParsedVote>;
|
|||
// 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)]
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
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.
|
||||
///
|
||||
/// However, a deserialization will always be performed if possible.
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
pending_events: EventListType::new(),
|
||||
}
|
||||
}
|
||||
// /// Create a new empty list of events, called in case of a first initialization.
|
||||
// ///
|
||||
// /// However, a deserialization will always be performed if possible.
|
||||
// fn new() -> Self {
|
||||
// Self {
|
||||
// pending_events: EventListType::new(),
|
||||
// }
|
||||
// }
|
||||
|
||||
/// Add a new event to the list of upcoming events.
|
||||
///
|
||||
|
|
@ -306,13 +349,15 @@ impl PendingEvents {
|
|||
/// 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());
|
||||
pub fn process_upcoming(
|
||||
&mut self,
|
||||
current_time: NaiveDateTime,
|
||||
ev_ctx: &EventHolder,
|
||||
) -> Result<(), IdleError> {
|
||||
self.find_upcoming(current_time)
|
||||
.iter()
|
||||
.try_for_each(|uuid| {
|
||||
self.launch(*uuid)?;
|
||||
self.launch(*uuid, ev_ctx)?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
|
@ -320,23 +365,23 @@ impl PendingEvents {
|
|||
/// 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> {
|
||||
fn launch(&mut self, uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> {
|
||||
let event = self
|
||||
.pending_events
|
||||
.remove(&uuid)
|
||||
.ok_or(IdleError::EventLaunch(uuid))?;
|
||||
add_ongoing_event(uuid, event)?;
|
||||
add_ongoing_event(uuid, event, ev_ctx)?;
|
||||
// make_into_ongoing_event(uuid)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Find all events that are scheduled to start before the given current time.
|
||||
/// Find all events that are scheduled to start after the given date.
|
||||
///
|
||||
/// 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)
|
||||
.filter(|&(_, e)| e.launch_date <= current_time)
|
||||
.map(|(k, _v)| (*k))
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -346,27 +391,28 @@ impl PendingEvents {
|
|||
.remove(&uuid)
|
||||
.ok_or(IdleError::DeleteEvent(uuid))
|
||||
}
|
||||
|
||||
// TODO: maybe add an update_upcoming(date) ?
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
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.
|
||||
///
|
||||
/// However, a deserialization will always be performed if possible.
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
ongoing_events: EventListType::new(),
|
||||
}
|
||||
}
|
||||
// /// Create a new empty list of ongoing events, called in case of a first initialization.
|
||||
// ///
|
||||
// /// However, a deserialization will always be performed if possible.
|
||||
// fn new() -> Self {
|
||||
// Self {
|
||||
// ongoing_events: EventListType::new(),
|
||||
// }
|
||||
// }
|
||||
|
||||
/// Remove all outdated votes for the current user
|
||||
///
|
||||
|
|
@ -374,29 +420,60 @@ impl OngoingEvents {
|
|||
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) {
|
||||
println!("{}", uuid);
|
||||
if self.ongoing_events.remove(&uuid).is_none() {
|
||||
// Should only happen during hard to reproduce race conditions
|
||||
#[cfg(not(tarpaulin_include))]
|
||||
failure.push(uuid);
|
||||
}
|
||||
}
|
||||
match failure.is_empty() {
|
||||
true => Ok(()),
|
||||
#[cfg(not(tarpaulin_include))]
|
||||
false => Err(IdleError::EventPrune(failure)),
|
||||
}
|
||||
}
|
||||
/// Remove all outdated votes for the current user
|
||||
///
|
||||
/// This function is expected to be called periodically by the watchdog.
|
||||
pub(crate) fn autoclose(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> {
|
||||
let failure = Vec::new();
|
||||
for uuid in self.find_autoclose(current_time) {
|
||||
// println!("{}", uuid);
|
||||
self.ongoing_events
|
||||
.get_mut(&uuid)
|
||||
.ok_or(IdleError::EventLaunch(uuid))?
|
||||
.close()
|
||||
}
|
||||
match failure.is_empty() {
|
||||
true => Ok(()),
|
||||
// Should only happen during hard to reproduce race conditions
|
||||
#[cfg(not(tarpaulin_include))]
|
||||
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.
|
||||
/// Find all events that are scheduled to be autoclosed.
|
||||
///
|
||||
/// Returns a vector of UUIDs corresponding to the old events.
|
||||
fn find_autoclose(&mut self, current_time: NaiveDateTime) -> Vec<Uuid> {
|
||||
self.ongoing_events
|
||||
.iter()
|
||||
// TODO: Remove this when you do the sensible thing and add a CLOSED_EVENT structure
|
||||
.filter(|(_, e)| {
|
||||
e.close_date <= current_time && !matches!(e.status, EventStatus::Closed)
|
||||
})
|
||||
.map(|(k, _)| *k)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Find all events that are too old and supposed to be pruned.
|
||||
///
|
||||
/// 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))
|
||||
.filter(|(_, e)| e.auto_delete_date <= current_time)
|
||||
.map(|(k, _)| *k)
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -405,7 +482,7 @@ impl OngoingEvents {
|
|||
///
|
||||
/// 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)?;
|
||||
event.launch()?;
|
||||
self.ongoing_events.insert(id, event);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -423,105 +500,131 @@ impl OngoingEvents {
|
|||
.ongoing_events
|
||||
.remove(&uuid)
|
||||
.ok_or(IdleError::LaunchingEvent(uuid))?;
|
||||
let str_event = event.to_string();
|
||||
let _str_event = event.to_string();
|
||||
// TODO: Do something with this string
|
||||
Ok(event)
|
||||
}
|
||||
// TODO: maybe add an update_ongoing(date) ?
|
||||
}
|
||||
|
||||
/// The thread safe list of pending events
|
||||
pub static PENDING_EVENTS: LazyLock<Mutex<PendingEvents>> =
|
||||
LazyLock::new(|| Mutex::new(PendingEvents::new()));
|
||||
/// The thread safe list of ongoing events
|
||||
pub static ONGOING_EVENTS: LazyLock<Mutex<OngoingEvents>> =
|
||||
LazyLock::new(|| Mutex::new(OngoingEvents::new()));
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Local;
|
||||
use chrono::{Days, Local};
|
||||
|
||||
use super::*;
|
||||
macro_rules! g {
|
||||
($ev: expr) => {
|
||||
$ev.lock().unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
// Test all structs can be safely initialized
|
||||
#[test]
|
||||
fn init_test() {
|
||||
let _e = PendingEvents::new();
|
||||
let _o = OngoingEvents::new();
|
||||
assert!(PENDING_EVENTS.lock().is_ok());
|
||||
assert!(ONGOING_EVENTS.lock().is_ok());
|
||||
|
||||
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());
|
||||
let ev_ctx = EventHolder::default();
|
||||
assert!(ev_ctx.pending_events.lock().is_ok());
|
||||
assert!(ev_ctx.ongoing_events.lock().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_base_vote_handling() {
|
||||
// assert!(ParsedVote::default().launch(Uuid::new_v4()).is_ok());
|
||||
let ev = ParsedVote::default();
|
||||
let ev_ctx = EventHolder::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(), &ev_ctx).unwrap();
|
||||
// assert!(gimme!(ev_ctx.pending_events).contains_key(&id)); // Is the vote present ?
|
||||
del_pending_event(id, &ev_ctx).unwrap();
|
||||
assert!(!g!(ev_ctx.pending_events).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
|
||||
let id = add_pending_event(ev.clone(), &ev_ctx).unwrap();
|
||||
make_into_ongoing_event(id, &ev_ctx).unwrap(); // Launching this event
|
||||
assert!(!g!(ev_ctx.pending_events).pending_events.contains_key(&id)); // Is the vote now not pending
|
||||
assert!(g!(ev_ctx.ongoing_events).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
|
||||
close_ongoing_event(id, &ev_ctx).unwrap();
|
||||
assert!(!g!(ev_ctx.ongoing_events).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
|
||||
let id = add_pending_event(ev.clone(), &ev_ctx).unwrap();
|
||||
make_into_ongoing_event(id, &ev_ctx).unwrap(); // Launching this event
|
||||
del_ongoing_event(id, &ev_ctx).unwrap();
|
||||
assert!(!g!(ev_ctx.ongoing_events).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)
|
||||
let ev = EventHolder::default();
|
||||
let now = Local::now().naive_local();
|
||||
let later = now.checked_add_days(Days::new(1)).unwrap();
|
||||
let very_later = now.checked_add_days(Days::new(3)).unwrap();
|
||||
let very_very_later = now.checked_add_days(Days::new(7)).unwrap();
|
||||
let event = ParsedVote {
|
||||
launch_date: later,
|
||||
close_date: very_later,
|
||||
auto_delete_date: very_very_later,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(now < later);
|
||||
assert!(later < very_later);
|
||||
|
||||
let id = add_pending_event(event, &ev).unwrap();
|
||||
assert!(g!(ev.pending_events).find_upcoming(now).is_empty()); // no upcomming events
|
||||
assert!(g!(ev.ongoing_events).find_old(now).is_empty()); // no old events
|
||||
assert!(g!(ev.ongoing_events).find_autoclose(now).is_empty()); // no old events
|
||||
g!(ev.pending_events).process_upcoming(now, &ev).unwrap(); // nothing should be processed
|
||||
g!(ev.ongoing_events).prune_old(now).unwrap(); // nothing should be processed
|
||||
g!(ev.ongoing_events).autoclose(now).unwrap(); // nothing should be processed
|
||||
assert!(g!(ev.pending_events).find_upcoming(now).is_empty()); // no upcomming events
|
||||
assert!(g!(ev.ongoing_events).find_old(now).is_empty()); // no old events
|
||||
assert!(g!(ev.ongoing_events).find_autoclose(now).is_empty()); // no old events
|
||||
assert!(g!(ev.pending_events).pending_events.contains_key(&id)); // it's still here
|
||||
assert!(!g!(ev.ongoing_events).ongoing_events.contains_key(&id)); // it's wasn't processed
|
||||
|
||||
// Now some time passed
|
||||
assert_eq!(g!(ev.pending_events).find_upcoming(later), vec![id]); // one upcomming event
|
||||
assert!(g!(ev.ongoing_events).find_old(later).is_empty()); // no old events
|
||||
assert!(g!(ev.ongoing_events).find_autoclose(later).is_empty()); // no old events
|
||||
g!(ev.pending_events).process_upcoming(later, &ev).unwrap(); // one event should be processed
|
||||
g!(ev.ongoing_events).prune_old(later).unwrap(); // nothing should be processed
|
||||
g!(ev.ongoing_events).autoclose(later).unwrap(); // nothing should be processed
|
||||
assert!(!g!(ev.pending_events).pending_events.contains_key(&id)); // it's not here anymore
|
||||
assert!(g!(ev.ongoing_events).ongoing_events.contains_key(&id)); // it was processed
|
||||
|
||||
// More time passed
|
||||
assert!(g!(ev.pending_events).find_upcoming(very_later).is_empty()); // one upcomming event
|
||||
assert_eq!(g!(ev.ongoing_events).find_autoclose(very_later), vec![id]); // one old event
|
||||
assert!(g!(ev.ongoing_events).find_old(very_later).is_empty()); // no old events
|
||||
g!(ev.pending_events)
|
||||
.process_upcoming(very_later, &ev)
|
||||
.unwrap(); // no event should be processed
|
||||
g!(ev.ongoing_events).prune_old(very_later).unwrap(); // nothing should be processed
|
||||
g!(ev.ongoing_events).autoclose(very_later).unwrap(); // nothing should be processed
|
||||
assert!(!g!(ev.pending_events).pending_events.contains_key(&id)); // it's not here anymore
|
||||
assert!(g!(ev.ongoing_events).ongoing_events.contains_key(&id)); // it was processed
|
||||
|
||||
// More more time passed
|
||||
assert!(g!(ev.pending_events)
|
||||
.find_upcoming(very_very_later)
|
||||
.is_empty()); // one upcomming event
|
||||
assert_eq!(g!(ev.ongoing_events).find_old(very_very_later), vec![id]); // one old event
|
||||
assert!(g!(ev.ongoing_events)
|
||||
.find_autoclose(very_very_later)
|
||||
.is_empty()); // no old events
|
||||
g!(ev.pending_events)
|
||||
.process_upcoming(very_very_later, &ev)
|
||||
.unwrap(); // no event should be processed
|
||||
g!(ev.ongoing_events).prune_old(very_very_later).unwrap(); // nothing should be processed
|
||||
g!(ev.ongoing_events).autoclose(very_very_later).unwrap(); // nothing should be processed
|
||||
assert!(!g!(ev.pending_events).pending_events.contains_key(&id)); // it's not here anymore
|
||||
assert!(!g!(ev.ongoing_events).ongoing_events.contains_key(&id)); // it was processed
|
||||
|
||||
// TODO: Check the status at several points
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn test_ongoing_events() {
|
||||
unimplemented!()
|
||||
}
|
||||
// #[test]
|
||||
// #[ignore]
|
||||
// fn test_ongoing_events() {
|
||||
// unimplemented!()
|
||||
// }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,12 +13,9 @@
|
|||
//! - `watchdog_update`: Updates the internal state of the scheduler,
|
||||
//! checks for and runs upcoming events, and performs garbage collection if necessary.
|
||||
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
use crate::votes::EventHolder;
|
||||
use chrono::{DateTime, Local, NaiveDate};
|
||||
|
||||
use crate::votes::{ONGOING_EVENTS, PENDING_EVENTS};
|
||||
|
||||
/// The main scheduler waiting and dispatch loop.
|
||||
///
|
||||
///
|
||||
|
|
@ -27,11 +24,12 @@ 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
|
||||
pub async fn main_scheduler_loop(mut interval: tokio::time::Interval) {
|
||||
pub async fn main_scheduler_loop(mut interval: tokio::time::Interval, ev_ctx: EventHolder) {
|
||||
loop {
|
||||
interval.tick().await;
|
||||
// tokio::spawn(async {watchdog_update().await;}); // For async task
|
||||
tokio::task::spawn_blocking(|| watchdog_update(Local::now()));
|
||||
let ev = ev_ctx.clone();
|
||||
tokio::task::spawn_blocking(move || watchdog_update(Local::now(), ev));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -43,14 +41,15 @@ pub async fn main_scheduler_loop(mut interval: tokio::time::Interval) {
|
|||
///
|
||||
/// 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>) {
|
||||
fn watchdog_update(current_time: DateTime<Local>, ev_ctx: EventHolder) {
|
||||
// Update day and tell if a day passed
|
||||
let is_new_day = update_date(current_time.date_naive());
|
||||
let is_new_day = update_date(current_time.date_naive(), &ev_ctx);
|
||||
// List all upcoming events and run all events that should be ran
|
||||
if let Err(e) = PENDING_EVENTS
|
||||
if let Err(e) = ev_ctx
|
||||
.pending_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.process_upcoming(current_time.naive_local())
|
||||
.process_upcoming(current_time.naive_local(), &ev_ctx)
|
||||
{
|
||||
// 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
|
||||
|
|
@ -60,7 +59,8 @@ fn watchdog_update(current_time: DateTime<Local>) {
|
|||
// Execute all scheduled tasks
|
||||
// * Clean old events if a new day passed
|
||||
if is_new_day {
|
||||
if let Err(e) = ONGOING_EVENTS
|
||||
if let Err(e) = ev_ctx
|
||||
.ongoing_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.prune_old(current_time.naive_local())
|
||||
|
|
@ -70,17 +70,28 @@ fn watchdog_update(current_time: DateTime<Local>) {
|
|||
#[cfg(not(tarpaulin_include))]
|
||||
log::error!("{}:{} {:?}", file!(), line!(), e);
|
||||
}
|
||||
if let Err(e) = ev_ctx
|
||||
.ongoing_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.autoclose(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 closed
|
||||
#[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.
|
||||
///
|
||||
/// This constant is used to track when a new day has started. When a new day is detected,
|
||||
/// it updates this value to reflect the current date and time.
|
||||
static OLD_DATE: LazyLock<Mutex<NaiveDate>> =
|
||||
LazyLock::new(|| Mutex::new(Local::now().date_naive()));
|
||||
// /// A lazily-initialized, thread-safe storage for the previous day's date.
|
||||
// ///
|
||||
// /// This constant is used to track when a new day has started. When a new day is detected,
|
||||
// /// it updates this value to reflect the current date and time.
|
||||
// static OLD_DATE: LazyLock<Mutex<NaiveDate>> =
|
||||
// LazyLock::new(|| Mutex::new(Local::now().date_naive()));
|
||||
|
||||
/// The `update_date` function updates the internal calendar state by taking a new date and comparing it with the previous day's date.
|
||||
///
|
||||
|
|
@ -88,11 +99,10 @@ static OLD_DATE: LazyLock<Mutex<NaiveDate>> =
|
|||
/// This function is critical for determining when to prune old events from the ongoing event list.
|
||||
/// ## Note
|
||||
/// This whole function exists only in the purpose of manually testing the autopruning and autotesting of all time-related function.
|
||||
fn update_date(date: NaiveDate) -> bool {
|
||||
let old = OLD_DATE.lock().unwrap().signed_duration_since(date);
|
||||
|
||||
fn update_date(date: NaiveDate, ev_ctx: &EventHolder) -> bool {
|
||||
let old = ev_ctx.old_date.lock().unwrap().signed_duration_since(date);
|
||||
if old.num_days() < 0 {
|
||||
*OLD_DATE.lock().unwrap() = date;
|
||||
*ev_ctx.old_date.lock().unwrap() = date;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
|
@ -107,20 +117,22 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn initialisation() {
|
||||
assert!(OLD_DATE.lock().is_ok());
|
||||
let ev_ctx = EventHolder::default();
|
||||
assert!(ev_ctx.old_date.lock().is_ok());
|
||||
let date = Local::now().date_naive();
|
||||
update_date(date);
|
||||
assert!(!update_date(date));
|
||||
update_date(date, &ev_ctx);
|
||||
assert!(!update_date(date, &ev_ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_watchdog_update() {
|
||||
let ctx = EventHolder::default();
|
||||
let date = Local::now();
|
||||
watchdog_update(date);
|
||||
watchdog_update(date, ctx.clone());
|
||||
let date2 = date.checked_add_days(Days::new(12)).unwrap();
|
||||
assert!(update_date(date2.date_naive()));
|
||||
assert!(update_date(date2.date_naive(), &ctx));
|
||||
let date2 = date.checked_add_days(Days::new(14)).unwrap();
|
||||
watchdog_update(date2);
|
||||
watchdog_update(date2, ctx.clone());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use idlefox::votes::{
|
||||
add_pending_event, close_ongoing_event, make_into_ongoing_event, ParsedVote,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn generic_integration_test() {
|
||||
let id = add_pending_event(ParsedVote::default()).unwrap();
|
||||
make_into_ongoing_event(id).unwrap();
|
||||
close_ongoing_event(id).unwrap();
|
||||
use idlefox::votes::{add_ongoing_event, EventHolder, ParsedVote};
|
||||
use uuid::Uuid;
|
||||
let uuid = Uuid::new_v4(); // A new id
|
||||
let parsed_vote = ParsedVote::default(); // A very legit event
|
||||
let ev_ctx = EventHolder::default();
|
||||
|
||||
add_ongoing_event(uuid, parsed_vote, &ev_ctx).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue