use super::*; fn queue_and_start(raw: &str) -> (u32, i64) { let v: Value = serde_json::from_str(raw).unwrap(); ( v["info"]["queueId"].as_u64().unwrap() as u32, v["info"]["gameStartTimestamp"].as_i64().unwrap(), ) } fn match_id(raw: &str) -> String { let v: Value = serde_json::from_str(raw).unwrap(); v["metadata"]["matchId"].as_str().unwrap().to_string() } struct Listing { owner: String, /// The queue the id is listed under. queue_id: u32, match_id: String, started_ms: i64, /// `None`: Riot lists the id but answers "not found" when asked for it. raw: Option, /// Unlisted Matches can only be fetched by their id. listed: bool, } impl Listing { fn of(owner: &str, raw: String) -> Listing { let (queue_id, started_ms) = queue_and_start(&raw); Listing { owner: owner.into(), queue_id, match_id: match_id(&raw), started_ms, raw: Some(raw), listed: true, } } } /// In-memory Match history that behaves like Riot's (newest first, paged, filtered by queue). pub struct FakeHistory { accounts: Vec, listings: Mutex>, /// Every call fails with this until it is cleared. failure: Mutex>, /// Match requests fail with this (after the general failure) until it is cleared. match_failure: Mutex>, /// Match id listings fail with this (after the general failure) until it is cleared. listing_failure: Mutex>, fail_after: Option, /// The next Match and timeline requests answer "rate limited", this many times. rate_limits: AtomicUsize, /// The next Match id listings answer "rate limited", this many times. listing_rate_limits: AtomicUsize, /// The next Riot ID resolutions answer "rate limited", this many times. resolve_rate_limits: AtomicUsize, /// What a "rate limited" answer asks to wait; none by default so tests do not sleep. retry_after: Duration, /// Lists in the order the Matches were added instead of newest first. as_given: bool, /// Called at the start of every fetch: announces it, then waits to be released. resolve_gate: Option<(Sender<()>, Mutex>)>, gate: Option<(Sender<()>, Mutex>)>, fetches: Arc, listed: Arc, calls: Arc, /// Mastery Points by puuid, as Riot lists them (champions with points only). mastery: Mutex>>, /// Mastery requests fail with this until it is cleared. mastery_failure: Mutex>, mastery_calls: Arc, /// Timelines by Match id; a Match without one answers "not found". timelines: Mutex>, /// Timeline requests fail with this (after the general failure) until it is cleared. timeline_failure: Mutex>, timeline_calls: Arc, /// Called by every timeline request once counted: announces it, then waits to be released /// (a closed `release` lets every request through). timeline_gate: Option<(Sender<()>, Mutex>)>, /// The platform of each Account's active region; "euw1" for those not set. platforms: Mutex>, /// Told of each request, e.g. "ids ", "match ", "mastery ". requests: Option>, } impl FakeHistory { pub fn new(account: Account, payloads: Vec) -> FakeHistory { FakeHistory { accounts: Vec::new(), listings: Mutex::default(), failure: Mutex::default(), match_failure: Mutex::default(), listing_failure: Mutex::default(), fail_after: None, rate_limits: AtomicUsize::new(0), listing_rate_limits: AtomicUsize::new(0), resolve_rate_limits: AtomicUsize::new(0), retry_after: Duration::ZERO, as_given: false, resolve_gate: None, gate: None, fetches: Arc::default(), listed: Arc::default(), calls: Arc::default(), mastery: Mutex::default(), mastery_failure: Mutex::default(), mastery_calls: Arc::default(), timelines: Mutex::default(), timeline_failure: Mutex::default(), timeline_calls: Arc::default(), timeline_gate: None, platforms: Mutex::default(), requests: None, } .with_account(account, payloads) } /// Another Account Riot can resolve; its payloads must have been built for its puuid. pub fn with_account(mut self, account: Account, payloads: Vec) -> FakeHistory { for raw in payloads { self.add_for(&account.puuid, raw); } self.accounts.push(account); self } /// Lists a payload under a queue other than its own: a sync only asks for Arena queues. pub fn listed_under(self, queue_id: u32, payload: String) -> FakeHistory { let owner = self.accounts[0].puuid.clone(); self.listings.lock().unwrap().push(Listing { queue_id, ..Listing::of(&owner, payload) }); self } /// A Match that appears for the first Account (e.g. one that has just been played). pub fn add(&self, payload: String) { self.add_for(&self.accounts[0].puuid, payload); } pub fn add_for(&self, puuid: &str, raw: String) { self.listings.lock().unwrap().push(Listing::of(puuid, raw)); } /// A Match Riot has but does not list, like one of a queue the app does not know. pub fn add_unlisted(&self, payload: String) { let owner = self.accounts[0].puuid.clone(); self.listings.lock().unwrap().push(Listing { listed: false, ..Listing::of(&owner, payload) }); } /// An id Riot lists (Arena 3x6) but cannot deliver. pub fn add_missing(&self, match_id: &str, started_ms: i64) { self.add_broken(match_id, started_ms, None); } /// An id Riot lists (Arena 3x6) whose payload is not a readable Match. pub fn add_unreadable(&self, match_id: &str, started_ms: i64, text: &str) { self.add_broken(match_id, started_ms, Some(text.into())); } fn add_broken(&self, match_id: &str, started_ms: i64, raw: Option) { let owner = self.accounts[0].puuid.clone(); self.listings.lock().unwrap().push(Listing { owner, queue_id: 1750, match_id: match_id.into(), started_ms, raw, listed: true, }); } /// Lists Matches in the order they were added, however old they are. pub fn delivered_as_given(mut self) -> FakeHistory { self.as_given = true; self } /// Every call fails with this error until `None` is set. pub fn fail_with(&self, error: Option) { *self.failure.lock().unwrap() = error; } /// Every Match request fails with this error until `None` is set (timelines are not /// affected). pub fn fail_match_with(&self, error: Option) { *self.match_failure.lock().unwrap() = error; } /// Every Match id listing fails with this error until `None` is set (the other requests are /// not affected). pub fn fail_listing_with(&self, error: Option) { *self.listing_failure.lock().unwrap() = error; } /// Every fetch after the first `n` fails with a network error. pub fn failing_after(mut self, n: usize) -> FakeHistory { self.fail_after = Some(n); self } /// The first `n` Match or timeline requests answer "rate limited". pub fn rate_limited(self, n: usize) -> FakeHistory { self.rate_limit_next(n); self } /// The next `n` Match or timeline requests answer "rate limited", with no delay. pub fn rate_limit_next(&self, n: usize) { self.rate_limits.store(n, Ordering::SeqCst); } /// The next `n` Match id listings answer "rate limited". pub fn rate_limit_listing_next(&self, n: usize) { self.listing_rate_limits.store(n, Ordering::SeqCst); } /// The next `n` Riot ID resolutions answer "rate limited". pub fn rate_limit_resolution_next(&self, n: usize) { self.resolve_rate_limits.store(n, Ordering::SeqCst); } /// A "rate limited" answer asks to wait this long. pub fn retry_after(mut self, wait: Duration) -> FakeHistory { self.retry_after = wait; self } fn rate_limit(&self) -> Result<(), SourceError> { self.limit_by(&self.rate_limits) } fn limit_by(&self, limits: &AtomicUsize) -> Result<(), SourceError> { let limited = limits .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) .is_ok(); match limited { true => Err(SourceError::RateLimited { retry_after: self.retry_after, }), false => Ok(()), } } pub fn gated_resolution(mut self, entered: Sender<()>, release: Receiver<()>) -> Self { self.resolve_gate = Some((entered, Mutex::new(release))); self } /// Each fetch sends on `entered`, then blocks until `release` delivers. pub fn gated(mut self, entered: Sender<()>, release: Receiver<()>) -> FakeHistory { self.gate = Some((entered, Mutex::new(release))); self } /// Payloads delivered by `fetch_match`, still readable after the fake is boxed. pub fn fetch_counter(&self) -> Arc { self.fetches.clone() } /// Match ids returned by `match_ids`. pub fn listed_counter(&self) -> Arc { self.listed.clone() } /// Calls of any kind made to the source. pub fn call_counter(&self) -> Arc { self.calls.clone() } /// The Mastery Points Riot lists for this Account (without any, its mastery request /// answers "not found"). pub fn with_mastery(self, puuid: &str, points: &[(u32, u64)]) -> FakeHistory { self.set_mastery(puuid, points); self } /// Replaces the Mastery Points Riot lists for this Account. pub fn set_mastery(&self, puuid: &str, points: &[(u32, u64)]) { self.mastery .lock() .unwrap() .insert(puuid.into(), points.to_vec()); } /// Every mastery request fails with this error until `None` is set (a sync is not affected). pub fn fail_mastery_with(&self, error: Option) { *self.mastery_failure.lock().unwrap() = error; } /// Mastery requests made, failed ones included. They are not counted by `call_counter`. pub fn mastery_counter(&self) -> Arc { self.mastery_calls.clone() } /// Riot has this timeline for the Match. pub fn with_timeline(self, match_id: &str, raw: &str) -> FakeHistory { self.set_timeline(match_id, raw); self } pub fn set_timeline(&self, match_id: &str, raw: &str) { (self.timelines.lock().unwrap()).insert(match_id.into(), raw.into()); } /// Each timeline request sends on `entered`, then blocks until `release` delivers or closes. pub fn timeline_gated(mut self, entered: Sender<()>, release: Receiver<()>) -> FakeHistory { self.timeline_gate = Some((entered, Mutex::new(release))); self } /// Every timeline request fails with this error until `None` is set (Matches are not /// affected). pub fn fail_timeline_with(&self, error: Option) { *self.timeline_failure.lock().unwrap() = error; } /// Timeline requests made, failed ones included (they also count as calls). pub fn timeline_counter(&self) -> Arc { self.timeline_calls.clone() } /// The Account plays on this platform (the app reads "EUW1" only). pub fn set_platform(&self, puuid: &str, platform: &str) { (self.platforms.lock().unwrap()).insert(puuid.into(), platform.into()); } /// Each request, failed ones included, is told to `requests` as it is made. pub fn logging_requests(mut self, requests: Sender) -> FakeHistory { self.requests = Some(requests); self } fn log(&self, request: String) { if let Some(requests) = &self.requests { let _ = requests.send(request); } } fn enter(&self, request: String) -> Result<(), SourceError> { self.log(request); self.calls.fetch_add(1, Ordering::SeqCst); match &*self.failure.lock().unwrap() { Some(error) => Err(error.clone()), None => Ok(()), } } } impl MatchHistorySource for FakeHistory { fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result { self.enter(format!("account {game_name}#{tag_line}"))?; self.limit_by(&self.resolve_rate_limits)?; if let Some((entered, release)) = &self.resolve_gate { entered.send(()).unwrap(); release.lock().unwrap().recv().unwrap(); } // Riot IDs are case-insensitive for Riot, too. self.accounts .iter() .find(|a| { a.game_name.eq_ignore_ascii_case(game_name) && a.tag_line.eq_ignore_ascii_case(tag_line) }) .cloned() .ok_or(SourceError::NotFound) } fn match_ids( &self, puuid: &str, queue_id: u32, start: usize, count: usize, start_time_s: Option, ) -> Result, SourceError> { self.enter(format!("ids {puuid}"))?; self.limit_by(&self.listing_rate_limits)?; if let Some(error) = &*self.listing_failure.lock().unwrap() { return Err(error.clone()); } let mut found: Vec<_> = self .listings .lock() .unwrap() .iter() .filter(|l| l.listed && l.owner == puuid && l.queue_id == queue_id) .filter(|l| start_time_s.is_none_or(|t| l.started_ms / 1000 >= t)) .map(|l| (l.started_ms, l.match_id.clone())) .collect(); if !self.as_given { found.sort_by_key(|(started_ms, _)| std::cmp::Reverse(*started_ms)); } let page: Vec = found .into_iter() .skip(start) .take(count) .map(|(_, id)| id) .collect(); self.listed.fetch_add(page.len(), Ordering::SeqCst); Ok(page) } fn fetch_match(&self, id: &str) -> Result { self.enter(format!("match {id}"))?; if let Some((entered, release)) = &self.gate { entered.send(()).unwrap(); release.lock().unwrap().recv().unwrap(); } self.rate_limit()?; if let Some(error) = &*self.match_failure.lock().unwrap() { return Err(error.clone()); } if self .fail_after .is_some_and(|n| self.fetches.load(Ordering::SeqCst) >= n) { return Err(SourceError::Network("connexion perdue".into())); } let raw = self .listings .lock() .unwrap() .iter() .find(|l| l.match_id == id) .and_then(|l| l.raw.clone()) .ok_or(SourceError::NotFound)?; self.fetches.fetch_add(1, Ordering::SeqCst); Ok(raw) } fn fetch_timeline(&self, id: &str) -> Result { self.enter(format!("timeline {id}"))?; self.timeline_calls.fetch_add(1, Ordering::SeqCst); self.rate_limit()?; if let Some((entered, release)) = &self.timeline_gate { entered.send(()).unwrap(); let _ = release.lock().unwrap().recv(); } if let Some(error) = &*self.timeline_failure.lock().unwrap() { return Err(error.clone()); } (self.timelines.lock().unwrap()) .get(id) .cloned() .ok_or(SourceError::NotFound) } fn champion_mastery( &self, platform: &str, puuid: &str, ) -> Result, SourceError> { self.log(format!("mastery {platform} {puuid}")); self.mastery_calls.fetch_add(1, Ordering::SeqCst); if let Some(error) = &*self.mastery_failure.lock().unwrap() { return Err(error.clone()); } self.mastery .lock() .unwrap() .get(puuid) .cloned() .ok_or(SourceError::NotFound) } fn account_platform(&self, puuid: &str) -> Result { self.enter(format!("platform {puuid}"))?; if !self.accounts.iter().any(|a| a.puuid == puuid) { return Err(SourceError::NotFound); } let platforms = self.platforms.lock().unwrap(); Ok(platforms .get(puuid) .cloned() .unwrap_or_else(|| "euw1".into())) } fn serves_platform(&self, platform: &str) -> bool { platform.eq_ignore_ascii_case("EUW1") } }