Fills coverage and doctests
This commit is contained in:
parent
199c7bd6c7
commit
47ffc337e8
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,
|
||||
));
|
||||
}
|
||||
|
|
|
|||
295
src/votes.rs
295
src/votes.rs
|
|
@ -14,17 +14,39 @@
|
|||
use std::{
|
||||
collections::HashMap,
|
||||
fmt::Display,
|
||||
sync::{LazyLock, Mutex},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use chrono::NaiveDateTime;
|
||||
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)?
|
||||
|
|
@ -209,12 +246,6 @@ pub(crate) enum EventStatus {
|
|||
/// The event was cancelled
|
||||
Cancelled,
|
||||
}
|
||||
// impl EventStatus {
|
||||
// /// Check if the event isn't closed, remove this abreration when you add another CLOSED_EVENT struct
|
||||
// fn not_closed(&self) -> bool {
|
||||
// matches!(self, EventStatus::Closed)
|
||||
// }
|
||||
// }
|
||||
|
||||
/// An event, wether ongoing or planned
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
|
|
@ -290,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.
|
||||
///
|
||||
|
|
@ -318,11 +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> {
|
||||
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(())
|
||||
})
|
||||
}
|
||||
|
|
@ -330,12 +365,12 @@ 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(())
|
||||
}
|
||||
|
|
@ -363,22 +398,21 @@ impl PendingEvents {
|
|||
/// 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
|
||||
///
|
||||
|
|
@ -466,28 +500,20 @@ 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::{Days, Local};
|
||||
|
||||
use super::*;
|
||||
macro_rules! gimme {
|
||||
($ev: ident) => {
|
||||
macro_rules! g {
|
||||
($ev: expr) => {
|
||||
$ev.lock().unwrap()
|
||||
};
|
||||
}
|
||||
|
|
@ -495,39 +521,40 @@ mod tests {
|
|||
// 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());
|
||||
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!(gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // Is the vote present ?
|
||||
del_pending_event(id).unwrap();
|
||||
assert!(!gimme!(PENDING_EVENTS).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!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // Is the vote now not pending
|
||||
assert!(gimme!(ONGOING_EVENTS).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!(!gimme!(ONGOING_EVENTS).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!(!gimme!(ONGOING_EVENTS).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]
|
||||
fn test_upcomming_events() {
|
||||
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();
|
||||
|
|
@ -541,54 +568,56 @@ mod tests {
|
|||
assert!(now < later);
|
||||
assert!(later < very_later);
|
||||
|
||||
let id = add_pending_event(event).unwrap();
|
||||
assert!(gimme!(PENDING_EVENTS).find_upcoming(now).is_empty()); // no upcomming events
|
||||
assert!(gimme!(ONGOING_EVENTS).find_old(now).is_empty()); // no old events
|
||||
assert!(gimme!(ONGOING_EVENTS).find_autoclose(now).is_empty()); // no old events
|
||||
gimme!(PENDING_EVENTS).process_upcoming(now).unwrap(); // nothing should be processed
|
||||
gimme!(ONGOING_EVENTS).prune_old(now).unwrap(); // nothing should be processed
|
||||
gimme!(ONGOING_EVENTS).autoclose(now).unwrap(); // nothing should be processed
|
||||
assert!(gimme!(PENDING_EVENTS).find_upcoming(now).is_empty()); // no upcomming events
|
||||
assert!(gimme!(ONGOING_EVENTS).find_old(now).is_empty()); // no old events
|
||||
assert!(gimme!(ONGOING_EVENTS).find_autoclose(now).is_empty()); // no old events
|
||||
assert!(gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // it's still here
|
||||
assert!(!gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // it's wasn't processed
|
||||
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!(gimme!(PENDING_EVENTS).find_upcoming(later), vec![id]); // one upcomming event
|
||||
assert!(gimme!(ONGOING_EVENTS).find_old(later).is_empty()); // no old events
|
||||
assert!(gimme!(ONGOING_EVENTS).find_autoclose(later).is_empty()); // no old events
|
||||
gimme!(PENDING_EVENTS).process_upcoming(later).unwrap(); // one event should be processed
|
||||
gimme!(ONGOING_EVENTS).prune_old(later).unwrap(); // nothing should be processed
|
||||
gimme!(ONGOING_EVENTS).autoclose(later).unwrap(); // nothing should be processed
|
||||
assert!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // it's not here anymore
|
||||
assert!(gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // it was processed
|
||||
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!(gimme!(PENDING_EVENTS).find_upcoming(very_later).is_empty()); // one upcomming event
|
||||
assert_eq!(gimme!(ONGOING_EVENTS).find_autoclose(very_later), vec![id]); // one old event
|
||||
assert!(gimme!(ONGOING_EVENTS).find_old(very_later).is_empty()); // no old events
|
||||
gimme!(PENDING_EVENTS).process_upcoming(very_later).unwrap(); // no event should be processed
|
||||
gimme!(ONGOING_EVENTS).prune_old(very_later).unwrap(); // nothing should be processed
|
||||
gimme!(ONGOING_EVENTS).autoclose(very_later).unwrap(); // nothing should be processed
|
||||
assert!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // it's not here anymore
|
||||
assert!(gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // it was processed
|
||||
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!(gimme!(PENDING_EVENTS)
|
||||
assert!(g!(ev.pending_events)
|
||||
.find_upcoming(very_very_later)
|
||||
.is_empty()); // one upcomming event
|
||||
assert_eq!(gimme!(ONGOING_EVENTS).find_old(very_very_later), vec![id]); // one old event
|
||||
assert!(gimme!(ONGOING_EVENTS)
|
||||
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
|
||||
gimme!(PENDING_EVENTS)
|
||||
.process_upcoming(very_very_later)
|
||||
g!(ev.pending_events)
|
||||
.process_upcoming(very_very_later, &ev)
|
||||
.unwrap(); // no event should be processed
|
||||
gimme!(ONGOING_EVENTS).prune_old(very_very_later).unwrap(); // nothing should be processed
|
||||
gimme!(ONGOING_EVENTS).autoclose(very_very_later).unwrap(); // nothing should be processed
|
||||
assert!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // it's not here anymore
|
||||
assert!(!gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // it was 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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