Compare commits

..

15 Commits

Author SHA1 Message Date
Dandaedre faba5f1422 Update Jenkinsfile
Rust CI IdleFox passed all CI checks.
Gitea/idlefox/pipeline/head This commit looks good Details
2026-09-13 14:01:18 +02:00
Dandaedre 048be0e619 Update Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:49:51 +02:00
Dandaedre 3968fb97ff Update Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:44:32 +02:00
Dandaedre fec62385a0 Add Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:18:22 +02:00
Dandaedre fca5e8ef7a Some typos 2025-01-17 23:58:02 +01:00
Dandaedre af2f1ef2ea Updates some dependencies 2025-01-17 16:28:29 +01:00
Dandaedre cb88215e7f Adds a basic config and a handling of the reaction emotes 2025-01-16 17:52:23 +01:00
Dandaedre 773c5dd2ff coverage (#46)
Reviewed-on: #46
Co-authored-by: Dandaedre <max.beffroi@gmail.com>
Co-committed-by: Dandaedre <max.beffroi@gmail.com>
2024-12-05 16:48:54 +01:00
Dandaedre 0e3a7fb3ad Adds a blanket implementation and a trait for Borrowable inner dictionnary 2024-12-05 04:56:59 -06:00
Dandaedre 9a671a16e7 Adds a way to peak into inner values of event holders and generate truly unique ids 2024-12-04 21:28:56 +01:00
Dandaedre 4cbeadaeeb Changes names for import's sake 2024-12-04 08:15:45 -06:00
Dandaedre 53b8f1df3e Adds more persistence tests 2024-12-03 05:46:59 -06:00
Dandaedre e179620113 Adds a mock of (untested) persistence 2024-12-01 18:42:52 +01:00
Dandaedre bbd008b092 Changes uuid::id to String with human_ids 2024-12-01 17:33:13 +01:00
Dandaedre 1a055c7e2a Adds a little more testing and coverage 2024-11-30 18:19:46 +01:00
22 changed files with 1263 additions and 236 deletions

4
.gitignore vendored
View File

@ -3,6 +3,8 @@
# will have compiled files and executables # will have compiled files and executables
debug/ debug/
target/ target/
test/
bobito/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # 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 # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
@ -28,3 +30,5 @@ tarpaulin-report.html
# A module summary # A module summary
summary.md summary.md
config.json

View File

@ -3,26 +3,18 @@ name = "idlefox"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
[features]
custom_emojis = []
[dependencies] [dependencies]
poise = "0.6.1" poise = "0.6.1"
poise_macros = "0.6.1"
tokio = { version = "1.41.0", features = ["rt-multi-thread"] } tokio = { version = "1.41.0", features = ["rt-multi-thread"] }
chrono = { version = "0.4.38", features = ["serde"] } chrono = { version = "0.4.38", features = ["serde"] }
human_ids = "0.1.1" human_ids = "0.1.1"
once_cell = { version = "1.20.2", features = ["std"] }
serde = { version = "1.0.214", features = ["alloc", "derive"] } serde = { version = "1.0.214", features = ["alloc", "derive"] }
thiserror = "1.0.65" thiserror = "1.0.65"
tracing = { version = "0.1.40", features = ["async-await", "std"] }
uuid = { version = "1.11.0", features = ["v4", "v7", "serde", "fast-rng"] }
simplelog = { version = "0.12.2", features = ["paris"] } simplelog = { version = "0.12.2", features = ["paris"] }
log = { version = "0.4.22", features = ["std"] } log = { version = "0.4.22", features = ["std"] }
nom = "7.1.3" nom = "7.1.3"
criterion = "0.5" criterion = "0.5"
serde_json = { version = "1.0.132", features = ["alloc"] } serde_json = { version = "1.0.132", features = ["alloc"] }
postcard = { version = "1.0.10", features = ["alloc"] }
ron = "0.8.1" ron = "0.8.1"
distance = "0.4.0" distance = "0.4.0"

326
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,326 @@
// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post
pipeline {
agent { label 'rust_no_docker' }
environment {
CARGO_TERM_COLOR = 'always'
RUST_BACKTRACE = '1'
// CI gets its own Cargo home. This prevents ~/.cargo/config*
// from injecting host-specific linker options.
CARGO_HOME = "${WORKSPACE}/.ci-cargo-home"
// Keep CI artifacts separate from local/project builds.
CARGO_TARGET_DIR = "${WORKSPACE}/target-ci"
// Explicitly use the native FreeBSD compiler/linker.
CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER = 'cc'
// Explicitly neutralize environment-provided Rust flags.
RUSTFLAGS = ''
CARGO_ENCODED_RUSTFLAGS = ''
}
stages {
stage('Checkout') {
steps {
checkout scm
sh '''
set -eu
git submodule sync --recursive
git submodule update --init --recursive
'''
}
}
stage('Setup Rust') {
steps {
sh '''
set -eu
if ! command -v rustup >/dev/null 2>&1; then
echo "ERROR: rustup is not installed on this worker." >&2
exit 1
fi
echo "Ensuring stable Rust is available..."
rustup toolchain install stable \
--profile minimal \
--component rustfmt \
--component clippy
rustup default stable
# ---------------------------------------------------------
# Prepare isolated Cargo environment
# ---------------------------------------------------------
rm -rf "${CARGO_HOME}"
mkdir -p "${CARGO_HOME}"
rm -rf "${CARGO_TARGET_DIR}"
mkdir -p "${CARGO_TARGET_DIR}"
# Cargo discovers .cargo/config* by walking upward from the
# current working directory. We therefore invoke Cargo from
# a neutral directory outside the repository.
CI_RUN_DIR="/tmp/idlefox-ci-${BUILD_NUMBER}"
rm -rf "${CI_RUN_DIR}"
mkdir -p "${CI_RUN_DIR}"
echo "${CI_RUN_DIR}" > .ci-run-dir
# ---------------------------------------------------------
# Information
# ---------------------------------------------------------
echo
echo "Rust:"
rustc --version
echo
echo "Cargo:"
cargo --version
echo
echo "rustfmt:"
rustfmt --version
echo
echo "Clippy:"
cargo clippy --version
echo
echo "Compiler:"
cc --version
echo
echo "Rust target:"
rustc -vV
echo
echo "Cargo home:"
echo "${CARGO_HOME}"
echo
echo "Cargo target directory:"
echo "${CARGO_TARGET_DIR}"
echo
echo "Neutral Cargo working directory:"
cat .ci-run-dir
echo
echo "Repository Cargo configuration files:"
find "${WORKSPACE}" \
-path '*/.cargo/config' \
-o \
-path '*/.cargo/config.toml' \
2>/dev/null || true
echo
echo "Any mold references in repository Cargo configuration:"
if [ -d "${WORKSPACE}/.cargo" ]; then
grep -Rni 'mold' "${WORKSPACE}/.cargo" || true
fi
echo
echo "CI linker:"
echo "${CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER}"
'''
}
}
stage('Format') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking Rust formatting..."
cargo fmt \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all \
-- \
--check
'''
}
}
stage('Check') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking all IdleFox targets..."
cargo check \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Test') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Running IdleFox tests..."
cargo test \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Clippy') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Running Clippy..."
cargo clippy \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Check Benchmarks') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking benchmark compilation..."
cargo check \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--benches \
--all-features
'''
}
}
stage('Build Release') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Building IdleFox release..."
cargo build \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--release \
--all-features
echo
echo "Release build completed."
BINARY="${CARGO_TARGET_DIR}/release/idlefox"
if [ ! -f "${BINARY}" ]; then
echo "ERROR: expected release binary was not produced:"
echo "${BINARY}"
exit 1
fi
echo
echo "Release binary:"
ls -lh "${BINARY}"
echo
echo "Binary type:"
file "${BINARY}" || true
'''
}
}
}
post {
success {
publishChecks(
conclusion: 'SUCCESS',
name: 'Rust CI',
summary: 'IdleFox passed all CI checks.',
text: 'Formatting, compilation checks, tests, Clippy, benchmark compilation, and release build completed successfully using the native FreeBSD linker.',
title: 'Build Successful'
)
echo '✅ IdleFox passed all CI checks.'
}
failure {
publishChecks(
conclusion: 'FAILURE',
name: 'Rust CI',
summary: 'IdleFox failed CI.',
text: 'Formatting, compilation, tests, Clippy, benchmarks, or the release build failed. Check the Jenkins log.',
title: 'Build Failed'
)
echo '❌ IdleFox CI failed.'
}
unstable {
publishChecks(
conclusion: 'ACTION_REQUIRED',
name: 'Rust CI',
summary: 'IdleFox CI is unstable.',
text: 'The Jenkins build completed with an unstable status.',
title: 'Build Unstable'
)
echo '⚠️ IdleFox CI is unstable.'
}
always {
sh '''
echo "Cleaning IdleFox CI environment..."
if [ -f .ci-run-dir ]; then
CI_RUN_DIR="$(cat .ci-run-dir)"
rm -rf "${CI_RUN_DIR}"
fi
rm -f .ci-run-dir
rm -rf .ci-cargo-home
# Keep target-ci for now so Jenkins retains incremental
# compilation between builds. Uncomment to make every build
# completely clean:
#
# rm -rf target-ci
'''
}
}
}

View File

@ -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. - `votes.rs`: Manages event and vote data structures, enabling voting functionality within Discord servers.
- `persistence.rs`: Ensures data persistence and integrity between bot runs. - `persistence.rs`: Ensures data persistence and integrity between bot runs.
- `server.rs`: Provides server-related functionalities, such as displaying votes and closing ongoing votes. - `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. - `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. A great emphasis is put on organizing the votes themselves, delaying posting them and editing the answers as time goes.

View File

@ -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: 84%"><title>test-coverage: 84%</title><linearGradient id="bms-c15e65abae712a1a" 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-c15e65abae712a1a"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-c15e65abae712a1a)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-c15e65abae712a1a)"/></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">84%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">84%</text></g></svg> <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: 88%"><title>test-coverage: 88%</title><linearGradient id="bms-7f01f1ef66d48313" 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-7f01f1ef66d48313"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-7f01f1ef66d48313)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-7f01f1ef66d48313)"/></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">88%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">88%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -2,12 +2,12 @@
//! //!
//! This module provides a centralized configuration system for IdleFox, allowing you to load and manage your settings in an efficient and flexible manner. //! This module provides a centralized configuration system for IdleFox, allowing you to load and manage your settings in an efficient and flexible manner.
//! //!
//! The primary goal of this module is to provide a robust and reliable way to store and retrieve configuration data from the `.idlefox.toml` file. //! The primary goal of this module is to provide a robust and reliable way to store and retrieve configuration data from the `config.json` file.
//! If the file does not exist or cannot be loaded, it will automatically create a default version for you. //! If the file does not exist or cannot be loaded, it will automatically create a default version for you.
//! //!
//! ### Key Features //! ### Key Features
//! //!
//! * **Config Loading**: Seamlessly load your existing config from the `.idlefox.toml` file, ensuring that all settings are preserved and up-to-date. //! * **Config Loading**: Seamlessly load your existing config from the `config.json` file, ensuring that all settings are preserved and up-to-date.
//! * **Default Config Creation**: Automatically generate a default configuration if the specified file cannot be loaded or is missing. //! * **Default Config Creation**: Automatically generate a default configuration if the specified file cannot be loaded or is missing.
//! * **Legacy Data Import**: Safely import old data from outdated configurations to minimize disruptions during upgrades. //! * **Legacy Data Import**: Safely import old data from outdated configurations to minimize disruptions during upgrades.
//! * **Faulty Data Recovery**: Implement measures to recover from importing faulty data, ensuring that your IdleFox instance remains stable and functional. //! * **Faulty Data Recovery**: Implement measures to recover from importing faulty data, ensuring that your IdleFox instance remains stable and functional.
@ -32,18 +32,131 @@
//! # } //! # }
//! //!
use std::fs::File; #![allow(clippy::all)]
use crate::IdleError;
use std::{fs::File, io::Write};
use log::LevelFilter; use log::LevelFilter;
use poise::serenity_prelude::{EmojiId, ReactionType};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger}; use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger};
use crate::error_handling::IdleError; pub type WeeklyReactionList = Vec<ReactionType>;
/// The global config /// A structure representing the global configuration for a Discord bot.
/// TODO: Update this doc as the config module is done ///
/// This struct contains various settings and parameters that influence how the bot
/// operates, such as which type of reaction is selected to indicate different days
/// in a weekly schedule, and custom emotes or Unicode characters used for reactions.
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub(crate) struct GlobalConfig {} pub struct GlobalConfig {
/// The type of reaction selected by the user. Either the default unicode emote or a custom set of emotes.
selected_reaction: SelectedReaction,
/// The list of 7 weekly emotes to use as reaction to indicate the weekly days.
custom_weekly_emotes: WeeklyReactionList,
/// The list of 7 weekly unicode emotes to use as reaction to indicate the weekly days.
custom_weekly_unicode: WeeklyReactionList,
}
impl Default for GlobalConfig {
fn default() -> Self {
GlobalConfig {
selected_reaction: SelectedReaction::Emotes,
custom_weekly_emotes: Self::emotes(),
custom_weekly_unicode: Self::unicode(),
}
}
}
impl GlobalConfig {
/// Try to load the config from disk and return a default config if none is found
pub fn try_load_from_disk() -> Result<GlobalConfig, IdleError> {
// let f = File::open("config.json").map_err(IdleError::LoadingConfig)?;
if let Ok(f) = File::open("config.json") {
Ok(serde_json::from_reader(f).map_err(IdleError::SerdeError)?)
} else {
Ok(GlobalConfig::default())
}
}
/// Try to save the config to disk
// Testing a bad serialisation is pointless
#[cfg(not(tarpaulin_include))]
pub fn try_save_to_disk(&self) -> Result<(), IdleError> {
let mut f = File::create("config.json").map_err(IdleError::SavingConfig)?;
f.write_all(
serde_json::to_string_pretty(&self)
.map_err(IdleError::SerdeError)?
.as_bytes(),
)
.map_err(IdleError::SavingConfig)?;
Ok(())
}
/// Generate the custom emote variant of the reactions
#[cfg(not(tarpaulin_include))]
fn emotes() -> WeeklyReactionList {
vec![
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486629961859154),
name: Some("Lu".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486631182405642),
name: Some("Ma".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486632352612424),
name: Some("Me".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486628409835642),
name: Some("Je".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486635087302737),
name: Some("Ve".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486633271169107),
name: Some("Sa".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486626023276604),
name: Some("Di".to_string()),
},
]
}
/// Generate the unicode variant of the reactions
fn unicode() -> WeeklyReactionList {
vec![
ReactionType::Unicode("1️⃣".to_string()),
ReactionType::Unicode("2️⃣".to_string()),
ReactionType::Unicode("3️⃣".to_string()),
ReactionType::Unicode("4️⃣".to_string()),
ReactionType::Unicode("5️⃣".to_string()),
ReactionType::Unicode("6️⃣".to_string()),
ReactionType::Unicode("7️⃣".to_string()),
]
}
}
/// The type of reaction to use
#[derive(Serialize, Deserialize)]
enum SelectedReaction {
/// Use the custom emotes provided
Emotes,
/// Use the default unicode one
Unicode,
}
/// Initializes a logger for logging purposes. /// Initializes a logger for logging purposes.
/// ///
@ -80,3 +193,42 @@ pub fn init_logger() -> Result<(), IdleError> {
]) ])
.map_err(IdleError::LoggerInitFailure) .map_err(IdleError::LoggerInitFailure)
} }
#[cfg(test)]
mod tests {
use std::fs;
use poise::serenity_prelude::ReactionType;
use super::GlobalConfig;
#[test]
fn test_default_cfg() {
let d = GlobalConfig::default();
assert!(d.custom_weekly_emotes.len() >= 7);
assert!(d.custom_weekly_unicode.len() >= 7);
for e in d.custom_weekly_emotes {
if let ReactionType::Custom {
animated,
id: _,
name,
} = e
{
assert_eq!(animated, false);
assert!(name.is_some());
}
}
}
#[test]
fn test_save_cfg() {
let c = GlobalConfig::default();
let try_save_to_disk = c.try_save_to_disk();
assert!(try_save_to_disk.is_ok());
}
#[test]
fn test_load_cfg() {
let _ = fs::remove_file("config.json");
let try_load_from_disk = GlobalConfig::try_load_from_disk();
assert!(try_load_from_disk.is_ok());
}
}

View File

@ -148,8 +148,8 @@ pub enum NaiveDateObject {
/// This struct provides an abstraction over a list of date objects, enabling both sequential iteration /// 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 /// 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. /// different sources of date information, allowing for flexible data manipulation based on the provided dates.
#[derive(Debug, Default, Serialize, Deserialize)] #[derive(Debug, Default, Serialize, Deserialize, Clone)]
#[cfg_attr(test, derive(PartialEq, Clone))] #[cfg_attr(test, derive(PartialEq, Eq))]
pub struct NaiveDateList { pub struct NaiveDateList {
/// The inner vector /// The inner vector
inner: Vec<NaiveDateObject>, inner: Vec<NaiveDateObject>,
@ -327,7 +327,7 @@ pub fn parse_single_date(input: &str, context: Option<NaiveDate>) -> Result<Naiv
} }
#[cfg(test)] #[cfg(test)]
pub(crate) mod tests { mod tests {
use super::*; use super::*;
use crate::date::date_parse::DateRange; use crate::date::date_parse::DateRange;
@ -500,4 +500,20 @@ pub(crate) mod tests {
// Simple roundtrip assertion // Simple roundtrip assertion
assert_eq!(list, ron::from_str(&s).unwrap()); assert_eq!(list, ron::from_str(&s).unwrap());
} }
#[test]
fn test_parse_single() {
let cx = NaiveDate::from_ymd_opt(2023, 2, 12);
let tv = vec![
("ven", cx, NaiveDate::from_ymd_opt(2023, 2, 17).unwrap()),
("11", cx, NaiveDate::from_ymd_opt(2023, 3, 11).unwrap()),
("22", cx, NaiveDate::from_ymd_opt(2023, 2, 22).unwrap()),
("dec 30", cx, NaiveDate::from_ymd_opt(2023, 12, 30).unwrap()),
];
for (input, context, res) in tv {
println!("{:?} ({:?}) => {:?}", input, Some(context), res);
assert_eq!(parse_single_date(input, context).unwrap(), res);
}
}
} }

View File

@ -17,7 +17,7 @@
//! left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`. //! left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`.
//! The function uses the context provided to resolve any relative dates within the input string. //! The function uses the context provided to resolve any relative dates within the input string.
//! //!
//! - [`parse_single_date`]: This function parses a given input string representing a single date and returns a `NaiveDate`. //! - [parse_single_date]: This function parses a given input string representing a single date and returns a `NaiveDate`.
//! If there are any unparsed parts left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`. //! If there are any unparsed parts left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`.
//! The function uses the context provided to resolve any relative dates within the input string. //! The function uses the context provided to resolve any relative dates within the input string.
//! //!

View File

@ -9,7 +9,8 @@ use chrono::Month;
use log::SetLoggerError; use log::SetLoggerError;
use poise::serenity_prelude; use poise::serenity_prelude;
use thiserror::Error; use thiserror::Error;
use uuid::Uuid;
use crate::ids::EventIdType;
/// Global error struct for idlefox /// Global error struct for idlefox
/// ///
@ -53,32 +54,32 @@ pub enum IdleError {
/// Indicates an event couldn't be launched /// Indicates an event couldn't be launched
/// ///
/// Raised when there's an issue launching an event usually indicates something went wrong with bookeeping. /// Raised when there's an issue launching an event usually indicates something went wrong with bookeeping.
/// Note that while a UUID is given, it may no longer exist in memory and might only be found in logs. /// Note that while a HUID is given, it may no longer exist in memory and might only be found in logs.
#[error("An event couldn't be launched (Id: {0})")] #[error("An event couldn't be launched (Id: {0})")]
EventLaunch(Uuid), EventLaunch(EventIdType),
/// Error indicating multiple events couldn't be pruned /// Error indicating multiple events couldn't be pruned
/// ///
/// Raised when one or more events cannot be removed from the ongoing events list. /// Raised when one or more events cannot be removed from the ongoing events list.
/// This usually indicates a problem with managing and updating the list of ongoing events. /// This usually indicates a problem with managing and updating the list of ongoing events.
/// Note that while a UUID is given, it may no longer exist in memory and might only be found in logs. /// Note that while a HUID is given, it may no longer exist in memory and might only be found in logs.
#[error("One or more events couldn't be removed from the ongoing events list (Id(s): {0:?})")] #[error("One or more events couldn't be removed from the ongoing events list (Id(s): {0:?})")]
EventPrune(Vec<Uuid>), EventPrune(Vec<EventIdType>),
/// Error indicating an event could not be deleted /// Error indicating an event could not be deleted
/// ///
/// This error is raised when attempting to delete an event fails, /// This error is raised when attempting to delete an event fails,
/// either due to a problem with bookkeping or because the specified UUID /// either due to a problem with bookkeping or because the specified HUID
/// does not correspond to any existing events anymore. /// does not correspond to any existing events anymore.
#[error("An event couldn't be deleted (Id: {0})")] #[error("An event couldn't be deleted (Id: {0})")]
DeleteEvent(Uuid), DeleteEvent(EventIdType),
/// Error indicating that an ongoing event launch couldn't be performed /// Error indicating that an ongoing event launch couldn't be performed
/// ///
/// This error was likely raised as a launch operation for an event was already underway. /// This error was likely raised as a launch operation for an event was already underway.
/// Launching multiple times for the same event may lead to inconsistent states or data corruption. /// Launching multiple times for the same event may lead to inconsistent states or data corruption.
#[error("Couldn't launch event (Id: {0})")] #[error("Couldn't launch event (Id: {0})")]
LaunchingEvent(Uuid), LaunchingEvent(EventIdType),
/// Error indicating a mutex was poisoned or couldn't be acquired /// Error indicating a mutex was poisoned or couldn't be acquired
/// ///
@ -89,14 +90,34 @@ pub enum IdleError {
/// Represents an error while acquiring a Discord group /// Represents an error while acquiring a Discord group
/// ///
/// Raised when there is an error attempting to acquire the discord group /// Raised when there is an error attempting to acquire the discord group
#[error("An error occured while tring to acquire the discord group: {0}")] #[error("An error occured while trying to acquire the discord group: {0}")]
AcquiringDiscordGroup(String), AcquiringDiscordGroup(String),
/// Indicates an error while acquiring Discord guilds /// Indicates an error while acquiring Discord guilds
/// ///
/// This may happen when a function was called outside of the context of a server (likely a DM to the bot). /// This may happen when a function was called outside of the context of a server (likely a DM to the bot).
#[error("An error occured while tring to acquire discord guilds")] #[error("An error occured while trying to acquire discord guilds")]
AcquiringDiscordGuild, AcquiringDiscordGuild,
/// Indicates an error occuring while trying to convert from a DiscordContainer into a ParsedVote
///
/// 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 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} {1}")]
BackupWriteError(String, 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} {1}")]
BackupReadError(String, std::io::Error),
/// Indicate a value couldn't be serialized
#[error("An error occured while trying to serialize data {0}")]
SerdeError(serde_json::Error),
/// Indlcate the config couldn't be loaded properly
#[error("An error occured while trying to load the config {0}")]
LoadingConfig(std::io::Error),
/// Indlcate the config couldn't be saved properly
#[error("An error occured while trying to save the config {0}")]
SavingConfig(std::io::Error),
} }
impl From<nom::Err<nom::error::Error<&str>>> for IdleError { impl From<nom::Err<nom::error::Error<&str>>> for IdleError {

View File

@ -1,13 +1,67 @@
//! Handle all Ids functionalities //! This module contains utilities for generating event ids.
//! //!
//! Features: //! Features:
//! Generating a human readable ID for a UUID //! Generating a human readable ID for a HUID
//! Finding the UUID from an ID //! Finding the HUID from an ID
//! Removing ID as needed //! Removing ID as needed
// use human_ids::generate; use crate::votes::EventHolder;
// use std::{env, time::Instant};
// let tk = env::var("DISCORD_TOKEN"); /// Generic type representing an ID
// let id = generate(None); pub type EventIdType = String;
// println!("Token: {:?} Id: {}", tk, id);
/// 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) {
// Testing this collision is not possible
#[cfg(not(tarpaulin_include))]
true => generate_unique_id(holder),
false => id,
}
}
#[cfg(test)]
mod test {
use crate::votes::{add_pending_event, EventHolder, EventPending};
use super::{generate_id, generate_unique_id};
#[test]
fn test_id_generation() {
let id = generate_id();
assert!(!id.is_empty())
}
#[test]
fn test_id_unique() {
let holder = EventHolder::default();
add_pending_event(EventPending::default(), &holder).unwrap();
let id = generate_unique_id(&holder);
assert!(!id.is_empty());
}
}

View File

@ -26,7 +26,6 @@ use crate::modules::handler;
use crate::votes::EventHolder; use crate::votes::EventHolder;
use distance::levenshtein; use distance::levenshtein;
use poise::serenity_prelude::{self as serenity}; use poise::serenity_prelude::{self as serenity};
use poise::Modal as _; use poise::Modal as _;
use crate::error_handling::IdleError; use crate::error_handling::IdleError;
@ -92,7 +91,7 @@ pub enum VoteTypeIdentifier {
WeeklyVote, WeeklyVote,
/// Represents a short-term vote, that can be of any length and can be cast at any time without any form or plan. /// Represents a short-term vote, that can be of any length and can be cast at any time without any form or plan.
ShortVote, 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, LongVote,
/// Indicates that the vote type has not been set yet, should only be used by default and is not a valid value. /// Indicates that the vote type has not been set yet, should only be used by default and is not a valid value.
#[default] #[default]
@ -423,5 +422,16 @@ mod tests {
find_role_from_str(Some("ffxivpogfish"), arguments.to_vec()), find_role_from_str(Some("ffxivpogfish"), arguments.to_vec()),
Some("ffxiv_progfish".to_string()) Some("ffxiv_progfish".to_string())
); );
assert!(find_role_from_str(None, arguments.to_vec()).is_none());
assert!(find_role_from_str(Some("Bob"), Vec::new()).is_none());
}
#[test]
fn create_container() {
VoteContainer::new(
"IO".to_string(),
"desc".to_string(),
VoteTypeIdentifier::WeeklyVote,
);
} }
} }

View File

@ -10,19 +10,19 @@
#![warn(clippy::missing_docs_in_private_items)] #![warn(clippy::missing_docs_in_private_items)]
pub mod config; // Maybe in lib pub mod config; // Maybe in lib
pub mod date; // Definitely in lib pub mod date; // Definitely in lib
mod error_handling; // Likely in lib mod error_handling; // Likely in lib
mod ids; // Definitely in lib pub mod ids; // Definitely in lib
pub mod io; // Maybe in lib pub mod io; // Maybe in lib
mod modules; // Maybe in lib mod modules; // Maybe in lib
mod persistence; // Likely in lib mod persistence; // Likely in lib
mod server; // Maybe in lib mod server; // Maybe in lib
pub mod votes; // Likely in lib pub mod votes; // Likely in lib
mod watchdog; // Definitely in lib mod watchdog; // Definitely in lib
// // Re export // // Re export
// pub use votes::add_future_event; // pub use votes::add_future_event;
// pub use votes::launch_future_event; // pub use votes::launch_future_event;
//
pub use error_handling::IdleError; pub use error_handling::IdleError;
pub use watchdog::main_scheduler_loop; pub use watchdog::main_scheduler_loop;

View File

@ -6,7 +6,105 @@
//! //!
//! //!
use crate::IdleError;
use serde::{de::DeserializeOwned, Serialize};
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_reader<Data, Reader>(rdr: Reader) -> Data
where
Data: Default + DeserializeOwned,
Reader: Read + Sized,
{
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_from_reader {
($r_type:ident, $path:expr) => {
Arc::new(std::sync::Mutex::new(load_from_reader::<$r_type, File>(
File::open($path).map_err(|e| IdleError::BackupReadError($path.to_owned(), e))?,
)))
};
}
// Testing a bad serialisation is pointless
#[cfg(not(tarpaulin_include))]
/// Tries to save the list to disk and return an error on failure
pub(crate) fn save_to_writer<Data, Writer>(data: Data, mut writer: Writer) -> Result<(), IdleError>
where
Data: Serialize,
Writer: Write + Sized + std::fmt::Debug,
{
writer
.write(
serde_json::to_string_pretty(&data)
.map_err(IdleError::SerdeError)?
.as_bytes(),
)
.map_err(|e| IdleError::BackupWriteError(format!("{:?}", writer), e))?;
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_to_writer {
($value:expr, $r_type:ident, $path:expr) => {
save_to_writer::<&$r_type, File>(
&$value.lock().unwrap(),
File::create($path).map_err(|e| IdleError::BackupWriteError($path.to_string(), e))?,
)?;
};
}
#[cfg(test)] #[cfg(test)]
mod tests { 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();
for _ in 0..10 {
e.add_pending_event(EventPending::default())?;
}
}
let _ = remove_dir_all("test");
let _ = create_dir("test");
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()
);
Ok(())
}
} }

View File

@ -4,6 +4,10 @@
//! Show all votes (pending and happening) //! Show all votes (pending and happening)
//! Allow vote closing //! 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)] #[cfg(test)]
mod tests { mod tests {

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, /// 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. /// including which user casted it, which event it pertains to, and what value or option was voted for.
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(test, derive(Clone))] #[cfg_attr(test, derive(Eq, PartialEq))]
pub struct Ballot { pub struct Ballot {
/// The event the vote refers to /// The event the vote refers to
linked_event: EventIdType, linked_event: EventIdType,

View File

@ -10,20 +10,25 @@
//! can be in, such as planned, ongoing, closed, and cancelled. This helps //! can be in, such as planned, ongoing, closed, and cancelled. This helps
//! to track and manage the progression of each voting event according to //! to track and manage the progression of each voting event according to
//! predefined rules and conditions. //! predefined rules and conditions.
#![allow(dead_code)]
use std::fmt::Display; use std::fmt::Display;
use chrono::NaiveDateTime; use chrono::{Days, Local, NaiveDate, NaiveDateTime, NaiveTime};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{date::NaiveDateList, io::VoteContainer, IdleError}; use crate::{
date::{parse_date_list, parse_single_date, NaiveDateList},
io::{VoteContainer, VoteTypeIdentifier},
IdleError,
};
use super::Ballot; use super::Ballot;
/// A pending event, waiting to be opened. In this state the even can be safely modified /// 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. /// and either manual input or the autostart date will start the vote.
#[derive(Serialize, Deserialize, Default)] #[derive(Serialize, Deserialize, Default, Clone)]
#[cfg_attr(test, derive(Clone))] #[cfg_attr(test, derive(Debug, PartialEq, Eq))]
pub struct EventPending { pub struct EventPending {
/// The parsed representation of the vote associated with this event. /// The parsed representation of the vote associated with this event.
/// It holds the details required for the voting process. /// It holds the details required for the voting process.
@ -38,8 +43,8 @@ impl EventPending {
} }
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize, Clone)]
#[cfg_attr(test, derive(Clone))] #[cfg_attr(test, derive(Debug, PartialEq))]
// An ongoing event, waiting to be closed thus allowing the ballots to be counted. // An ongoing event, waiting to be closed thus allowing the ballots to be counted.
pub struct EventOngoing { pub struct EventOngoing {
/// The parsed representation of the vote associated with this event. /// The parsed representation of the vote associated with this event.
@ -61,8 +66,8 @@ impl EventOngoing {
} }
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize, Clone)]
#[cfg_attr(test, derive(Clone))] // #[cfg_attr(test, derive(Clone))]
/// A closed event, while the users cannot interract with it in this state, /// 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. /// 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 /// All events have an expiry date and in this state the event will be cleaned
@ -81,8 +86,8 @@ pub struct EventClosed {
/// This structure is specifically used within the application to encapsulate both /// 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 /// ongoing and planned voting events, providing a clear and organized way to manage their
/// data throughout their lifecycle. /// data throughout their lifecycle.
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
#[cfg_attr(test, derive(Clone))] #[cfg_attr(test, derive(Eq, PartialEq))]
pub(super) struct ParsedVote { pub(super) struct ParsedVote {
/// The title of the even /// The title of the even
pub(super) title: String, pub(super) title: String,
@ -105,18 +110,56 @@ impl ParsedVote {
pub(super) fn launch(&mut self) -> Result<(), IdleError> { pub(super) fn launch(&mut self) -> Result<(), IdleError> {
// TODO: Define this // TODO: Define this
// self.status = EventStatus::Started; // self.status = EventStatus::Started;
// Maybe send a message ? the bot will need the Uuid of the event to be able to add reaction // Maybe send a message ? the bot will need the Huid of the event to be able to add reaction
// TODO: This is a vkypoint, as this method will need an IO interaction // TODO: This is a vkypoint, as this method will need an IO interaction
Ok(()) Ok(())
} }
} }
impl TryFrom<VoteContainer> for ParsedVote { impl ParsedVote {
type Error = IdleError; /// Try to parse a vote from a votecontainer
fn try_from_with_context(
fn try_from(value: VoteContainer) -> Result<Self, Self::Error> { value: VoteContainer,
let _ = value; context: Option<NaiveDate>,
todo!() vote_type: VoteTypeIdentifier,
) -> Result<Self, IdleError> {
let context = context.unwrap_or(Local::now().date_naive());
let close_date = parse_single_date(
&value.date_end.ok_or(IdleError::DiscordContainerParse)?,
Some(context),
)?
.and_time(NaiveTime::from_hms_opt(20, 00, 00).unwrap());
// TODO: Have a better auto_delete threshold
let auto_delete_date = close_date.checked_add_days(Days::new(12)).unwrap();
// TODO: Use this to have better date selection handling
match vote_type {
VoteTypeIdentifier::WeeklyVote => {
// Start is next week, end is end of week, days is all week
}
VoteTypeIdentifier::ShortVote => {
// Start is ?, end is ?, days must be given
}
VoteTypeIdentifier::LongVote => (),
VoteTypeIdentifier::Uninitialised => (),
}
Ok(Self {
title: value.title,
description: value.description,
// TODO: Have a logic to find a good start date
launch_date: parse_single_date(
&value.start_date.ok_or(IdleError::DiscordContainerParse)?,
Some(context),
)?
.and_time(NaiveTime::from_hms_opt(20, 00, 00).unwrap()),
close_date,
auto_delete_date,
votes: Vec::new(),
// TODO: How can days be empty ? Add the non_days.
list_candidates: parse_date_list(
&value.days.ok_or(IdleError::DiscordContainerParse)?,
Some(context),
)?,
})
} }
} }
@ -127,3 +170,35 @@ impl Display for ParsedVote {
write!(f, "{:?}", self) write!(f, "{:?}", self)
} }
} }
#[cfg(test)]
mod test {
use super::{EventPending, ParsedVote};
use crate::io::{VoteContainer, VoteTypeIdentifier};
use chrono::NaiveDate;
#[test]
// TODO: Complete this test
fn test_display() {
let pv = ParsedVote::default();
let _ = format!("{}", pv);
let eo = EventPending::default().into_ongoing();
let _ = format!("{}", eo);
}
#[test]
#[ignore]
// TODO: Complete this test
fn test_conversion() {
let cx = NaiveDate::from_ymd_opt(2000, 12, 12);
let v = ParsedVote::try_from_with_context(
VoteContainer::default(),
cx,
VoteTypeIdentifier::WeeklyVote,
);
println!("{:?}", v);
assert!(v.is_ok());
}
}

View File

@ -1,17 +1,23 @@
//! Submodule including all helper functions to handle vote creation and evolution //! Submodule including all helper functions to handle vote creation and evolution
//! //!
use std::sync::Arc; use crate::{config::GlobalConfig, votes::traits::BorrowInner};
use chrono::NaiveDate; use chrono::NaiveDate;
use uuid::Uuid; use std::{
fs::{create_dir, File},
use crate::IdleError; sync::Arc,
};
use super::{ use super::{
events::{EventOngoing, EventPending}, events::{EventOngoing, EventPending},
holders::ListClosedEvents, holders::{ListClosedEvents, TypedEvent},
ListOngoingEvents, ListPendingEvents, ListOngoingEvents, ListPendingEvents,
}; };
use crate::{
ids::EventIdType,
load_from_reader,
persistence::{load_from_reader, save_to_writer},
save_to_writer, IdleError,
};
/// Adds a parsed vote to the list of planned events. /// Adds a parsed vote to the list of planned events.
/// ///
@ -28,21 +34,25 @@ use super::{
/// let parsed_vote = EventPending::default(); /// let parsed_vote = EventPending::default();
/// let id = add_pending_event(parsed_vote, &ev_ctx).unwrap(); /// let id = add_pending_event(parsed_vote, &ev_ctx).unwrap();
/// ``` /// ```
pub fn add_pending_event(event: EventPending, ev_ctx: &EventHolder) -> Result<Uuid, IdleError> { pub fn add_pending_event(
event: EventPending,
ev_ctx: &EventHolder,
) -> Result<EventIdType, IdleError> {
ev_ctx ev_ctx
.pending_events .pending_events
.lock() .lock()
.unwrap() .unwrap()
// .map_err(|_| IdleError::MutexError)?
.add_pending_event(event) .add_pending_event(event)
} }
/// Launches a pending event by transferring it from the pending to ongoing events list. /// Launches a pending event by transferring it from the pending to ongoing events list.
/// ///
/// This function identifies an event by its UUID and moves it from the planned (pending) events to the ongoing events. If the event is successfully launched, it returns `Ok(())`. Otherwise, it returns an error of type `IdleError`. /// This function identifies an event by its HUID and moves it from the planned
/// (pending) events to the ongoing events. If the event is successfully launched, it returns `Ok(())`.
/// Otherwise, it returns an error of type `IdleError`.
/// ///
/// ## Parameters: /// ## Parameters:
/// - `uuid`: A `Uuid` that uniquely identifies the event to be launched. /// - `Huid`: A `Huid` that uniquely identifies the event to be launched.
/// ///
/// ## Example: /// ## Example:
/// ```rust /// ```rust
@ -50,39 +60,33 @@ pub fn add_pending_event(event: EventPending, ev_ctx: &EventHolder) -> Result<Uu
/// let ev_ctx = EventHolder::default(); /// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap(); /// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
/// ///
/// make_into_ongoing_event(id, &ev_ctx).unwrap() /// make_into_ongoing_event(&id, &ev_ctx).unwrap()
/// ``` /// ```
pub fn make_into_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> { pub fn make_into_ongoing_event(huid: &EventIdType, ev_ctx: &EventHolder) -> Result<(), IdleError> {
ev_ctx ev_ctx.pending_events.lock().unwrap().launch(huid, ev_ctx)
.pending_events
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.launch(uuid, ev_ctx)
} }
/// Manually adds an ongoing event. /// Manually adds an ongoing event.
/// ///
/// This function is intended for internal use and directly adds an event /// This function is intended for internal use and directly adds an event
/// to the list of ongoing events. It expects a UUID and a parsed vote as inputs, /// to the list of ongoing events. It expects a HUID and a parsed vote as inputs,
/// using which it updates the `OngoingEvents` instance. /// using which it updates the `OngoingEvents` instance.
/// ///
/// ## Parameters: /// ## Parameters:
/// - `uuid`: A `Uuid` that uniquely identifies the event to be added. /// - `huid`: A `Huid` that uniquely identifies the event to be added.
/// - `event`: A `ParsedVote` struct representing the details of the ongoing event to be added. /// - `event`: A `ParsedVote` struct representing the details of the ongoing event to be added.
/// ///
/// ## Example: /// ## Example:
/// ```rust /// ```rust
/// # use uuid::Uuid; /// use idlefox::ids::generate_id;
/// use idlefox::votes::{add_ongoing_event, EventPending, EventHolder}; /// use idlefox::votes::{add_ongoing_event, EventHolder, EventPending};
/// let ev_ctx = EventHolder::default(); /// let ev_ctx = EventHolder::default();
/// let uuid = Uuid::new_v4(); // A new id /// let huid = generate_id(); // A new id
/// let ongoing = EventPending::default().into_ongoing(); // A very legit event /// let ongoing = EventPending::default().into_ongoing(); // A very legit event
/// /// add_ongoing_event(&huid, ongoing, &ev_ctx).unwrap();
/// add_ongoing_event(uuid, ongoing, &ev_ctx).unwrap();
/// ``` /// ```
pub fn add_ongoing_event( pub fn add_ongoing_event(
uuid: Uuid, huid: &EventIdType,
event: EventOngoing, event: EventOngoing,
ev_ctx: &EventHolder, ev_ctx: &EventHolder,
) -> Result<(), IdleError> { ) -> Result<(), IdleError> {
@ -90,15 +94,14 @@ pub fn add_ongoing_event(
.ongoing_events .ongoing_events
.lock() .lock()
.unwrap() .unwrap()
// .map_err(|_| IdleError::MutexError)? .add_event(huid, event)?;
.add_event(uuid, event)?;
Ok(()) Ok(())
} }
/// Destroy an event without closing it and officially ending it /// Destroy an event without closing it and officially ending it
/// ///
/// This function removes an ongoing event from the list of ongoing events. /// This function removes an ongoing event from the list of ongoing events.
/// It expects a UUID as input and returns a `Result` containing either a `ParsedVote` /// It expects a HUID as input and returns a `Result` containing either a `ParsedVote`
/// struct representing the details of the removed event or an `IdleError`. /// struct representing the details of the removed event or an `IdleError`.
/// ///
/// ## Example: /// ## Example:
@ -108,23 +111,21 @@ pub fn add_ongoing_event(
/// # }; /// # };
/// let ev_ctx = EventHolder::default(); /// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap(); /// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
/// make_into_ongoing_event(id, &ev_ctx).unwrap(); /// make_into_ongoing_event(&id, &ev_ctx).unwrap();
/// ///
/// del_ongoing_event(id, &ev_ctx).unwrap(); /// del_ongoing_event(&id, &ev_ctx).unwrap();
/// ``` /// ```
pub fn del_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<EventOngoing, IdleError> { pub fn del_ongoing_event(
ev_ctx huid: &EventIdType,
.ongoing_events ev_ctx: &EventHolder,
.lock() ) -> Result<EventOngoing, IdleError> {
.unwrap() ev_ctx.ongoing_events.lock().unwrap().del_event(huid)
// .map_err(|_| IdleError::MutexError)?
.del_event(uuid)
} }
/// Destroy a pending event without closing it /// Destroy a pending event without closing it
/// ///
/// This function removes a pending event from the list of pending events. /// This function removes a pending event from the list of pending events.
/// It expects a UUID as input and returns a `Result` containing either a `ParsedVote` /// It expects a HUID as input and returns a `Result` containing either a `ParsedVote`
/// struct representing the details of the removed event or an `IdleError`. /// struct representing the details of the removed event or an `IdleError`.
/// ///
/// ## Example: /// ## Example:
@ -134,21 +135,19 @@ pub fn del_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<EventOngoin
/// # }; /// # };
/// let ev_ctx = EventHolder::default(); /// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap(); /// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
/// del_pending_event(id, &ev_ctx).unwrap(); /// del_pending_event(&id, &ev_ctx).unwrap();
/// ``` /// ```
pub fn del_pending_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<EventPending, IdleError> { pub fn del_pending_event(
ev_ctx huid: &EventIdType,
.pending_events ev_ctx: &EventHolder,
.lock() ) -> Result<EventPending, IdleError> {
.unwrap() ev_ctx.pending_events.lock().unwrap().del_event(huid)
// .map_err(|_| IdleError::MutexError)?
.del_event(uuid)
} }
/// This function is used to close an ongoing event and return the parsed vote associated with it. If the closure is successful, the owned event is returned for post-treatment. /// This function is used to close an ongoing event and return the parsed vote associated with it. If the closure is successful, the owned event is returned for post-treatment.
/// # Arguments /// # Arguments
/// ///
/// * `uuid` - A Uuid representing the identifier of the event that is to be closed. /// * `huid` - A Huid representing the identifier of the event that is to be closed.
/// ///
/// ## Example: /// ## Example:
/// ```rust /// ```rust
@ -157,16 +156,15 @@ pub fn del_pending_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<EventPendin
/// # }; /// # };
/// let ev_ctx = EventHolder::default(); /// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap(); /// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
/// make_into_ongoing_event(id, &ev_ctx).unwrap(); /// make_into_ongoing_event(&id, &ev_ctx).unwrap();
/// close_ongoing_event(id, &ev_ctx).unwrap(); /// close_ongoing_event(&id, &ev_ctx).unwrap();
/// ``` /// ```
pub fn close_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> { pub fn close_ongoing_event(huid: &EventIdType, ev_ctx: &EventHolder) -> Result<(), IdleError> {
ev_ctx ev_ctx
.ongoing_events .ongoing_events
.lock() .lock()
.unwrap() .unwrap()
// .map_err(|_| IdleError::MutexError)? .close_event(huid, ev_ctx)
.close_event(uuid, ev_ctx)
} }
/// A link to all events, to be shared between threads related to this event pool. /// A link to all events, to be shared between threads related to this event pool.
@ -190,10 +188,145 @@ pub struct EventHolder {
/// Closed events have been voted up but havent been deleted and can therefore be watched or opened again. /// 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 /// These events will be autodeleted after a while
pub closed_events: Arc<std::sync::Mutex<ListClosedEvents>>, pub closed_events: Arc<std::sync::Mutex<ListClosedEvents>>,
/// A reference-counted pointer to a mutex-protected `NaiveDate` instance, representing the last date the watchdog was updated. /// A reference-counted pointer to a mutex-protected `NaiveDate` instance, representing the last date the watchdog was updated.
pub old_date: Arc<std::sync::Mutex<NaiveDate>>, pub old_date: Arc<std::sync::Mutex<NaiveDate>>,
/// The newly created discord context /// The newly created discord context
pub discord_ctx: Arc<tokio::sync::Mutex<Option<poise::serenity_prelude::Context>>>, pub discord_ctx: Arc<tokio::sync::Mutex<Option<poise::serenity_prelude::Context>>>,
/// A link to the active config
pub config: Arc<std::sync::RwLock<GlobalConfig>>,
}
/// 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(save_path: Option<&str>) -> Result<Self, IdleError> {
let save_path = save_path.unwrap_or("data");
Ok(Self {
pending_events: load_from_reader!(
ListPendingEvents,
save_path.to_owned() + "/pending_events.json"
),
ongoing_events: load_from_reader!(
ListOngoingEvents,
save_path.to_owned() + "/ongoing_events.json"
),
closed_events: load_from_reader!(
ListClosedEvents,
save_path.to_owned() + "/closed_events.json"
),
old_date: load_from_reader!(NaiveDate, save_path.to_owned() + "/old_date.json"),
config: Arc::new(std::sync::RwLock::new(GlobalConfig::try_load_from_disk()?)),
..Default::default()
})
}
pub fn try_save_to_disk(&self, save_path: Option<&str>) -> Result<(), IdleError> {
let save_path = save_path.unwrap_or("data");
let _ = create_dir(save_path);
save_to_writer!(
self.pending_events,
ListPendingEvents,
save_path.to_owned() + "/pending_events.json"
);
save_to_writer!(
self.ongoing_events,
ListOngoingEvents,
save_path.to_owned() + "/ongoing_events.json"
);
save_to_writer!(
self.closed_events,
ListClosedEvents,
save_path.to_owned() + "/closed_events.json"
);
save_to_writer!(
&self.old_date,
NaiveDate,
save_path.to_owned() + "/old_date.json"
);
self.config.read().unwrap().try_save_to_disk()?;
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.ongoing_events).contains_key(id)
|| inner!(self.closed_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()))
})
}
}
#[cfg(test)]
mod test {
use crate::votes::{holders::TypedEvent, EventPending};
use super::{add_pending_event, close_ongoing_event, make_into_ongoing_event, EventHolder};
#[test]
fn test_save_load() {
let hld = EventHolder::default();
let (a, b, c) = (
add_pending_event(EventPending::default(), &hld).unwrap(),
add_pending_event(EventPending::default(), &hld).unwrap(),
add_pending_event(EventPending::default(), &hld).unwrap(),
);
make_into_ongoing_event(&b, &hld).unwrap();
make_into_ongoing_event(&c, &hld).unwrap();
close_ongoing_event(&c, &hld).unwrap();
assert!(hld.contains_event(&a));
assert!(hld.contains_event(&b));
assert!(hld.contains_event(&c));
hld.try_save_to_disk(Some("bobito")).unwrap();
let hld2 = EventHolder::try_load_from_disk(Some("bobito")).unwrap();
assert!(hld2.contains_event(&a));
assert!(hld2.contains_event(&b));
assert!(hld2.contains_event(&c));
let (a2, b2, c2) = (
hld.find_event(&a).unwrap(),
hld.find_event(&b).unwrap(),
hld.find_event(&c).unwrap(),
);
// match (a2, b2, c2) {
// TypedEvent::Ongoing(),TypedEvent::Pending(),TypedEvent::Closed() => (),
// _ =>
// }
assert!(matches!(a2, TypedEvent::Pending(_)));
assert!(matches!(b2, TypedEvent::Ongoing(_)));
assert!(matches!(c2, TypedEvent::Closed(_)));
}
} }

View File

@ -11,11 +11,14 @@
//! The module aims to provide a robust framework for managing event lifecycles within an //! The module aims to provide a robust framework for managing event lifecycles within an
//! application, ensuring separation between pending and ongoing events and supporting //! application, ensuring separation between pending and ongoing events and supporting
//! actions such as adding, launching, processing, and autoclosing events. //! actions such as adding, launching, processing, and autoclosing events.
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::IdleError; use crate::{
ids::{generate_id, EventIdType},
IdleError,
};
use super::{ use super::{
add_ongoing_event, add_ongoing_event,
@ -25,26 +28,27 @@ use super::{
/// The list of pending events, not yet started /// 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)] #[derive(Serialize, Deserialize, Default)]
#[cfg_attr(test, derive(Debug, PartialEq, Clone))]
pub struct ListPendingEvents { pub struct ListPendingEvents {
/// The list of pending events /// The list of pending events
pending_events: PendingHashmap, pub(super) pending_events: PendingHashmap,
} }
impl ListPendingEvents { impl ListPendingEvents {
/// Add a new event to the list of upcoming events. /// Add a new event to the list of upcoming events.
/// ///
/// This function generates a new UUID for the event before adding it to the list. /// 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<Uuid, IdleError> { pub fn add_pending_event(&mut self, event: EventPending) -> Result<EventIdType, IdleError> {
let id = Uuid::new_v4(); let id = generate_id();
self.pending_events.insert(id, event); self.pending_events.insert(id.clone(), event);
Ok(id) 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( pub fn process_upcoming(
&mut self, &mut self,
current_time: NaiveDateTime, current_time: NaiveDateTime,
@ -52,8 +56,8 @@ impl ListPendingEvents {
) -> Result<(), IdleError> { ) -> Result<(), IdleError> {
self.find_upcoming(current_time) self.find_upcoming(current_time)
.iter() .iter()
.try_for_each(|uuid| { .try_for_each(|huid| {
self.launch(*uuid, ev_ctx)?; self.launch(huid, ev_ctx)?;
Ok(()) Ok(())
}) })
} }
@ -61,52 +65,66 @@ impl ListPendingEvents {
/// Launch the specified event by moving it from pending events to ongoing events. /// 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. /// Returns an `IdleError` if the event cannot be found in pending events.
pub(super) fn launch(&mut self, uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> { pub(super) fn launch(
&mut self,
huid: &EventIdType,
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
let event = self let event = self
.pending_events .pending_events
.remove(&uuid) .remove(huid)
.ok_or(IdleError::EventLaunch(uuid))?; .ok_or(IdleError::EventLaunch(huid.to_string()))?;
add_ongoing_event(uuid, event.into_ongoing(), ev_ctx)?; add_ongoing_event(huid, event.into_ongoing(), ev_ctx)?;
// make_into_ongoing_event(uuid)?; // make_into_ongoing_event(huid)?;
Ok(()) Ok(())
} }
/// Find all events that are scheduled to start after the given date. /// Find all events that are scheduled to start after the given date.
/// ///
/// Returns a vector of UUIDs corresponding to the upcoming events. /// Returns a vector of HUIDs corresponding to the upcoming events.
pub(super) fn find_upcoming(&self, current_time: NaiveDateTime) -> Vec<Uuid> { /// TODO: Consider returning references
pub(super) fn find_upcoming(&self, current_time: NaiveDateTime) -> Vec<EventIdType> {
self.pending_events self.pending_events
.iter() .iter()
.filter(|&(_, e)| e.parsed_vote.launch_date <= current_time) .filter(|&(_, e)| e.parsed_vote.launch_date <= current_time)
.map(|(k, _v)| (*k)) .map(|(k, _v)| (k.clone()))
.collect() .collect()
} }
/// delete the event without launching it /// delete the event without launching it
pub fn del_event(&mut self, uuid: Uuid) -> Result<EventPending, IdleError> { pub fn del_event(&mut self, huid: &EventIdType) -> Result<EventPending, IdleError> {
self.pending_events self.pending_events
.remove(&uuid) .remove(huid)
.ok_or(IdleError::DeleteEvent(uuid)) .ok_or(IdleError::DeleteEvent(huid.to_string()))
} }
// TODO: maybe add an update_upcoming(date) ? // TODO: maybe add an update_upcoming(date) ?
// ///
// pub fn contains_event(&self, id: &str) -> bool {
// self.pending_events.contains_key(id)
// }
} }
/// The list of ongoing events, not yet closed /// The list of ongoing events, not yet closed
/// ///
/// This struct represents the collection of events that have been initiated but have not yet concluded. /// This struct represents the collection of events that have been initiated but have not yet concluded.
#[derive(Serialize, Deserialize, Default)] #[derive(Serialize, Deserialize, Default, Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct ListOngoingEvents { pub struct ListOngoingEvents {
/// The list of ongoing events /// The list of ongoing events
ongoing_events: OngoingHashmap, pub(super) ongoing_events: OngoingHashmap,
} }
impl ListOngoingEvents { impl ListOngoingEvents {
/// Add a new event to the list of ongoing events. /// Add a new event to the list of ongoing events.
/// ///
/// This function also launch the event based and adds a callback with the Uuid of the original caller. /// This function also launch the event based and adds a callback with the Huid of the original caller.
pub(crate) fn add_event(&mut self, id: Uuid, mut event: EventOngoing) -> Result<(), IdleError> { pub(crate) fn add_event(
&mut self,
huid: &EventIdType,
mut event: EventOngoing,
) -> Result<(), IdleError> {
event.parsed_vote.launch()?; event.parsed_vote.launch()?;
self.ongoing_events.insert(id, event); self.ongoing_events.insert(huid.clone(), event);
Ok(()) Ok(())
} }
@ -119,8 +137,8 @@ impl ListOngoingEvents {
ev_ctx: &EventHolder, ev_ctx: &EventHolder,
) -> Result<(), IdleError> { ) -> Result<(), IdleError> {
let failure = Vec::new(); let failure = Vec::new();
for uuid in self.find_autoclose(current_time) { for huid in self.find_autoclose(current_time) {
self.close_event(uuid, ev_ctx)?; self.close_event(&huid, ev_ctx)?;
} }
match failure.is_empty() { match failure.is_empty() {
true => Ok(()), true => Ok(()),
@ -134,38 +152,41 @@ impl ListOngoingEvents {
/// puting it into the closed event list. /// puting it into the closed event list.
/// ///
/// Doing so allow for the vote result to be read while it is valid /// Doing so allow for the vote result to be read while it is valid
pub fn close_event(&mut self, uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> { pub fn close_event(
&mut self,
huid: &EventIdType,
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
// TODO: Another vkypoint, as we cant continue without knowing how to send a message // TODO: Another vkypoint, as we cant continue without knowing how to send a message
let event = self let event = self
.ongoing_events .ongoing_events
.remove(&uuid) .remove(huid)
.ok_or(IdleError::LaunchingEvent(uuid))?; .ok_or(IdleError::LaunchingEvent(huid.to_string()))?;
ev_ctx ev_ctx
.closed_events .closed_events
.lock() .lock()
.unwrap() .unwrap()
.add_event(uuid, event.into_closed())?; .add_event(huid.clone(), event.into_closed())?;
Ok(()) Ok(())
} }
/// delete the event without launching it /// delete the event without launching it
pub fn del_event(&mut self, uuid: Uuid) -> Result<EventOngoing, IdleError> { pub fn del_event(&mut self, huid: &EventIdType) -> Result<EventOngoing, IdleError> {
self.ongoing_events self.ongoing_events
.remove(&uuid) .remove(huid)
.ok_or(IdleError::DeleteEvent(uuid)) .ok_or(IdleError::DeleteEvent(huid.to_string()))
} }
/// Find all events that are scheduled to be autoclosed. /// Find all events that are scheduled to be autoclosed.
/// ///
/// Returns a vector of UUIDs corresponding to the old events. /// Returns a vector of HUIDs corresponding to the old events.
pub(super) fn find_autoclose(&mut self, current_time: NaiveDateTime) -> Vec<Uuid> { pub(super) fn find_autoclose(&mut self, current_time: NaiveDateTime) -> Vec<EventIdType> {
self.ongoing_events self.ongoing_events
.iter() .iter()
.filter(|(_, e)| e.parsed_vote.close_date <= current_time) .filter(|(_, e)| e.parsed_vote.close_date <= current_time)
.map(|(k, _)| *k) .map(|(k, _)| k.clone())
.collect() .collect()
} }
// TODO: maybe add an update_ongoing(date) ?
} }
/// The list of closed events /// The list of closed events
@ -175,24 +196,24 @@ impl ListOngoingEvents {
#[derive(Serialize, Deserialize, Default)] #[derive(Serialize, Deserialize, Default)]
pub struct ListClosedEvents { pub struct ListClosedEvents {
/// The list of closed events /// The list of closed events
closed_events: ClosedHashmap, pub(super) closed_events: ClosedHashmap,
} }
impl ListClosedEvents { impl ListClosedEvents {
/// Add a closed event to the list of closed events /// Add a closed event to the list of closed events
pub fn add_event(&mut self, uuid: Uuid, event: EventClosed) -> Result<(), IdleError> { pub fn add_event(&mut self, huid: EventIdType, event: EventClosed) -> Result<(), IdleError> {
self.closed_events.insert(uuid, event); self.closed_events.insert(huid, event);
Ok(()) Ok(())
} }
/// Find all events that are too old and supposed to be pruned. /// Find all events that are too old and supposed to be pruned.
/// ///
/// Returns a vector of UUIDs corresponding to the old events. /// Returns a vector of HUIDs corresponding to the old events.
pub(super) fn find_old(&mut self, current_time: NaiveDateTime) -> Vec<Uuid> { pub(super) fn find_old(&mut self, current_time: NaiveDateTime) -> Vec<EventIdType> {
self.closed_events self.closed_events
.iter() .iter()
.filter(|(_, e)| e.parsed_vote.auto_delete_date <= current_time) .filter(|(_, e)| e.parsed_vote.auto_delete_date <= current_time)
.map(|(k, _)| *k) .map(|(k, _)| k.clone())
.collect() .collect()
} }
/// Remove all outdated votes for the current user /// Remove all outdated votes for the current user
@ -200,12 +221,12 @@ impl ListClosedEvents {
/// This function is expected to be called periodically by the watchdog. /// This function is expected to be called periodically by the watchdog.
pub(crate) fn prune_old(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> { pub(crate) fn prune_old(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> {
let mut failure = Vec::new(); let mut failure = Vec::new();
for uuid in self.find_old(current_time) { for huid in self.find_old(current_time) {
println!("{}", uuid); println!("{}", huid);
if self.closed_events.remove(&uuid).is_none() { if self.closed_events.remove(&huid).is_none() {
// Should only happen during hard to reproduce race conditions // Should only happen during hard to reproduce race conditions
#[cfg(not(tarpaulin_include))] #[cfg(not(tarpaulin_include))]
failure.push(uuid); failure.push(huid.clone());
} }
} }
match failure.is_empty() { match failure.is_empty() {
@ -216,6 +237,18 @@ impl ListClosedEvents {
} }
} }
/// 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)] #[cfg(test)]
mod tests { mod tests {
use chrono::{Days, Local}; use chrono::{Days, Local};
@ -248,20 +281,20 @@ mod tests {
// Can we add a vote ? // Can we add a vote ?
let id = add_pending_event(ev.clone(), &ev_ctx).unwrap(); let id = add_pending_event(ev.clone(), &ev_ctx).unwrap();
// assert!(gimme!(ev_ctx.pending_events).contains_key(&id)); // Is the vote present ? // assert!(gimme!(ev_ctx.pending_events).contains_key(&id)); // Is the vote present ?
del_pending_event(id, &ev_ctx).unwrap(); del_pending_event(&id, &ev_ctx).unwrap();
assert!(!g!(ev_ctx.pending_events).pending_events.contains_key(&id)); // Is the vote now deleted assert!(!g!(ev_ctx.pending_events).pending_events.contains_key(&id)); // Is the vote now deleted
let id = add_pending_event(ev.clone(), &ev_ctx).unwrap(); let id = add_pending_event(ev.clone(), &ev_ctx).unwrap();
make_into_ongoing_event(id, &ev_ctx).unwrap(); // Launching this event 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.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 assert!(g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now ongoing
close_ongoing_event(id, &ev_ctx).unwrap(); close_ongoing_event(&id, &ev_ctx).unwrap();
assert!(!g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now not ongoing assert!(!g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now not ongoing
let id = add_pending_event(ev.clone(), &ev_ctx).unwrap(); let id = add_pending_event(ev.clone(), &ev_ctx).unwrap();
make_into_ongoing_event(id, &ev_ctx).unwrap(); // Launching this event make_into_ongoing_event(&id, &ev_ctx).unwrap(); // Launching this event
del_ongoing_event(id, &ev_ctx).unwrap(); del_ongoing_event(&id, &ev_ctx).unwrap();
assert!(!g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now not ongoing assert!(!g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now not ongoing
} }
@ -298,7 +331,7 @@ mod tests {
assert!(!g!(ev.closed_events).closed_events.contains_key(&id)); // not deleted assert!(!g!(ev.closed_events).closed_events.contains_key(&id)); // not deleted
// Now some time passed // Now some time passed
assert_eq!(g!(ev.pending_events).find_upcoming(later), vec![id]); // one upcomming event assert_eq!(g!(ev.pending_events).find_upcoming(later), vec![id.clone()]); // one upcomming event
assert!(g!(ev.closed_events).find_old(later).is_empty()); // no old events assert!(g!(ev.closed_events).find_old(later).is_empty()); // no old events
assert!(g!(ev.ongoing_events).find_autoclose(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.pending_events).process_upcoming(later, &ev).unwrap(); // one event should be processed
@ -310,7 +343,10 @@ mod tests {
// More time passed // More time passed
assert!(g!(ev.pending_events).find_upcoming(very_later).is_empty()); // one upcomming event 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_eq!(
g!(ev.ongoing_events).find_autoclose(very_later),
vec![id.clone()]
); // one old event
assert!(g!(ev.closed_events).find_old(very_later).is_empty()); // no old events assert!(g!(ev.closed_events).find_old(very_later).is_empty()); // no old events
g!(ev.pending_events) g!(ev.pending_events)
.process_upcoming(very_later, &ev) .process_upcoming(very_later, &ev)
@ -325,7 +361,10 @@ mod tests {
assert!(g!(ev.pending_events) assert!(g!(ev.pending_events)
.find_upcoming(very_very_later) .find_upcoming(very_very_later)
.is_empty()); // one upcomming event .is_empty()); // one upcomming event
assert_eq!(g!(ev.closed_events).find_old(very_very_later), vec![id]); // one old event assert_eq!(
g!(ev.closed_events).find_old(very_very_later),
vec![id.clone()]
); // one old event
assert!(g!(ev.ongoing_events) assert!(g!(ev.ongoing_events)
.find_autoclose(very_very_later) .find_autoclose(very_very_later)
.is_empty()); // no old events .is_empty()); // no old events
@ -341,4 +380,10 @@ mod tests {
// TODO: Check the status at several points // TODO: Check the status at several points
} }
#[ignore]
#[test]
fn serialisation_check() {
todo!()
}
} }

View File

@ -19,6 +19,7 @@ mod ballots;
mod events; mod events;
mod helper_functions; mod helper_functions;
mod holders; mod holders;
mod traits;
// Republish // Republish
pub use ballots::Ballot; pub use ballots::Ballot;
@ -29,7 +30,7 @@ pub use holders::{ListOngoingEvents, ListPendingEvents};
use std::collections::HashMap; use std::collections::HashMap;
use uuid::Uuid; use crate::ids::EventIdType;
/// The hashmap of pending votes /// The hashmap of pending votes
type PendingHashmap = HashMap<EventIdType, EventPending>; type PendingHashmap = HashMap<EventIdType, EventPending>;
@ -38,11 +39,6 @@ type OngoingHashmap = HashMap<EventIdType, EventOngoing>;
/// The hashmap of closed votes, still available for reading to check the results /// The hashmap of closed votes, still available for reading to check the results
type ClosedHashmap = HashMap<EventIdType, EventClosed>; type ClosedHashmap = HashMap<EventIdType, EventClosed>;
/// Placeholder datatype
///
/// Links to an event, active or planned
pub type EventIdType = Uuid;
/// Placeholder user data type /// Placeholder user data type
/// ///
/// Links back to an user /// Links back to an user

142
src/votes/traits.rs Normal file
View File

@ -0,0 +1,142 @@
//! 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<R> {
/// Borrow the inner ongoing events
fn borrow_inner(&self) -> &HashMap<String, R>;
}
impl BorrowInner<EventClosed> for ListClosedEvents {
/// Borrow the inner ongoing events
fn borrow_inner(&self) -> &HashMap<String, EventClosed> {
&self.closed_events
}
}
impl BorrowInner<EventOngoing> for ListOngoingEvents {
/// Borrow the inner ongoing events
fn borrow_inner(&self) -> &HashMap<String, EventOngoing> {
&self.ongoing_events
}
}
impl BorrowInner<EventPending> for ListPendingEvents {
/// Borrow the inner ongoing events
fn borrow_inner(&self) -> &HashMap<String, EventPending> {
&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<R> {
/// Borrow the inner ongoing events
fn borrow_mut_inner(&mut self) -> &mut HashMap<String, R>;
}
/// Blanket inner dictionnary implementation
///
/// This trait is meant to allow for inner dictionnary manipulation
pub(crate) trait EventManipulation<R> {
/// Get a key in the inner hashmap
fn get_key(&self, s: &str) -> Option<&R>;
// /// Insert a key in the inner hashmap
// fn insert(&self, s: &str);
}
impl<T, R> EventManipulation<R> for T
where
T: BorrowInner<R>,
{
fn get_key(&self, s: &str) -> Option<&R> {
self.borrow_inner().get(s)
}
}
#[cfg(test)]
mod tests {
use crate::votes::events::ParsedVote;
use super::*;
#[derive(Default)]
struct TestI {
inner: HashMap<String, usize>,
}
impl BorrowInner<usize> for TestI {
fn borrow_inner(&self) -> &HashMap<String, usize> {
&self.inner
}
}
impl BorrowMutInner<usize> for TestI {
fn borrow_mut_inner(&mut self) -> &mut HashMap<String, usize> {
&mut self.inner
}
}
impl BorrowMutInner<EventPending> for ListPendingEvents {
fn borrow_mut_inner(&mut self) -> &mut HashMap<String, EventPending> {
&mut self.pending_events
}
}
#[test]
fn test_borrow_impl() {
let mut i = TestI::default();
assert!(i.borrow_inner().is_empty());
i.borrow_mut_inner().insert("Bob".to_owned(), 3);
assert!(i.borrow_inner().contains_key("Bob"));
}
#[test]
fn test_blanket_implementation() {
let mut i = TestI::default();
assert!(i.get_key("blanket").is_none());
i.borrow_mut_inner().insert("blanket".to_owned(), 42);
assert!(i.get_key("blanket").is_some());
}
#[test]
fn test_manual_implementation() {
let (mut e, mut v, mut w) = (
ListClosedEvents::default(),
ListOngoingEvents::default(),
ListPendingEvents::default(),
);
let pv = ParsedVote::default();
assert!(e.get_key("blanket1").is_none());
e.add_event(
"blanket1".to_owned(),
EventClosed {
parsed_vote: pv.clone(),
},
)
.unwrap();
assert!(e.get_key("blanket1").is_some());
assert!(v.get_key("blanket2").is_none());
v.add_event(
&"blanket2".to_owned(),
EventOngoing {
parsed_vote: pv.clone(),
},
)
.unwrap();
assert!(v.get_key("blanket2").is_some());
assert!(w.get_key("blanket3").is_none());
w.borrow_mut_inner()
.insert("blanket3".to_owned(), EventPending::default());
assert!(w.get_key("blanket3").is_some());
}
}

View File

@ -15,9 +15,7 @@
use crate::votes::EventHolder; use crate::votes::EventHolder;
use chrono::{DateTime, Local, NaiveDate}; use chrono::{DateTime, Local, NaiveDate};
use poise::serenity_prelude::{ use poise::serenity_prelude::{self, CacheHttp, ChannelId};
self, CacheHttp, ChannelId, CreateMessage, EmojiId, Mention, ReactionType, RoleId,
};
/// The main scheduler waiting and dispatch loop. /// The main scheduler waiting and dispatch loop.
/// ///
@ -38,60 +36,21 @@ pub async fn main_scheduler_loop(mut interval: tokio::time::Interval, ev_ctx: Ev
} }
/// Close to finding out /// Close to finding out
#[cfg(not(tarpaulin_include))] // Just a test function
async fn fk_around(ev_ctx: &EventHolder) { async fn fk_around(ev_ctx: &EventHolder) {
println!( println!(
"In the fk_around function ({}):", "In the fk_around function ({}):",
Local::now() // &ev_ctx Local::now() // &ev_ctx
); );
if let Some(discord_ctx) = ev_ctx.discord_ctx.lock().await.as_mut() { if let Some(discord_ctx) = ev_ctx.discord_ctx.lock().await.as_mut() {
println!("Full discord ctx : {:#?}", discord_ctx); println!("Fking around : {:#?}", discord_ctx);
let mut m = serenity_prelude::Message::default();
let m = CreateMessage::new().content(format!( m.content = "Bob".into();
"Hello {}",
Mention::from(RoleId::new(1222612097091768371))
));
// let mut m = serenity_prelude::Message::default();
// discord_ctx.http.get_scheduled_event_users(, , , , )
// discord_ctx.http.get_user(UserId::new(1));
// let m = m
// m.content = format!("Hello {}", Mention::from(UserId::new(1)));
// m.mentions = vec![User::];
// m.mention_roles = vec![];
let r = discord_ctx let r = discord_ctx
.http() .http()
.send_message(ChannelId::new(1300786300143800351), Vec::new(), &m) .send_message(ChannelId::new(1300786300143800351), Vec::new(), &m)
.await; .await;
println!("{:?}", r); println!("{:?}", r);
if let Ok(msg) = r {
#[cfg(not(feature = "custom_emojis"))]
let msg_result = discord_ctx
.http()
.create_reaction(
msg.channel_id,
msg.id,
&ReactionType::Unicode("1️⃣".to_string()),
)
.await;
#[cfg(feature = "custom_emojis")]
let msg_result = discord_ctx
.http()
.create_reaction(
msg.channel_id,
msg.id,
&ReactionType::Custom {
animated: false,
id: (EmojiId::new(1329095596396642375)),
name: (Some("Foxo".to_string())),
},
)
.await;
println!("{:?}", msg_result);
}
} }
} }

View File

@ -3,12 +3,12 @@ mod tests {
#[test] #[test]
fn generic_integration_test() { fn generic_integration_test() {
use idlefox::votes::{ use idlefox::ids::generate_id;
add_pending_event, make_into_ongoing_event, EventHolder, EventPending, use idlefox::votes::{add_ongoing_event, EventHolder, EventPending};
};
let ev_ctx = EventHolder::default(); let ev_ctx = EventHolder::default();
let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap(); let huid = generate_id(); // A new id
let ongoing = EventPending::default().into_ongoing(); // A very legit event
make_into_ongoing_event(id, &ev_ctx).unwrap() add_ongoing_event(&huid, ongoing, &ev_ctx).unwrap();
} }
} }