Fix the final champ select review findings (#13)
CI / core (pull_request) Successful in 51s
CI / core (push) Successful in 49s

This commit was merged in pull request #51.
This commit is contained in:
nessar authored and nessar committed 2026-11-19 22:17:14 +01:00
1 parent cf15eeeb8f
commit 304d958c72
12 files changed
+612 -375

No files matched your search

+164 -83
View File
@@ -1,10 +1,11 @@
//! The local player's pick and the champions offered during an Arena champ select.
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use serde_json::Value;
use crate::league_client::parse;
use crate::client::Gameflow;
use crate::league_client::{lock, parse};
use crate::{ChampionRow, ChampionState, ClientError};
pub(crate) const PICKABLE_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids";
@@ -19,10 +20,10 @@ pub struct ChampSelect {
/// The five anvil champions; empty when the client reports none. The client calls them
/// crowd favorites.
pub anvil_champions: Vec<u32>,
/// The champions the draft offers, before its bans and the other players' picks. Shared with
/// the client's cache instead of cloned on every session event.
/// The champions the champ select offers, before its bans and the other players' picks.
/// Shared with the client's cache instead of cloned on every session event.
pickable: Arc<HashSet<u32>>,
/// Banned or taken by another player in this session.
/// Banned or taken by another player in this champ select.
excluded: HashSet<u32>,
}
@@ -46,24 +47,21 @@ fn array(value: &Value) -> Result<&[Value], ClientError> {
}
fn ids(body: &str) -> Result<HashSet<u32>, ClientError> {
Ok(array(&parse(body)?)?
.iter()
.filter_map(champion_id)
.collect())
let value = parse(body)?;
let ids =
ids_in(&value).ok_or_else(|| ClientError::Other("Liste de champions illisible".into()))?;
Ok(ids.into_iter().collect())
}
fn ids_from_event(data: &Value) -> Option<HashSet<u32>> {
data.as_array()
.map(|ids| ids.iter().filter_map(champion_id).collect())
}
fn ordered_ids(data: &Value) -> Option<Vec<u32>> {
data.as_array()
/// The champion ids of a list, from a body or from an event's data.
fn ids_in(value: &Value) -> Option<Vec<u32>> {
value
.as_array()
.map(|ids| ids.iter().filter_map(champion_id).collect())
}
impl ChampSelect {
/// A selection with nothing banned or taken, for tests and callers with a ready pool.
/// A champ select with nothing banned or taken, for callers with a ready pool.
pub fn new(current: Option<u32>, pickable: HashSet<u32>, anvil_champions: Vec<u32>) -> Self {
Self {
current,
@@ -73,19 +71,7 @@ impl ChampSelect {
}
}
/// The champions the client offers, minus those disabled for this draft. The pickable list
/// is the client's answer to what the player can pick: it already includes free-rotation and
/// rented champions, so ownership is not consulted.
pub fn pickable_champions(
pickable: &str,
disabled: &str,
) -> Result<Arc<HashSet<u32>>, ClientError> {
let pickable = ids(pickable)?;
let disabled = ids(disabled)?;
Ok(Arc::new(pickable.difference(&disabled).copied().collect()))
}
pub fn from_session(
fn from_session(
session: &Value,
pickable: Arc<HashSet<u32>>,
anvil_champions: Vec<u32>,
@@ -144,21 +130,98 @@ impl ChampSelect {
self.current == Some(id) || (self.pickable.contains(&id) && !self.excluded.contains(&id))
}
/// Whether both selections offer the same champions, whatever the current pick. The shared
/// set makes the common case a pointer comparison.
/// Whether both champ selects offer the same champions, whatever the current pick. The
/// shared set makes the common case a pointer comparison.
pub fn same_pickable(&self, other: &Self) -> bool {
(Arc::ptr_eq(&self.pickable, &other.pickable) || self.pickable == other.pickable)
&& self.excluded == other.excluded
}
/// A champion still to complete in the Challenge and pickable in this draft. The player's
/// own hovered or locked champion stays in the list while not Completed: they can pick it.
/// A champion still to complete in the Challenge and pickable in this champ select. The
/// player's own hovered or locked champion stays in the list while not Completed: they can
/// pick it.
pub fn remaining(&self, row: &ChampionRow) -> bool {
row.state.is_some_and(|s| s != ChampionState::Completed) && self.can_pick(row.champion.id)
}
}
/// The champion lists of a draft: fetched once, then updated from the client's events.
/// The live champ select, read the one way both the real client and the tests read it: the
/// session the client sent as an event, else its answer to a session request, and the champion
/// lists read once per champ select.
#[derive(Default)]
pub struct ChampSelectReader {
lists: Mutex<Option<ChampSelectLists>>,
/// The latest session the client sent as an event, taken by the next read.
session: Mutex<Option<Value>>,
}
impl ChampSelectReader {
/// Forgets the champ select: the next read belongs to a new one.
pub(crate) fn reset(&self) {
*lock(&self.lists) = None;
*lock(&self.session) = None;
}
/// Follows a gameflow read: anything but an Arena champ select ends the cached one, whose
/// lists must not leak into the next.
pub fn reset_unless_arena_champ_select(&self, flow: &Gameflow) {
if !flow.is_arena_champ_select() {
self.reset();
}
}
/// Keeps the session the client sent as an event for the next read, which then needs no
/// session request.
pub fn set_session(&self, session: Value) {
if session.is_object() {
*lock(&self.session) = Some(session);
}
}
/// Reads the live champ select. `session` and `lists` make the requests; they run only when
/// the event session or the champion lists are missing, and never under a lock.
pub fn read(
&self,
session: impl FnOnce() -> Result<String, ClientError>,
lists: impl FnOnce() -> Result<(String, String, Option<String>), ClientError>,
) -> Result<ChampSelect, ClientError> {
let session = match lock(&self.session).take() {
Some(session) => session,
None => parse(&session()?)?,
};
if lock(&self.lists).is_none() {
let (pickable, disabled, anvil) = lists()?;
let lists = ChampSelectLists::from_bodies(&pickable, &disabled, anvil.as_deref())?;
*lock(&self.lists) = Some(lists);
}
let lists = lock(&self.lists);
let lists = lists.as_ref().expect("set just above");
ChampSelect::from_session(&session, lists.pickable(), lists.anvil().to_vec())
}
/// Applies the client's pickable list event.
pub(crate) fn set_pickable(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_pickable(data);
}
}
/// Applies the client's disabled list event.
pub(crate) fn set_disabled(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_disabled(data);
}
}
/// Applies the client's anvil champions event.
pub(crate) fn set_anvil(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_anvil(data);
}
}
}
/// The champion lists of a champ select: read once, then updated from the client's events.
#[derive(Debug, Default)]
pub(crate) struct ChampSelectLists {
/// The client's pickable list, before the disabled champions are removed.
@@ -170,7 +233,7 @@ pub(crate) struct ChampSelectLists {
}
impl ChampSelectLists {
pub(crate) fn fetch(
pub(crate) fn from_bodies(
pickable: &str,
disabled: &str,
anvil: Option<&str>,
@@ -182,7 +245,7 @@ impl ChampSelectLists {
};
if let Some(body) = anvil
&& let Ok(value) = parse(body)
&& let Some(ids) = ordered_ids(&value)
&& let Some(ids) = ids_in(&value)
{
lists.anvil = ids;
}
@@ -202,31 +265,23 @@ impl ChampSelectLists {
&self.anvil
}
/// Applies one client event. Returns false when the topic concerns something else; the lists
/// it does not concern are left untouched.
pub(crate) fn apply_event(&mut self, topic: &str, data: &Value) -> bool {
match topic {
PICKABLE_EVENT => {
if let Some(ids) = ids_from_event(data) {
self.offered = ids;
self.rebuild();
}
true
}
DISABLED_EVENT => {
if let Some(ids) = ids_from_event(data) {
self.disabled = ids;
self.rebuild();
}
true
}
ANVIL_EVENT => {
if let Some(ids) = ordered_ids(data) {
self.anvil = ids;
}
true
}
_ => false,
fn set_pickable(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.offered = ids.into_iter().collect();
self.rebuild();
}
}
fn set_disabled(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.disabled = ids.into_iter().collect();
self.rebuild();
}
}
fn set_anvil(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.anvil = ids;
}
}
}
@@ -236,56 +291,82 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn pickable_excludes_disabled_champions() {
assert_eq!(
&*ChampSelect::pickable_champions("[1,2,3]", "[3]").unwrap(),
&HashSet::from([1, 2])
);
}
#[test]
fn the_lists_change_only_for_the_events_that_concern_them() {
let mut lists = ChampSelectLists::fetch("[1,2,3]", "[3]", Some("[9,8]")).unwrap();
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(), [9, 8]);
// A gameflow event used to clear the whole cache, costing three requests again.
assert!(!lists.apply_event(
"OnJsonApiEvent_lol-gameflow_v1_session",
&json!({"phase": "ChampSelect"})
));
// 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(), [9, 8]);
assert!(lists.apply_event(PICKABLE_EVENT, &json!([1, 4])));
lists.set_pickable(&json!([1, 4]));
assert_eq!(&*lists.pickable(), &HashSet::from([1, 4]));
assert_eq!(lists.anvil(), [9, 8]);
assert!(lists.apply_event(DISABLED_EVENT, &json!([1])));
lists.set_disabled(&json!([1]));
assert_eq!(&*lists.pickable(), &HashSet::from([4]));
assert!(lists.apply_event(ANVIL_EVENT, &json!([5, 6])));
lists.set_anvil(&json!([5, 6]));
assert_eq!(lists.anvil(), [5, 6]);
}
#[test]
fn the_anvil_champions_are_read_once_when_the_draft_starts() {
fn the_anvil_champions_are_read_once_when_the_champ_select_starts() {
assert!(
ChampSelectLists::fetch("[]", "[]", None)
ChampSelectLists::from_bodies("[]", "[]", None)
.unwrap()
.anvil()
.is_empty()
);
assert_eq!(
ChampSelectLists::fetch("[]", "[]", Some("[1,2]"))
ChampSelectLists::from_bodies("[]", "[]", Some("[1,2]"))
.unwrap()
.anvil(),
[1, 2]
);
// A malformed anvil answer only loses the anvil list, not the pickable one.
let lists = ChampSelectLists::fetch("[7]", "[]", Some("not json")).unwrap();
let lists = ChampSelectLists::from_bodies("[7]", "[]", Some("not json")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([7]));
assert!(lists.anvil().is_empty());
}
#[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));
}
}
+65 -9
View File
@@ -8,10 +8,8 @@ pub trait GameClientSource: Send + Sync {
/// Value of the Champs Completed counter of the progression track with this exact name;
/// `None` when the client has no such track.
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, ClientError>;
/// Reads the live Arena selection after gameflow enters champ select.
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError> {
Err(ClientError::Absent)
}
/// Reads the live Arena champ select after gameflow enters champ select.
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError>;
/// Blocks until the client reports an event or `timeout` elapses, and says which kind it was.
fn wait_for_event(&self, timeout: Duration) -> ClientEvent;
}
@@ -20,14 +18,14 @@ pub trait GameClientSource: Send + Sync {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ClientEvent {
/// The champ select session or one of its champion lists changed.
Selection,
ChampSelect,
/// Anything else.
#[default]
Other,
}
/// One read of the client, shared by the follower round and the live selection: a wake makes one
/// gameflow request, not one per reader.
/// One read of the client, shared by the follower round and the live champ select: a wake makes
/// one gameflow request, not one per reader.
#[derive(Clone, Debug)]
pub struct ClientSnapshot {
pub signed_in: Result<(String, String), ClientError>,
@@ -36,9 +34,16 @@ pub struct ClientSnapshot {
impl ClientSnapshot {
pub fn read(source: &dyn GameClientSource) -> Self {
let signed_in = source.signed_in();
// Nobody signed in means the login screen: no gameflow request. Carrying the error keeps
// `Absent` meaning "no champ select" and a transient failure keeping the one shown.
let gameflow = match &signed_in {
Ok(_) => source.gameflow(),
Err(error) => Err(error.clone()),
};
Self {
signed_in: source.signed_in(),
gameflow: source.gameflow(),
signed_in,
gameflow,
}
}
@@ -96,8 +101,59 @@ impl Gameflow {
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
/// A client whose sign-in and gameflow answers are fixed; counts the gameflow requests.
struct Source {
signed_in: Result<(String, String), ClientError>,
gameflow_calls: AtomicUsize,
}
impl GameClientSource for Source {
fn signed_in(&self) -> Result<(String, String), ClientError> {
self.signed_in.clone()
}
fn gameflow(&self) -> Result<Gameflow, ClientError> {
self.gameflow_calls.fetch_add(1, Ordering::SeqCst);
Ok(Gameflow::default())
}
fn official_progress(&self, _: &str) -> Result<Option<u32>, ClientError> {
Ok(None)
}
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError> {
Err(ClientError::Absent)
}
fn wait_for_event(&self, _: Duration) -> ClientEvent {
ClientEvent::Other
}
}
#[test]
fn a_login_screen_makes_no_gameflow_request() {
let source = Source {
signed_in: Err(ClientError::Absent),
gameflow_calls: AtomicUsize::new(0),
};
let snapshot = ClientSnapshot::read(&source);
assert_eq!(snapshot.gameflow, Err(ClientError::Absent));
assert_eq!(source.gameflow_calls.load(Ordering::SeqCst), 0);
// A transient failure is carried, so a shown champ select stays.
let source = Source {
signed_in: Err(ClientError::Other("panne".into())),
gameflow_calls: AtomicUsize::new(0),
};
let snapshot = ClientSnapshot::read(&source);
assert_eq!(snapshot.gameflow, Err(ClientError::Other("panne".into())));
assert_eq!(source.gameflow_calls.load(Ordering::SeqCst), 0);
}
#[test]
fn client_phases_map_to_game_phases() {
for (name, phase) in [
+16 -9
View File
@@ -139,7 +139,8 @@ pub fn same_riot_id(a: &str, b: &str) -> bool {
a.to_lowercase() == b.to_lowercase()
}
fn account_riot_id(account: &Account) -> String {
/// `gameName#tagLine` of an Account, the one place an Account's Riot ID is built.
pub fn account_riot_id(account: &Account) -> String {
riot_id(&account.game_name, &account.tag_line)
}
@@ -206,7 +207,8 @@ impl Tracker {
)
}
/// One read of the client for this wake; the follower round and the live selection share it.
/// One read of the client for this wake; the follower round and the live champ select share
/// it.
pub fn client_snapshot(&self) -> ClientSnapshot {
match &self.client {
Some(client) => ClientSnapshot::read(client.as_ref()),
@@ -332,14 +334,9 @@ impl Tracker {
self.status() != before || added > 0
}
/// The signed-in Riot ID and its live pick, independent of slow Match history imports.
/// The signed-in Riot ID and its live pick, from a client read already made for this wake.
/// `Err` means the read failed: keep what is shown. `Ok(None)` means no Arena champ select
/// is running.
pub fn champ_select(&self) -> Result<Option<(String, crate::ChampSelect)>, crate::ClientError> {
self.champ_select_with(&self.client_snapshot())
}
/// The live pick from a client read already made for this wake.
pub fn champ_select_with(
&self,
snapshot: &ClientSnapshot,
@@ -365,7 +362,7 @@ impl Tracker {
/// Blocks until a client event or a timeout, shorter while a Match is pending: the rounds
/// events cause try it only once its time has come. The event says whether only the live
/// selection needs another read.
/// champ select needs another read.
pub fn wait_for_client(&self) -> ClientEvent {
let timeout = if self.follow().pending.is_empty() {
WAIT_OTHERWISE
@@ -532,6 +529,16 @@ mod tests {
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> = [
+120 -100
View File
@@ -17,7 +17,7 @@ use tungstenite::{Connector, Message, WebSocket, client_tls_with_config};
use ureq::Agent;
use ureq::tls::{Certificate, RootCerts, TlsConfig};
use crate::champ_select::{ANVIL_EVENT, ChampSelectLists, DISABLED_EVENT, PICKABLE_EVENT};
use crate::champ_select::{ANVIL_EVENT, ChampSelectReader, DISABLED_EVENT, PICKABLE_EVENT};
use crate::client::{ClientError, ClientEvent, GameClientSource, GamePhase, Gameflow};
use crate::riot::encode;
@@ -52,14 +52,7 @@ pub struct LeagueClient {
/// configuration is downloaded once per track.
tracks: Mutex<HashMap<String, (String, Option<String>)>>,
events: Mutex<Option<Events>>,
champion_lists: Mutex<ChampSelectCache>,
}
/// The champion lists of the current draft and the latest session the client sent as an event.
#[derive(Default)]
struct ChampSelectCache {
lists: Option<ChampSelectLists>,
session: Option<Value>,
champ_select_reader: ChampSelectReader,
}
struct Events(WebSocket<MaybeTlsStream<TcpStream>>);
@@ -100,7 +93,7 @@ impl LeagueClient {
agent,
tracks: Mutex::default(),
events: Mutex::default(),
champion_lists: Mutex::default(),
champ_select_reader: ChampSelectReader::default(),
}
}
@@ -175,35 +168,23 @@ impl GameClientSource for LeagueClient {
fn gameflow(&self) -> Result<Gameflow, ClientError> {
let (status, body) = self.get("/lol-gameflow/v1/session")?;
let flow = decode_gameflow(status, &body)?;
if !flow.is_arena_champ_select() {
*lock(&self.champion_lists) = ChampSelectCache::default();
}
self.champ_select_reader
.reset_unless_arena_champ_select(&flow);
Ok(flow)
}
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError> {
let session = {
let mut cache = lock(&self.champion_lists);
cache.session.take()
};
let session = match session {
Some(session) => session,
None => parse(&self.get_ok(SESSION)?)?,
};
let mut cache = lock(&self.champion_lists);
if cache.lists.is_none() {
let pickable = self.get_ok(PICKABLE)?;
let disabled = self.get_ok(DISABLED)?;
// The anvil list is a bonus: a failed read leaves it empty until an event delivers it.
let anvil = self.get_ok(ANVIL_CHAMPIONS).ok();
cache.lists = Some(ChampSelectLists::fetch(
&pickable,
&disabled,
anvil.as_deref(),
)?);
}
let lists = cache.lists.as_ref().expect("set just above");
crate::ChampSelect::from_session(&session, lists.pickable(), lists.anvil().to_vec())
self.champ_select_reader.read(
|| self.get_ok(SESSION),
|| {
let pickable = self.get_ok(PICKABLE)?;
let disabled = self.get_ok(DISABLED)?;
// The anvil list is a bonus: a failed read leaves it empty until an event
// delivers it.
let anvil = self.get_ok(ANVIL_CHAMPIONS).ok();
Ok((pickable, disabled, anvil))
},
)
}
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, ClientError> {
@@ -235,7 +216,7 @@ impl GameClientSource for LeagueClient {
let mut events = lock(&self.events);
if events.is_none() {
// A reconnection may follow a client restart: the lists belong to the previous one.
*lock(&self.champion_lists) = ChampSelectCache::default();
self.champ_select_reader.reset();
*events = self.connect();
// Re-read the snapshot after subscribing.
if events.is_some() {
@@ -261,7 +242,12 @@ impl GameClientSource for LeagueClient {
let Some((topic, data)) = decode_event(&text) else {
continue;
};
return self.apply_event(&topic, data);
match self.apply_event(&topic, data) {
// A deleted session carries nothing to show: keep waiting, the gameflow
// event that follows ends the champ select view.
None => continue,
Some(event) => return event,
}
}
Ok(Message::Close(_)) => *events = None,
Ok(_) => continue,
@@ -275,29 +261,35 @@ impl GameClientSource for LeagueClient {
}
impl LeagueClient {
/// Applies one event to the cache, touching only the list it concerns.
fn apply_event(&self, topic: &str, data: Value) -> ClientEvent {
/// Applies one event, touching only the list it concerns. `None` when the event carries
/// nothing to show: a deleted champ select session, which must cost no request.
fn apply_event(&self, topic: &str, data: Value) -> Option<ClientEvent> {
match topic {
SESSION_EVENT => {
let mut cache = lock(&self.champion_lists);
if data.is_object() {
cache.session = Some(data);
if data.is_null() {
return None;
}
ClientEvent::Selection
self.champ_select_reader.set_session(data);
Some(ClientEvent::ChampSelect)
}
PICKABLE_EVENT | DISABLED_EVENT | ANVIL_EVENT => {
let mut cache = lock(&self.champion_lists);
if let Some(lists) = cache.lists.as_mut() {
lists.apply_event(topic, &data);
}
ClientEvent::Selection
PICKABLE_EVENT => {
self.champ_select_reader.set_pickable(&data);
Some(ClientEvent::ChampSelect)
}
_ => ClientEvent::Other,
DISABLED_EVENT => {
self.champ_select_reader.set_disabled(&data);
Some(ClientEvent::ChampSelect)
}
ANVIL_EVENT => {
self.champ_select_reader.set_anvil(&data);
Some(ClientEvent::ChampSelect)
}
_ => Some(ClientEvent::Other),
}
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
@@ -319,7 +311,8 @@ fn tls_config() -> Result<ClientConfig, rustls::Error> {
}
/// A rejected certificate, a timeout or a dropped connection is worth telling apart from a
/// client that is simply not there (nothing listens): the first ones say nothing about the draft.
/// client that is simply not there (nothing listens): the first ones say nothing about the champ
/// select.
fn transport_error(e: ureq::Error) -> ClientError {
match e {
ureq::Error::Tls(_) | ureq::Error::Rustls(_) => {
@@ -661,47 +654,65 @@ mod tests {
format!(r#"[8,"{topic}",{{"data":{data},"eventType":"{event_type}","uri":"/x"}}]"#)
}
/// A session body the reader can assemble, with this local pick.
fn session(current: u32) -> String {
format!(
r#"{{"localPlayerCellId":16,"myTeam":[{{"cellId":16,"championId":{current},
"championPickIntent":0}},{{"cellId":17,"championId":0,
"championPickIntent":0}}],"actions":[],
"bans":{{"myTeamBans":[],"theirTeamBans":[]}}}}"#
)
}
#[test]
fn a_raw_event_frame_updates_the_cached_session_and_lists() {
use serde_json::json;
use std::collections::HashSet;
let client = LeagueClient::in_dir(PathBuf::new());
*lock(&client.champion_lists) = ChampSelectCache {
lists: Some(ChampSelectLists::fetch("[1,2]", "[]", Some("[]")).unwrap()),
session: None,
};
client
.champ_select_reader
.read(
|| Ok(session(0)),
|| Ok(("[1,2]".into(), "[]".into(), Some("[]".into()))),
)
.unwrap();
let apply = |topic, event_type, data: &str| {
let (topic, data) = decode_event(&frame(topic, event_type, data)).unwrap();
client.apply_event(&topic, data)
};
assert_eq!(
apply(SESSION_EVENT, "Update", r#"{"localPlayerCellId":16}"#),
ClientEvent::Selection
apply(SESSION_EVENT, "Update", &session(16)),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(ANVIL_EVENT, "Update", "[9,8]"),
ClientEvent::Selection
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(PICKABLE_EVENT, "Update", "[2]"),
ClientEvent::Selection
Some(ClientEvent::ChampSelect)
);
// A Delete carries no data: it neither wipes nor corrupts what is cached.
// A deleted session carries nothing: it costs no request. Other Deletes change nothing
// either, but still wake the follower.
assert_eq!(apply(SESSION_EVENT, "Delete", "null"), None);
assert_eq!(
apply(SESSION_EVENT, "Delete", "null"),
ClientEvent::Selection
apply(ANVIL_EVENT, "Delete", "null"),
Some(ClientEvent::ChampSelect)
);
assert_eq!(apply(ANVIL_EVENT, "Delete", "null"), ClientEvent::Selection);
assert_eq!(
apply(PICKABLE_EVENT, "Delete", "null"),
ClientEvent::Selection
Some(ClientEvent::ChampSelect)
);
let cache = lock(&client.champion_lists);
assert_eq!(cache.session, Some(json!({"localPlayerCellId": 16})));
let lists = cache.lists.as_ref().unwrap();
assert_eq!(lists.anvil(), [9, 8]);
assert_eq!(&*lists.pickable(), &HashSet::from([2]));
// The event session replaces the request and the updated lists are used.
let pick = client
.champ_select_reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.unwrap();
assert_eq!(pick.current, Some(16));
assert_eq!(pick.anvil_champions, [9, 8]);
assert!(!pick.can_pick(1));
assert!(pick.can_pick(2));
}
#[test]
@@ -723,44 +734,53 @@ mod tests {
#[test]
fn events_update_only_the_list_they_concern() {
use serde_json::json;
use std::collections::HashSet;
let client = LeagueClient::in_dir(PathBuf::new());
*lock(&client.champion_lists) = ChampSelectCache {
lists: Some(ChampSelectLists::fetch("[1,2]", "[2]", Some("[9]")).unwrap()),
session: None,
};
client
.champ_select_reader
.read(
|| Ok(session(0)),
|| Ok(("[1,2]".into(), "[2]".into(), Some("[9]".into()))),
)
.unwrap();
// A gameflow event leaves the champion lists alone; the old code cleared them all.
assert_eq!(
client.apply_event("OnJsonApiEvent_lol-gameflow_v1_session", json!({})),
ClientEvent::Other
Some(ClientEvent::Other)
);
{
let cache = lock(&client.champion_lists);
let lists = cache.lists.as_ref().unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([1]));
assert_eq!(lists.anvil(), [9]);
}
let read = || {
client
.champ_select_reader
.read(|| Ok(session(0)), || panic!("the lists must stay cached"))
.unwrap()
};
let pick = read();
assert_eq!(pick.anvil_champions, [9]);
assert!(pick.can_pick(1));
assert!(!pick.can_pick(2));
assert_eq!(
client.apply_event(PICKABLE_EVENT, json!([1, 3])),
ClientEvent::Selection
Some(ClientEvent::ChampSelect)
);
let pick = read();
assert!(pick.can_pick(1));
assert!(pick.can_pick(3));
assert!(!pick.can_pick(2));
// A session event is kept for the next read instead of a request.
assert_eq!(
&*lock(&client.champion_lists)
.lists
.as_ref()
.unwrap()
.pickable(),
&HashSet::from([1, 3])
client.apply_event(SESSION_EVENT, serde_json::from_str(&session(16)).unwrap()),
Some(ClientEvent::ChampSelect)
);
// A session event is kept for the next read instead of a GET.
assert_eq!(
client.apply_event(SESSION_EVENT, json!({"localPlayerCellId": 16})),
ClientEvent::Selection
);
assert_eq!(
lock(&client.champion_lists).session,
Some(json!({"localPlayerCellId": 16}))
assert!(
client
.champ_select_reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.is_ok()
);
}
+3 -2
View File
@@ -13,7 +13,7 @@ mod seasons;
mod statistics;
mod tracker;
pub use champ_select::ChampSelect;
pub use champ_select::{ChampSelect, ChampSelectReader};
pub use champion_search::ChampionSearch;
pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon};
pub use client::{ClientError, ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow};
@@ -21,7 +21,8 @@ pub use config::{Config, Preferences, ThemePreference, data_dir};
pub use date::Date;
pub use error::{Error, SourceError};
pub use follow::{
MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem, riot_id, same_riot_id,
MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem, account_riot_id, riot_id,
same_riot_id,
};
pub use league_client::{LeagueClient, decode_gameflow};
pub use model::{Account, Format, Match, SyncProgress, SyncReport};