diff --git a/Cargo.lock b/Cargo.lock index 85b507c..653b54e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -308,6 +308,7 @@ dependencies = [ "reqwest 0.13.5", "riichi_hand", "scraper", + "slug", "tokio", ] diff --git a/README.md b/README.md index f59f085..77bbbfd 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ cargo run --bin chombot --release Please note that the working directory serves as a persistence storage for the bot's state, so the bot process must have write permissions for it. ### Creating channels -`/create_channel` creates a text channel in the current channel's category (or a chosen one), if both you and the bot could create it there. +`/create_channel` creates a text channel in the current channel's category (or a chosen one), if both you and the bot could create it there. Its name suggestions come from the [EMA calendar](http://mahjong-europe.org/ranking/Calendar.html); picking a tournament names the channel like `🏆2026-02-kraków-hatsumi-taikai-2026` and sets the topic to `Kraków :: 14-15 lutego 2026 :: https://...`. ### chombot-kcc In addition to the base version of Chombot, there is also an enhanced version called Chombot-kcc available. This is version tailored for the needs of Krakow Chombo Club and contains a few additional (possibly hermetic) features. diff --git a/chombot-common/Cargo.toml b/chombot-common/Cargo.toml index 4d3c015..37d97e9 100644 --- a/chombot-common/Cargo.toml +++ b/chombot-common/Cargo.toml @@ -18,4 +18,5 @@ poise.workspace = true reqwest.workspace = true riichi_hand.workspace = true scraper.workspace = true +slug.workspace = true tokio.workspace = true diff --git a/chombot-common/src/chombot.rs b/chombot-common/src/chombot.rs index f0f92a7..d82e216 100644 --- a/chombot-common/src/chombot.rs +++ b/chombot-common/src/chombot.rs @@ -1,5 +1,6 @@ use std::error::Error; use std::fmt::{Display, Formatter}; +use std::sync::Arc; use riichi_hand::image::RgbaImage; use riichi_hand::parser::{HandParseError, HandParser}; @@ -9,6 +10,8 @@ use riichi_hand::raster_renderer::fluffy_stuff_tile_sets::{ use riichi_hand::raster_renderer::martin_persson_tile_sets::MARTIN_PERSSON_TILE_SET; use riichi_hand::raster_renderer::{HandRenderError, RasterRenderer, RenderOptions, TileSet}; +use crate::tournaments_watcher::cache::TournamentsCache; + #[derive(Debug)] pub enum ChombotBaseError { HandParserError(HandParseError), @@ -55,12 +58,19 @@ pub enum TileStyle { } #[derive(Default)] -pub struct ChombotBase {} +pub struct ChombotBase { + tournaments: Arc, +} impl ChombotBase { #[must_use] - pub const fn new() -> Self { - Self {} + pub fn new() -> Self { + Self::default() + } + + #[must_use] + pub const fn tournaments(&self) -> &Arc { + &self.tournaments } pub fn render_hand(hand: &str, tile_style: &TileStyle) -> ChombotResult { diff --git a/chombot-common/src/lib.rs b/chombot-common/src/lib.rs index c436ed2..c256bba 100644 --- a/chombot-common/src/lib.rs +++ b/chombot-common/src/lib.rs @@ -5,12 +5,15 @@ #![allow(clippy::missing_errors_doc)] #![allow(clippy::missing_panics_doc)] +use std::sync::Arc; + use poise::Context; use poise::serenity_prelude::Context as SerenityContext; use crate::chombot::ChombotBase; use crate::data_watcher::DataWatcher; -use crate::tournaments_watcher::ema::get_rcr_tournaments; +use crate::tournaments_watcher::cache::TournamentsCache; +use crate::tournaments_watcher::ema::Tournaments; use crate::tournaments_watcher::notifier::{ TournamentWatcherChannelListProvider, TournamentsChannelMessageNotifier, }; @@ -22,6 +25,7 @@ pub mod data_watcher; pub mod discord_utils; pub mod scraping_utils; pub mod slash_commands; +pub mod tournament_channel; pub mod tournaments_watcher; pub trait ChombotPoiseUserData: Sync { @@ -33,11 +37,17 @@ pub type ChombotPoiseContext<'a, T> = Context<'a, T, anyhow::Error>; pub fn start_tournaments_watcher( channel_list_provider: T, ctx: SerenityContext, + tournaments: Arc, ) { let notifier = TournamentsChannelMessageNotifier::new(channel_list_provider); tokio::spawn(async move { - DataWatcher::new(notifier, get_rcr_tournaments) - .run(&ctx) - .await; + DataWatcher::new(notifier, || async { + tournaments + .get() + .await + .map(|tournaments| Some(Tournaments::clone(&tournaments))) + }) + .run(&ctx) + .await; }); } diff --git a/chombot-common/src/slash_commands/create_channel.rs b/chombot-common/src/slash_commands/create_channel.rs index d56abb0..5332d43 100644 --- a/chombot-common/src/slash_commands/create_channel.rs +++ b/chombot-common/src/slash_commands/create_channel.rs @@ -1,14 +1,26 @@ +use std::time::Duration; + use anyhow::{Result, anyhow}; +use itertools::Itertools; use poise::CreateReply; -use poise::serenity_prelude::{ChannelId, GuildId}; +use poise::serenity_prelude::{AutocompleteChoice, ChannelId, CreateAutocompleteResponse, GuildId}; use crate::channel_creator::{ - ChannelCreation, ChannelName, Placement, TextChannelRequest, create_text_channel, - decide_placement, + CHANNEL_NAME_MAX_LENGTH, ChannelCreation, ChannelName, Placement, TextChannelRequest, + create_text_channel, decide_placement, truncate_chars, +}; +use crate::tournament_channel::{ + polish_city, polish_date, tournament_channel_name, tournament_topic, }; +use crate::tournaments_watcher::ema::{TournamentEntry, Tournaments}; use crate::{ChombotPoiseContext, ChombotPoiseUserData}; -/// Create a text channel. +const AUTOCOMPLETE_MAX_CHOICES: usize = 25; +/// Discord waits 3 seconds for autocomplete suggestions. +const AUTOCOMPLETE_TIMEOUT: Duration = Duration::from_millis(2500); +const TOURNAMENT_LOOKUP_TIMEOUT: Duration = Duration::from_secs(10); + +/// Create a text channel, e.g. for an upcoming EMA tournament. #[poise::command( slash_command, guild_only, @@ -16,18 +28,19 @@ use crate::{ChombotPoiseContext, ChombotPoiseUserData}; )] pub async fn create_channel( ctx: ChombotPoiseContext<'_, T>, - #[description = "Channel name"] + #[description = "Channel name; start typing to pick an EMA tournament"] + #[autocomplete = "autocomplete_tournament"] #[max_length = 100] name: String, #[description = "Category to create the channel in (default: this channel's category)"] #[channel_types("Category")] category: Option, - #[description = "Channel topic"] + #[description = "Channel topic (defaults to the tournament's place, date and website)"] #[max_length = 1024] topic: Option, ) -> Result<()> { let guild_id = ctx.guild_id().ok_or_else(|| anyhow!("Guild ID is None"))?; - let Some(name) = ChannelName::new(&name) else { + let Some(plain_name) = ChannelName::new(&name) else { ctx.send( CreateReply::default() .content("That name doesn't contain any characters usable in a channel name.") @@ -46,13 +59,23 @@ pub async fn create_channel( }; ctx.defer().await?; + let tournament = ctx + .data() + .chombot() + .tournaments() + .get_within(TOURNAMENT_LOOKUP_TIMEOUT) + .await + .and_then(|tournaments| find_tournament(&tournaments, &name, &plain_name).cloned()); let creation = create_text_channel( ctx.serenity_context(), guild_id, TextChannelRequest { - name, + name: tournament + .as_ref() + .and_then(tournament_channel_name) + .unwrap_or(plain_name), placement, - topic, + topic: topic.or_else(|| tournament.as_ref().map(tournament_topic)), audit_log_reason: &format!("Requested by {} via /create_channel", ctx.author().name), }, ) @@ -89,3 +112,160 @@ async fn placement( .map(|guild| decide_placement(&guild, &author, &bot, requested, current_channel.as_ref())); placement.ok_or_else(|| anyhow!("Guild {guild_id} is not cached")) } + +async fn autocomplete_tournament( + ctx: ChombotPoiseContext<'_, T>, + partial: &str, +) -> CreateAutocompleteResponse { + let Some(tournaments) = ctx + .data() + .chombot() + .tournaments() + .get_within(AUTOCOMPLETE_TIMEOUT) + .await + else { + return CreateAutocompleteResponse::new(); + }; + + let choices = matching_tournaments(&tournaments, partial) + .into_iter() + .map(|entry| { + let label = choice_label(entry); + AutocompleteChoice::new(label.clone(), label) + }) + .collect(); + CreateAutocompleteResponse::new().set_choices(choices) +} + +/// Upcoming tournaments first, then the rest. +fn matching_tournaments<'a>( + tournaments: &'a Tournaments, + partial: &str, +) -> Vec<&'a TournamentEntry> { + let partial = partial.trim().to_lowercase(); + let mut matching: Vec<&TournamentEntry> = tournaments + .0 + .iter() + .filter(|entry| { + entry.name.to_lowercase().contains(&partial) + || entry.place.to_lowercase().contains(&partial) + }) + .unique_by(|entry| (&entry.name, &entry.place, &entry.date)) + .collect(); + matching.sort_by_key(|entry| !entry.results_status.is_empty()); + matching.truncate(AUTOCOMPLETE_MAX_CHOICES); + matching +} + +/// E.g. `Hatsumi Taikai 2026 (14-15 lutego 2026, Kraków)`. Picking a +/// suggestion submits its label, which tells namesakes apart. +fn choice_label(entry: &TournamentEntry) -> String { + let details = [polish_date(&entry.date), polish_city(&entry.place)] + .into_iter() + .filter(|detail| !detail.is_empty()) + .join(", "); + let label = if details.is_empty() { + entry.name.clone() + } else { + format!("{} ({details})", entry.name) + }; + truncate_chars(&label, CHANNEL_NAME_MAX_LENGTH) +} + +/// The tournament with the label `name`, or else named `name`, preferring +/// one without results yet. +fn find_tournament<'a>( + tournaments: &'a Tournaments, + name: &str, + channel_name: &ChannelName, +) -> Option<&'a TournamentEntry> { + let by_label = tournaments + .0 + .iter() + .find(|entry| choice_label(entry) == name.trim()); + let mut by_name = tournaments + .0 + .iter() + .filter(|entry| ChannelName::new(&entry.name).as_ref() == Some(channel_name)); + + by_label.or_else(|| { + by_name + .clone() + .find(|entry| entry.results_status.is_empty()) + .or_else(|| by_name.next()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(name: &str, date: &str, place: &str, results: &str) -> TournamentEntry { + TournamentEntry { + name: name.to_owned(), + url: String::new(), + rules: "Riichi".to_owned(), + date: date.to_owned(), + place: place.to_owned(), + approval_status: "OK".to_owned(), + registration_start: String::new(), + results_status: results.to_owned(), + } + } + + fn calendar() -> Tournaments { + Tournaments(vec![ + entry( + "Pumpkin Tiles 2026", + "10-11 October 2026", + "Tbilisi", + "EMA waiting for results !", + ), + entry("Pumpkin Tiles 2026", "31 October 2026", "Yerevan", ""), + entry("Warsaw Riichi Cup", "5 December 2026", "Warsaw", ""), + entry("Warsaw Riichi Cup", "5 December 2026", "Warsaw", ""), + entry("Hatsumi Taikai 2027", "13-14 February 2027", "Krakow", ""), + ]) + } + + #[test] + fn suggests_upcoming_tournaments_first() { + let calendar = calendar(); + let suggest = |partial: &str| -> Vec { + matching_tournaments(&calendar, partial) + .into_iter() + .map(choice_label) + .collect() + }; + + assert_eq!( + suggest(""), + vec![ + "Pumpkin Tiles 2026 (31 października 2026, Erywań)", + "Warsaw Riichi Cup (5 grudnia 2026, Warszawa)", + "Hatsumi Taikai 2027 (13-14 lutego 2027, Kraków)", + "Pumpkin Tiles 2026 (10-11 października 2026, Tbilisi)", + ] + ); + assert_eq!( + suggest("WARSAW"), + vec!["Warsaw Riichi Cup (5 grudnia 2026, Warszawa)"] + ); + } + + #[test] + fn finds_picked_or_typed_tournament() { + let calendar = calendar(); + let find = |name: &str| { + find_tournament(&calendar, name, &ChannelName::new(name).unwrap()) + .map(|entry| entry.place.as_str()) + }; + + assert_eq!( + find("Pumpkin Tiles 2026 (10-11 października 2026, Tbilisi)"), + Some("Tbilisi") + ); + assert_eq!(find("pumpkin tiles 2026"), Some("Yerevan")); + assert_eq!(find("Something else"), None); + } +} diff --git a/chombot-common/src/tournament_channel/mod.rs b/chombot-common/src/tournament_channel/mod.rs new file mode 100644 index 0000000..f961a34 --- /dev/null +++ b/chombot-common/src/tournament_channel/mod.rs @@ -0,0 +1,188 @@ +use std::fmt::Write; + +use slug::slugify; + +use crate::channel_creator::ChannelName; +use crate::tournament_channel::polish_names::{MONTHS, POLISH_CITY_NAMES}; +use crate::tournaments_watcher::ema::TournamentEntry; + +mod polish_names; + +/// E.g. `🏆2026-02-kraków-hatsumi-taikai-2026`; the city is left out if the +/// tournament name already contains it. +#[must_use] +pub fn tournament_channel_name(entry: &TournamentEntry) -> Option { + let mut raw = String::from("🏆"); + if let Some((_, month, year)) = parse_date(&entry.date) { + let _ = write!(raw, "{year}-{month:02}-"); + } + + let city = polish_city(&entry.place); + let name = slugify(&entry.name); + if !contains_words(&name, &slugify(&entry.place)) && !contains_words(&name, &slugify(&city)) { + let _ = write!(raw, "{city}-"); + } + + raw.push_str(&entry.name); + ChannelName::new(&raw) +} + +/// E.g. `Kraków :: 14-15 lutego 2026 :: https://...`. +#[must_use] +pub fn tournament_topic(entry: &TournamentEntry) -> String { + [ + polish_city(&entry.place), + polish_date(&entry.date), + entry.url.clone(), + ] + .into_iter() + .filter(|part| !part.is_empty()) + .collect::>() + .join(" :: ") +} + +#[must_use] +pub fn polish_city(place: &str) -> String { + let place = place.trim(); + let key = slugify(place); + POLISH_CITY_NAMES + .iter() + .find(|(ascii, _)| *ascii == key) + .map_or_else(|| place.to_owned(), |(_, polish)| (*polish).to_owned()) +} + +/// `14-15 February 2026` → `14-15 lutego 2026`; unparseable dates are kept. +#[must_use] +pub fn polish_date(date: &str) -> String { + let Some((days, month, year)) = parse_date(date) else { + return date.trim().to_owned(); + }; + let polish_month = |month: usize| MONTHS[month - 1].1; + + match days + .split_once('-') + .map(|(start, end)| (start.parse::(), end.parse::())) + { + // Runs into the next month, e.g. `31-1 January 2026`. + Some((Ok(start), Ok(end))) if end < start => { + let (next_month, next_year) = if month == 12 { + (1, year + 1) + } else { + (month + 1, year) + }; + let first = polish_month(month); + let next = polish_month(next_month); + if next_year == year { + format!("{start} {first} - {end} {next} {year}") + } else { + format!("{start} {first} {year} - {end} {next} {next_year}") + } + } + _ => format!("{days} {} {year}", polish_month(month)), + } +} + +/// Parses ` ` into days, month number and year. +fn parse_date(date: &str) -> Option<(&str, usize, u16)> { + let mut words = date.split_whitespace().rev(); + let year = words.next()?.parse().ok()?; + let month = words.next()?; + let month = MONTHS + .iter() + .position(|(english, _)| english.eq_ignore_ascii_case(month))?; + let days = words.next()?; + words.next().is_none().then_some((days, month + 1, year)) +} + +/// Whether the words of slug `needle` appear consecutively in slug `haystack`. +fn contains_words(haystack: &str, needle: &str) -> bool { + let haystack: Vec<&str> = haystack.split('-').collect(); + let needle: Vec<&str> = needle.split('-').collect(); + haystack + .windows(needle.len()) + .any(|window| window == needle) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(name: &str, date: &str, place: &str, url: &str) -> TournamentEntry { + TournamentEntry { + name: name.to_owned(), + url: url.to_owned(), + rules: "Riichi".to_owned(), + date: date.to_owned(), + place: place.to_owned(), + approval_status: "OK".to_owned(), + registration_start: String::new(), + results_status: String::new(), + } + } + + fn channel_name(name: &str, date: &str, place: &str) -> String { + tournament_channel_name(&entry(name, date, place, "")) + .unwrap() + .as_str() + .to_owned() + } + + #[test] + fn follows_the_server_convention() { + let hatsumi = entry( + "Hatsumi Taikai 2026", + "14-15 February 2026", + "Krakow", + "https://chombo.club/tournaments/2025/12/15/hatsumi-taikai-2026/", + ); + + assert_eq!( + tournament_channel_name(&hatsumi).unwrap().as_str(), + "🏆2026-02-kraków-hatsumi-taikai-2026" + ); + assert_eq!( + tournament_topic(&hatsumi), + "Kraków :: 14-15 lutego 2026 :: \ + https://chombo.club/tournaments/2025/12/15/hatsumi-taikai-2026/" + ); + assert_eq!( + tournament_topic(&entry("Cup", "TBA", "Oss", "")), + "Oss :: TBA" + ); + } + + #[test] + fn names_channels() { + assert_eq!( + channel_name( + "Zensekai no Heiwa no Taikai 2026", + "25-26 March 2026", + "Cologne" + ), + "🏆2026-03-kolonia-zensekai-no-heiwa-no-taikai-2026" + ); + assert_eq!( + channel_name("Vienna Riichi Open 2026", "5-6 December 2026", "Vienna"), + "🏆2026-12-vienna-riichi-open-2026" + ); + assert_eq!( + channel_name("Boss Cup", "1 May 2026", "Oss"), + "🏆2026-05-oss-boss-cup" + ); + assert_eq!(channel_name("Cup", "sometime", "Warsaw"), "🏆warszawa-cup"); + } + + #[test] + fn translates_dates() { + assert_eq!(polish_date("24 January 2026"), "24 stycznia 2026"); + assert_eq!( + polish_date("31-1 January 2026"), + "31 stycznia - 1 lutego 2026" + ); + assert_eq!( + polish_date("30-2 December 2026"), + "30 grudnia 2026 - 2 stycznia 2027" + ); + assert_eq!(polish_date("14-15 Smarch 2026"), "14-15 Smarch 2026"); + } +} diff --git a/chombot-common/src/tournament_channel/polish_names.rs b/chombot-common/src/tournament_channel/polish_names.rs new file mode 100644 index 0000000..e12fac1 --- /dev/null +++ b/chombot-common/src/tournament_channel/polish_names.rs @@ -0,0 +1,134 @@ +/// English month names and their Polish genitive forms ("14 lutego"). +pub(super) const MONTHS: [(&str, &str); 12] = [ + ("january", "stycznia"), + ("february", "lutego"), + ("march", "marca"), + ("april", "kwietnia"), + ("may", "maja"), + ("june", "czerwca"), + ("july", "lipca"), + ("august", "sierpnia"), + ("september", "września"), + ("october", "października"), + ("november", "listopada"), + ("december", "grudnia"), +]; + +/// Polish names of cities, keyed by the slug of the EMA calendar's spelling. +/// Other cities are used as the calendar writes them. +pub(super) const POLISH_CITY_NAMES: &[(&str, &str)] = &[ + ("aachen", "Akwizgran"), + ("antwerp", "Antwerpia"), + ("antwerpen", "Antwerpia"), + ("athens", "Ateny"), + ("athina", "Ateny"), + ("basel", "Bazylea"), + ("belgrade", "Belgrad"), + ("beograd", "Belgrad"), + ("bern", "Berno"), + ("berne", "Berno"), + ("bialystok", "Białystok"), + ("bologna", "Bolonia"), + ("bratislava", "Bratysława"), + ("bruges", "Brugia"), + ("brugge", "Brugia"), + ("brussel", "Bruksela"), + ("brussels", "Bruksela"), + ("bruxelles", "Bruksela"), + ("bucharest", "Bukareszt"), + ("bucuresti", "Bukareszt"), + ("budapest", "Budapeszt"), + ("cluj-napoca", "Kluż-Napoka"), + ("cologne", "Kolonia"), + ("copenhagen", "Kopenhaga"), + ("cracow", "Kraków"), + ("czestochowa", "Częstochowa"), + ("den-haag", "Haga"), + ("dresden", "Drezno"), + ("edinburgh", "Edynburg"), + ("firenze", "Florencja"), + ("florence", "Florencja"), + ("frankfurt-am-main", "Frankfurt nad Menem"), + ("gdansk", "Gdańsk"), + ("geneva", "Genewa"), + ("geneve", "Genewa"), + ("genoa", "Genua"), + ("genova", "Genua"), + ("gent", "Gandawa"), + ("ghent", "Gandawa"), + ("gothenburg", "Göteborg"), + ("hannover", "Hanower"), + ("hanover", "Hanower"), + ("istanbul", "Stambuł"), + ("kaunas", "Kowno"), + ("kharkiv", "Charków"), + ("kharkov", "Charków"), + ("kiev", "Kijów"), + ("kobenhavn", "Kopenhaga"), + ("koln", "Kolonia"), + ("kosice", "Koszyce"), + ("krakow", "Kraków"), + ("kyiv", "Kijów"), + ("lausanne", "Lozanna"), + ("leipzig", "Lipsk"), + ("lisboa", "Lizbona"), + ("lisbon", "Lizbona"), + ("ljubljana", "Lublana"), + ("lodz", "Łódź"), + ("london", "Londyn"), + ("lucerne", "Lucerna"), + ("luzern", "Lucerna"), + ("lviv", "Lwów"), + ("madrid", "Madryt"), + ("marseille", "Marsylia"), + ("milan", "Mediolan"), + ("milano", "Mediolan"), + ("minsk", "Mińsk"), + ("munchen", "Monachium"), + ("munich", "Monachium"), + ("murcia", "Murcja"), + ("myslowice", "Mysłowice"), + ("naples", "Neapol"), + ("napoli", "Neapol"), + ("nice", "Nicea"), + ("nuremberg", "Norymberga"), + ("nurnberg", "Norymberga"), + ("odesa", "Odessa"), + ("olomouc", "Ołomuniec"), + ("padova", "Padwa"), + ("padua", "Padwa"), + ("paris", "Paryż"), + ("pilsen", "Pilzno"), + ("plzen", "Pilzno"), + ("poznan", "Poznań"), + ("prague", "Praga"), + ("praha", "Praga"), + ("reunion-island", "Reunion"), + ("riga", "Ryga"), + ("roma", "Rzym"), + ("rome", "Rzym"), + ("rzeszow", "Rzeszów"), + ("sevilla", "Sewilla"), + ("seville", "Sewilla"), + ("stockholm", "Sztokholm"), + ("strasbourg", "Strasburg"), + ("the-hague", "Haga"), + ("torino", "Turyn"), + ("torun", "Toruń"), + ("toulouse", "Tuluza"), + ("trieste", "Triest"), + ("turin", "Turyn"), + ("valencia", "Walencja"), + ("venezia", "Wenecja"), + ("venice", "Wenecja"), + ("verona", "Werona"), + ("vienna", "Wiedeń"), + ("vilnius", "Wilno"), + ("warsaw", "Warszawa"), + ("wien", "Wiedeń"), + ("wroclaw", "Wrocław"), + ("yerevan", "Erywań"), + ("zaragoza", "Saragossa"), + ("zielona-gora", "Zielona Góra"), + ("zurich", "Zurych"), +]; diff --git a/chombot-common/src/tournaments_watcher/cache.rs b/chombot-common/src/tournaments_watcher/cache.rs new file mode 100644 index 0000000..366e4fd --- /dev/null +++ b/chombot-common/src/tournaments_watcher/cache.rs @@ -0,0 +1,86 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use log::{info, warn}; +use tokio::sync::Mutex; +use tokio::time::timeout; + +use crate::tournaments_watcher::ema::{Tournaments, TournamentsFetchError, get_tournaments}; + +const CACHE_TTL: Duration = Duration::from_mins(10); + +/// The EMA RCR tournament list, fetched on demand and cached for +/// [`CACHE_TTL`]. +#[derive(Default)] +pub struct TournamentsCache { + cached: Mutex)>>, + /// Held while fetching, so that only one fetch runs at a time and the + /// cached list stays readable meanwhile. + refreshing: Mutex<()>, +} + +impl TournamentsCache { + /// Falls back to a stale list if refreshing fails. + pub async fn get(&self) -> Result, TournamentsFetchError> { + if let Some(tournaments) = self.fresh().await { + return Ok(tournaments); + } + let _refreshing = self.refreshing.lock().await; + if let Some(tournaments) = self.fresh().await { + return Ok(tournaments); + } + + match get_tournaments().await { + Ok(tournaments) => { + let tournaments = Arc::new(tournaments.into_rcr_only()); + info!( + "Got {} RCR tournaments: {:?}", + tournaments.0.len(), + tournaments.0 + ); + *self.cached.lock().await = Some((Instant::now(), tournaments.clone())); + Ok(tournaments) + } + Err(err) => match self.last_fetched().await { + Some(stale) => { + warn!("Could not refresh the tournament list, using stale data: {err}"); + Ok(stale) + } + None => Err(err), + }, + } + } + + /// Like [`Self::get`], but gives up (logging why) after `limit`, falling + /// back to a stale list if there is one. + pub async fn get_within(&self, limit: Duration) -> Option> { + match timeout(limit, self.get()).await { + Ok(Ok(tournaments)) => Some(tournaments), + Ok(Err(err)) => { + warn!("{err}"); + None + } + Err(_) => { + warn!("Timed out fetching the tournament list"); + self.last_fetched().await + } + } + } + + async fn fresh(&self) -> Option> { + self.cached + .lock() + .await + .as_ref() + .filter(|(fetched_at, _)| fetched_at.elapsed() < CACHE_TTL) + .map(|(_, tournaments)| tournaments.clone()) + } + + async fn last_fetched(&self) -> Option> { + self.cached + .lock() + .await + .as_ref() + .map(|(_, tournaments)| tournaments.clone()) + } +} diff --git a/chombot-common/src/tournaments_watcher/ema.rs b/chombot-common/src/tournaments_watcher/ema.rs index b9f5e68..66a8c6c 100644 --- a/chombot-common/src/tournaments_watcher/ema.rs +++ b/chombot-common/src/tournaments_watcher/ema.rs @@ -4,7 +4,6 @@ use std::fmt::{Display, Formatter}; use anyhow::{anyhow, bail}; use itertools::Itertools; -use log::info; use reqwest::Url; use scraper::{ElementRef, Html, Selector}; @@ -34,7 +33,7 @@ impl Tournaments { } #[must_use] - fn into_rcr_only(self) -> Self { + pub(crate) fn into_rcr_only(self) -> Self { let filtered = self .0 .into_iter() @@ -244,16 +243,6 @@ fn clean_url(href: &str) -> String { } } -pub async fn get_rcr_tournaments() -> Result, TournamentsFetchError> { - let tournaments = get_tournaments().await?.into_rcr_only(); - info!( - "Got {} RCR tournaments: {:?}", - tournaments.get().len(), - tournaments.get() - ); - Ok(Some(tournaments)) -} - pub async fn get_tournaments() -> Result { let body = create_chombot_http_client() .map_err(TournamentsFetchError::FetchError)? diff --git a/chombot-common/src/tournaments_watcher/mod.rs b/chombot-common/src/tournaments_watcher/mod.rs index ded2f5c..69b69ab 100644 --- a/chombot-common/src/tournaments_watcher/mod.rs +++ b/chombot-common/src/tournaments_watcher/mod.rs @@ -1,2 +1,3 @@ +pub mod cache; pub mod ema; pub mod notifier; diff --git a/chombot-kcc/src/main.rs b/chombot-kcc/src/main.rs index 35b68d0..6e06ecd 100644 --- a/chombot-kcc/src/main.rs +++ b/chombot-kcc/src/main.rs @@ -135,7 +135,11 @@ async fn main() { ChannelId::from(args.tournaments_watcher_channel_id.expect( "Tournaments watcher feature enabled but no channel ID provided", )); - start_tournaments_watcher(tournaments_watcher_channel_id, ctx.clone()); + start_tournaments_watcher( + tournaments_watcher_channel_id, + ctx.clone(), + chombot.tournaments().clone(), + ); } if args.feature_chombohall_reminder { let channel_id = diff --git a/chombot/src/main.rs b/chombot/src/main.rs index b6821a9..7a28594 100644 --- a/chombot/src/main.rs +++ b/chombot/src/main.rs @@ -64,7 +64,11 @@ async fn main() { }) .setup(move |ctx, ready, framework| { Box::pin(async move { - start_tournaments_watcher(config_ref.clone(), ctx.clone()); + start_tournaments_watcher( + config_ref.clone(), + ctx.clone(), + chombot.tournaments().clone(), + ); poise::builtins::register_globally(ctx, &framework.options().commands).await?; info!("{} is connected!", ready.user.name); Ok(PoiseUserData {