419 lines
14 KiB
Rust
419 lines
14 KiB
Rust
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<String>,
|
|
/// 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<Account>,
|
|
listings: Mutex<Vec<Listing>>,
|
|
/// Every call fails with this until it is cleared.
|
|
failure: Mutex<Option<SourceError>>,
|
|
fail_after: Option<usize>,
|
|
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.
|
|
resolve_gate: Option<(Sender<()>, Mutex<Receiver<()>>)>,
|
|
gate: Option<(Sender<()>, Mutex<Receiver<()>>)>,
|
|
fetches: Arc<AtomicUsize>,
|
|
listed: Arc<AtomicUsize>,
|
|
calls: Arc<AtomicUsize>,
|
|
/// Mastery Points by puuid, as Riot lists them (champions with points only).
|
|
mastery: Mutex<HashMap<String, Vec<(u32, u64)>>>,
|
|
/// Mastery requests fail with this until it is cleared.
|
|
mastery_failure: Mutex<Option<SourceError>>,
|
|
mastery_calls: Arc<AtomicUsize>,
|
|
/// Timelines by Match id; a Match without one answers "not found".
|
|
timelines: Mutex<HashMap<String, String>>,
|
|
/// Timeline requests fail with this (after the general failure) until it is cleared.
|
|
timeline_failure: Mutex<Option<SourceError>>,
|
|
timeline_calls: Arc<AtomicUsize>,
|
|
/// 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<Receiver<()>>)>,
|
|
/// The platform of each Account's active region; "euw1" for those not set.
|
|
platforms: Mutex<HashMap<String, String>>,
|
|
/// Told of each request, e.g. "ids <puuid>", "match <id>", "mastery <platform> <puuid>".
|
|
requests: Option<Sender<String>>,
|
|
}
|
|
|
|
impl FakeHistory {
|
|
pub fn new(account: Account, payloads: Vec<String>) -> FakeHistory {
|
|
FakeHistory {
|
|
accounts: Vec::new(),
|
|
listings: Mutex::default(),
|
|
failure: Mutex::default(),
|
|
fail_after: None,
|
|
rate_limit_once: AtomicBool::new(false),
|
|
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<String>) -> 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<String>) {
|
|
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<SourceError>) {
|
|
*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
|
|
}
|
|
|
|
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<AtomicUsize> {
|
|
self.fetches.clone()
|
|
}
|
|
|
|
/// Match ids returned by `match_ids`.
|
|
pub fn listed_counter(&self) -> Arc<AtomicUsize> {
|
|
self.listed.clone()
|
|
}
|
|
|
|
/// Calls of any kind made to the source.
|
|
pub fn call_counter(&self) -> Arc<AtomicUsize> {
|
|
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<SourceError>) {
|
|
*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<AtomicUsize> {
|
|
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<SourceError>) {
|
|
*self.timeline_failure.lock().unwrap() = error;
|
|
}
|
|
|
|
/// Timeline requests made, failed ones included (they also count as calls).
|
|
pub fn timeline_counter(&self) -> Arc<AtomicUsize> {
|
|
self.timeline_calls.clone()
|
|
}
|
|
|
|
/// The Account plays on this platform (the key 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<String>) -> 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<Account, SourceError> {
|
|
self.enter(format!("account {game_name}#{tag_line}"))?;
|
|
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<i64>,
|
|
) -> Result<Vec<String>, SourceError> {
|
|
self.enter(format!("ids {puuid}"))?;
|
|
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<String> = 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<String, SourceError> {
|
|
self.enter(format!("match {id}"))?;
|
|
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 fetch_timeline(&self, id: &str) -> Result<String, SourceError> {
|
|
self.enter(format!("timeline {id}"))?;
|
|
self.timeline_calls.fetch_add(1, Ordering::SeqCst);
|
|
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<Vec<(u32, u64)>, 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<String, SourceError> {
|
|
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")
|
|
}
|
|
}
|