Add core: Match import, statistics and game client following
Core half of tickets #4 to #12, behind one public interface tested with fake sources and a real SQLite database: - import of Arena Match history from the Riot API, idempotent and resumable, with a sync mark written only when a sync completes - Season table, champion catalog, Challenge summary, champion rows, chart series, Season and Format scopes - game client port and adapter: signed-in Account, end of an Arena game fetched by its id, Official Progress cross-check - update problems reported for banners while stored data stays readable The app crate is adapted in the next commit. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
1c5cbea9b9
commit
c44cf52a6a
21 files changed
+6472
-13
No files matched your search
@@ -0,0 +1,258 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
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<String>,
|
||||
host: String,
|
||||
agent: Agent,
|
||||
/// Send times of recent requests, oldest first.
|
||||
sent: Mutex<VecDeque<Instant>>,
|
||||
}
|
||||
|
||||
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<String, SourceError> {
|
||||
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!("{}{path_and_query}", self.host);
|
||||
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<T>(
|
||||
agent: &Agent,
|
||||
url: &str,
|
||||
riot_token: Option<&str>,
|
||||
read: impl FnOnce(&mut Body) -> Result<T, ureq::Error>,
|
||||
) -> Result<T, SourceError> {
|
||||
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<Account, SourceError> {
|
||||
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<i64>,
|
||||
) -> Result<Vec<String>, 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<String, SourceError> {
|
||||
self.get(&format!("/lol/match/v5/matches/{}", encode(match_id)))
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_account(body: &str) -> Result<Account, SourceError> {
|
||||
serde_json::from_str(body).map_err(|e| SourceError::Other(format!("Compte illisible : {e}")))
|
||||
}
|
||||
|
||||
fn decode_ids(body: &str) -> Result<Vec<String>, SourceError> {
|
||||
serde_json::from_str(body)
|
||||
.map_err(|e| SourceError::Other(format!("Liste de Parties illisible : {e}")))
|
||||
}
|
||||
|
||||
/// 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<Instant>, 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));
|
||||
}
|
||||
|
||||
#[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_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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user