Split large core modules into focused child modules (#102)

This commit is contained in:
nessar committed 2026-11-22 16:49:32 +01:00
1 parent b9023c1d15
commit 4548b6ac64
12 files changed
+674 -644

No files matched your search

+1 -217
View File
@@ -321,220 +321,4 @@ impl ChampSelectLists {
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn the_lists_change_only_for_the_events_that_concern_them() {
let mut lists = ChampSelectLists::from_bodies("[1,2,3]", "[3]", Some("[9,8]")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
assert_eq!(lists.anvil(), Some(&[9, 8][..]));
// A Delete carries no data: it changes nothing.
lists.set_pickable(&Value::Null);
lists.set_anvil(&Value::Null);
assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
assert_eq!(lists.anvil(), Some(&[9, 8][..]));
lists.set_pickable(&json!([1, 4]));
assert_eq!(&*lists.pickable(), &HashSet::from([1, 4]));
assert_eq!(lists.anvil(), Some(&[9, 8][..]));
lists.set_disabled(&json!([1]));
assert_eq!(&*lists.pickable(), &HashSet::from([4]));
lists.set_anvil(&json!([5, 6]));
assert_eq!(lists.anvil(), Some(&[5, 6][..]));
}
#[test]
fn the_anvil_champions_are_read_once_when_the_champ_select_starts() {
let anvil = |body| {
ChampSelectLists::from_bodies("[]", "[]", body)
.unwrap()
.anvil()
.map(<[u32]>::to_vec)
};
// No answer, or one that is not a list: the client gave no list.
assert_eq!(anvil(None), None);
assert_eq!(anvil(Some("not json")), None);
assert_eq!(anvil(Some(r#"{"error":"x"}"#)), None);
// An empty list is a list: the client says there are none.
assert_eq!(anvil(Some("[]")), Some(vec![]));
assert_eq!(anvil(Some("[1,2]")), Some(vec![1, 2]));
// The client's order is kept.
assert_eq!(anvil(Some("[9,1,5]")), Some(vec![9, 1, 5]));
// A malformed anvil answer only loses the anvil list, not the pickable one.
let lists = ChampSelectLists::from_bodies("[7]", "[]", Some("not json")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([7]));
assert_eq!(lists.anvil(), None);
}
#[test]
fn an_anvil_event_gives_a_list_from_unknown_and_a_delete_keeps_the_value() {
let mut lists = ChampSelectLists::from_bodies("[]", "[]", None).unwrap();
lists.set_anvil(&Value::Null);
assert_eq!(lists.anvil(), None);
lists.set_anvil(&json!([4, 2]));
assert_eq!(lists.anvil(), Some(&[4, 2][..]));
lists.set_anvil(&Value::Null);
assert_eq!(lists.anvil(), Some(&[4, 2][..]));
// An empty list from an event is a known empty list.
lists.set_anvil(&json!([]));
assert_eq!(lists.anvil(), Some(&[][..]));
}
fn session(
local_intent: u32,
ally_id: u32,
ally_intent: u32,
actions: Value,
bans: Value,
) -> Value {
json!({
"localPlayerCellId": 16,
"myTeam": [
{"cellId": 16, "team": 1, "championId": 0, "championPickIntent": local_intent},
{"cellId": 17, "team": 1, "championId": ally_id, "championPickIntent": ally_intent},
{"cellId": 18, "team": 2, "championId": 77, "championPickIntent": 0},
],
"actions": actions,
"bans": bans,
})
}
fn champ_select(current_session: Value) -> ChampSelect {
ChampSelect::from_session(
&current_session,
Arc::new(HashSet::from([1, 2, 3, 4, 5, 6])),
Some(vec![1, 2]),
)
.unwrap()
}
fn reasons(banned: bool, taken_by_ally: bool, not_offered: bool) -> Unpickable {
Unpickable {
banned,
taken_by_ally,
not_offered,
}
}
#[test]
fn every_reason_that_applies_is_given() {
let pick = champ_select(session(
0,
2,
0,
json!([[
{"type": "ban", "championId": 1, "completed": true},
{"type": "ban", "championId": 3, "completed": false},
{"type": "pick", "championId": 4, "completed": true},
]]),
json!({"myTeamBans": [5], "theirTeamBans": [2]}),
));
// A completed ban, either team's ban list.
assert_eq!(pick.unpickable(1), reasons(true, false, false));
assert_eq!(pick.unpickable(5), reasons(true, false, false));
// Banned and taken by an ally add up; a ban in progress or a pick action count for
// nothing; a player of the other team is not an ally.
assert_eq!(pick.unpickable(2), reasons(true, true, false));
assert_eq!(pick.unpickable(3), Unpickable::default());
assert_eq!(pick.unpickable(4), Unpickable::default());
assert_eq!(pick.unpickable(77), reasons(false, false, true));
// Not in the client's pickable list.
assert_eq!(pick.unpickable(99), reasons(false, false, true));
assert_eq!(pick.unpickable(6), Unpickable::default());
// `can_pick` agrees with the reasons.
for id in [1, 2, 3, 4, 5, 6, 77, 99] {
assert_eq!(
pick.can_pick(id),
pick.unpickable(id) == Unpickable::default(),
"champion {id}"
);
}
}
#[test]
fn an_ally_pre_pick_takes_nothing_but_the_confirmed_pick_does() {
let hover = champ_select(session(0, 0, 3, json!([]), json!({})));
assert_eq!(hover.unpickable(3), Unpickable::default());
let locked = champ_select(session(0, 3, 3, json!([]), json!({})));
assert_eq!(locked.unpickable(3), reasons(false, true, false));
}
#[test]
fn a_disabled_champion_is_not_offered() {
let lists = ChampSelectLists::from_bodies("[1,2,3]", "[3]", None).unwrap();
let pick = ChampSelect::from_session(
&session(0, 0, 0, json!([]), json!({})),
lists.pickable(),
None,
)
.unwrap();
assert_eq!(pick.unpickable(3), reasons(false, false, true));
assert_eq!(pick.unpickable(1), Unpickable::default());
}
#[test]
fn the_players_own_pick_is_never_greyed() {
// Hovered then locked, though the data also bans it, takes it and does not offer it.
let banned = json!([[{"type": "ban", "championId": 99, "completed": true}]]);
let intent = champ_select(session(99, 99, 0, banned.clone(), json!({})));
assert_eq!(intent.current, Some(99));
assert_eq!(intent.unpickable(99), Unpickable::default());
let mut locked = session(0, 99, 0, banned, json!({"myTeamBans": [99]}));
locked["myTeam"][0]["championId"] = json!(99);
let locked = champ_select(locked);
assert_eq!(locked.unpickable(99), Unpickable::default());
assert!(locked.can_pick(99));
}
#[test]
fn two_champ_selects_differ_by_their_bans_and_ally_picks() {
let plain = champ_select(session(0, 0, 0, json!([]), json!({})));
let banned = champ_select(session(0, 0, 0, json!([]), json!({"myTeamBans": [3]})));
let taken = champ_select(session(0, 3, 0, json!([]), json!({})));
assert!(!plain.same_pickable(&banned));
assert!(!plain.same_pickable(&taken));
assert!(!banned.same_pickable(&taken));
assert_ne!(plain, banned);
}
#[test]
fn a_read_uses_the_session_of_an_event_and_reads_the_lists_once() {
let reader = ChampSelectReader::default();
let session = || {
Ok(
r#"{"localPlayerCellId":16,"myTeam":[{"cellId":16,"championId":0,
"championPickIntent":0}],"actions":[],
"bans":{"myTeamBans":[],"theirTeamBans":[]}}"#
.to_string(),
)
};
let lists = || {
Ok((
"[1,2]".to_string(),
"[]".to_string(),
Some("[9]".to_string()),
))
};
reader.read(session, lists).unwrap();
// A session event replaces the request; the lists stay cached.
reader.set_session(json!({
"localPlayerCellId": 16,
"myTeam": [{"cellId": 16, "championId": 2, "championPickIntent": 0}],
"actions": [],
"bans": {"myTeamBans": [], "theirTeamBans": []}
}));
let pick = reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.unwrap();
assert_eq!(pick.current, Some(2));
}
}
mod tests;
+215
View File
@@ -0,0 +1,215 @@
use super::*;
use serde_json::json;
#[test]
fn the_lists_change_only_for_the_events_that_concern_them() {
let mut lists = ChampSelectLists::from_bodies("[1,2,3]", "[3]", Some("[9,8]")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
assert_eq!(lists.anvil(), Some(&[9, 8][..]));
// A Delete carries no data: it changes nothing.
lists.set_pickable(&Value::Null);
lists.set_anvil(&Value::Null);
assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
assert_eq!(lists.anvil(), Some(&[9, 8][..]));
lists.set_pickable(&json!([1, 4]));
assert_eq!(&*lists.pickable(), &HashSet::from([1, 4]));
assert_eq!(lists.anvil(), Some(&[9, 8][..]));
lists.set_disabled(&json!([1]));
assert_eq!(&*lists.pickable(), &HashSet::from([4]));
lists.set_anvil(&json!([5, 6]));
assert_eq!(lists.anvil(), Some(&[5, 6][..]));
}
#[test]
fn the_anvil_champions_are_read_once_when_the_champ_select_starts() {
let anvil = |body| {
ChampSelectLists::from_bodies("[]", "[]", body)
.unwrap()
.anvil()
.map(<[u32]>::to_vec)
};
// No answer, or one that is not a list: the client gave no list.
assert_eq!(anvil(None), None);
assert_eq!(anvil(Some("not json")), None);
assert_eq!(anvil(Some(r#"{"error":"x"}"#)), None);
// An empty list is a list: the client says there are none.
assert_eq!(anvil(Some("[]")), Some(vec![]));
assert_eq!(anvil(Some("[1,2]")), Some(vec![1, 2]));
// The client's order is kept.
assert_eq!(anvil(Some("[9,1,5]")), Some(vec![9, 1, 5]));
// A malformed anvil answer only loses the anvil list, not the pickable one.
let lists = ChampSelectLists::from_bodies("[7]", "[]", Some("not json")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([7]));
assert_eq!(lists.anvil(), None);
}
#[test]
fn an_anvil_event_gives_a_list_from_unknown_and_a_delete_keeps_the_value() {
let mut lists = ChampSelectLists::from_bodies("[]", "[]", None).unwrap();
lists.set_anvil(&Value::Null);
assert_eq!(lists.anvil(), None);
lists.set_anvil(&json!([4, 2]));
assert_eq!(lists.anvil(), Some(&[4, 2][..]));
lists.set_anvil(&Value::Null);
assert_eq!(lists.anvil(), Some(&[4, 2][..]));
// An empty list from an event is a known empty list.
lists.set_anvil(&json!([]));
assert_eq!(lists.anvil(), Some(&[][..]));
}
fn session(
local_intent: u32,
ally_id: u32,
ally_intent: u32,
actions: Value,
bans: Value,
) -> Value {
json!({
"localPlayerCellId": 16,
"myTeam": [
{"cellId": 16, "team": 1, "championId": 0, "championPickIntent": local_intent},
{"cellId": 17, "team": 1, "championId": ally_id, "championPickIntent": ally_intent},
{"cellId": 18, "team": 2, "championId": 77, "championPickIntent": 0},
],
"actions": actions,
"bans": bans,
})
}
fn champ_select(current_session: Value) -> ChampSelect {
ChampSelect::from_session(
&current_session,
Arc::new(HashSet::from([1, 2, 3, 4, 5, 6])),
Some(vec![1, 2]),
)
.unwrap()
}
fn reasons(banned: bool, taken_by_ally: bool, not_offered: bool) -> Unpickable {
Unpickable {
banned,
taken_by_ally,
not_offered,
}
}
#[test]
fn every_reason_that_applies_is_given() {
let pick = champ_select(session(
0,
2,
0,
json!([[
{"type": "ban", "championId": 1, "completed": true},
{"type": "ban", "championId": 3, "completed": false},
{"type": "pick", "championId": 4, "completed": true},
]]),
json!({"myTeamBans": [5], "theirTeamBans": [2]}),
));
// A completed ban, either team's ban list.
assert_eq!(pick.unpickable(1), reasons(true, false, false));
assert_eq!(pick.unpickable(5), reasons(true, false, false));
// Banned and taken by an ally add up; a ban in progress or a pick action count for
// nothing; a player of the other team is not an ally.
assert_eq!(pick.unpickable(2), reasons(true, true, false));
assert_eq!(pick.unpickable(3), Unpickable::default());
assert_eq!(pick.unpickable(4), Unpickable::default());
assert_eq!(pick.unpickable(77), reasons(false, false, true));
// Not in the client's pickable list.
assert_eq!(pick.unpickable(99), reasons(false, false, true));
assert_eq!(pick.unpickable(6), Unpickable::default());
// `can_pick` agrees with the reasons.
for id in [1, 2, 3, 4, 5, 6, 77, 99] {
assert_eq!(
pick.can_pick(id),
pick.unpickable(id) == Unpickable::default(),
"champion {id}"
);
}
}
#[test]
fn an_ally_pre_pick_takes_nothing_but_the_confirmed_pick_does() {
let hover = champ_select(session(0, 0, 3, json!([]), json!({})));
assert_eq!(hover.unpickable(3), Unpickable::default());
let locked = champ_select(session(0, 3, 3, json!([]), json!({})));
assert_eq!(locked.unpickable(3), reasons(false, true, false));
}
#[test]
fn a_disabled_champion_is_not_offered() {
let lists = ChampSelectLists::from_bodies("[1,2,3]", "[3]", None).unwrap();
let pick = ChampSelect::from_session(
&session(0, 0, 0, json!([]), json!({})),
lists.pickable(),
None,
)
.unwrap();
assert_eq!(pick.unpickable(3), reasons(false, false, true));
assert_eq!(pick.unpickable(1), Unpickable::default());
}
#[test]
fn the_players_own_pick_is_never_greyed() {
// Hovered then locked, though the data also bans it, takes it and does not offer it.
let banned = json!([[{"type": "ban", "championId": 99, "completed": true}]]);
let intent = champ_select(session(99, 99, 0, banned.clone(), json!({})));
assert_eq!(intent.current, Some(99));
assert_eq!(intent.unpickable(99), Unpickable::default());
let mut locked = session(0, 99, 0, banned, json!({"myTeamBans": [99]}));
locked["myTeam"][0]["championId"] = json!(99);
let locked = champ_select(locked);
assert_eq!(locked.unpickable(99), Unpickable::default());
assert!(locked.can_pick(99));
}
#[test]
fn two_champ_selects_differ_by_their_bans_and_ally_picks() {
let plain = champ_select(session(0, 0, 0, json!([]), json!({})));
let banned = champ_select(session(0, 0, 0, json!([]), json!({"myTeamBans": [3]})));
let taken = champ_select(session(0, 3, 0, json!([]), json!({})));
assert!(!plain.same_pickable(&banned));
assert!(!plain.same_pickable(&taken));
assert!(!banned.same_pickable(&taken));
assert_ne!(plain, banned);
}
#[test]
fn a_read_uses_the_session_of_an_event_and_reads_the_lists_once() {
let reader = ChampSelectReader::default();
let session = || {
Ok(
r#"{"localPlayerCellId":16,"myTeam":[{"cellId":16,"championId":0,
"championPickIntent":0}],"actions":[],
"bans":{"myTeamBans":[],"theirTeamBans":[]}}"#
.to_string(),
)
};
let lists = || {
Ok((
"[1,2]".to_string(),
"[]".to_string(),
Some("[9]".to_string()),
))
};
reader.read(session, lists).unwrap();
// A session event replaces the request; the lists stay cached.
reader.set_session(json!({
"localPlayerCellId": 16,
"myTeam": [{"cellId": 16, "championId": 2, "championPickIntent": 0}],
"actions": [],
"bans": {"myTeamBans": [], "theirTeamBans": []}
}));
let pick = reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.unwrap();
assert_eq!(pick.current, Some(2));
}
+5 -180
View File
@@ -1,16 +1,17 @@
//! Keeping the active Account up to date by following the game client.
mod pending;
mod progress;
use std::sync::{MutexGuard, PoisonError};
use std::thread;
use std::time::Duration;
use rusqlite::{OptionalExtension, params};
use rusqlite::OptionalExtension;
use crate::client::{ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow};
use crate::error::{Error, SourceError};
use crate::model::{Account, FollowedMatch, SyncProgress, SyncReport};
use crate::seasons::Season;
use crate::statistics::{Scope, SeasonScope};
use crate::tracker::{Fetched, Tracker, account_from_row};
use crate::tracker::{Tracker, account_from_row};
/// Tries at the Match of an Arena game that just ended, one per `RETRY_EVERY_MS` (about 30
/// minutes: Riot publishes it only when the whole game is over, which a player eliminated early
@@ -483,100 +484,6 @@ impl Tracker {
result
}
/// One try at the Match of a finished Arena game: fetched by its id when the client gave it
/// and a stored Match gives the platform, else looked for by a normal sync. Returns the
/// number of Matches added and whether the wait for this one is over.
fn look_for_match(
&self,
account: &Account,
game_id: Option<u64>,
on_progress: &mut dyn FnMut(SyncProgress),
on_match: &mut dyn FnMut(FollowedMatch),
) -> (usize, bool) {
let puuid = &account.puuid;
let platform = self.platform_of(puuid).ok().flatten();
let Some(match_id) = game_id.zip(platform).map(|(id, p)| format!("{p}_{id}")) else {
let newest_before = self.latest_start_ms(puuid).ok().flatten();
// The earliest bound of the games waiting without an id, if they all have one.
let started_after = (self.follow().pending.iter())
.filter(|p| p.game_id.is_none())
.map(|p| p.started_after_ms)
.min()
.flatten();
// Not over: `update` ends the waits without an id, a fetch by id ends the others.
let added = self
.update(&account_riot_id(account), on_progress)
.map_or(0, |report| report.added);
if added > 0
&& let Ok(Some(id)) =
self.followed_in_sync(puuid, game_id, newest_before, started_after)
{
self.report(puuid, &id, on_match);
}
return (added, false);
};
match self.fetch_and_store(puuid, &match_id) {
Ok(fetched) => {
let added = usize::from(fetched == Fetched::Added);
self.clear_problem(added);
if added > 0 {
self.refresh_mastery(puuid);
self.report(puuid, &match_id, on_match);
}
(added, fetched != Fetched::NotFound)
}
Err(e) => {
self.record(UpdateProblem::from(&e));
(0, false)
}
}
}
/// The followed game among the Matches a sync has just stored: the one with the client's id
/// for it, else the newest Match when it is newer than every Match stored before and started
/// after the game's bound (`Pending::started_after_ms`): an older Match the sync also brings
/// is history. Without that id nor a bound, a first import is only history.
fn followed_in_sync(
&self,
puuid: &str,
game_id: Option<u64>,
newest_before: Option<i64>,
started_after: Option<i64>,
) -> Result<Option<String>, Error> {
let db = self.db();
let newest = match game_id {
// Only reached without a platform, so without any Match stored before the sync.
Some(id) => db.query_row(
"SELECT match_id, started_at_ms FROM matches
WHERE puuid = ?1 AND match_id LIKE '%\\_' || ?2 ESCAPE '\\'",
params![puuid, id.to_string()],
|row| Ok((row.get::<_, String>(0)?, i64::MIN)),
),
None => db.query_row(
"SELECT match_id, started_at_ms FROM matches WHERE puuid = ?1
ORDER BY started_at_ms DESC LIMIT 1",
[puuid],
|row| Ok((row.get(0)?, row.get(1)?)),
),
}
.optional()?;
let followed = |started: i64| match started_after {
Some(after) => started >= after && newest_before.is_none_or(|b| started > b),
None => newest_before.is_some_and(|b| started > b),
};
Ok(newest
.filter(|(_, started)| game_id.is_some() || followed(*started))
.map(|(id, _)| id))
}
/// Tells `on_match` what the stored Match `match_id` brought; a read error only loses the
/// animation.
fn report(&self, puuid: &str, match_id: &str, on_match: &mut dyn FnMut(FollowedMatch)) {
if let Ok(Some(event)) = self.followed_match(puuid, match_id) {
on_match(event);
}
}
fn remember_active(&self, account: &Account) -> Result<(), Error> {
self.db().execute(
"INSERT OR REPLACE INTO meta (name, value) VALUES ('last_active_puuid', ?1)",
@@ -584,89 +491,7 @@ impl Tracker {
)?;
Ok(())
}
/// Compares the client's reading with the Challenge of the active Account.
fn update_progress_check(&self) {
let (official, account) = {
let follow = self.follow();
(follow.official.clone(), follow.updating.clone())
};
let check = match (official, account) {
(Some((season, official)), Some(account)) => {
let scope = Scope {
season: SeasonScope::Season(season),
format: None,
};
match self.statistics(&account.puuid, &scope) {
Ok(stats) => {
let app = stats.challenge.map_or(0, |c| c.completed);
if app == official as usize {
ProgressCheck::Agrees(official)
} else {
ProgressCheck::Differs { app, official }
}
}
Err(_) => ProgressCheck::Absent,
}
}
_ => ProgressCheck::Absent,
};
self.follow().official_progress = check;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
use std::time::Duration;
#[test]
fn account_riot_ids_join_name_and_tag() {
let account = Account {
puuid: "p".into(),
game_name: "Joueur".into(),
tag_line: "EUW".into(),
};
assert_eq!(account_riot_id(&account), "Joueur#EUW");
}
#[test]
fn every_problem_has_its_own_message() {
let messages: HashSet<String> = [
UpdateProblem::MissingKey,
UpdateProblem::InvalidKey,
UpdateProblem::Network,
UpdateProblem::RateLimited,
UpdateProblem::NoAccount,
UpdateProblem::MatchPending,
UpdateProblem::Other("panne".into()),
]
.iter()
.map(UpdateProblem::message)
.collect();
assert_eq!(messages.len(), 7);
assert!(messages.iter().all(|m| !m.is_empty()));
}
#[test]
fn errors_map_to_problems() {
let source = |e| UpdateProblem::from(&Error::Source(e));
assert_eq!(source(SourceError::MissingKey), UpdateProblem::MissingKey);
assert_eq!(source(SourceError::InvalidKey), UpdateProblem::InvalidKey);
assert_eq!(
source(SourceError::Network("x".into())),
UpdateProblem::Network
);
let limited = SourceError::RateLimited {
retry_after: Duration::ZERO,
};
assert_eq!(source(limited), UpdateProblem::RateLimited);
assert!(matches!(
source(SourceError::NotFound),
UpdateProblem::Other(_)
));
let storage = UpdateProblem::from(&Error::Storage("disque plein".into()));
assert!(matches!(storage, UpdateProblem::Other(m) if m.contains("disque plein")));
}
}
mod tests;
+102
View File
@@ -0,0 +1,102 @@
use rusqlite::{OptionalExtension, params};
use super::{UpdateProblem, account_riot_id};
use crate::error::Error;
use crate::model::{Account, FollowedMatch, SyncProgress};
use crate::tracker::{Fetched, Tracker};
impl Tracker {
/// One try at the Match of a finished Arena game: fetched by its id when the client gave it
/// and a stored Match gives the platform, else looked for by a normal sync. Returns the
/// number of Matches added and whether the wait for this one is over.
pub(super) fn look_for_match(
&self,
account: &Account,
game_id: Option<u64>,
on_progress: &mut dyn FnMut(SyncProgress),
on_match: &mut dyn FnMut(FollowedMatch),
) -> (usize, bool) {
let puuid = &account.puuid;
let platform = self.platform_of(puuid).ok().flatten();
let Some(match_id) = game_id.zip(platform).map(|(id, p)| format!("{p}_{id}")) else {
let newest_before = self.latest_start_ms(puuid).ok().flatten();
// The earliest bound of the games waiting without an id, if they all have one.
let started_after = (self.follow().pending.iter())
.filter(|p| p.game_id.is_none())
.map(|p| p.started_after_ms)
.min()
.flatten();
// Not over: `update` ends the waits without an id, a fetch by id ends the others.
let added = self
.update(&account_riot_id(account), on_progress)
.map_or(0, |report| report.added);
if added > 0
&& let Ok(Some(id)) =
self.followed_in_sync(puuid, game_id, newest_before, started_after)
{
self.report(puuid, &id, on_match);
}
return (added, false);
};
match self.fetch_and_store(puuid, &match_id) {
Ok(fetched) => {
let added = usize::from(fetched == Fetched::Added);
self.clear_problem(added);
if added > 0 {
self.refresh_mastery(puuid);
self.report(puuid, &match_id, on_match);
}
(added, fetched != Fetched::NotFound)
}
Err(e) => {
self.record(UpdateProblem::from(&e));
(0, false)
}
}
}
/// The followed game among the Matches a sync has just stored: the one with the client's id
/// for it, else the newest Match when it is newer than every Match stored before and started
/// after the game's bound (`Pending::started_after_ms`): an older Match the sync also brings
/// is history. Without that id nor a bound, a first import is only history.
fn followed_in_sync(
&self,
puuid: &str,
game_id: Option<u64>,
newest_before: Option<i64>,
started_after: Option<i64>,
) -> Result<Option<String>, Error> {
let db = self.db();
let newest = match game_id {
// Only reached without a platform, so without any Match stored before the sync.
Some(id) => db.query_row(
"SELECT match_id, started_at_ms FROM matches
WHERE puuid = ?1 AND match_id LIKE '%\\_' || ?2 ESCAPE '\\'",
params![puuid, id.to_string()],
|row| Ok((row.get::<_, String>(0)?, i64::MIN)),
),
None => db.query_row(
"SELECT match_id, started_at_ms FROM matches WHERE puuid = ?1
ORDER BY started_at_ms DESC LIMIT 1",
[puuid],
|row| Ok((row.get(0)?, row.get(1)?)),
),
}
.optional()?;
let followed = |started: i64| match started_after {
Some(after) => started >= after && newest_before.is_none_or(|b| started > b),
None => newest_before.is_some_and(|b| started > b),
};
Ok(newest
.filter(|(_, started)| game_id.is_some() || followed(*started))
.map(|(id, _)| id))
}
/// Tells `on_match` what the stored Match `match_id` brought; a read error only loses the
/// animation.
fn report(&self, puuid: &str, match_id: &str, on_match: &mut dyn FnMut(FollowedMatch)) {
if let Ok(Some(event)) = self.followed_match(puuid, match_id) {
on_match(event);
}
}
}
+34
View File
@@ -0,0 +1,34 @@
use super::ProgressCheck;
use crate::statistics::{Scope, SeasonScope};
use crate::tracker::Tracker;
impl Tracker {
/// Compares the client's reading with the Challenge of the active Account.
pub(super) fn update_progress_check(&self) {
let (official, account) = {
let follow = self.follow();
(follow.official.clone(), follow.updating.clone())
};
let check = match (official, account) {
(Some((season, official)), Some(account)) => {
let scope = Scope {
season: SeasonScope::Season(season),
format: None,
};
match self.statistics(&account.puuid, &scope) {
Ok(stats) => {
let app = stats.challenge.map_or(0, |c| c.completed);
if app == official as usize {
ProgressCheck::Agrees(official)
} else {
ProgressCheck::Differs { app, official }
}
}
Err(_) => ProgressCheck::Absent,
}
}
_ => ProgressCheck::Absent,
};
self.follow().official_progress = check;
}
}
+52
View File
@@ -0,0 +1,52 @@
use super::*;
use std::collections::HashSet;
use std::time::Duration;
#[test]
fn account_riot_ids_join_name_and_tag() {
let account = Account {
puuid: "p".into(),
game_name: "Joueur".into(),
tag_line: "EUW".into(),
};
assert_eq!(account_riot_id(&account), "Joueur#EUW");
}
#[test]
fn every_problem_has_its_own_message() {
let messages: HashSet<String> = [
UpdateProblem::MissingKey,
UpdateProblem::InvalidKey,
UpdateProblem::Network,
UpdateProblem::RateLimited,
UpdateProblem::NoAccount,
UpdateProblem::MatchPending,
UpdateProblem::Other("panne".into()),
]
.iter()
.map(UpdateProblem::message)
.collect();
assert_eq!(messages.len(), 7);
assert!(messages.iter().all(|m| !m.is_empty()));
}
#[test]
fn errors_map_to_problems() {
let source = |e| UpdateProblem::from(&Error::Source(e));
assert_eq!(source(SourceError::MissingKey), UpdateProblem::MissingKey);
assert_eq!(source(SourceError::InvalidKey), UpdateProblem::InvalidKey);
assert_eq!(
source(SourceError::Network("x".into())),
UpdateProblem::Network
);
let limited = SourceError::RateLimited {
retry_after: Duration::ZERO,
};
assert_eq!(source(limited), UpdateProblem::RateLimited);
assert!(matches!(
source(SourceError::NotFound),
UpdateProblem::Other(_)
));
let storage = UpdateProblem::from(&Error::Storage("disque plein".into()));
assert!(matches!(storage, UpdateProblem::Other(m) if m.contains("disque plein")));
}
+4 -101
View File
@@ -1,5 +1,8 @@
//! Challenge figures and champion statistics, computed on demand from stored Matches.
use std::cmp::Ordering;
mod rows;
pub(crate) use rows::collate;
pub use rows::{Column, StateFilter, sort_rows};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::OsStr;
use std::ops::Range;
@@ -165,106 +168,6 @@ pub struct Charts {
pub attempts_to_complete: [usize; 5],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Column {
Champion,
Matches,
BestPlacement,
Top1,
Wins,
AveragePlacement,
Attempts,
LastMatch,
State,
}
/// Sorts rows by a column. Rows with no value in it go last whatever the direction; ties
/// are broken by champion name.
pub fn sort_rows(rows: &mut [ChampionRow], column: Column, descending: bool) {
rows.sort_by(|a, b| {
let by_name = || {
collate(&a.champion.name)
.cmp(&collate(&b.champion.name))
.then(a.champion.id.cmp(&b.champion.id))
};
if column == Column::Champion {
return if descending {
by_name().reverse()
} else {
by_name()
};
}
match (value(a, column), value(b, column)) {
(Some(x), Some(y)) if descending => y.total_cmp(&x),
(Some(x), Some(y)) => x.total_cmp(&y),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
}
.then_with(by_name)
});
}
fn value(row: &ChampionRow, column: Column) -> Option<f64> {
match column {
Column::Champion => None,
Column::Matches => Some(row.matches as f64),
Column::BestPlacement => row.best_placement.map(f64::from),
Column::Top1 => Some(row.top1 as f64),
Column::Wins => Some(row.wins as f64),
Column::AveragePlacement => row.average_placement,
Column::Attempts => row.attempts.map(|n| n as f64),
Column::LastMatch => row.last_match_ms.map(|ms| ms as f64),
Column::State => row.state.map(|state| match state {
ChampionState::Completed => 0.0,
ChampionState::InProgress => 1.0,
ChampionState::NeverPlayed => 2.0,
}),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateFilter {
All,
Completed,
/// In progress or never played.
Remaining,
NeverPlayed,
}
impl StateFilter {
/// A row with no state is only kept by `All`.
pub fn keeps(&self, row: &ChampionRow) -> bool {
match self {
StateFilter::All => true,
StateFilter::Completed => row.state == Some(ChampionState::Completed),
StateFilter::Remaining => matches!(
row.state,
Some(ChampionState::InProgress | ChampionState::NeverPlayed)
),
StateFilter::NeverPlayed => row.state == Some(ChampionState::NeverPlayed),
}
}
}
/// Alphabetical order for French names: case and accents do not count.
pub(crate) fn collate(name: &str) -> String {
name.to_lowercase()
.chars()
.map(|c| match c {
'à' | 'á' | 'â' | 'ä' | 'ã' | 'å' => 'a',
'é' | 'è' | 'ê' | 'ë' => 'e',
'í' | 'ì' | 'î' | 'ï' => 'i',
'ó' | 'ò' | 'ô' | 'ö' | 'õ' => 'o',
'ú' | 'ù' | 'û' | 'ü' => 'u',
'ý' | 'ÿ' => 'y',
'ñ' => 'n',
'ç' => 'c',
other => other,
})
.collect()
}
#[derive(Default)]
struct Progress {
attempts: usize,
+103
View File
@@ -0,0 +1,103 @@
use std::cmp::Ordering;
use super::{ChampionRow, ChampionState};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Column {
Champion,
Matches,
BestPlacement,
Top1,
Wins,
AveragePlacement,
Attempts,
LastMatch,
State,
}
/// Sorts rows by a column. Rows with no value in it go last whatever the direction; ties
/// are broken by champion name.
pub fn sort_rows(rows: &mut [ChampionRow], column: Column, descending: bool) {
rows.sort_by(|a, b| {
let by_name = || {
collate(&a.champion.name)
.cmp(&collate(&b.champion.name))
.then(a.champion.id.cmp(&b.champion.id))
};
if column == Column::Champion {
return if descending {
by_name().reverse()
} else {
by_name()
};
}
match (value(a, column), value(b, column)) {
(Some(x), Some(y)) if descending => y.total_cmp(&x),
(Some(x), Some(y)) => x.total_cmp(&y),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
}
.then_with(by_name)
});
}
fn value(row: &ChampionRow, column: Column) -> Option<f64> {
match column {
Column::Champion => None,
Column::Matches => Some(row.matches as f64),
Column::BestPlacement => row.best_placement.map(f64::from),
Column::Top1 => Some(row.top1 as f64),
Column::Wins => Some(row.wins as f64),
Column::AveragePlacement => row.average_placement,
Column::Attempts => row.attempts.map(|n| n as f64),
Column::LastMatch => row.last_match_ms.map(|ms| ms as f64),
Column::State => row.state.map(|state| match state {
ChampionState::Completed => 0.0,
ChampionState::InProgress => 1.0,
ChampionState::NeverPlayed => 2.0,
}),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateFilter {
All,
Completed,
/// In progress or never played.
Remaining,
NeverPlayed,
}
impl StateFilter {
/// A row with no state is only kept by `All`.
pub fn keeps(&self, row: &ChampionRow) -> bool {
match self {
StateFilter::All => true,
StateFilter::Completed => row.state == Some(ChampionState::Completed),
StateFilter::Remaining => matches!(
row.state,
Some(ChampionState::InProgress | ChampionState::NeverPlayed)
),
StateFilter::NeverPlayed => row.state == Some(ChampionState::NeverPlayed),
}
}
}
/// Alphabetical order for French names: case and accents do not count.
pub(crate) fn collate(name: &str) -> String {
name.to_lowercase()
.chars()
.map(|c| match c {
'à' | 'á' | 'â' | 'ä' | 'ã' | 'å' => 'a',
'é' | 'è' | 'ê' | 'ë' => 'e',
'í' | 'ì' | 'î' | 'ï' => 'i',
'ó' | 'ò' | 'ô' | 'ö' | 'õ' => 'o',
'ú' | 'ù' | 'û' | 'ü' => 'u',
'ý' | 'ÿ' => 'y',
'ñ' => 'n',
'ç' => 'c',
other => other,
})
.collect()
}
+6 -146
View File
@@ -1,11 +1,15 @@
mod payload;
mod storage;
use payload::decode_match;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread;
use storage::insert_match;
use rusqlite::{Connection, OptionalExtension, Row, params};
use serde::Deserialize;
use crate::champions::ChampionSource;
use crate::client::GameClientSource;
@@ -470,149 +474,5 @@ fn with_retry<T>(mut call: impl FnMut() -> Result<T, SourceError>) -> Result<T,
call()
}
/// Returns whether the Match was new.
fn insert_match(
db: &Connection,
puuid: &str,
m: &Match,
queue_id: u32,
raw: &str,
) -> rusqlite::Result<bool> {
let inserted = db.execute(
"INSERT OR IGNORE INTO matches
(puuid, match_id, queue_id, champion_id, champion_name, placement, win, started_at_ms, raw)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
params![
puuid,
m.match_id,
queue_id,
m.champion_id,
m.champion_name,
m.placement,
m.win,
m.started_at_ms,
raw
],
)?;
Ok(inserted == 1)
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Payload {
metadata: PayloadMetadata,
info: PayloadInfo,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PayloadMetadata {
match_id: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PayloadInfo {
queue_id: u32,
game_mode: String,
game_start_timestamp: i64,
/// Read one by one: only the Account's own entry has to be complete.
participants: Vec<serde_json::Value>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Participant {
champion_id: u32,
champion_name: String,
placement: u8,
win: bool,
}
/// The Match (with its raw queue id) the Account played in a Riot match-v5 payload, or
/// `None` when the payload is not an Arena Match of this Account.
fn decode_match(raw: &str, puuid: &str) -> Result<Option<(Match, u32)>, serde_json::Error> {
let payload: Payload = serde_json::from_str(raw)?;
let info = payload.info;
if info.game_mode != "CHERRY" {
return Ok(None);
}
let Some(format) = Format::from_queue(info.queue_id) else {
return Ok(None);
};
let Some(me) = info.participants.into_iter().find(|p| p["puuid"] == puuid) else {
return Ok(None);
};
let me: Participant = serde_json::from_value(me)?;
let m = Match {
match_id: payload.metadata.match_id,
format,
champion_id: me.champion_id,
champion_name: me.champion_name,
placement: me.placement,
win: me.win,
started_at_ms: info.game_start_timestamp,
};
Ok(Some((m, info.queue_id)))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
const FIXTURE: &str = include_str!("../tests/fixtures/riot/match_1740_EUW1_9000000005.json");
#[test]
fn decodes_the_accounts_participant() {
let (m, queue_id) = decode_match(FIXTURE, "fixture-puuid-self")
.unwrap()
.unwrap();
assert_eq!(queue_id, 1740);
assert_eq!(
m,
Match {
match_id: "EUW1_9000000005".into(),
format: Format::BraveryArena,
champion_id: 19,
champion_name: "Warwick".into(),
placement: 5,
win: false,
started_at_ms: 1794424080842,
}
);
}
#[test]
fn ignores_payloads_without_the_account() {
assert!(decode_match(FIXTURE, "someone-else").unwrap().is_none());
}
#[test]
fn raw_payload_is_stored_unmodified_and_only_once() {
let db = Connection::open_in_memory().unwrap();
db.execute_batch(SCHEMA).unwrap();
let (m, queue_id) = decode_match(FIXTURE, "fixture-puuid-self")
.unwrap()
.unwrap();
assert!(insert_match(&db, "p", &m, queue_id, FIXTURE).unwrap());
assert!(!insert_match(&db, "p", &m, queue_id, FIXTURE).unwrap());
let raw: String = db
.query_row("SELECT raw FROM matches", [], |row| row.get(0))
.unwrap();
assert_eq!(raw, FIXTURE);
}
#[test]
fn rate_limit_is_retried_a_few_times_then_reported() {
let mut calls = 0;
let result: Result<(), _> = with_retry(|| {
calls += 1;
Err(SourceError::RateLimited {
retry_after: Duration::ZERO,
})
});
assert!(matches!(result, Err(SourceError::RateLimited { .. })));
assert_eq!(calls, RATE_LIMIT_RETRIES + 1);
}
}
mod tests;
+65
View File
@@ -0,0 +1,65 @@
use serde::Deserialize;
use crate::model::{Format, Match};
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Payload {
metadata: PayloadMetadata,
info: PayloadInfo,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PayloadMetadata {
match_id: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PayloadInfo {
queue_id: u32,
game_mode: String,
game_start_timestamp: i64,
/// Read one by one: only the Account's own entry has to be complete.
participants: Vec<serde_json::Value>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Participant {
champion_id: u32,
champion_name: String,
placement: u8,
win: bool,
}
/// The Match (with its raw queue id) the Account played in a Riot match-v5 payload, or
/// `None` when the payload is not an Arena Match of this Account.
pub(super) fn decode_match(
raw: &str,
puuid: &str,
) -> Result<Option<(Match, u32)>, serde_json::Error> {
let payload: Payload = serde_json::from_str(raw)?;
let info = payload.info;
if info.game_mode != "CHERRY" {
return Ok(None);
}
let Some(format) = Format::from_queue(info.queue_id) else {
return Ok(None);
};
let Some(me) = info.participants.into_iter().find(|p| p["puuid"] == puuid) else {
return Ok(None);
};
let me: Participant = serde_json::from_value(me)?;
let m = Match {
match_id: payload.metadata.match_id,
format,
champion_id: me.champion_id,
champion_name: me.champion_name,
placement: me.placement,
win: me.win,
started_at_ms: info.game_start_timestamp,
};
Ok(Some((m, info.queue_id)))
}
+30
View File
@@ -0,0 +1,30 @@
use rusqlite::{Connection, params};
use crate::model::Match;
/// Returns whether the Match was new.
pub(super) fn insert_match(
db: &Connection,
puuid: &str,
m: &Match,
queue_id: u32,
raw: &str,
) -> rusqlite::Result<bool> {
let inserted = db.execute(
"INSERT OR IGNORE INTO matches
(puuid, match_id, queue_id, champion_id, champion_name, placement, win, started_at_ms, raw)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
params![
puuid,
m.match_id,
queue_id,
m.champion_id,
m.champion_name,
m.placement,
m.win,
m.started_at_ms,
raw
],
)?;
Ok(inserted == 1)
}
+57
View File
@@ -0,0 +1,57 @@
use super::*;
use std::time::Duration;
const FIXTURE: &str = include_str!("../../tests/fixtures/riot/match_1740_EUW1_9000000005.json");
#[test]
fn decodes_the_accounts_participant() {
let (m, queue_id) = decode_match(FIXTURE, "fixture-puuid-self")
.unwrap()
.unwrap();
assert_eq!(queue_id, 1740);
assert_eq!(
m,
Match {
match_id: "EUW1_9000000005".into(),
format: Format::BraveryArena,
champion_id: 19,
champion_name: "Warwick".into(),
placement: 5,
win: false,
started_at_ms: 1794424080842,
}
);
}
#[test]
fn ignores_payloads_without_the_account() {
assert!(decode_match(FIXTURE, "someone-else").unwrap().is_none());
}
#[test]
fn raw_payload_is_stored_unmodified_and_only_once() {
let db = Connection::open_in_memory().unwrap();
db.execute_batch(SCHEMA).unwrap();
let (m, queue_id) = decode_match(FIXTURE, "fixture-puuid-self")
.unwrap()
.unwrap();
assert!(insert_match(&db, "p", &m, queue_id, FIXTURE).unwrap());
assert!(!insert_match(&db, "p", &m, queue_id, FIXTURE).unwrap());
let raw: String = db
.query_row("SELECT raw FROM matches", [], |row| row.get(0))
.unwrap();
assert_eq!(raw, FIXTURE);
}
#[test]
fn rate_limit_is_retried_a_few_times_then_reported() {
let mut calls = 0;
let result: Result<(), _> = with_retry(|| {
calls += 1;
Err(SourceError::RateLimited {
retry_after: Duration::ZERO,
})
});
assert!(matches!(result, Err(SourceError::RateLimited { .. })));
assert_eq!(calls, RATE_LIMIT_RETRIES + 1);
}