use std::collections::VecDeque; use std::sync::{Mutex, PoisonError}; use std::thread; use std::time::{Duration, Instant}; use serde::Deserialize; use ureq::{Agent, Body}; use crate::error::SourceError; use crate::model::Account; use crate::tracker::MatchHistorySource; /// Personal-key limits: (requests, window). const LIMITS: [(usize, Duration); 2] = [ (20, Duration::from_secs(1)), (100, Duration::from_secs(120)), ]; const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(10); /// Riot web API adapter. Deliberately has no `Debug`: it holds the API key. pub struct RiotApi { key: Mutex, host: String, agent: Agent, /// Send times of recent requests, oldest first. sent: Mutex>, } impl RiotApi { /// `region` is the routing value, e.g. "europe". pub fn new(api_key: String, region: &str) -> RiotApi { RiotApi { key: Mutex::new(api_key), host: format!("https://{region}.api.riotgames.com"), agent: agent(), sent: Mutex::new(VecDeque::new()), } } /// Replaces the key used by all later requests. pub fn set_key(&self, api_key: String) { *self.key.lock().unwrap_or_else(PoisonError::into_inner) = api_key; } fn get(&self, path_and_query: &str) -> Result { self.get_on(&self.host, path_and_query) } fn get_on(&self, host: &str, path_and_query: &str) -> Result { let key = self .key .lock() .unwrap_or_else(PoisonError::into_inner) .clone(); if key.is_empty() { return Err(SourceError::MissingKey); } let wait = reserve_slot( &mut self.sent.lock().unwrap_or_else(PoisonError::into_inner), Instant::now(), ); thread::sleep(wait); let url = format!("{host}{path_and_query}"); get(&self.agent, &url, Some(&key), |body| body.read_to_string()) } } /// The HTTP client shared by the adapters. pub(crate) fn agent() -> Agent { Agent::config_builder() .http_status_as_error(false) .user_agent("arena-tracker") // the default UA is blocked by Cloudflare on some clients .timeout_global(Some(Duration::from_secs(30))) .build() .into() } /// GETs `url` (sending the Riot token when given) and reads a successful body with `read`; /// other statuses become `SourceError`s. pub(crate) fn get( agent: &Agent, url: &str, riot_token: Option<&str>, read: impl FnOnce(&mut Body) -> Result, ) -> Result { let mut request = agent.get(url); if let Some(token) = riot_token { request = request.header("X-Riot-Token", token); } let mut response = request .call() .map_err(|e| SourceError::Network(e.to_string()))?; match response.status().as_u16() { 200..=299 => read(response.body_mut()).map_err(|e| SourceError::Network(e.to_string())), 401 | 403 => Err(SourceError::InvalidKey), 404 => Err(SourceError::NotFound), 429 => Err(SourceError::RateLimited { retry_after: response .headers() .get("retry-after") .and_then(|v| v.to_str().ok()) .and_then(|v| v.trim().parse().ok()) .map_or(DEFAULT_RETRY_AFTER, Duration::from_secs), }), status => Err(SourceError::Other(format!("HTTP {status}"))), } } impl MatchHistorySource for RiotApi { fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result { let path = format!( "/riot/account/v1/accounts/by-riot-id/{}/{}", encode(game_name), encode(tag_line) ); decode_account(&self.get(&path)?) } fn match_ids( &self, puuid: &str, queue_id: u32, start: usize, count: usize, start_time_s: Option, ) -> Result, SourceError> { let mut path = format!( "/lol/match/v5/matches/by-puuid/{}/ids?queue={queue_id}&start={start}&count={count}", encode(puuid) ); if let Some(t) = start_time_s { path.push_str(&format!("&startTime={t}")); } decode_ids(&self.get(&path)?) } fn fetch_match(&self, match_id: &str) -> Result { self.get(&format!("/lol/match/v5/matches/{}", encode(match_id))) } /// Mastery lives on the platform host (e.g. `euw1`), not on the regional one. fn champion_mastery( &self, platform: &str, puuid: &str, ) -> Result, SourceError> { // The platform becomes part of the host: nothing but letters and digits goes through. if platform.is_empty() || !platform.bytes().all(|b| b.is_ascii_alphanumeric()) { return Err(SourceError::Other(format!( "Plateforme invalide : {platform}" ))); } let host = format!( "https://{}.api.riotgames.com", platform.to_ascii_lowercase() ); let path = format!( "/lol/champion-mastery/v4/champion-masteries/by-puuid/{}", encode(puuid) ); decode_mastery(&self.get_on(&host, &path)?) } } fn decode_account(body: &str) -> Result { serde_json::from_str(body).map_err(|e| SourceError::Other(format!("Compte illisible : {e}"))) } fn decode_ids(body: &str) -> Result, SourceError> { serde_json::from_str(body) .map_err(|e| SourceError::Other(format!("Liste de Parties illisible : {e}"))) } fn decode_mastery(body: &str) -> Result, SourceError> { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct Entry { champion_id: u32, champion_points: u64, } let entries: Vec = serde_json::from_str(body) .map_err(|e| SourceError::Other(format!("Maîtrise illisible : {e}")))?; Ok(entries .into_iter() .map(|e| (e.champion_id, e.champion_points)) .collect()) } /// Percent-encodes everything but RFC 3986 unreserved characters. pub(crate) fn encode(segment: &str) -> String { let mut out = String::new(); for byte in segment.bytes() { match byte { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { out.push(byte as char) } _ => out.push_str(&format!("%{byte:02X}")), } } out } /// Books the next request in the sliding windows and returns how long to wait before sending it. fn reserve_slot(sent: &mut VecDeque, now: Instant) -> Duration { let longest = LIMITS[1].1; while sent .front() .is_some_and(|&t| now.saturating_duration_since(t) >= longest) { sent.pop_front(); } // A window of `max` requests is full when `max` requests are booked inside it; the new // one may go once the oldest of them leaves. let wait = LIMITS .iter() .filter(|&&(max, _)| sent.len() >= max) .map(|&(max, window)| (sent[sent.len() - max] + window).saturating_duration_since(now)) .max() .unwrap_or_default(); sent.push_back(now + wait); wait } #[cfg(test)] mod tests { use super::*; #[test] fn without_a_key_no_request_is_sent() { let api = RiotApi::new(String::new(), "europe"); assert_eq!( api.resolve_account("Joueur", "EUW"), Err(SourceError::MissingKey) ); assert_eq!( api.match_ids("p", 1700, 0, 100, None), Err(SourceError::MissingKey) ); assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey)); assert_eq!( api.champion_mastery("EUW1", "p"), Err(SourceError::MissingKey) ); } #[test] fn an_invalid_platform_is_rejected_without_a_request() { // With a key, a request would be attempted (and fail on the network, not as `Other`). let api = RiotApi::new("RGAPI-test".into(), "europe"); for platform in ["", "euw1.evil.example/", "eu w1", "euw1@host", "é"] { assert!( matches!( api.champion_mastery(platform, "p"), Err(SourceError::Other(_)) ), "{platform:?}" ); } assert!(api.sent.lock().unwrap().is_empty()); } #[test] fn the_key_can_be_replaced_without_rebuilding_the_adapter() { let api = RiotApi::new(String::new(), "europe"); api.set_key("RGAPI-new".into()); assert_eq!(*api.key.lock().unwrap(), "RGAPI-new"); api.set_key(String::new()); assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey)); } #[test] fn decodes_the_account_response() { let account = decode_account(include_str!("../tests/fixtures/riot/account.json")).unwrap(); assert_eq!( account, Account { puuid: "fixture-puuid-self".into(), game_name: "Joueur".into(), tag_line: "EUW".into(), } ); } #[test] fn decodes_the_champion_mastery_response() { let points = decode_mastery(include_str!("../tests/fixtures/riot/champion_mastery.json")).unwrap(); assert_eq!(points, [(222, 154_320), (103, 27_500), (51, 0)]); assert_eq!(decode_mastery("[]").unwrap(), []); assert!(decode_mastery("{}").is_err()); } #[test] fn decodes_a_match_id_list() { assert_eq!( decode_ids(r#"["EUW1_1","EUW1_2"]"#).unwrap(), ["EUW1_1", "EUW1_2"] ); assert!(decode_ids("{}").is_err()); } #[test] fn path_segments_are_percent_encoded() { assert_eq!(encode("Joueur"), "Joueur"); assert_eq!(encode("Été #1/é"), "%C3%89t%C3%A9%20%231%2F%C3%A9"); } #[test] fn throttle_spaces_requests_under_both_limits() { let t0 = Instant::now(); let mut sent = VecDeque::new(); for _ in 0..20 { assert_eq!(reserve_slot(&mut sent, t0), Duration::ZERO); } // 21st request waits for the 1 s window. assert_eq!(reserve_slot(&mut sent, t0), Duration::from_secs(1)); // 100 requests fit in 120 s: spread over time so only the long window is full. let mut sent = VecDeque::new(); for i in 0..100u64 { let now = t0 + Duration::from_secs(i); assert_eq!(reserve_slot(&mut sent, now), Duration::ZERO); } let now = t0 + Duration::from_secs(100); assert_eq!(reserve_slot(&mut sent, now), Duration::from_secs(20)); // Once the oldest request left the window, no wait is needed. let later = t0 + Duration::from_secs(121); assert_eq!(reserve_slot(&mut sent, later), Duration::ZERO); } }