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>, fail_after: Option, rate_limit_once: AtomicBool, /// 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. 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, } impl FakeHistory { pub fn new(account: Account, payloads: Vec) -> FakeHistory { FakeHistory { accounts: Vec::new(), listings: Mutex::default(), failure: Mutex::default(), fail_after: None, rate_limit_once: AtomicBool::new(false), as_given: false, gate: None, fetches: Arc::default(), listed: Arc::default(), calls: Arc::default(), mastery: Mutex::default(), mastery_failure: Mutex::default(), mastery_calls: Arc::default(), } .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 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 fetch answers "rate limited" once. pub fn rate_limited_once(mut self) -> FakeHistory { self.rate_limit_once = AtomicBool::new(true); 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() } fn enter(&self) -> Result<(), SourceError> { 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()?; // 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()?; 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()?; if let Some((entered, release)) = &self.gate { entered.send(()).unwrap(); release.lock().unwrap().recv().unwrap(); } if self.rate_limit_once.swap(false, Ordering::SeqCst) { return Err(SourceError::RateLimited { retry_after: Duration::ZERO, }); } 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 champion_mastery( &self, _platform: &str, puuid: &str, ) -> Result, SourceError> { 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) } }