Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a23e7ffbac | ||
|
|
1f0e92194a | ||
|
|
88acc1b0df | ||
|
|
7b0b9863e0 | ||
|
|
5343e49996 | ||
|
|
6140bc34fb |
No files matched your search
@@ -38,7 +38,7 @@ use gpui_kit::base::async_util::unbounded;
|
||||
use gpui_kit::component::*;
|
||||
use gpui_kit::*;
|
||||
|
||||
use page::{ChampionSortChosen, Launch, LiveMatchStarted, Page, RecapOpened};
|
||||
use page::{ChampionSortChosen, Launch, LiveMatchStarted, MatchEndShown, Page};
|
||||
use settings::{SettingsEvent, SettingsForm, SettingsStore, apply_theme};
|
||||
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
|
||||
use worker::{CatalogRefresh, spawn_follower};
|
||||
@@ -133,9 +133,13 @@ impl RootView {
|
||||
}
|
||||
},
|
||||
);
|
||||
// The end of a Match showed its recap: « Paramètres » gives way as for a champ select,
|
||||
// but the window stays as it is, hidden, minimised or behind League: never in front.
|
||||
let recap = cx.subscribe_in(&page, window, |this, _, _: &RecapOpened, window, cx| {
|
||||
// The end of a game showed its recap or the Challenge: as for a champ select, « Paramètres »
|
||||
// gives way and the window comes above the others, League keeping the keyboard.
|
||||
let recap = cx.subscribe_in(&page, window, |this, _, _: &MatchEndShown, window, cx| {
|
||||
if let Some(hwnd) = tray::window_hwnd(window) {
|
||||
cx.spawn(async move |_, _| tray::reveal(hwnd, true))
|
||||
.detach();
|
||||
}
|
||||
if this.screen == Screen::Settings {
|
||||
this.show_page(window, cx);
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ mod displayed;
|
||||
mod friends;
|
||||
mod home;
|
||||
mod hover;
|
||||
mod import_view;
|
||||
mod in_game;
|
||||
mod lifecycle;
|
||||
mod links;
|
||||
@@ -112,10 +113,10 @@ pub struct ChampSelectTransition {
|
||||
}
|
||||
impl EventEmitter<ChampSelectTransition> for Page {}
|
||||
|
||||
/// The end of a Match opened its recap in « Parties »: « Paramètres » gives way, as for a champ
|
||||
/// select, but the window is left as it is (#129).
|
||||
pub struct RecapOpened;
|
||||
impl EventEmitter<RecapOpened> for Page {}
|
||||
/// The end of a game was decided: « Parties » opened its recap, or « Défi » shows. As for a champ
|
||||
/// select, « Paramètres » gives way and the window comes above the others (#129).
|
||||
pub struct MatchEndShown;
|
||||
impl EventEmitter<MatchEndShown> for Page {}
|
||||
|
||||
/// The player chose a sort for the cards: to be saved with the other preferences.
|
||||
pub struct ChampionSortChosen(pub ChampionSort);
|
||||
@@ -234,6 +235,7 @@ pub struct Page {
|
||||
/// The Account of the last requested statistics.
|
||||
shown: Option<String>,
|
||||
progress: Option<SyncProgress>,
|
||||
import_view: import_view::ImportView,
|
||||
refresh: RefreshGate,
|
||||
stats_job: RefreshGate,
|
||||
stats_generation: u64,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{PAGE_PADDING, Page, Tab, shown};
|
||||
use crate::stage;
|
||||
use crate::text::{CLIENT_ABSENT, official_differs, sync_line};
|
||||
use crate::text::{CLIENT_ABSENT, official_differs};
|
||||
#[cfg(test)]
|
||||
use arena_tracker_core::{ChampionSort, StateFilter};
|
||||
use arena_tracker_core::{ProgressCheck, UpdateProblem};
|
||||
@@ -105,11 +105,7 @@ impl Render for Page {
|
||||
.and_then(|entry| entry.sweep(now))
|
||||
.map(|progress| stage::sweep(progress, window.viewport_size(), cx));
|
||||
let muted = cx.theme().muted_foreground;
|
||||
let busy = self.busy();
|
||||
let status_line = (!busy)
|
||||
.then(|| self.friend_status())
|
||||
.flatten()
|
||||
.unwrap_or_else(|| sync_line(busy, self.progress, self.crashed, self.stored).into());
|
||||
let status_line = self.status_line(now);
|
||||
|
||||
div()
|
||||
// The pointer takes over from the keyboard: the card it lifted goes down.
|
||||
|
||||
@@ -70,6 +70,7 @@ impl Page {
|
||||
self.home_filter = StateFilter::All;
|
||||
}
|
||||
self.rescope(window, cx);
|
||||
self.show_import(true, cx);
|
||||
}
|
||||
|
||||
/// The Account whose data the page shows: during a champ select or a Live Match the one
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! takes a Riot ID, and the import of a Friend's history. Nothing here runs on a timer: a Friend's
|
||||
//! Matches are fetched when it is added, when it is chosen in the selector and on « Actualiser ».
|
||||
|
||||
use super::import_view::wait_until;
|
||||
use super::{AccountItem, AccountList, Page, RELOAD_EVERY};
|
||||
use crate::input_frame::input_frame;
|
||||
use crate::text::friend_sync_line;
|
||||
@@ -39,11 +40,23 @@ struct Import {
|
||||
/// Asked for while another ran: the latest Friend asked for wins.
|
||||
queued: Option<String>,
|
||||
line: Option<SharedString>,
|
||||
/// The last progress of the import running.
|
||||
progress: Option<SyncProgress>,
|
||||
/// The Friend whose last import failed, and why.
|
||||
error: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl Friends {
|
||||
/// The puuid of the Friend whose import runs.
|
||||
pub(super) fn import_running(&self) -> Option<&str> {
|
||||
self.import.running.as_deref()
|
||||
}
|
||||
|
||||
/// The last progress of the import running, if it has told one.
|
||||
pub(super) fn import_progress(&self) -> Option<SyncProgress> {
|
||||
self.import.progress
|
||||
}
|
||||
|
||||
pub(super) fn new(window: &mut Window, cx: &mut Context<Page>) -> (Friends, Subscription) {
|
||||
let input = cx.new(|cx| InputState::new(window, cx).placeholder("Pseudo#TAG"));
|
||||
let enter = cx.subscribe(&input, |page, _, event: &InputEvent, cx| {
|
||||
@@ -213,6 +226,7 @@ impl Page {
|
||||
let import = &mut self.friends.import;
|
||||
import.error.take_if(|(failed, _)| *failed == puuid);
|
||||
import.queued = None;
|
||||
import.progress = None;
|
||||
import.line = self
|
||||
.accounts
|
||||
.iter()
|
||||
@@ -230,9 +244,14 @@ impl Page {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let puuid = self.current_puuid(puuid, window, cx);
|
||||
let puuid = puuid.as_str();
|
||||
if self.friends.import.running.as_deref() != Some(puuid) {
|
||||
return;
|
||||
}
|
||||
let now = cx.background_executor().now();
|
||||
self.import_view.friend_until = wait_until(progress, now);
|
||||
self.friends.import.progress = Some(progress);
|
||||
self.friends.import.line = self
|
||||
.accounts
|
||||
.iter()
|
||||
@@ -251,9 +270,11 @@ impl Page {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let puuid = self.current_puuid(&puuid, window, cx);
|
||||
let import = &mut self.friends.import;
|
||||
import.running = None;
|
||||
import.line = None;
|
||||
import.progress = None;
|
||||
if let Err(message) = outcome {
|
||||
import.error = Some((puuid.clone(), message));
|
||||
}
|
||||
@@ -265,6 +286,40 @@ impl Page {
|
||||
}
|
||||
}
|
||||
|
||||
/// What an import message names may have changed PUUID since the import started (a new Riot
|
||||
/// key, `Tracker::replaced_puuid`): the Accounts are read again, so the page follows it.
|
||||
fn current_puuid(
|
||||
&mut self,
|
||||
puuid: &str,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> String {
|
||||
let Some(new) = self.tracker.replaced_puuid(puuid) else {
|
||||
return puuid.into();
|
||||
};
|
||||
if self.friends.import.running.as_deref() == Some(puuid) {
|
||||
self.reload_accounts(window, cx);
|
||||
}
|
||||
new
|
||||
}
|
||||
|
||||
/// The PUUIDs the page holds follow the ones that replaced them (see `current_puuid`), so
|
||||
/// the Account shown stays the same.
|
||||
pub(in crate::page) fn follow_replaced_puuids(&mut self) {
|
||||
let import = &mut self.friends.import;
|
||||
let held = [
|
||||
self.pinned.as_mut(),
|
||||
import.running.as_mut(),
|
||||
import.queued.as_mut(),
|
||||
import.error.as_mut().map(|(puuid, _)| puuid),
|
||||
];
|
||||
for puuid in held.into_iter().flatten() {
|
||||
if let Some(new) = self.tracker.replaced_puuid(puuid) {
|
||||
*puuid = new;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Friend's addition or import panicked: nothing is known to run any more.
|
||||
pub(in crate::page) fn friend_crashed(&mut self) {
|
||||
self.friends.pending = false;
|
||||
|
||||
@@ -332,3 +332,35 @@ async fn a_friend_who_signs_in_to_the_client_stays_a_friend_and_is_not_imported(
|
||||
assert_eq!(items, [("Alice", false), ("Bob", false), ("Carl", true)]);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn a_friend_shown_while_its_puuid_changes_stays_shown_and_its_import_goes_on(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (page, mut window, handles) = on_carl(cx).await;
|
||||
handles.new_key.store(true, Ordering::SeqCst);
|
||||
handles.third.store(true, Ordering::SeqCst);
|
||||
handles.gate.set(false);
|
||||
|
||||
// Chosen again, Carl is rekeyed before its new Match is awaited.
|
||||
pick(&page, &mut window, "Carl");
|
||||
cx.condition(&page, |p, _| p.pinned.as_deref() == Some("Carl2"))
|
||||
.await;
|
||||
page.read_with(&window, |p, _| {
|
||||
assert_eq!(p.friends.import.running.as_deref(), Some("Carl2"));
|
||||
assert_eq!(p.viewed().map(|a| a.puuid.as_str()), Some("Carl2"));
|
||||
assert_eq!(
|
||||
p.friend_status().as_deref(),
|
||||
Some("Import de Carl : 0 / 1 Parties")
|
||||
);
|
||||
});
|
||||
assert_eq!(selected(&page, &mut window).as_deref(), Some("Carl2"));
|
||||
|
||||
handles.gate.set(true);
|
||||
imported(&page, cx, 3).await;
|
||||
assert_eq!(status_line(&page, &mut window), None);
|
||||
page.read_with(&window, |p, _| {
|
||||
assert_eq!(p.pinned.as_deref(), Some("Carl2"));
|
||||
assert!(p.friends.ids.contains("Carl2") && p.friend_error().is_none());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! What an import shows beyond its count (#140): the arc around the ring and the status line's
|
||||
//! countdown while the Riot quota makes it wait. No timer runs outside a wait, and the ring is
|
||||
//! told at most once a second (rule #1).
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use arena_tracker_core::{SyncProgress, account_riot_id};
|
||||
use gpui_kit::*;
|
||||
|
||||
use super::Page;
|
||||
use crate::text::{quota_line, sync_line};
|
||||
|
||||
/// An import of fewer Matches than this shows no arc: a short sync must not flash it.
|
||||
const ARC_FROM: usize = 10;
|
||||
const EVERY: Duration = Duration::from_secs(1);
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ImportView {
|
||||
/// When the quota wait told by the own sync, or by the Friend's import, ends.
|
||||
pub(super) own_until: Option<Instant>,
|
||||
pub(super) friend_until: Option<Instant>,
|
||||
/// The countdown's timer, while a wait is on: dropped, it stops.
|
||||
counting: Option<Task<()>>,
|
||||
/// The signed-in Riot ID and the puuid of the Account it names, once resolved: forgotten
|
||||
/// when the Accounts are read again.
|
||||
pub(super) signed_in: Option<(std::sync::Arc<str>, Option<String>)>,
|
||||
/// What the ring was given last, and when.
|
||||
arc: Option<(usize, usize)>,
|
||||
arc_at: Option<Instant>,
|
||||
}
|
||||
|
||||
/// When the wait `progress` tells ends, from `now`.
|
||||
pub(super) fn wait_until(progress: SyncProgress, now: Instant) -> Option<Instant> {
|
||||
progress.quota_wait.map(|wait| now + wait)
|
||||
}
|
||||
|
||||
impl Page {
|
||||
/// The header's status line: the quota wait, else the import or sync going on, else the
|
||||
/// last result.
|
||||
pub(super) fn status_line(&self, now: Instant) -> SharedString {
|
||||
if let Some(secs) = self.quota_secs_left(now) {
|
||||
return quota_line(secs).into();
|
||||
}
|
||||
let busy = self.busy();
|
||||
(!busy)
|
||||
.then(|| self.friend_status())
|
||||
.flatten()
|
||||
.unwrap_or_else(|| sync_line(busy, self.progress, self.crashed, self.stored).into())
|
||||
}
|
||||
|
||||
/// The seconds left, rounded up, of the quota wait the status line tells: the own sync's,
|
||||
/// which comes first as its line does, else the Friend's.
|
||||
fn quota_secs_left(&self, now: Instant) -> Option<u64> {
|
||||
let (progress, until) = if self.busy() {
|
||||
(self.progress?, self.import_view.own_until?)
|
||||
} else {
|
||||
(
|
||||
self.friends.import_progress()?,
|
||||
self.import_view.friend_until?,
|
||||
)
|
||||
};
|
||||
progress.quota_wait?;
|
||||
let left = until.checked_duration_since(now).filter(|d| !d.is_zero())?;
|
||||
Some(left.as_millis().div_ceil(1000) as u64)
|
||||
}
|
||||
|
||||
/// After a message of an import or a change of the Account shown: starts the countdown if a
|
||||
/// wait is on, and gives the ring what it shows.
|
||||
pub(super) fn show_import(&mut self, force: bool, cx: &mut Context<Self>) {
|
||||
self.count_down(cx);
|
||||
self.show_arc(force, cx);
|
||||
}
|
||||
|
||||
/// One timer for the whole wait: it draws the status line again each second and ends with it.
|
||||
fn count_down(&mut self, cx: &mut Context<Self>) {
|
||||
if self
|
||||
.quota_secs_left(cx.background_executor().now())
|
||||
.is_none()
|
||||
{
|
||||
self.import_view.counting = None;
|
||||
return;
|
||||
}
|
||||
if self.import_view.counting.is_some() {
|
||||
return;
|
||||
}
|
||||
self.import_view.counting = Some(cx.spawn(async move |page, cx| {
|
||||
loop {
|
||||
cx.background_executor().timer(EVERY).await;
|
||||
let more = page.update(cx, |page, cx| {
|
||||
cx.notify();
|
||||
page.show_arc(false, cx);
|
||||
let more = page
|
||||
.quota_secs_left(cx.background_executor().now())
|
||||
.is_some();
|
||||
if !more {
|
||||
page.import_view.counting = None;
|
||||
}
|
||||
more
|
||||
});
|
||||
if !more.unwrap_or(false) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/// (fetched, to fetch) of the import of the Account shown, once it is long enough to show.
|
||||
fn arc_wanted(&mut self) -> Option<(usize, usize)> {
|
||||
let own = self.progress.filter(|p| p.to_fetch >= ARC_FROM);
|
||||
if own.is_some() {
|
||||
self.resolve_signed_in();
|
||||
}
|
||||
let shown = self.displayed()?.puuid.as_str();
|
||||
let friend = (self.friends.import_running() == Some(shown))
|
||||
.then(|| self.friends.import_progress())
|
||||
.flatten();
|
||||
let progress = friend.or_else(|| {
|
||||
// The Account the follower or the refresh imports is the one signed in to the client;
|
||||
// one not read yet shows no arc, rather than the previous Account's.
|
||||
let imported = match &self.import_view.signed_in {
|
||||
Some((_, puuid)) => puuid.as_deref(),
|
||||
None => self.active_account().map(|a| a.puuid.as_str()),
|
||||
};
|
||||
(imported? == shown).then_some(own?)
|
||||
})?;
|
||||
(progress.to_fetch >= ARC_FROM).then_some((progress.fetched, progress.to_fetch))
|
||||
}
|
||||
|
||||
/// Resolves the Account of the signed-in Riot ID when it changes, so an own import builds no
|
||||
/// Riot ID per Account at each message (see `phase_account`).
|
||||
fn resolve_signed_in(&mut self) {
|
||||
let Some(id) = self.tracker.signed_in_riot_id_folded() else {
|
||||
self.import_view.signed_in = None;
|
||||
return;
|
||||
};
|
||||
if self
|
||||
.import_view
|
||||
.signed_in
|
||||
.as_ref()
|
||||
.is_none_or(|(known, _)| *known != id)
|
||||
{
|
||||
let named = (self.accounts.iter()).find(|a| account_riot_id(a).to_lowercase() == *id);
|
||||
self.import_view.signed_in = Some((id, named.map(|a| a.puuid.clone())));
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the ring the arc: at once when it appears, disappears or `force`, else at most once
|
||||
/// a second.
|
||||
fn show_arc(&mut self, force: bool, cx: &mut Context<Self>) {
|
||||
let wanted = self.arc_wanted();
|
||||
let now = cx.background_executor().now();
|
||||
let view = &mut self.import_view;
|
||||
let toggled = wanted.is_some() != view.arc.is_some();
|
||||
let due = view.arc_at.is_none_or(|at| now.duration_since(at) >= EVERY);
|
||||
if wanted == view.arc || !(force || toggled || due) {
|
||||
return;
|
||||
}
|
||||
view.arc = wanted;
|
||||
view.arc_at = Some(now);
|
||||
self.ring
|
||||
.update(cx, |ring, cx| ring.set_progress(wanted, cx));
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
//! The end of a Match opens its recap (#129): when its end-of-game block arrives, « Parties »
|
||||
//! shows the new Match, from any screen, never bringing the window forward nor taking the focus.
|
||||
//! shows the new Match, from any screen; the window comes forward without taking the focus.
|
||||
//! With the preference off, or when the game ended without a block, the Challenge shows instead.
|
||||
//! The animation of the end of the Match plays on « Parties » then (#110). Each game's end is
|
||||
//! decided once: nothing brings the player back to either screen afterwards.
|
||||
//! During a Live Match, « En partie » stays until the block or the lobby (#109).
|
||||
|
||||
use crate::page::{ALL_SEASONS, Page, RecapOpened, Tab};
|
||||
use crate::page::{ALL_SEASONS, MatchEndShown, Page, Tab};
|
||||
use crate::worker::MatchEntry;
|
||||
use arena_tracker_core::{FollowedMatch, GameEnd, SeasonScope};
|
||||
use gpui_kit::component::IndexPath;
|
||||
@@ -54,6 +54,7 @@ impl Page {
|
||||
self.show_account(None, window, cx);
|
||||
}
|
||||
self.set_tab(Tab::Challenge, window, cx);
|
||||
cx.emit(MatchEndShown);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -82,6 +83,7 @@ impl Page {
|
||||
self.show_account(None, window, cx);
|
||||
}
|
||||
self.set_tab(Tab::Challenge, window, cx);
|
||||
cx.emit(MatchEndShown);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +120,7 @@ impl Page {
|
||||
// Already drawn, the screen does not open again by itself: an earlier recap goes.
|
||||
self.open_matches(cx);
|
||||
}
|
||||
cx.emit(RecapOpened);
|
||||
cx.emit(MatchEndShown);
|
||||
}
|
||||
|
||||
/// The Season and Format of « Statistiques » hide the Match that just ended: to its Season
|
||||
|
||||
@@ -160,7 +160,8 @@ impl Page {
|
||||
.list
|
||||
.update(cx, |list, cx| list.set_rows(rows, selected.as_deref(), cx));
|
||||
if choose {
|
||||
self.request_recap(false);
|
||||
// The Match chosen for the player, as one they click, shows their row.
|
||||
self.request_recap(true);
|
||||
}
|
||||
self.dress_banner(cx);
|
||||
}
|
||||
|
||||
@@ -217,6 +217,7 @@ impl Page {
|
||||
pinned: None,
|
||||
shown: None,
|
||||
progress: None,
|
||||
import_view: Default::default(),
|
||||
refresh: RefreshGate::default(),
|
||||
stats_job: RefreshGate::default(),
|
||||
stats_generation: 0,
|
||||
|
||||
@@ -32,6 +32,7 @@ impl Page {
|
||||
self.accounts.clone_from(&directory.accounts);
|
||||
self.last_active.clone_from(&directory.last_active);
|
||||
self.friends.ids.clone_from(&directory.friends);
|
||||
self.follow_replaced_puuids();
|
||||
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
|
||||
self.pinned = None;
|
||||
}
|
||||
@@ -41,6 +42,7 @@ impl Page {
|
||||
if changed {
|
||||
// The live champ select's Account may now be in the list: resolve it again.
|
||||
self.phase_riot_id = None;
|
||||
self.import_view.signed_in = None;
|
||||
}
|
||||
if changed {
|
||||
(self.account_select).update(cx, |select, cx| {
|
||||
|
||||
@@ -18,6 +18,8 @@ pub(crate) mod client_fixtures;
|
||||
pub(crate) mod friends_fixtures;
|
||||
mod grid;
|
||||
mod home;
|
||||
mod import_arc;
|
||||
mod import_quota;
|
||||
mod in_game;
|
||||
mod in_game_end;
|
||||
mod in_game_fixtures;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The Riot source of the Friends' tests: Alice and Bob as in `TwoAccounts`, and Carl (a Friend
|
||||
//! of the app's region, two Matches) and Dora (another region). A gate holds Carl's Matches
|
||||
//! back, so a test sees an import under way.
|
||||
//! back the first time each is fetched, so a test sees an import under way.
|
||||
|
||||
use super::client_fixtures::FakeClient;
|
||||
use super::matches_fixtures::TwoAccounts;
|
||||
@@ -43,6 +43,15 @@ pub(in crate::page) struct Handles {
|
||||
pub(in crate::page) third: Arc<AtomicBool>,
|
||||
/// The relay is down: it answers for no Riot ID.
|
||||
pub(in crate::page) relay_down: Arc<AtomicBool>,
|
||||
/// Carl has twelve Matches, `long` ones, instead: an import long enough to draw the arc.
|
||||
pub(in crate::page) many: Arc<AtomicBool>,
|
||||
/// Riot's key changed: Carl is now `Carl2`, his Matches the same.
|
||||
pub(in crate::page) new_key: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
/// The id of Carl's `i`th long Match.
|
||||
fn long(i: usize) -> String {
|
||||
format!("EUW1_92000000{i:02}")
|
||||
}
|
||||
|
||||
struct Riot {
|
||||
@@ -56,6 +65,11 @@ impl MatchHistorySource for Riot {
|
||||
return Err(SourceError::Unavailable);
|
||||
}
|
||||
match game_name {
|
||||
"Carl" if self.handles.new_key.load(Ordering::SeqCst) => Ok(Account {
|
||||
puuid: "Carl2".into(),
|
||||
game_name: game_name.into(),
|
||||
tag_line: tag_line.into(),
|
||||
}),
|
||||
"Alice" | "Bob" | "Carl" | "Dora" => self.inner.resolve_account(game_name, tag_line),
|
||||
_ => Err(SourceError::NotFound),
|
||||
}
|
||||
@@ -69,27 +83,42 @@ impl MatchHistorySource for Riot {
|
||||
count: usize,
|
||||
since: Option<i64>,
|
||||
) -> Result<Vec<String>, SourceError> {
|
||||
if puuid != "Carl" {
|
||||
if !matches!(puuid, "Carl" | "Carl2") {
|
||||
return self.inner.match_ids(puuid, queue_id, start, count, since);
|
||||
}
|
||||
if queue_id != 1750 || start != 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if self.handles.many.load(Ordering::SeqCst) {
|
||||
return Ok((0..12).map(long).collect());
|
||||
}
|
||||
let skip = usize::from(!self.handles.third.load(Ordering::SeqCst));
|
||||
Ok(CARL[skip..].iter().map(|id| id.to_string()).collect())
|
||||
}
|
||||
|
||||
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
|
||||
let Some(at) = CARL.iter().position(|carl| *carl == id) else {
|
||||
let long_at = (0..12).find(|i| long(*i) == id);
|
||||
let Some(at) = CARL.iter().position(|carl| *carl == id).or(long_at) else {
|
||||
return self.inner.fetch_match(id);
|
||||
};
|
||||
self.handles.gate.pass();
|
||||
// A Match fetched again (the proof of a changed PUUID) is not one the import waits for.
|
||||
if !self.handles.fetched.lock().unwrap().iter().any(|f| f == id) {
|
||||
self.handles.gate.pass();
|
||||
}
|
||||
self.handles.fetched.lock().unwrap().push(id.into());
|
||||
let start = ["1794000000000", "1792000000000", "1790000000000"][at];
|
||||
let carl = if self.handles.new_key.load(Ordering::SeqCst) {
|
||||
"Carl2"
|
||||
} else {
|
||||
"Carl"
|
||||
};
|
||||
let start = match long_at {
|
||||
Some(i) => (1_790_000_000_000_i64 + i as i64 * 1000).to_string(),
|
||||
None => ["1794000000000", "1792000000000", "1790000000000"][at].into(),
|
||||
};
|
||||
Ok(MATCH_1750
|
||||
.replace("EUW1_9000000006", id)
|
||||
.replace("1794763752767", start)
|
||||
.replace("fixture-puuid-self", "Carl"))
|
||||
.replace("1794763752767", &start)
|
||||
.replace("fixture-puuid-self", carl))
|
||||
}
|
||||
|
||||
fn account_platform(&self, puuid: &str) -> Result<String, SourceError> {
|
||||
@@ -111,7 +140,9 @@ pub(in crate::page) fn tracker() -> (Tracker, Arc<Mutex<String>>, Handles) {
|
||||
}),
|
||||
fetched: Arc::default(),
|
||||
third: Arc::default(),
|
||||
many: Arc::default(),
|
||||
relay_down: Arc::default(),
|
||||
new_key: Arc::default(),
|
||||
};
|
||||
let client = FakeClient::new("Alice");
|
||||
let source = Riot {
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
//! The import's arc on the ring (#140): shown for the import of the Account displayed, once it
|
||||
//! is 10 Matches long, and the ring stays a cached view while it advances. The Riot source of
|
||||
//! the Friend's import is simulated (`friends_fixtures`); the own sync's progress arrives as the
|
||||
//! follower's does, through `Page::apply`.
|
||||
|
||||
use super::banner_fixtures::ring_renders;
|
||||
use super::friends_fixtures::{Handles, tracker};
|
||||
use super::page_fixtures::{champions, draw, open_page_with_tracker, show, statistics};
|
||||
use crate::card_grid::CardHovered;
|
||||
use crate::page::Page;
|
||||
use crate::worker::Msg;
|
||||
use arena_tracker_core::SyncProgress;
|
||||
use gpui_kit::{
|
||||
Entity, Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px,
|
||||
};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The page on Alice (signed in to the client), Carl stored as a Friend and not imported yet.
|
||||
pub(super) async fn on_alice(
|
||||
cx: &mut TestAppContext,
|
||||
) -> (Entity<Page>, VisualTestContext, Handles) {
|
||||
cx.executor().allow_parking();
|
||||
let (tracker, _, handles) = tracker();
|
||||
tracker.add_friend("Carl#EUW").unwrap();
|
||||
let (page, window) = open_page_with_tracker(cx, tracker);
|
||||
cx.condition(&page, |p, _| p.stats.is_some() && !p.pending_round)
|
||||
.await;
|
||||
(page, window, handles)
|
||||
}
|
||||
|
||||
pub(super) fn progress(fetched: usize, to_fetch: usize) -> SyncProgress {
|
||||
SyncProgress {
|
||||
fetched,
|
||||
to_fetch,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A message of the worker, as the page receives it.
|
||||
pub(super) fn tell(page: &Entity<Page>, cx: &mut VisualTestContext, msg: Msg) {
|
||||
cx.update(|window, cx| page.update(cx, |page, cx| page.apply(msg, window, cx)));
|
||||
}
|
||||
|
||||
pub(super) fn arc(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<(usize, usize)> {
|
||||
page.read_with(cx, |p, cx| p.ring.read(cx).progress())
|
||||
}
|
||||
|
||||
pub(super) fn choose(page: &Entity<Page>, cx: &mut VisualTestContext, puuid: &str) {
|
||||
cx.update(|window, cx| page.update(cx, |p, cx| p.choose_account(puuid, window, cx)));
|
||||
}
|
||||
|
||||
/// One second of the test clock, the timers having fired.
|
||||
pub(super) fn second(cx: &mut VisualTestContext) {
|
||||
cx.executor().advance_clock(Duration::from_secs(1));
|
||||
cx.run_until_parked();
|
||||
draw(cx);
|
||||
}
|
||||
|
||||
fn round(page: &Entity<Page>, cx: &mut VisualTestContext) -> Msg {
|
||||
Msg::Round {
|
||||
status: page.read_with(cx, |p, _| p.tracker.status()),
|
||||
reload: false,
|
||||
matches: Vec::new(),
|
||||
game_end: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn the_own_sync_of_the_account_shown_draws_the_arc_until_it_ends(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let cx = &mut window;
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
|
||||
// A sync of fewer than 10 Matches never flashes it.
|
||||
tell(&page, cx, Msg::Progress(progress(1, 9)));
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
|
||||
tell(&page, cx, Msg::Progress(progress(0, 12)));
|
||||
assert_eq!(arc(&page, cx), Some((0, 12)));
|
||||
second(cx);
|
||||
tell(&page, cx, Msg::Progress(progress(5, 12)));
|
||||
assert_eq!(arc(&page, cx), Some((5, 12)));
|
||||
|
||||
// It goes with the sync, and does not come back for the next short one.
|
||||
let end = round(&page, cx);
|
||||
tell(&page, cx, end);
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
tell(&page, cx, Msg::Progress(progress(1, 2)));
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn the_sync_of_another_account_than_the_one_shown_draws_no_arc(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let cx = &mut window;
|
||||
choose(&page, cx, "Bob");
|
||||
tell(&page, cx, Msg::Progress(progress(2, 12)));
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
|
||||
// Back on Alice, whose sync it is: the arc is there at once.
|
||||
choose(&page, cx, "Alice");
|
||||
assert_eq!(arc(&page, cx), Some((2, 12)));
|
||||
choose(&page, cx, "Bob");
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn a_friends_import_draws_the_arc_while_the_friend_is_shown_and_ends_with_it(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (page, mut window, handles) = on_alice(cx).await;
|
||||
handles.gate.set(false);
|
||||
choose(&page, &mut window, "Carl");
|
||||
cx.condition(&page, |p, _| {
|
||||
p.friend_status().as_deref() == Some("Import de Carl : 0 / 2 Parties")
|
||||
})
|
||||
.await;
|
||||
let cx = &mut window;
|
||||
// Two Matches: no arc.
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
|
||||
let friend = |progress| Msg::FriendProgress {
|
||||
puuid: "Carl".into(),
|
||||
progress,
|
||||
};
|
||||
tell(&page, cx, friend(progress(3, 12)));
|
||||
assert_eq!(arc(&page, cx), Some((3, 12)));
|
||||
second(cx);
|
||||
tell(&page, cx, friend(progress(4, 12)));
|
||||
assert_eq!(arc(&page, cx), Some((4, 12)));
|
||||
|
||||
// Another Account shown: only the status line tells the import goes on.
|
||||
choose(&page, cx, "Alice");
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
choose(&page, cx, "Carl");
|
||||
assert_eq!(arc(&page, cx), Some((4, 12)));
|
||||
|
||||
handles.gate.set(true);
|
||||
cx.condition(&page, |p, _| p.friends.import_running().is_none())
|
||||
.await;
|
||||
assert_eq!(arc(&page, &mut window), None);
|
||||
}
|
||||
|
||||
// The worker runs the import, the simulated Riot source gives Carl twelve Matches.
|
||||
#[gpui::test]
|
||||
async fn a_real_import_of_twelve_matches_draws_the_arc_while_it_runs_and_not_after(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (page, mut window, handles) = on_alice(cx).await;
|
||||
handles.many.store(true, Ordering::SeqCst);
|
||||
handles.gate.set(false);
|
||||
choose(&page, &mut window, "Carl");
|
||||
cx.condition(&page, |p, cx| p.ring.read(cx).progress() == Some((0, 12)))
|
||||
.await;
|
||||
|
||||
handles.gate.set(true);
|
||||
cx.condition(&page, |p, _| p.friends.import_running().is_none())
|
||||
.await;
|
||||
assert_eq!(arc(&page, &mut window), None);
|
||||
assert_eq!(handles.fetched.lock().unwrap().len(), 12);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn a_crash_takes_the_arc_away(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let cx = &mut window;
|
||||
tell(&page, cx, Msg::Progress(progress(0, 12)));
|
||||
assert_eq!(arc(&page, cx), Some((0, 12)));
|
||||
tell(&page, cx, Msg::Crashed);
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
}
|
||||
|
||||
// Rule #1: the ring is drawn again for the arc appearing, disappearing and a new count at most
|
||||
// once a second, never by a second of waiting, a hover or a scroll elsewhere.
|
||||
#[gpui::test]
|
||||
async fn the_ring_is_drawn_again_only_for_the_arc_and_at_most_once_a_second(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let cx = &mut window;
|
||||
show(&page, cx, statistics(0, 170, champions(170)));
|
||||
draw(cx);
|
||||
let renders = ring_renders(&page, cx);
|
||||
let tessellations = |page: &Entity<Page>, cx: &mut VisualTestContext| {
|
||||
page.read_with(cx, |p, cx| p.ring.read(cx).tessellations.get())
|
||||
};
|
||||
|
||||
tell(&page, cx, Msg::Progress(progress(1, 12)));
|
||||
draw(cx);
|
||||
assert_eq!(ring_renders(&page, cx), renders + 1);
|
||||
|
||||
// Two messages within the same second: no more drawing.
|
||||
tell(&page, cx, Msg::Progress(progress(2, 12)));
|
||||
tell(&page, cx, Msg::Progress(progress(3, 12)));
|
||||
draw(cx);
|
||||
assert_eq!(ring_renders(&page, cx), renders + 1);
|
||||
|
||||
// The pointer on a card lights its tick, once; elsewhere on the card nothing changes.
|
||||
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
|
||||
let card = cx.debug_bounds("card-1").unwrap();
|
||||
cx.simulate_mouse_move(card.center(), None, Modifiers::none());
|
||||
draw(cx);
|
||||
assert_eq!(page.read_with(cx, |p, cx| p.ring.read(cx).lit()), Some(1));
|
||||
assert_eq!(ring_renders(&page, cx), renders + 2);
|
||||
cx.simulate_mouse_move(
|
||||
card.center() + point(px(10.), px(10.)),
|
||||
None,
|
||||
Modifiers::none(),
|
||||
);
|
||||
draw(cx);
|
||||
assert_eq!(ring_renders(&page, cx), renders + 2);
|
||||
|
||||
// The grid scrolls under the pointer: the ring is drawn again only for each change of the
|
||||
// card under it, and the arc is not tessellated again.
|
||||
let changes = Rc::new(Cell::new(0));
|
||||
let _subscription = cx.update(|_, cx| {
|
||||
let changes = changes.clone();
|
||||
cx.subscribe(&grid, move |_, _: &CardHovered, _| {
|
||||
changes.set(changes.get() + 1)
|
||||
})
|
||||
});
|
||||
let at = card.center();
|
||||
let made = tessellations(&page, cx);
|
||||
for _ in 0..3 {
|
||||
let (was_changed, was_drawn) = (changes.get(), ring_renders(&page, cx));
|
||||
cx.simulate_event(ScrollEvent {
|
||||
position: at,
|
||||
delta: ScrollDelta::Pixels(point(px(0.), px(-200.))),
|
||||
..Default::default()
|
||||
});
|
||||
draw(cx);
|
||||
assert_eq!(
|
||||
ring_renders(&page, cx) - was_drawn,
|
||||
changes.get() - was_changed
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
changes.get() > 0,
|
||||
"no scroll changed the card under the pointer"
|
||||
);
|
||||
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
|
||||
assert_eq!(tessellations(&page, cx), made);
|
||||
let scrolled = ring_renders(&page, cx);
|
||||
|
||||
// The next second brings the count, once, however many messages.
|
||||
second(cx);
|
||||
tell(&page, cx, Msg::Progress(progress(4, 12)));
|
||||
tell(&page, cx, Msg::Progress(progress(5, 12)));
|
||||
draw(cx);
|
||||
assert_eq!(arc(&page, cx), Some((4, 12)));
|
||||
assert_eq!(ring_renders(&page, cx), scrolled + 1);
|
||||
|
||||
// Another tick lit draws the ring again, but tessellates nothing: the arc is kept.
|
||||
let made = tessellations(&page, cx);
|
||||
let lit = page.read_with(cx, |p, cx| p.ring.read(cx).lit());
|
||||
let other = if lit == Some(2) { 3 } else { 2 };
|
||||
cx.update(|_, cx| {
|
||||
page.update(cx, |p, cx| {
|
||||
p.ring.update(cx, |r, cx| r.set_lit(Some(other), cx))
|
||||
})
|
||||
});
|
||||
draw(cx);
|
||||
assert_eq!(ring_renders(&page, cx), scrolled + 2);
|
||||
assert_eq!(tessellations(&page, cx), made);
|
||||
|
||||
// The end: it goes, once.
|
||||
let end = round(&page, cx);
|
||||
tell(&page, cx, end);
|
||||
draw(cx);
|
||||
assert_eq!(ring_renders(&page, cx), scrolled + 3);
|
||||
}
|
||||
|
||||
// An Account signed in to the client that the page has not read yet is not the previous one.
|
||||
#[gpui::test]
|
||||
async fn an_import_of_a_signed_in_account_not_read_yet_draws_no_arc(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let cx = &mut window;
|
||||
page.update(cx, |p, _| p.accounts.retain(|a| a.puuid != "Alice"));
|
||||
tell(&page, cx, Msg::Progress(progress(0, 12)));
|
||||
assert_eq!(arc(&page, cx), None);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! The status line while the import waits for the Riot quota (#140): the seconds left, counted
|
||||
//! down by one timer that exists only for the wait.
|
||||
|
||||
use super::banner_fixtures::ring_renders;
|
||||
use super::import_arc::{arc, choose, on_alice, progress, second, tell};
|
||||
use super::page_fixtures::draw;
|
||||
use crate::page::Page;
|
||||
use crate::worker::Msg;
|
||||
use arena_tracker_core::SyncProgress;
|
||||
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn line(page: &Entity<Page>, cx: &mut VisualTestContext) -> String {
|
||||
page.read_with(cx, |p, cx| {
|
||||
p.status_line(cx.background_executor().now()).to_string()
|
||||
})
|
||||
}
|
||||
|
||||
fn waiting(fetched: usize, to_fetch: usize, secs: u64) -> SyncProgress {
|
||||
SyncProgress {
|
||||
quota_wait: Some(Duration::from_secs(secs)),
|
||||
..progress(fetched, to_fetch)
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times the page is told it changed from now on.
|
||||
fn notifications(page: &Entity<Page>, cx: &mut VisualTestContext) -> Rc<Cell<usize>> {
|
||||
let told = Rc::new(Cell::new(0));
|
||||
let counted = told.clone();
|
||||
cx.update(|_, cx| {
|
||||
cx.observe(page, move |_, _| counted.set(counted.get() + 1))
|
||||
.detach()
|
||||
});
|
||||
told
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn the_own_sync_counts_the_wait_down_then_the_import_line_comes_back(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let cx = &mut window;
|
||||
tell(&page, cx, Msg::Progress(progress(3, 12)));
|
||||
assert_eq!(line(&page, cx), "Import en cours : 3 / 12 Parties");
|
||||
|
||||
tell(&page, cx, Msg::Progress(waiting(3, 12, 12)));
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 12 s");
|
||||
second(cx);
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 11 s");
|
||||
cx.executor().advance_clock(Duration::from_millis(500));
|
||||
// Rounded up: 10.5 s left say 11.
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 11 s");
|
||||
for _ in 0..10 {
|
||||
second(cx);
|
||||
}
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 1 s");
|
||||
|
||||
tell(&page, cx, Msg::Progress(progress(3, 12)));
|
||||
assert_eq!(line(&page, cx), "Import en cours : 3 / 12 Parties");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn a_wait_that_passed_without_news_falls_back_to_the_import_line(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let cx = &mut window;
|
||||
tell(&page, cx, Msg::Progress(waiting(3, 12, 2)));
|
||||
second(cx);
|
||||
second(cx);
|
||||
assert_eq!(line(&page, cx), "Import en cours : 3 / 12 Parties");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn nothing_ticks_before_a_wait_nor_after_it(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let cx = &mut window;
|
||||
let told = notifications(&page, cx);
|
||||
for _ in 0..3 {
|
||||
second(cx);
|
||||
}
|
||||
assert_eq!(told.get(), 0);
|
||||
|
||||
// The wait: the page is drawn again each second, and the ring is not.
|
||||
tell(&page, cx, Msg::Progress(progress(3, 12)));
|
||||
draw(cx);
|
||||
let renders = ring_renders(&page, cx);
|
||||
tell(&page, cx, Msg::Progress(waiting(3, 12, 30)));
|
||||
let before = told.get();
|
||||
for _ in 0..3 {
|
||||
second(cx);
|
||||
}
|
||||
assert_eq!(told.get() - before, 3);
|
||||
assert_eq!(ring_renders(&page, cx), renders);
|
||||
assert_eq!(arc(&page, cx), Some((3, 12)));
|
||||
|
||||
// Resumed: the timer has ended itself.
|
||||
tell(&page, cx, Msg::Progress(progress(4, 12)));
|
||||
let before = told.get();
|
||||
for _ in 0..3 {
|
||||
second(cx);
|
||||
}
|
||||
assert_eq!(told.get(), before);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn a_friends_import_tells_its_wait_too_and_the_own_sync_keeps_its_priority(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (page, mut window, handles) = on_alice(cx).await;
|
||||
handles.gate.set(false);
|
||||
choose(&page, &mut window, "Carl");
|
||||
cx.condition(&page, |p, _| {
|
||||
p.friend_status().as_deref() == Some("Import de Carl : 0 / 2 Parties")
|
||||
})
|
||||
.await;
|
||||
let cx = &mut window;
|
||||
let friend = |progress| Msg::FriendProgress {
|
||||
puuid: "Carl".into(),
|
||||
progress,
|
||||
};
|
||||
|
||||
tell(&page, cx, friend(waiting(0, 2, 5)));
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 5 s");
|
||||
second(cx);
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 4 s");
|
||||
|
||||
// The own sync's line comes first, waiting or not.
|
||||
tell(&page, cx, Msg::Progress(progress(1, 12)));
|
||||
assert_eq!(line(&page, cx), "Import en cours : 1 / 12 Parties");
|
||||
tell(&page, cx, Msg::Progress(waiting(1, 12, 20)));
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 20 s");
|
||||
|
||||
// Its end brings the Friend's wait back, still counting.
|
||||
let status = page.read_with(cx, |p, _| p.tracker.status());
|
||||
let end = Msg::Round {
|
||||
status,
|
||||
reload: false,
|
||||
matches: Vec::new(),
|
||||
game_end: None,
|
||||
};
|
||||
tell(&page, cx, end);
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 4 s");
|
||||
second(cx);
|
||||
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 3 s");
|
||||
|
||||
tell(&page, cx, friend(progress(0, 2)));
|
||||
assert_eq!(line(&page, cx), "Import de Carl : 0 / 2 Parties");
|
||||
handles.gate.set(true);
|
||||
}
|
||||
@@ -69,11 +69,13 @@ async fn with_the_preference_off_the_block_of_the_live_match_shows_the_challenge
|
||||
game_ends(&page, &fake, &mut window);
|
||||
settle_tabs(&page, &mut window);
|
||||
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
|
||||
assert_eq!(opened.get(), 0);
|
||||
assert_eq!(opened.get(), 1);
|
||||
client.lobby();
|
||||
client.read(&page, &mut window);
|
||||
settle_tabs(&page, &mut window);
|
||||
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
|
||||
// The lobby that follows decides nothing more.
|
||||
assert_eq!(opened.get(), 1);
|
||||
draw(&mut window);
|
||||
assert!(window.debug_bounds("tab-in-game").is_none());
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::matches_provisional::{GAME, LEFT_AT_MS, MATCH, block, tracker_before_
|
||||
use super::page_fixtures::{draw, frame_after, open_page_with_tracker, season, switch_tab};
|
||||
use crate::page::ALL_SEASONS;
|
||||
use crate::page::matches::Recap;
|
||||
use crate::page::{Page, RecapOpened, Tab};
|
||||
use crate::page::{MatchEndShown, Page, Tab};
|
||||
use crate::worker::Msg;
|
||||
use arena_tracker_core::{ChampSelect, FollowedMatch, Format, GameEnd, MatchEnd, SeasonScope};
|
||||
use gpui_kit::component::select::SelectEvent;
|
||||
@@ -16,7 +16,7 @@ use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// The page on Alice's Matches before the game ends, Alice's client, which holds its block, and
|
||||
/// how many times the page said it opened a recap.
|
||||
/// how many times the page said it showed the end of a game.
|
||||
pub(super) fn before_the_end(
|
||||
cx: &mut TestAppContext,
|
||||
) -> (Entity<Page>, VisualTestContext, FakeClient, Rc<Cell<usize>>) {
|
||||
@@ -33,7 +33,7 @@ fn before_the_end_in(
|
||||
let opened = Rc::new(Cell::new(0));
|
||||
let counted = opened.clone();
|
||||
window.update(|_, cx| {
|
||||
cx.subscribe(&page, move |_, _: &RecapOpened, _| {
|
||||
cx.subscribe(&page, move |_, _: &MatchEndShown, _| {
|
||||
counted.set(counted.get() + 1)
|
||||
})
|
||||
.detach()
|
||||
@@ -224,7 +224,7 @@ async fn with_the_preference_off_the_challenge_shows_and_the_match_is_listed(
|
||||
settle_tabs(&page, &mut window);
|
||||
|
||||
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
|
||||
assert_eq!(opened.get(), 0);
|
||||
assert_eq!(opened.get(), 1);
|
||||
// In the history all the same: « Parties » opened by hand chooses it, the most recent.
|
||||
switch_tab(&page, &mut window, Tab::Matches);
|
||||
its_recap(&page, cx).await;
|
||||
@@ -306,7 +306,7 @@ async fn a_game_that_ends_without_its_block_shows_the_challenge(cx: &mut TestApp
|
||||
game_ends_without_its_block(&page, &mut window, 9_000_000_022);
|
||||
settle_tabs(&page, &mut window);
|
||||
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
|
||||
assert_eq!(opened.get(), 0);
|
||||
assert_eq!(opened.get(), 2);
|
||||
left_alone(&mut window, true);
|
||||
}
|
||||
|
||||
|
||||
@@ -236,6 +236,26 @@ async fn the_details_are_not_kept_from_one_match_to_another(cx: &mut TestAppCont
|
||||
assert_eq!(unfolded(&page, &mut window), None);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn opening_the_screen_centers_the_displayed_accounts_row(cx: &mut TestAppContext) {
|
||||
use gpui_kit::{px, size};
|
||||
|
||||
let (page, mut window) = open_matches(cx).await;
|
||||
switch_tab(&page, &mut window, Tab::Challenge);
|
||||
let banner = window.debug_bounds("banner").unwrap().size.height;
|
||||
window.simulate_resize(size(px(1280.), banner + px(380.)));
|
||||
switch_tab(&page, &mut window, Tab::Matches);
|
||||
recap_ready(&page, cx).await;
|
||||
window.run_until_parked();
|
||||
draw(&mut window);
|
||||
let row = window.debug_bounds("recap-account").unwrap();
|
||||
let viewport = window.debug_bounds("recap-viewport").unwrap();
|
||||
assert!(
|
||||
(row.center().y - viewport.center().y).abs() < px(1.),
|
||||
"{row:?} in {viewport:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn choosing_a_match_centers_the_displayed_accounts_row(cx: &mut TestAppContext) {
|
||||
use gpui_kit::{px, size};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::import_view::wait_until;
|
||||
use super::{Page, RELOAD_EVERY, Tab};
|
||||
use crate::worker::{Msg, spawn_refresh};
|
||||
use gpui_kit::*;
|
||||
@@ -6,6 +7,8 @@ impl Page {
|
||||
pub(in crate::page) fn apply(&mut self, msg: Msg, window: &mut Window, cx: &mut Context<Self>) {
|
||||
match msg {
|
||||
Msg::Progress(progress) => {
|
||||
let now = cx.background_executor().now();
|
||||
self.import_view.own_until = wait_until(progress, now);
|
||||
self.progress = Some(progress);
|
||||
if self.last_reload.elapsed() >= RELOAD_EVERY {
|
||||
self.reload_in_background(window, cx);
|
||||
@@ -148,6 +151,7 @@ impl Page {
|
||||
self.mark_crashed();
|
||||
}
|
||||
}
|
||||
self.show_import(false, cx);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
|
||||
+32
-1
@@ -4,7 +4,7 @@
|
||||
//! two by Mastery Points (A to Z while the points are unknown, as the cards).
|
||||
//!
|
||||
//! A cached view (rule #1): laid out from the style its parent gives, drawn again only when its
|
||||
//! ticks or the lit one change, never by a hover or a scroll elsewhere.
|
||||
//! ticks, the lit one or the import's arc change, never by a hover or a scroll elsewhere.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::f32::consts::{FRAC_PI_2, TAU};
|
||||
@@ -18,6 +18,7 @@ use crate::motion::{MATCH_SETTLE, MatchAnimation, MatchEnd, ease_out};
|
||||
use crate::theme::{ring_never, ring_played};
|
||||
|
||||
mod aim;
|
||||
mod arc;
|
||||
mod ticks;
|
||||
pub use ticks::{Tick, ticks};
|
||||
|
||||
@@ -185,8 +186,12 @@ pub struct Ring {
|
||||
ticks: Rc<[Tick]>,
|
||||
/// The champion whose card is under the pointer.
|
||||
lit: Option<u32>,
|
||||
/// The import of the Account shown, as (fetched, to fetch): its arc is drawn around the ticks.
|
||||
progress: Option<(usize, usize)>,
|
||||
/// Made by the paint, for its size; forgotten with the ticks.
|
||||
geometry: Rc<RefCell<Option<Geometry>>>,
|
||||
/// The arc's paths, made by the paint for its size and progress.
|
||||
arc: Rc<RefCell<arc::Cache>>,
|
||||
/// How many times it was drawn: the tests check it stays light.
|
||||
#[cfg(test)]
|
||||
pub(crate) renders: usize,
|
||||
@@ -201,7 +206,9 @@ impl Ring {
|
||||
ticks: Rc::new([]),
|
||||
anvil: None,
|
||||
lit: None,
|
||||
progress: None,
|
||||
geometry: Rc::default(),
|
||||
arc: Rc::default(),
|
||||
#[cfg(test)]
|
||||
renders: 0,
|
||||
#[cfg(test)]
|
||||
@@ -255,6 +262,14 @@ impl Ring {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the import's arc, or none; the ring is drawn again only when it changes.
|
||||
pub fn set_progress(&mut self, progress: Option<(usize, usize)>, cx: &mut Context<Self>) {
|
||||
if self.progress != progress {
|
||||
self.progress = progress;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn ticks(&self) -> &[Tick] {
|
||||
&self.ticks
|
||||
@@ -265,6 +280,11 @@ impl Ring {
|
||||
self.anvil.as_deref()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn progress(&self) -> Option<(usize, usize)> {
|
||||
self.progress
|
||||
}
|
||||
|
||||
pub(crate) fn lit(&self) -> Option<u32> {
|
||||
self.lit
|
||||
}
|
||||
@@ -401,8 +421,10 @@ impl Render for Ring {
|
||||
]
|
||||
.map(|state| (state, color(state)));
|
||||
let (disc, crown, lit_color) = (theme.background, theme.primary, theme.foreground);
|
||||
let (progress, rest) = (self.progress, ring_never(theme));
|
||||
let ticks = self.ticks.clone();
|
||||
let geometry = self.geometry.clone();
|
||||
let arcs = self.arc.clone();
|
||||
let anvil = self.anvil.clone();
|
||||
#[cfg(test)]
|
||||
let tessellations = self.tessellations.clone();
|
||||
@@ -439,6 +461,15 @@ impl Render for Ring {
|
||||
if let Some(path) = &geometry.crown {
|
||||
window.paint_path(moved(path, bounds.origin), crown);
|
||||
}
|
||||
let mut arcs = arcs.borrow_mut();
|
||||
if !arcs.fits(bounds.size, progress) {
|
||||
#[cfg(test)]
|
||||
if progress.is_some() {
|
||||
tessellations.set(tessellations.get() + 1);
|
||||
}
|
||||
arcs.remake(bounds.size, progress);
|
||||
}
|
||||
arcs.paint(bounds.origin, (rest, crown), window);
|
||||
// Only the lit tick is tessellated when the pointer changes card.
|
||||
if let Some((index, state)) = lit {
|
||||
let mut path = PathBuilder::fill();
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! The import's arc (#140): a thin circle outside the ticks, its done part from noon clockwise.
|
||||
//! Pure geometry, in the ring's SVG units.
|
||||
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
use gpui_kit::*;
|
||||
|
||||
use super::{C, Frame, moved};
|
||||
|
||||
/// Just outside the ticks, which end at `R2`.
|
||||
const RADIUS: f32 = 256.;
|
||||
const WIDTH: f32 = 3.;
|
||||
/// Segments of a full turn.
|
||||
const STEPS: f32 = 120.;
|
||||
|
||||
/// How much of the import is done, from 0 to 1.
|
||||
pub(super) fn fraction(fetched: usize, to_fetch: usize) -> f32 {
|
||||
if to_fetch == 0 {
|
||||
return 0.;
|
||||
}
|
||||
(fetched as f32 / to_fetch as f32).clamp(0., 1.)
|
||||
}
|
||||
|
||||
/// The polyline of the first `fraction` of the turn: from noon, clockwise. Empty for nothing.
|
||||
pub(super) fn points(fraction: f32) -> Vec<(f32, f32)> {
|
||||
let sweep = fraction.clamp(0., 1.) * TAU;
|
||||
if sweep == 0. {
|
||||
return Vec::new();
|
||||
}
|
||||
let steps = (sweep / TAU * STEPS).ceil();
|
||||
(0..=steps as usize)
|
||||
.map(|i| {
|
||||
let angle = sweep * i as f32 / steps;
|
||||
(C + RADIUS * angle.sin(), C - RADIUS * angle.cos())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The arc's paths, made at the origin and moved where the ring is painted: the circle for a
|
||||
/// size, the part done for a progress, so a paint for the same ones tessellates nothing.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Cache {
|
||||
size: Size<Pixels>,
|
||||
progress: Option<(usize, usize)>,
|
||||
rest: Option<Path<Pixels>>,
|
||||
done: Option<Path<Pixels>>,
|
||||
}
|
||||
|
||||
/// The polyline of the first `fraction` of the turn, stroked in `frame`.
|
||||
fn stroke(frame: Frame, fraction: f32) -> Option<Path<Pixels>> {
|
||||
let mut points = points(fraction).into_iter().map(|(x, y)| frame.point(x, y));
|
||||
let mut stroke = PathBuilder::stroke(px(WIDTH * frame.scale));
|
||||
stroke.move_to(points.next()?);
|
||||
for at in points {
|
||||
stroke.line_to(at);
|
||||
}
|
||||
stroke.build().ok()
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
/// Whether what is held is what `progress` in `size` needs.
|
||||
pub(super) fn fits(&self, size: Size<Pixels>, progress: Option<(usize, usize)>) -> bool {
|
||||
self.progress == progress && (progress.is_none() || self.size == size)
|
||||
}
|
||||
|
||||
/// Makes the paths for `progress` in `size`, or lets go of them without progress.
|
||||
pub(super) fn remake(&mut self, size: Size<Pixels>, progress: Option<(usize, usize)>) {
|
||||
let Some((fetched, to_fetch)) = progress else {
|
||||
*self = Cache::default();
|
||||
return;
|
||||
};
|
||||
let frame = Frame::of(Bounds {
|
||||
origin: Point::default(),
|
||||
size,
|
||||
});
|
||||
if self.size != size || self.rest.is_none() {
|
||||
self.rest = stroke(frame, 1.);
|
||||
}
|
||||
self.done = stroke(frame, fraction(fetched, to_fetch));
|
||||
(self.size, self.progress) = (size, progress);
|
||||
}
|
||||
|
||||
/// Paints the whole circle in `rest`, then the part done in `done`.
|
||||
pub(super) fn paint(
|
||||
&self,
|
||||
origin: Point<Pixels>,
|
||||
(rest, done): (Hsla, Hsla),
|
||||
window: &mut Window,
|
||||
) {
|
||||
for (path, color) in [(&self.rest, rest), (&self.done, done)] {
|
||||
if let Some(path) = path {
|
||||
window.paint_path(moved(path, origin), color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{C, RADIUS, WIDTH, fraction, points};
|
||||
use crate::ring::{R2, shape};
|
||||
use arena_tracker_core::ChampionState;
|
||||
|
||||
fn near(a: (f32, f32), b: (f32, f32)) -> bool {
|
||||
(a.0 - b.0).abs() < 0.01 && (a.1 - b.1).abs() < 0.01
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arc_starts_at_noon_and_turns_clockwise() {
|
||||
let quarter = points(0.25);
|
||||
assert!(near(quarter[0], (C, C - RADIUS)));
|
||||
assert!(near(*quarter.last().unwrap(), (C + RADIUS, C)));
|
||||
assert!(near(*points(0.5).last().unwrap(), (C, C + RADIUS)));
|
||||
// A full turn closes on noon.
|
||||
let circle = points(1.);
|
||||
assert!(near(circle[0], *circle.last().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_done_draws_no_arc_and_the_fraction_is_clamped() {
|
||||
assert!(points(0.).is_empty() && points(-1.).is_empty());
|
||||
assert_eq!(points(7.), points(1.));
|
||||
assert_eq!(fraction(0, 12), 0.);
|
||||
assert_eq!(fraction(3, 12), 0.25);
|
||||
assert_eq!(fraction(20, 12), 1.);
|
||||
assert_eq!(fraction(5, 0), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arc_lies_just_outside_the_ticks() {
|
||||
let outermost = [
|
||||
ChampionState::Completed,
|
||||
ChampionState::InProgress,
|
||||
ChampionState::NeverPlayed,
|
||||
]
|
||||
.map(|state| shape(state).1)
|
||||
.into_iter()
|
||||
.fold(R2, f32::max);
|
||||
assert!(RADIUS - WIDTH / 2. > outermost);
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,8 @@ const CHANNELS: [(UpdateChannel, &str); 2] = [
|
||||
];
|
||||
const LOGON_LABEL: &str = "Lancer à l’ouverture de session Windows";
|
||||
const RECAP_LABEL: &str = "Ouvrir le récapitulatif en fin de Partie";
|
||||
const RECAP_HINT: &str = "À la fin d’une Partie Arena, « Parties » l’affiche, sans mettre la fenêtre \
|
||||
au premier plan. Désactivé, le Défi reste affiché.";
|
||||
const RECAP_HINT: &str = "À la fin d’une Partie Arena, « Parties » l’affiche et la fenêtre passe \
|
||||
au premier plan. Désactivé, le Défi s’affiche.";
|
||||
// Not « Disponible »: the interface word of a Pickable champion (CONTEXT.md).
|
||||
const LOGON_UNAVAILABLE: &str = "Réservé à la version installée.";
|
||||
|
||||
|
||||
+6
-10
@@ -4,10 +4,10 @@ use std::sync::Arc;
|
||||
use arena_tracker_core::{ChampionSort, Config, Preferences, RiotApi, Tracker, UpdateChannel};
|
||||
use gpui_kit::{
|
||||
AppContext as _, Entity, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext,
|
||||
VisualTestContext, WindowOptions, WindowVisibility, point,
|
||||
VisualTestContext, WindowOptions, point,
|
||||
};
|
||||
|
||||
use super::{LiveMatchStarted, RecapOpened, RootView, Screen, SettingsStore, Setup};
|
||||
use super::{LiveMatchStarted, MatchEndShown, RootView, Screen, SettingsStore, Setup};
|
||||
use crate::card_images::tests::TestDir;
|
||||
use crate::title_bar::{BAR_HEIGHT, BUTTON_WIDTH};
|
||||
use crate::worker::UpdateChecked;
|
||||
@@ -129,24 +129,20 @@ fn the_chosen_sort_is_saved_with_the_preferences_and_found_again_at_the_next_lau
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_end_of_a_match_closes_the_settings_and_leaves_the_window_as_it_is(cx: &mut TestAppContext) {
|
||||
fn the_end_of_a_game_closes_the_settings_without_activating_the_window(cx: &mut TestAppContext) {
|
||||
let dir = TestDir::new("recap-129");
|
||||
let (mut window, root) = open_app(cx, &dir.path().join("config.toml"), Config::load_or_default);
|
||||
let cx = &mut window;
|
||||
cx.update(|window, cx| root.update(cx, |root, cx| root.open_settings(window, cx)));
|
||||
// In League, the window hidden in the notification area.
|
||||
// In League: the game has the keyboard.
|
||||
cx.deactivate_window();
|
||||
cx.simulate_visibility_change(WindowVisibility::Hidden);
|
||||
|
||||
let page = root.read_with(cx, |root, _| root.page.clone());
|
||||
page.update(cx, |_, cx| cx.emit(RecapOpened));
|
||||
page.update(cx, |_, cx| cx.emit(MatchEndShown));
|
||||
cx.run_until_parked();
|
||||
|
||||
assert!(root.read_with(cx, |root, _| root.screen == Screen::Page));
|
||||
cx.update(|window, cx| {
|
||||
assert_eq!(cx.active_window(), None, "the window was activated");
|
||||
assert!(!window.is_visible(), "the window was shown");
|
||||
});
|
||||
cx.update(|_, cx| assert_eq!(cx.active_window(), None, "the window was activated"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
||||
@@ -135,6 +135,11 @@ pub fn friend_sync_line(name: &str, progress: Option<SyncProgress>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status line while the import waits for the Riot quota, `secs` left.
|
||||
pub fn quota_line(secs: u64) -> String {
|
||||
format!("Quota Riot atteint : reprise dans {secs} s")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -229,6 +234,7 @@ mod tests {
|
||||
let progress = SyncProgress {
|
||||
fetched: 3,
|
||||
to_fetch: 10,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
friend_sync_line("Bob", Some(progress)),
|
||||
@@ -237,11 +243,18 @@ mod tests {
|
||||
assert_eq!(friend_sync_line("Bob", None), "Import de Bob…");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_quota_line_counts_the_seconds_left() {
|
||||
assert_eq!(quota_line(12), "Quota Riot atteint : reprise dans 12 s");
|
||||
assert_eq!(quota_line(1), "Quota Riot atteint : reprise dans 1 s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sync_line_follows_what_is_running() {
|
||||
let progress = SyncProgress {
|
||||
fetched: 3,
|
||||
to_fetch: 10,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
sync_line(true, Some(progress), false, Some(5)),
|
||||
@@ -254,6 +267,7 @@ mod tests {
|
||||
let nothing = SyncProgress {
|
||||
fetched: 0,
|
||||
to_fetch: 0,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
sync_line(true, Some(nothing), false, Some(5)),
|
||||
|
||||
@@ -23,11 +23,14 @@ pub fn spawn_friend_import(tracker: Arc<Tracker>, puuid: String, tx: Sender<Msg>
|
||||
let mut last = None;
|
||||
let result = tracker.import_friend(&puuid, &mut |progress| {
|
||||
let now = std::time::Instant::now();
|
||||
if last.is_some_and(|last| now.duration_since(last) < std::time::Duration::from_secs(1))
|
||||
{
|
||||
// The start and the end of a quota wait always pass.
|
||||
if last.is_some_and(|(at, wait): (_, Option<_>)| {
|
||||
wait == progress.quota_wait
|
||||
&& now.duration_since(at) < std::time::Duration::from_secs(1)
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
last = Some(now);
|
||||
last = Some((now, progress.quota_wait));
|
||||
let _ = tx.try_send(Msg::FriendProgress {
|
||||
puuid: puuid.clone(),
|
||||
progress,
|
||||
|
||||
@@ -121,6 +121,14 @@ impl Follow {
|
||||
self.blocks_synced = true;
|
||||
}
|
||||
|
||||
/// The Account's PUUID changed (`tracker/rekey.rs`): what the session holds follows it.
|
||||
pub(crate) fn rekey(&mut self, old: &str, new: &str) {
|
||||
if let Some(a) = self.updating.as_mut().filter(|a| a.puuid == old) {
|
||||
a.puuid = new.into();
|
||||
}
|
||||
self.watches.iter_mut().for_each(|w| w.rekey(old, new));
|
||||
}
|
||||
|
||||
/// The Account was deleted: nothing of it stays to keep its Riot ID from being adopted
|
||||
/// again (with a full import) or its Matches from being stored again.
|
||||
pub(crate) fn forget(&mut self, account: &Account) {
|
||||
|
||||
@@ -16,6 +16,12 @@ impl Watch {
|
||||
pub(super) fn is_of(&self, puuid: &str) -> bool {
|
||||
self.puuid == puuid
|
||||
}
|
||||
|
||||
pub(super) fn rekey(&mut self, old: &str, new: &str) {
|
||||
if self.puuid == old {
|
||||
self.puuid = new.into();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
|
||||
@@ -106,10 +106,12 @@ pub struct FollowedMatch {
|
||||
pub end: MatchEnd,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SyncProgress {
|
||||
pub fetched: usize,
|
||||
pub to_fetch: usize,
|
||||
/// Set while the import waits for the Riot quota: how long from now.
|
||||
pub quota_wait: Option<std::time::Duration>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
||||
+31
-83
@@ -5,21 +5,24 @@ mod deletion;
|
||||
mod directory;
|
||||
pub use directory::AccountDirectory;
|
||||
mod friends;
|
||||
mod import;
|
||||
mod mastery;
|
||||
mod payload;
|
||||
mod provisional;
|
||||
mod rekey;
|
||||
mod storage;
|
||||
|
||||
pub(crate) use blocks::StoredBlock;
|
||||
pub use deletion::AccountSummary;
|
||||
pub use friends::{AddFriendError, AddedFriend};
|
||||
use payload::decode_match;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::Range;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use storage::store_match;
|
||||
|
||||
use rusqlite::{Connection, OptionalExtension, Row, params};
|
||||
@@ -32,8 +35,6 @@ use crate::follow::Follow;
|
||||
use crate::model::{Account, Format, Match, SyncProgress, SyncReport};
|
||||
use crate::seasons::{Season, default_seasons};
|
||||
|
||||
/// Arena queues Riot lists Matches under (the PBE queue 1704 is left out on purpose).
|
||||
const QUEUES: [u32; 4] = [1700, 1710, 1740, 1750];
|
||||
const PAGE_SIZE: usize = 100;
|
||||
/// A Match is published when the whole game ends, so one that started before the newest
|
||||
/// stored Match (a player eliminated early who queued again) can show up later.
|
||||
@@ -57,6 +58,8 @@ pub struct Tracker {
|
||||
corrections: AtomicUsize,
|
||||
/// Captured before selecting an account. A later deletion invalidates an in-flight lookup.
|
||||
deletions: AtomicUsize,
|
||||
/// The PUUIDs replaced since the tracker opened, old to new (`replaced_puuid`).
|
||||
replaced: Mutex<HashMap<String, String>>,
|
||||
/// Followed Matches whose Death Recap is to be fetched, for the app's background thread.
|
||||
pub(crate) death_recaps: DeathRecapQueue,
|
||||
}
|
||||
@@ -77,6 +80,7 @@ impl Tracker {
|
||||
sync_lock: Mutex::new(()),
|
||||
corrections: AtomicUsize::new(0),
|
||||
deletions: AtomicUsize::new(0),
|
||||
replaced: Mutex::default(),
|
||||
death_recaps: DeathRecapQueue::default(),
|
||||
})
|
||||
}
|
||||
@@ -108,8 +112,13 @@ impl Tracker {
|
||||
let (game_name, tag_line) =
|
||||
split_riot_id(riot_id).ok_or_else(|| Error::InvalidRiotId(riot_id.into()))?;
|
||||
log::info!("Sync of {riot_id} started");
|
||||
let account = with_retry(|| self.history.resolve_account(game_name, tag_line))?;
|
||||
// shortcut: Riot API puuids are scoped to the key's application, so the same Riot ID under the relay's production key becomes a second Account; merging them safely needs proof of identity (#150).
|
||||
let account = import::told(SyncProgress::default(), on_progress, |on_wait| {
|
||||
with_retry_told(
|
||||
|| self.history.resolve_account(game_name, tag_line),
|
||||
on_wait,
|
||||
)
|
||||
})?;
|
||||
self.rekey(&account, &|| {})?;
|
||||
{
|
||||
let db = self.db();
|
||||
if self.deletion_count() != deletions
|
||||
@@ -153,7 +162,7 @@ impl Tracker {
|
||||
/// A Match Riot does not have or that cannot be read is skipped rather than failing the
|
||||
/// caller: one bad id must not block the rest.
|
||||
pub(crate) fn fetch_and_store(&self, puuid: &str, match_id: &str) -> Result<Fetched, Error> {
|
||||
self.fetch_match_when(puuid, match_id, &|| {})
|
||||
self.fetch_match_when(puuid, match_id, &|| {}, &mut |_| {})
|
||||
}
|
||||
|
||||
fn fetch_match_when(
|
||||
@@ -161,8 +170,10 @@ impl Tracker {
|
||||
puuid: &str,
|
||||
match_id: &str,
|
||||
before_send: &dyn Fn(),
|
||||
on_wait: &mut dyn FnMut(Duration),
|
||||
) -> Result<Fetched, Error> {
|
||||
let raw = match with_retry(|| self.history.fetch_match_when(match_id, before_send)) {
|
||||
let fetch = || self.history.fetch_match_when(match_id, before_send);
|
||||
let raw = match with_retry_told(fetch, on_wait) {
|
||||
Ok(raw) => raw,
|
||||
Err(SourceError::NotFound) => return Ok(Fetched::NotFound),
|
||||
Err(e) => return Err(e.into()),
|
||||
@@ -314,7 +325,7 @@ impl Tracker {
|
||||
}
|
||||
|
||||
/// The ids of the Account's published Matches.
|
||||
fn match_ids_stored(&self, puuid: &str) -> Result<HashSet<String>, Error> {
|
||||
pub(super) fn match_ids_stored(&self, puuid: &str) -> Result<HashSet<String>, Error> {
|
||||
let db = self.db();
|
||||
let mut stmt =
|
||||
db.prepare("SELECT match_id FROM matches WHERE puuid = ?1 AND provisional = 0")?;
|
||||
@@ -323,80 +334,6 @@ impl Tracker {
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Downloads each missing Match once across the ordered listing steps.
|
||||
fn import_matches(
|
||||
&self,
|
||||
puuid: &str,
|
||||
steps: impl IntoIterator<Item = Option<i64>>,
|
||||
friend_gate: Option<&dyn Fn()>,
|
||||
on_progress: &mut dyn FnMut(SyncProgress),
|
||||
) -> Result<usize, Error> {
|
||||
let before_send = friend_gate.unwrap_or(&|| {});
|
||||
let friend = friend_gate.is_some();
|
||||
let mut known = self.match_ids_stored(puuid)?;
|
||||
let mut progress = SyncProgress {
|
||||
fetched: 0,
|
||||
to_fetch: 0,
|
||||
};
|
||||
let mut added = 0;
|
||||
for (step, since_s) in steps.into_iter().enumerate() {
|
||||
let mut to_fetch = self.list_match_ids(puuid, since_s, friend_gate)?;
|
||||
if step == 0 {
|
||||
// Looked for until Riot publishes them, like a sync does.
|
||||
to_fetch.extend(self.provisional_ids(puuid)?);
|
||||
}
|
||||
to_fetch.retain(|id| known.insert(id.clone()));
|
||||
progress.to_fetch += to_fetch.len();
|
||||
on_progress(progress);
|
||||
for match_id in &to_fetch {
|
||||
if friend {
|
||||
self.stored_account(puuid)?;
|
||||
}
|
||||
if self.fetch_match_when(puuid, match_id, before_send)? == Fetched::Added {
|
||||
added += 1;
|
||||
}
|
||||
progress.fetched += 1;
|
||||
on_progress(progress);
|
||||
}
|
||||
}
|
||||
Ok(added)
|
||||
}
|
||||
|
||||
/// Lists every queue, yielding to higher-priority requests at each dispatch.
|
||||
fn list_match_ids(
|
||||
&self,
|
||||
puuid: &str,
|
||||
since_s: Option<i64>,
|
||||
friend_gate: Option<&dyn Fn()>,
|
||||
) -> Result<Vec<String>, Error> {
|
||||
let mut ids = Vec::new();
|
||||
for queue_id in QUEUES {
|
||||
let mut start = 0;
|
||||
loop {
|
||||
if friend_gate.is_some() {
|
||||
self.stored_account(puuid)?;
|
||||
}
|
||||
let page = with_retry(|| {
|
||||
self.history.match_ids_when(
|
||||
puuid,
|
||||
queue_id,
|
||||
start,
|
||||
PAGE_SIZE,
|
||||
since_s,
|
||||
friend_gate.unwrap_or(&|| {}),
|
||||
)
|
||||
})?;
|
||||
let full_page = page.len() == PAGE_SIZE;
|
||||
ids.extend(page);
|
||||
if !full_page {
|
||||
break;
|
||||
}
|
||||
start += PAGE_SIZE;
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn account_from_row(row: &Row) -> rusqlite::Result<Account> {
|
||||
@@ -455,11 +392,22 @@ pub(crate) enum Fetched {
|
||||
/// quota frees up in time, and an import must not stop for it. The source bounds each wait
|
||||
/// (at least a second, at most ten minutes, see `SourceError::RateLimited`).
|
||||
pub(crate) fn with_retry<T>(
|
||||
call: impl FnMut() -> Result<T, SourceError>,
|
||||
) -> Result<T, SourceError> {
|
||||
with_retry_told(call, &mut |_| {})
|
||||
}
|
||||
|
||||
/// `with_retry` that tells each wait to `on_wait` before sleeping it.
|
||||
pub(crate) fn with_retry_told<T>(
|
||||
mut call: impl FnMut() -> Result<T, SourceError>,
|
||||
on_wait: &mut dyn FnMut(Duration),
|
||||
) -> Result<T, SourceError> {
|
||||
loop {
|
||||
match call() {
|
||||
Err(SourceError::RateLimited { retry_after }) => thread::sleep(retry_after),
|
||||
Err(SourceError::RateLimited { retry_after }) => {
|
||||
on_wait(retry_after);
|
||||
thread::sleep(retry_after);
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
|
||||
use rusqlite::{OptionalExtension, params};
|
||||
|
||||
use super::{OVERLAP_S, Tracker, account_from_row, split_riot_id, with_retry};
|
||||
use super::import::told;
|
||||
use super::{OVERLAP_S, Tracker, account_from_row, split_riot_id, with_retry, with_retry_told};
|
||||
use crate::error::{Error, SourceError};
|
||||
use crate::follow::{UpdateProblem, account_riot_id, riot_id, same_riot_id, wall_clock_ms};
|
||||
use crate::model::{Account, SyncProgress, SyncReport};
|
||||
@@ -142,6 +143,8 @@ impl Tracker {
|
||||
/// Challenge fills meanwhile. `on_progress` counts the Matches of the whole call: its
|
||||
/// `to_fetch` grows when the older Matches are listed.
|
||||
///
|
||||
/// A new Riot key may have changed its PUUID: that is looked at first (`rekey.rs`).
|
||||
///
|
||||
/// Each request waits for the active Account's (a round, a refresh, a finished game's
|
||||
/// Match not published yet); the relay keeps both within the quota. Blocks
|
||||
/// for long: call it from a low-priority background thread, never the follower's. Fails
|
||||
@@ -151,7 +154,28 @@ impl Tracker {
|
||||
puuid: &str,
|
||||
on_progress: &mut dyn FnMut(SyncProgress),
|
||||
) -> Result<SyncReport, Error> {
|
||||
let account = self.stored_account(puuid)?;
|
||||
let gate = || self.wait_for_follower();
|
||||
let mut account = self.stored_account(puuid)?;
|
||||
// Before any request that carries the stored PUUID: a new key may have changed it.
|
||||
let resolved = told(SyncProgress::default(), on_progress, |on_wait| {
|
||||
let resolve = || {
|
||||
gate();
|
||||
(self.history).resolve_account(&account.game_name, &account.tag_line)
|
||||
};
|
||||
with_retry_told(resolve, on_wait)
|
||||
});
|
||||
match resolved {
|
||||
Ok(resolved) if resolved.puuid != account.puuid => {
|
||||
self.rekey(&resolved, &gate)?;
|
||||
// Without proof nothing moved: the requested Account stays.
|
||||
let current = self.replaced_puuid(puuid);
|
||||
account = self.stored_account(current.as_deref().unwrap_or(puuid))?;
|
||||
}
|
||||
// The Riot ID changed: nothing tells the PUUID changed too.
|
||||
Ok(_) | Err(SourceError::NotFound) => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
let puuid = account.puuid.as_str();
|
||||
let who = account_riot_id(&account);
|
||||
log::info!("Import of {who} started");
|
||||
let steps = match self.synced_until_ms(puuid)? {
|
||||
@@ -162,7 +186,6 @@ impl Tracker {
|
||||
season_start.into_iter().map(Some).chain([None]).collect()
|
||||
}
|
||||
};
|
||||
let gate = || self.wait_for_follower();
|
||||
let added = self.import_matches(puuid, steps, Some(&gate), on_progress)?;
|
||||
self.mark_synced(puuid)?;
|
||||
self.stored_account(puuid)?;
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! The import of an Account's Matches: listing what is missing, then fetching each Match.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use super::{Fetched, PAGE_SIZE, Tracker, with_retry_told};
|
||||
use crate::error::Error;
|
||||
use crate::model::SyncProgress;
|
||||
|
||||
/// Arena queues Riot lists Matches under (the PBE queue 1704 is left out on purpose).
|
||||
const QUEUES: [u32; 4] = [1700, 1710, 1740, 1750];
|
||||
|
||||
/// Runs one request of an import: each Riot quota wait it tells is reported as `progress` with
|
||||
/// the wait, and the import line comes back (`progress` alone) once the request has answered.
|
||||
pub(super) fn told<T>(
|
||||
progress: SyncProgress,
|
||||
on_progress: &mut dyn FnMut(SyncProgress),
|
||||
request: impl FnOnce(&mut dyn FnMut(Duration)) -> T,
|
||||
) -> T {
|
||||
let mut waited = false;
|
||||
let result = request(&mut |wait| {
|
||||
waited = true;
|
||||
on_progress(SyncProgress {
|
||||
quota_wait: Some(wait),
|
||||
..progress
|
||||
});
|
||||
});
|
||||
if waited {
|
||||
on_progress(progress);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
/// Downloads each missing Match once across the ordered listing steps.
|
||||
pub(super) fn import_matches(
|
||||
&self,
|
||||
puuid: &str,
|
||||
steps: impl IntoIterator<Item = Option<i64>>,
|
||||
friend_gate: Option<&dyn Fn()>,
|
||||
on_progress: &mut dyn FnMut(SyncProgress),
|
||||
) -> Result<usize, Error> {
|
||||
let before_send = friend_gate.unwrap_or(&|| {});
|
||||
let friend = friend_gate.is_some();
|
||||
let mut known = self.match_ids_stored(puuid)?;
|
||||
let mut progress = SyncProgress::default();
|
||||
let mut added = 0;
|
||||
for (step, since_s) in steps.into_iter().enumerate() {
|
||||
let mut to_fetch =
|
||||
self.list_match_ids(puuid, since_s, friend_gate, progress, on_progress)?;
|
||||
if step == 0 {
|
||||
// Looked for until Riot publishes them, like a sync does.
|
||||
to_fetch.extend(self.provisional_ids(puuid)?);
|
||||
}
|
||||
to_fetch.retain(|id| known.insert(id.clone()));
|
||||
progress.to_fetch += to_fetch.len();
|
||||
on_progress(progress);
|
||||
for match_id in &to_fetch {
|
||||
if friend {
|
||||
self.stored_account(puuid)?;
|
||||
}
|
||||
let fetched = told(progress, on_progress, |on_wait| {
|
||||
self.fetch_match_when(puuid, match_id, before_send, on_wait)
|
||||
})?;
|
||||
if fetched == Fetched::Added {
|
||||
added += 1;
|
||||
}
|
||||
progress.fetched += 1;
|
||||
on_progress(progress);
|
||||
}
|
||||
}
|
||||
Ok(added)
|
||||
}
|
||||
|
||||
/// Lists every queue, yielding to higher-priority requests at each dispatch.
|
||||
fn list_match_ids(
|
||||
&self,
|
||||
puuid: &str,
|
||||
since_s: Option<i64>,
|
||||
friend_gate: Option<&dyn Fn()>,
|
||||
progress: SyncProgress,
|
||||
on_progress: &mut dyn FnMut(SyncProgress),
|
||||
) -> Result<Vec<String>, Error> {
|
||||
let mut ids = Vec::new();
|
||||
for queue_id in QUEUES {
|
||||
let mut start = 0;
|
||||
loop {
|
||||
if friend_gate.is_some() {
|
||||
self.stored_account(puuid)?;
|
||||
}
|
||||
let page = told(progress, on_progress, |on_wait| {
|
||||
let list = || {
|
||||
self.history.match_ids_when(
|
||||
puuid,
|
||||
queue_id,
|
||||
start,
|
||||
PAGE_SIZE,
|
||||
since_s,
|
||||
friend_gate.unwrap_or(&|| {}),
|
||||
)
|
||||
};
|
||||
with_retry_told(list, on_wait)
|
||||
})?;
|
||||
let full_page = page.len() == PAGE_SIZE;
|
||||
ids.extend(page);
|
||||
if !full_page {
|
||||
break;
|
||||
}
|
||||
start += PAGE_SIZE;
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
//! Follows an Account when its PUUID changes: a PUUID depends on the Riot application of the
|
||||
//! API key, so a new key gives every Account another one for the same Riot ID (#150). A stored
|
||||
//! Account takes the new PUUID only on proof that it is the same Account, never on the Riot ID
|
||||
//! alone (a Friend may have been renamed, its name taken by someone else); without proof
|
||||
//! nothing changes.
|
||||
|
||||
use rusqlite::{OptionalExtension, params};
|
||||
|
||||
use super::{
|
||||
OVERLAP_S, PAGE_SIZE, Tracker, friends::platform_key, mastery::mastery_key,
|
||||
payload::decode_match, synced_until_key, with_retry,
|
||||
};
|
||||
use crate::error::{Error, SourceError};
|
||||
use crate::follow::{account_riot_id, same_riot_id};
|
||||
use crate::journal::short;
|
||||
use crate::model::Account;
|
||||
|
||||
impl Tracker {
|
||||
/// The PUUID that replaced this one since the tracker opened: the app uses it to keep
|
||||
/// showing the same Account.
|
||||
pub fn replaced_puuid(&self, puuid: &str) -> Option<String> {
|
||||
let replaced = self.replaced.lock().unwrap_or_else(|e| e.into_inner());
|
||||
replaced.get(puuid).cloned()
|
||||
}
|
||||
|
||||
/// Moves every stored Account with the Riot ID of `resolved` (what Riot answers now) to its
|
||||
/// PUUID, when the proof holds (`is_same_account`). `gate` runs before each request of it.
|
||||
pub(super) fn rekey(&self, resolved: &Account, gate: &dyn Fn()) -> Result<(), Error> {
|
||||
let riot_id = account_riot_id(resolved);
|
||||
let stored = self.account_directory();
|
||||
let stale = (stored.accounts.iter())
|
||||
.filter(|a| a.puuid != resolved.puuid && same_riot_id(&account_riot_id(a), &riot_id));
|
||||
for old in stale {
|
||||
if self.is_same_account(&old.puuid, &resolved.puuid, gate)? {
|
||||
self.move_puuid(&old.puuid, resolved)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a published Match stored for `old` is listed for `new` too, and `new` has the
|
||||
/// same champion and Placement in it: anyone who shared the Match would pass the first, and
|
||||
/// (champion, Placement) names one participant of an Arena Match (a Placement is a team's,
|
||||
/// a champion is unique within a team).
|
||||
fn is_same_account(&self, old: &str, new: &str, gate: &dyn Fn()) -> Result<bool, Error> {
|
||||
let newest: Option<(u32, i64)> = self
|
||||
.db()
|
||||
.query_row(
|
||||
"SELECT queue_id, started_at_ms FROM matches
|
||||
WHERE puuid = ?1 AND provisional = 0 ORDER BY started_at_ms DESC LIMIT 1",
|
||||
[old],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((queue_id, started_at_ms)) = newest else {
|
||||
return Ok(false);
|
||||
};
|
||||
// shortcut: one page (the 100 newest Matches of that queue since the stored one), so an Account not synced for more than 100 Matches of one queue stays unproven; page through if that ever happens.
|
||||
let listed = with_retry(|| {
|
||||
let since_s = Some(started_at_ms / 1000 - OVERLAP_S);
|
||||
(self.history).match_ids_when(new, queue_id, 0, PAGE_SIZE, since_s, gate)
|
||||
})?;
|
||||
let stored = self.match_ids_stored(old)?;
|
||||
let Some(id) = listed.into_iter().find(|id| stored.contains(id)) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let raw = match with_retry(|| self.history.fetch_match_when(&id, gate)) {
|
||||
Ok(raw) => raw,
|
||||
Err(SourceError::NotFound) => return Ok(false),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let Ok(Some((played, _))) = decode_match(&raw, new) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let kept = self.stored_match(old, &id)?;
|
||||
Ok(kept.is_some_and(|m| {
|
||||
(m.champion_id, m.placement) == (played.champion_id, played.placement)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Replaces the PUUID everywhere in one transaction; a new PUUID already stored is merged,
|
||||
/// its own marks and published Matches winning.
|
||||
fn move_puuid(&self, old: &str, resolved: &Account) -> Result<(), Error> {
|
||||
let new = resolved.puuid.as_str();
|
||||
let mut db = self.db();
|
||||
let tx = db.transaction()?;
|
||||
// Another caller may have moved it already, or it was deleted during the proof.
|
||||
if !(tx.prepare("SELECT 1 FROM accounts WHERE puuid = ?1")?).exists([old])? {
|
||||
return Ok(());
|
||||
}
|
||||
for sql in [
|
||||
"DELETE FROM matches WHERE puuid = ?2 AND provisional = 1 AND match_id IN
|
||||
(SELECT match_id FROM matches WHERE puuid = ?1 AND provisional = 0)",
|
||||
"DELETE FROM matches WHERE puuid = ?1 AND match_id IN
|
||||
(SELECT match_id FROM matches WHERE puuid = ?2)",
|
||||
// The stored Riot responses name the Account's participant by PUUID (`match_recap` reads it).
|
||||
"UPDATE matches SET puuid = ?2, raw = replace(raw, ?1, ?2) WHERE puuid = ?1",
|
||||
"UPDATE OR IGNORE mastery SET puuid = ?2 WHERE puuid = ?1",
|
||||
"UPDATE meta SET value = ?2 WHERE name = 'last_active_puuid' AND value = ?1",
|
||||
] {
|
||||
tx.execute(sql, params![old, new])?;
|
||||
}
|
||||
tx.execute("DELETE FROM mastery WHERE puuid = ?1", [old])?;
|
||||
for key in [synced_until_key, mastery_key, platform_key] {
|
||||
let (from, to) = (key(old), key(new));
|
||||
tx.execute(
|
||||
"UPDATE OR IGNORE meta SET name = ?2 WHERE name = ?1",
|
||||
[&from, &to],
|
||||
)?;
|
||||
tx.execute("DELETE FROM meta WHERE name = ?1", [&from])?;
|
||||
}
|
||||
if tx
|
||||
.prepare("SELECT 1 FROM accounts WHERE puuid = ?1")?
|
||||
.exists([new])?
|
||||
{
|
||||
tx.execute(
|
||||
"UPDATE accounts SET friend = MAX(friend,
|
||||
(SELECT friend FROM accounts WHERE puuid = ?1)) WHERE puuid = ?2",
|
||||
params![old, new],
|
||||
)?;
|
||||
tx.execute("DELETE FROM accounts WHERE puuid = ?1", [old])?;
|
||||
} else {
|
||||
tx.execute(
|
||||
"UPDATE accounts SET puuid = ?2, game_name = ?3, tag_line = ?4 WHERE puuid = ?1",
|
||||
params![old, new, resolved.game_name, resolved.tag_line],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
self.refresh_directory(&db)?;
|
||||
self.follow().rekey(old, new);
|
||||
(self.replaced.lock().unwrap_or_else(|e| e.into_inner())).insert(old.into(), new.into());
|
||||
log::info!(
|
||||
"Account {} moved to another PUUID ({} to {})",
|
||||
account_riot_id(resolved),
|
||||
short(old),
|
||||
short(new)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::tracker::tests::NoHistory;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn moving_a_puuid_twice_or_one_not_stored_changes_nothing() {
|
||||
let tracker = Tracker::open(Path::new(":memory:"), Box::new(NoHistory)).unwrap();
|
||||
tracker
|
||||
.db()
|
||||
.execute(
|
||||
"INSERT INTO accounts (puuid, game_name, tag_line, friend) VALUES ('old', 'P', 'EUW', 1)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
let new = Account {
|
||||
puuid: "new".into(),
|
||||
game_name: "P".into(),
|
||||
tag_line: "EUW".into(),
|
||||
};
|
||||
|
||||
tracker.move_puuid("old", &new).unwrap();
|
||||
// Two callers proved the same change: the second finds nothing to move.
|
||||
tracker.move_puuid("old", &new).unwrap();
|
||||
tracker.move_puuid("never-stored", &new).unwrap();
|
||||
|
||||
assert_eq!(tracker.friends().unwrap(), [new]);
|
||||
assert_eq!(tracker.replaced_puuid("old").as_deref(), Some("new"));
|
||||
assert_eq!(tracker.replaced_puuid("never-stored"), None);
|
||||
}
|
||||
}
|
||||
@@ -152,7 +152,7 @@ fn a_database_of_the_previous_version_gains_the_provisional_flag_and_keeps_its_m
|
||||
assert_eq!(open().matches("p").unwrap(), matches);
|
||||
}
|
||||
|
||||
struct NoHistory;
|
||||
pub(super) struct NoHistory;
|
||||
|
||||
impl MatchHistorySource for NoHistory {
|
||||
fn resolve_account(&self, _: &str, _: &str) -> Result<Account, SourceError> {
|
||||
|
||||
@@ -47,9 +47,17 @@ pub struct FakeHistory {
|
||||
failure: Mutex<Option<SourceError>>,
|
||||
/// Match requests fail with this (after the general failure) until it is cleared.
|
||||
match_failure: Mutex<Option<SourceError>>,
|
||||
/// Match id listings fail with this (after the general failure) until it is cleared.
|
||||
listing_failure: Mutex<Option<SourceError>>,
|
||||
fail_after: Option<usize>,
|
||||
/// 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.
|
||||
@@ -84,8 +92,12 @@ impl FakeHistory {
|
||||
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,
|
||||
@@ -181,6 +193,12 @@ impl FakeHistory {
|
||||
*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<SourceError>) {
|
||||
*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);
|
||||
@@ -198,13 +216,33 @@ impl FakeHistory {
|
||||
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> {
|
||||
let limited = (self.rate_limits)
|
||||
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: Duration::ZERO,
|
||||
retry_after: self.retry_after,
|
||||
}),
|
||||
false => Ok(()),
|
||||
}
|
||||
@@ -318,6 +356,7 @@ impl FakeHistory {
|
||||
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}"))?;
|
||||
self.limit_by(&self.resolve_rate_limits)?;
|
||||
if let Some((entered, release)) = &self.resolve_gate {
|
||||
entered.send(()).unwrap();
|
||||
release.lock().unwrap().recv().unwrap();
|
||||
@@ -342,6 +381,10 @@ impl MatchHistorySource for FakeHistory {
|
||||
start_time_s: Option<i64>,
|
||||
) -> Result<Vec<String>, 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()
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use arena_tracker_core::{
|
||||
DamageSums, DeathRecap, DeathRecapState, Effect, GameCatalog, GameData, MatchRecap,
|
||||
Account, DamageSums, DeathRecap, DeathRecapState, Effect, GameCatalog, GameData, MatchRecap,
|
||||
SourceError, Tracker,
|
||||
};
|
||||
use common::{FakeHistory, RIOT_ID, SELF_PUUID, recorded_account};
|
||||
@@ -318,3 +318,25 @@ fn deleting_the_last_owner_while_a_timeline_is_in_flight_discards_the_response()
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_death_recap_is_still_read_after_the_account_changes_puuid() {
|
||||
let world = world();
|
||||
let first = world.fetch().unwrap();
|
||||
let new = "fixture-puuid-new-key";
|
||||
let account = Account {
|
||||
puuid: new.into(),
|
||||
..recorded_account()
|
||||
};
|
||||
let history = FakeHistory::new(account, vec![RECAP_MATCH.replace(SELF_PUUID, new)]);
|
||||
let tracker = Tracker::open(&world.dir.path().join("arena.db"), Box::new(history)).unwrap();
|
||||
|
||||
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
|
||||
|
||||
let recap = tracker.match_recap(new, MATCH_ID).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
tracker.death_recap(&recap, &catalog(&world.dir)).unwrap(),
|
||||
first
|
||||
);
|
||||
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 0);
|
||||
}
|
||||
@@ -212,6 +212,8 @@ mod deletion;
|
||||
mod friends;
|
||||
#[path = "follow/in_game.rs"]
|
||||
mod in_game;
|
||||
#[path = "follow/key_change.rs"]
|
||||
mod key_change;
|
||||
#[path = "follow/live_matches.rs"]
|
||||
mod live_matches;
|
||||
#[path = "follow/pending_matches.rs"]
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Riot's key changes while the app runs: the Account being updated follows its new PUUID.
|
||||
use super::provisional_matches::{game, published, start_game};
|
||||
use super::*;
|
||||
use arena_tracker_core::MatchHistorySource;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
const NEW: &str = "fixture-puuid-new-key";
|
||||
|
||||
/// Riot under the old key until `new_key` is set, then under the new one.
|
||||
struct Switch {
|
||||
old: Arc<FakeHistory>,
|
||||
new: Arc<FakeHistory>,
|
||||
new_key: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Switch {
|
||||
fn now(&self) -> &FakeHistory {
|
||||
match self.new_key.load(Ordering::SeqCst) {
|
||||
true => &self.new,
|
||||
false => &self.old,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MatchHistorySource for Switch {
|
||||
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
|
||||
self.now().resolve_account(game_name, tag_line)
|
||||
}
|
||||
|
||||
fn match_ids(
|
||||
&self,
|
||||
puuid: &str,
|
||||
queue_id: u32,
|
||||
start: usize,
|
||||
count: usize,
|
||||
start_time_s: Option<i64>,
|
||||
) -> Result<Vec<String>, SourceError> {
|
||||
self.now()
|
||||
.match_ids(puuid, queue_id, start, count, start_time_s)
|
||||
}
|
||||
|
||||
fn fetch_match(&self, match_id: &str) -> Result<String, SourceError> {
|
||||
self.now().fetch_match(match_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_account_updated_follows_its_new_puuid_when_the_key_changes_during_the_session() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let new_key = Arc::new(AtomicBool::new(false));
|
||||
let account = Account {
|
||||
puuid: NEW.into(),
|
||||
..recorded_account()
|
||||
};
|
||||
let all = payloads(&s2_matches());
|
||||
let under_new = all.iter().map(|p| played_by(p, NEW)).collect();
|
||||
let source = Switch {
|
||||
old: Arc::new(FakeHistory::new(recorded_account(), all.clone())),
|
||||
new: Arc::new(FakeHistory::new(account, under_new)),
|
||||
new_key: new_key.clone(),
|
||||
};
|
||||
let client = FakeClient::recorded();
|
||||
let tracker = Tracker::open(&dir.path().join("arena.db"), Box::new(source))
|
||||
.unwrap()
|
||||
.with_seasons(seasons())
|
||||
.with_client(Box::new(client.clone()));
|
||||
round(&tracker);
|
||||
let updating = |tracker: &Tracker| tracker.status().updating.map(|a| a.puuid);
|
||||
assert_eq!(updating(&tracker).as_deref(), Some(SELF_PUUID));
|
||||
|
||||
// The client closes (a refresh then syncs the Account kept up to date) and the key changes.
|
||||
client.sign_out();
|
||||
round(&tracker);
|
||||
new_key.store(true, Ordering::SeqCst);
|
||||
tracker.refresh(&mut |_| {}).unwrap();
|
||||
|
||||
assert_eq!(updating(&tracker).as_deref(), Some(NEW));
|
||||
assert_eq!(tracker.replaced_puuid(SELF_PUUID).as_deref(), Some(NEW));
|
||||
assert_eq!(tracker.accounts().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
/// A game ended under the old key: its Provisional Match is stored and looked for. Then the
|
||||
/// client closes and the key changes. Returns what Riot's new key tells, and its requests.
|
||||
fn provisional_then_key_change() -> (World, Tracker, Arc<FakeHistory>, mpsc::Receiver<String>) {
|
||||
let world = World::new(&s2_matches());
|
||||
let new_key = Arc::new(AtomicBool::new(false));
|
||||
let all = payloads(&s2_matches());
|
||||
let account = Account {
|
||||
puuid: NEW.into(),
|
||||
..recorded_account()
|
||||
};
|
||||
let (requests, log) = mpsc::channel();
|
||||
let new = FakeHistory::new(account, all.iter().map(|p| played_by(p, NEW)).collect())
|
||||
.logging_requests(requests);
|
||||
let new = Arc::new(new);
|
||||
let source = Switch {
|
||||
old: world.history.clone(),
|
||||
new: new.clone(),
|
||||
new_key: new_key.clone(),
|
||||
};
|
||||
let tracker = Tracker::open(&world.dir.path().join("arena.db"), Box::new(source))
|
||||
.unwrap()
|
||||
.with_seasons(seasons())
|
||||
.with_client(Box::new(world.client.clone()));
|
||||
start_game(&world, &tracker);
|
||||
world
|
||||
.client
|
||||
.create_end_of_game_block(&end_of_game_block(game().0, 222, 3));
|
||||
world.client.set_phase("EndOfGame", true);
|
||||
assert_eq!(reported_round(&tracker).len(), 1);
|
||||
world.client.sign_out();
|
||||
round(&tracker);
|
||||
new_key.store(true, Ordering::SeqCst);
|
||||
(world, tracker, new, log)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_look_up_of_a_provisional_match_follows_the_new_puuid_and_ends_with_its_publication() {
|
||||
let (_world, tracker, new, log) = provisional_then_key_change();
|
||||
new.add_unlisted(played_by(&published(5), NEW));
|
||||
|
||||
// The refresh moves the Account, and publishes the Match under the new PUUID.
|
||||
tracker.refresh(&mut |_| {}).unwrap();
|
||||
assert!(tracker.matches(NEW).unwrap().iter().all(|m| !m.provisional));
|
||||
let _ = log.try_iter().count();
|
||||
|
||||
// Its window is over with its publication: no later round asks for it again.
|
||||
for _ in 0..3 {
|
||||
round(&tracker);
|
||||
}
|
||||
assert_eq!(
|
||||
log.try_iter().filter(|r| r.starts_with("match ")).count(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_provisional_match_stays_readable_with_its_block_after_the_account_moves() {
|
||||
let (world, tracker, _new, _log) = provisional_then_key_change();
|
||||
let blocks = || {
|
||||
let db = rusqlite::Connection::open(world.dir.path().join("arena.db")).unwrap();
|
||||
let sql = "SELECT COUNT(*) FROM end_of_game_blocks WHERE raw != ''";
|
||||
db.query_row(sql, [], |row| row.get::<_, i64>(0)).unwrap()
|
||||
};
|
||||
assert_eq!(blocks(), 1_i64);
|
||||
|
||||
tracker.refresh(&mut |_| {}).unwrap();
|
||||
|
||||
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 0);
|
||||
let recap = tracker.match_recap(NEW, &game().1).unwrap().unwrap();
|
||||
assert!(recap.provisional);
|
||||
assert_eq!(
|
||||
(recap.teams.iter().flat_map(|t| &t.players))
|
||||
.filter(|p| p.is_account)
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(blocks(), 1_i64, "its end-of-game block is kept");
|
||||
}
|
||||
@@ -102,5 +102,9 @@ mod accounts;
|
||||
mod compatibility;
|
||||
#[path = "import/concurrency.rs"]
|
||||
mod concurrency;
|
||||
#[path = "import/quota.rs"]
|
||||
mod quota;
|
||||
#[path = "import/rekey.rs"]
|
||||
mod rekey;
|
||||
#[path = "import/sync.rs"]
|
||||
mod sync;
|
||||
@@ -50,10 +50,11 @@ fn an_account_resolved_to_another_puuid_is_a_second_account() {
|
||||
let before = first.matches("P1").unwrap();
|
||||
drop(first);
|
||||
|
||||
// Under another key it is P2: nothing proves it is the same Account.
|
||||
// Under another key it is P2, and none of P1's Matches is among its own: nothing proves it
|
||||
// is the same Account (`import/rekey.rs` has the proof).
|
||||
let tracker = open(
|
||||
&db,
|
||||
FakeHistory::new(account("P2"), build("P2", &[1, 2, 3])),
|
||||
FakeHistory::new(account("P2"), build("P2", &[3, 4, 5])),
|
||||
);
|
||||
|
||||
let report = sync(&tracker);
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
use super::*;
|
||||
|
||||
const WAIT: Duration = Duration::from_millis(5);
|
||||
|
||||
fn limited() -> FakeHistory {
|
||||
FakeHistory::new(recorded_account(), recorded_matches()).retry_after(WAIT)
|
||||
}
|
||||
|
||||
/// What a sync tells, as (fetched, to_fetch, quota_wait).
|
||||
fn told(tracker: &Tracker) -> Vec<(usize, usize, Option<Duration>)> {
|
||||
let mut progress = Vec::new();
|
||||
let report = tracker
|
||||
.sync(RIOT_ID, &mut |p| {
|
||||
progress.push((p.fetched, p.to_fetch, p.quota_wait))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!((report.added, report.stored), (6, 6));
|
||||
progress
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rate_limited_listing_tells_its_wait_then_the_import_line_comes_back() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let history = limited();
|
||||
history.rate_limit_listing_next(1);
|
||||
let tracker = open(&dir.path().join("arena.db"), history);
|
||||
|
||||
let progress = told(&tracker);
|
||||
|
||||
assert_eq!(progress[..2], [(0, 0, Some(WAIT)), (0, 0, None)]);
|
||||
assert_eq!(progress.last(), Some(&(6, 6, None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rate_limited_match_fetch_tells_its_wait_then_the_import_line_comes_back() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let history = limited();
|
||||
history.rate_limit_next(2);
|
||||
let tracker = open(&dir.path().join("arena.db"), history);
|
||||
|
||||
let progress = told(&tracker);
|
||||
|
||||
// Listed (0 / 6), then the first fetch waits twice and resumes with the same counts.
|
||||
assert_eq!(
|
||||
progress[..5],
|
||||
[
|
||||
(0, 6, None),
|
||||
(0, 6, Some(WAIT)),
|
||||
(0, 6, Some(WAIT)),
|
||||
(0, 6, None),
|
||||
(1, 6, None)
|
||||
]
|
||||
);
|
||||
assert_eq!(progress.len(), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_without_a_wait_never_tells_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tracker = open(&dir.path().join("arena.db"), limited());
|
||||
|
||||
assert!(told(&tracker).iter().all(|(_, _, wait)| wait.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rate_limited_resolution_of_a_friend_tells_its_wait() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
let ami = Account {
|
||||
puuid: "ami-puuid".into(),
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
};
|
||||
let history = FakeHistory::new(ami, Vec::new()).retry_after(WAIT);
|
||||
let tracker = open(&db, history);
|
||||
tracker.add_friend("Ami#FIX").unwrap();
|
||||
drop(tracker);
|
||||
let history = FakeHistory::new(
|
||||
Account {
|
||||
puuid: "ami-puuid".into(),
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
},
|
||||
Vec::new(),
|
||||
)
|
||||
.retry_after(WAIT);
|
||||
history.rate_limit_resolution_next(1);
|
||||
let tracker = open(&db, history);
|
||||
let mut waits = Vec::new();
|
||||
|
||||
tracker
|
||||
.import_friend("ami-puuid", &mut |p| waits.push(p.quota_wait))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(waits[..2], [Some(WAIT), None]);
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//! A new Riot key gives every Account another PUUID for the same Riot ID (#150): the stored
|
||||
//! Account follows it on proof that it is the same Account, else nothing changes.
|
||||
use super::*;
|
||||
use rusqlite::Connection;
|
||||
|
||||
const NEW: &str = "fixture-puuid-new-key";
|
||||
const FRIEND_OLD: &str = "friend-old-key";
|
||||
const FRIEND_NEW: &str = "friend-new-key";
|
||||
const PROVISIONAL_MS: i64 = 1_010_000_000;
|
||||
|
||||
/// The Matches of `five_matches`, as Riot lists them for another PUUID.
|
||||
fn under(puuid: &str, payloads: Vec<String>) -> Vec<String> {
|
||||
payloads.iter().map(|p| played_by(p, puuid)).collect()
|
||||
}
|
||||
|
||||
/// Riot under another key: the same Riot ID, another PUUID.
|
||||
fn new_key(puuid: &str, payloads: Vec<String>) -> FakeHistory {
|
||||
let account = Account {
|
||||
puuid: puuid.into(),
|
||||
..recorded_account()
|
||||
};
|
||||
FakeHistory::new(account, under(puuid, payloads))
|
||||
}
|
||||
|
||||
fn old_matches() -> Vec<String> {
|
||||
five_matches(1_000_000)
|
||||
}
|
||||
|
||||
/// What the app stored besides, for the same Account: a Provisional Match, Mastery Points, a
|
||||
/// platform and the last active Account.
|
||||
fn store_besides(db: &Path, puuid: &str) {
|
||||
Connection::open(db)
|
||||
.unwrap()
|
||||
.execute_batch(&format!(
|
||||
"INSERT INTO mastery VALUES ('{puuid}', 1, 100);
|
||||
INSERT INTO meta VALUES ('mastery:{puuid}', '1'), ('platform:{puuid}', 'EUW1'),
|
||||
('last_active_puuid', '{puuid}');
|
||||
INSERT INTO matches VALUES ('{puuid}', 'EUW1_77', 1750, 7, 'G', 3, 0,
|
||||
{PROVISIONAL_MS}, '{{}}', 1);"
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Every stored row of the tables a PUUID lives in, as text.
|
||||
fn dump(db: &Path) -> Vec<String> {
|
||||
let db = Connection::open(db).unwrap();
|
||||
[
|
||||
"SELECT 'account '||puuid||' '||game_name||'#'||tag_line||' '||friend FROM accounts",
|
||||
"SELECT 'match '||puuid||' '||match_id||' '||provisional||' '||raw FROM matches",
|
||||
"SELECT 'mastery '||puuid||' '||champion_id||' '||points FROM mastery",
|
||||
"SELECT 'meta '||name||'='||value FROM meta",
|
||||
]
|
||||
.iter()
|
||||
.flat_map(|sql| {
|
||||
let mut stmt = db.prepare(sql).unwrap();
|
||||
let mut rows: Vec<String> = (stmt.query_map([], |row| row.get(0)).unwrap())
|
||||
.map(Result::unwrap)
|
||||
.collect();
|
||||
rows.sort();
|
||||
rows
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn meta(db: &Path, name: &str) -> Option<String> {
|
||||
let prefix = format!("meta {name}=");
|
||||
dump(db)
|
||||
.iter()
|
||||
.find_map(|row| row.strip_prefix(&prefix).map(String::from))
|
||||
}
|
||||
|
||||
fn puuids(tracker: &Tracker) -> Vec<String> {
|
||||
(tracker.accounts().unwrap().into_iter())
|
||||
.map(|a| a.puuid)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn flagged_players(tracker: &Tracker, puuid: &str, match_id: &str) -> usize {
|
||||
let recap = tracker.match_recap(puuid, match_id).unwrap().unwrap();
|
||||
(recap.teams.iter().flat_map(|t| &t.players))
|
||||
.filter(|p| p.is_account)
|
||||
.count()
|
||||
}
|
||||
|
||||
fn ids_requests(requests: &mpsc::Receiver<String>) -> usize {
|
||||
requests
|
||||
.try_iter()
|
||||
.filter(|r| r.starts_with("ids "))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Synced under the old key, with the rest stored.
|
||||
fn old_world(db: &Path) {
|
||||
sync(&open(
|
||||
db,
|
||||
FakeHistory::new(recorded_account(), old_matches()),
|
||||
));
|
||||
store_besides(db, SELF_PUUID);
|
||||
}
|
||||
|
||||
/// The new key's Riot knows a Match more, and publishes the Provisional one.
|
||||
fn new_key_with_news(requests: mpsc::Sender<String>) -> FakeHistory {
|
||||
let mut all = old_matches();
|
||||
all.push(payload(
|
||||
"EUW1_5",
|
||||
1750,
|
||||
5,
|
||||
"Champion",
|
||||
2,
|
||||
true,
|
||||
1_006_000_000,
|
||||
));
|
||||
all.push(payload("EUW1_77", 1750, 7, "G", 3, false, PROVISIONAL_MS));
|
||||
new_key(NEW, all).logging_requests(requests)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_follows_its_new_puuid_with_everything_stored_for_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
old_world(&db);
|
||||
let mark = meta(&db, &format!("synced_until_ms:{SELF_PUUID}")).unwrap();
|
||||
let (requests, log) = mpsc::channel();
|
||||
let history = new_key_with_news(requests);
|
||||
let fetches = history.fetch_counter();
|
||||
let tracker = open(&db, history);
|
||||
assert_eq!(flagged_players(&tracker, SELF_PUUID, "EUW1_0"), 1);
|
||||
|
||||
let report = sync(&tracker);
|
||||
|
||||
assert_eq!(report.account.puuid, NEW);
|
||||
assert_eq!((report.added, report.stored), (1, 7));
|
||||
// Only the proof's Match, the Match it did not have and the Provisional one are fetched.
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
3,
|
||||
"the proof's Match, then two"
|
||||
);
|
||||
// The proof comes right after the resolution, before the listing.
|
||||
let requests: Vec<String> = log.try_iter().collect();
|
||||
assert_eq!(requests[..2], ["account Joueur#EUW", &format!("ids {NEW}")]);
|
||||
assert_eq!(puuids(&tracker), [NEW]);
|
||||
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 0);
|
||||
let stored = tracker.matches(NEW).unwrap();
|
||||
assert!(stored.iter().all(|m| !m.provisional));
|
||||
assert_eq!(stored.len(), 7);
|
||||
assert_eq!(flagged_players(&tracker, NEW, "EUW1_0"), 1);
|
||||
assert_eq!(tracker.mastery(NEW).unwrap().unwrap()[&1], 100);
|
||||
assert_eq!(tracker.mastery(SELF_PUUID).unwrap(), None);
|
||||
assert_eq!(tracker.last_active_account().unwrap().unwrap().puuid, NEW);
|
||||
assert_eq!(
|
||||
meta(&db, &format!("synced_until_ms:{NEW}")).unwrap(),
|
||||
"1010000000"
|
||||
);
|
||||
assert!(mark.parse::<i64>().unwrap() < 1_010_000_000);
|
||||
assert_eq!(
|
||||
meta(&db, &format!("platform:{NEW}")).as_deref(),
|
||||
Some("EUW1")
|
||||
);
|
||||
assert!(dump(&db).iter().all(|row| !row.contains(SELF_PUUID)));
|
||||
assert_eq!(tracker.replaced_puuid(SELF_PUUID).as_deref(), Some(NEW));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_it_again_changes_nothing_and_sends_no_proof_request() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
old_world(&db);
|
||||
let (requests, log) = mpsc::channel();
|
||||
let tracker = open(&db, new_key_with_news(requests));
|
||||
sync(&tracker);
|
||||
// One listing per queue and the proof request.
|
||||
assert_eq!(ids_requests(&log), 5);
|
||||
let before = dump(&db);
|
||||
|
||||
sync(&tracker);
|
||||
|
||||
assert_eq!(ids_requests(&log), 4);
|
||||
assert_eq!(dump(&db), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interrupted_rekey_starts_again_without_loss() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
old_world(&db);
|
||||
let before = dump(&db);
|
||||
let history = new_key(NEW, old_matches());
|
||||
history.fail_listing_with(Some(SourceError::Network("coupure".into())));
|
||||
let tracker = open(&db, history);
|
||||
|
||||
assert!(tracker.sync(RIOT_ID, &mut |_| {}).is_err());
|
||||
|
||||
assert_eq!(dump(&db), before);
|
||||
assert_eq!(tracker.replaced_puuid(SELF_PUUID), None);
|
||||
drop(tracker);
|
||||
// The next launch.
|
||||
let tracker = open(&db, new_key(NEW, old_matches()));
|
||||
sync(&tracker);
|
||||
assert_eq!(puuids(&tracker), [NEW]);
|
||||
assert_eq!(tracker.match_count(NEW).unwrap(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_changes_without_a_published_match_in_common() {
|
||||
for provisional_only in [false, true] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
sync(&open(&db, FakeHistory::new(recorded_account(), Vec::new())));
|
||||
if provisional_only {
|
||||
store_besides(&db, SELF_PUUID);
|
||||
}
|
||||
let before = dump(&db);
|
||||
|
||||
// Riot lists Matches for the new PUUID, among them the Provisional one.
|
||||
let tracker = open(&db, new_key(NEW, old_matches()));
|
||||
let report = sync(&tracker);
|
||||
|
||||
assert_eq!(report.account.puuid, NEW);
|
||||
let mut puuids = puuids(&tracker);
|
||||
puuids.sort();
|
||||
assert_eq!(puuids, [NEW, SELF_PUUID]);
|
||||
let after = dump(&db);
|
||||
assert!(
|
||||
before.iter().all(|row| after.contains(row)),
|
||||
"{provisional_only}"
|
||||
);
|
||||
assert_eq!(tracker.replaced_puuid(SELF_PUUID), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_puuid_already_stored_is_merged_and_the_published_match_wins() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
old_world(&db);
|
||||
// Under the new key, with Matches of its own: nothing proves it is the same Account.
|
||||
let own = vec![payload(
|
||||
"EUW1_10",
|
||||
1750,
|
||||
10,
|
||||
"Champion",
|
||||
1,
|
||||
true,
|
||||
1_020_000_000,
|
||||
)];
|
||||
let second = open(&db, new_key(NEW, own.clone()));
|
||||
sync(&second);
|
||||
assert_eq!(puuids(&second).len(), 2);
|
||||
drop(second);
|
||||
let sql = Connection::open(&db).unwrap();
|
||||
sql.execute_batch(&format!(
|
||||
"UPDATE accounts SET friend = 1 WHERE puuid = '{SELF_PUUID}';
|
||||
-- published on the old side, Provisional on the new one
|
||||
INSERT INTO matches VALUES ('{NEW}', 'EUW1_3', 1750, 1, 'P', 1, 0, 1, 'provisional', 1);
|
||||
-- Provisional on the old side, published on the new one
|
||||
INSERT INTO matches VALUES ('{SELF_PUUID}', 'EUW1_90', 1750, 1, 'P', 1, 0, 2, 'old', 1);
|
||||
INSERT INTO matches VALUES ('{NEW}', 'EUW1_90', 1750, 1, 'P', 1, 0, 2, 'new', 0);
|
||||
INSERT INTO mastery VALUES ('{NEW}', 1, 999), ('{NEW}', 2, 5);
|
||||
INSERT INTO meta VALUES ('mastery:{NEW}', '1');"
|
||||
))
|
||||
.unwrap();
|
||||
drop(sql);
|
||||
let mut all = old_matches();
|
||||
all.extend(own);
|
||||
let tracker = open(&db, new_key(NEW, all));
|
||||
|
||||
sync(&tracker);
|
||||
|
||||
assert_eq!(puuids(&tracker), [NEW]);
|
||||
assert_eq!(tracker.friends().unwrap().len(), 1);
|
||||
let rows = dump(&db);
|
||||
let matches: Vec<_> = rows.iter().filter(|r| r.starts_with("match ")).collect();
|
||||
// The five of the old key, EUW1_10, EUW1_90 and the Provisional EUW1_77, none twice.
|
||||
assert_eq!(matches.len(), 8, "{matches:?}");
|
||||
assert!(rows.contains(&format!("match {NEW} EUW1_90 0 new")));
|
||||
let provisional: Vec<_> = (tracker.matches(NEW).unwrap().into_iter())
|
||||
.filter(|m| m.provisional)
|
||||
.map(|m| m.match_id)
|
||||
.collect();
|
||||
assert_eq!(provisional, ["EUW1_77"]);
|
||||
assert_eq!(flagged_players(&tracker, NEW, "EUW1_3"), 1);
|
||||
// The new Account's own Mastery Points win.
|
||||
let mastery = tracker.mastery(NEW).unwrap().unwrap();
|
||||
assert_eq!((mastery[&1], mastery[&2]), (999, 5));
|
||||
assert!(rows.iter().all(|r| !r.contains(SELF_PUUID)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_friend_follows_its_new_puuid_and_stays_a_friend() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
let ami = |puuid: &str| Account {
|
||||
puuid: puuid.into(),
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
};
|
||||
let matches = || {
|
||||
(0..3)
|
||||
.map(|i| {
|
||||
payload(
|
||||
&format!("EUW1_f{i}"),
|
||||
1750,
|
||||
5,
|
||||
"Champion",
|
||||
2,
|
||||
true,
|
||||
1_000_000_000 + i * 1_000_000,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let old = open(
|
||||
&db,
|
||||
FakeHistory::new(ami(FRIEND_OLD), under(FRIEND_OLD, matches())),
|
||||
);
|
||||
old.add_friend("Ami#FIX").unwrap();
|
||||
old.import_friend(FRIEND_OLD, &mut |_| {}).unwrap();
|
||||
drop(old);
|
||||
let (requests, log) = mpsc::channel();
|
||||
let history =
|
||||
FakeHistory::new(ami(FRIEND_NEW), under(FRIEND_NEW, matches())).logging_requests(requests);
|
||||
let fetches = history.fetch_counter();
|
||||
let tracker = open(&db, history);
|
||||
|
||||
let report = tracker.import_friend(FRIEND_OLD, &mut |_| {}).unwrap();
|
||||
|
||||
assert_eq!(report.account, ami(FRIEND_NEW));
|
||||
assert_eq!((report.added, report.stored), (0, 3));
|
||||
// Only the proof's Match. The sync mark moved with the Friend: one listing step after the
|
||||
// proof's request, not a first import's two.
|
||||
assert_eq!(fetches.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(ids_requests(&log), 5);
|
||||
assert_eq!(tracker.friends().unwrap(), [ami(FRIEND_NEW)]);
|
||||
assert_eq!(tracker.accounts().unwrap(), [ami(FRIEND_NEW)]);
|
||||
assert_eq!(
|
||||
tracker.replaced_puuid(FRIEND_OLD).as_deref(),
|
||||
Some(FRIEND_NEW)
|
||||
);
|
||||
assert_eq!(
|
||||
meta(&db, &format!("platform:{FRIEND_NEW}")).as_deref(),
|
||||
Some("EUW1")
|
||||
);
|
||||
assert!(dump(&db).iter().all(|row| !row.contains(FRIEND_OLD)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_friend_whose_riot_id_changed_is_imported_under_its_stored_puuid() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
let ami = Account {
|
||||
puuid: FRIEND_OLD.into(),
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
};
|
||||
let old = open(&db, FakeHistory::new(ami.clone(), Vec::new()));
|
||||
old.add_friend("Ami#FIX").unwrap();
|
||||
drop(old);
|
||||
// Riot knows no Account with that Riot ID any more.
|
||||
let tracker = open(&db, FakeHistory::new(recorded_account(), Vec::new()));
|
||||
|
||||
let report = tracker.import_friend(FRIEND_OLD, &mut |_| {}).unwrap();
|
||||
|
||||
assert_eq!(report.account, ami);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_friend_whose_riot_id_belongs_to_another_stored_account_is_imported_as_itself() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
let ami = |puuid: &str| Account {
|
||||
puuid: puuid.into(),
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
};
|
||||
let matches = |from: i64| {
|
||||
(0..2)
|
||||
.map(|i| {
|
||||
payload(
|
||||
&format!("EUW1_{from}{i}"),
|
||||
1750,
|
||||
5,
|
||||
"Champion",
|
||||
2,
|
||||
true,
|
||||
1_000_000_000 + from * 1_000 + i,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// Your own Account, and the Friend: each with Matches of its own.
|
||||
sync(&open(
|
||||
&db,
|
||||
FakeHistory::new(recorded_account(), five_matches(1_000_000)),
|
||||
));
|
||||
let old = open(
|
||||
&db,
|
||||
FakeHistory::new(ami(FRIEND_OLD), under(FRIEND_OLD, matches(1))),
|
||||
);
|
||||
old.add_friend("Ami#FIX").unwrap();
|
||||
old.import_friend(FRIEND_OLD, &mut |_| {}).unwrap();
|
||||
drop(old);
|
||||
let before = dump(&db);
|
||||
// Now "Ami#FIX" resolves to your own Account, sharing no Match with the Friend.
|
||||
let history = FakeHistory::new(
|
||||
Account {
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
..recorded_account()
|
||||
},
|
||||
five_matches(1_000_000),
|
||||
);
|
||||
let fetches = history.fetch_counter();
|
||||
let tracker = open(&db, history);
|
||||
|
||||
let report = tracker.import_friend(FRIEND_OLD, &mut |_| {}).unwrap();
|
||||
|
||||
assert_eq!(report.account, ami(FRIEND_OLD));
|
||||
assert_eq!(fetches.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(tracker.replaced_puuid(FRIEND_OLD), None);
|
||||
assert_eq!(tracker.friends().unwrap(), [ami(FRIEND_OLD)]);
|
||||
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 5);
|
||||
assert_eq!(tracker.match_count(FRIEND_OLD).unwrap(), 2);
|
||||
assert!(before.iter().all(|row| dump(&db).contains(row)));
|
||||
}
|
||||
|
||||
#[path = "rekey/identity.rs"]
|
||||
mod identity;
|
||||
@@ -0,0 +1,138 @@
|
||||
//! The proof names the Account, not anyone who shared the Match.
|
||||
use super::*;
|
||||
|
||||
/// Your own Account (five Matches), and a Friend stored as `Ami#FIX` whose newest Match is the
|
||||
/// last of yours: the same Match, another champion.
|
||||
fn duo_world(db: &Path) {
|
||||
sync(&open(
|
||||
db,
|
||||
FakeHistory::new(recorded_account(), old_matches()),
|
||||
));
|
||||
let alone = payload("EUW1_alone", 1750, 99, "Champion", 8, false, 900_000_000);
|
||||
let together = payload("EUW1_4", 1750, 77, "Champion", 2, false, 1_004_000_000);
|
||||
let friend = FakeHistory::new(
|
||||
Account {
|
||||
puuid: FRIEND_OLD.into(),
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
},
|
||||
under(FRIEND_OLD, vec![alone, together]),
|
||||
);
|
||||
let tracker = open(db, friend);
|
||||
tracker.add_friend("Ami#FIX").unwrap();
|
||||
tracker.import_friend(FRIEND_OLD, &mut |_| {}).unwrap();
|
||||
assert_eq!(tracker.match_count(FRIEND_OLD).unwrap(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_taking_a_friends_old_riot_id_does_not_absorb_the_friend() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
duo_world(&db);
|
||||
let before = dump(&db);
|
||||
// You renamed to the Riot ID the Friend had (the stored one is stale, the Friend renamed).
|
||||
let renamed = Account {
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
..recorded_account()
|
||||
};
|
||||
let tracker = open(&db, FakeHistory::new(renamed, old_matches()));
|
||||
|
||||
let report = tracker.sync("Ami#FIX", &mut |_| {}).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
(report.account.puuid.as_str(), report.added),
|
||||
(SELF_PUUID, 0)
|
||||
);
|
||||
assert_eq!(tracker.replaced_puuid(FRIEND_OLD), None);
|
||||
assert_eq!(tracker.friends().unwrap().len(), 1);
|
||||
assert_eq!(tracker.match_count(FRIEND_OLD).unwrap(), 2);
|
||||
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 5);
|
||||
let after = dump(&db);
|
||||
// Only your own Account's name changed.
|
||||
let friend_rows = |rows: &[String]| -> Vec<String> {
|
||||
(rows.iter())
|
||||
.filter(|r| r.contains(FRIEND_OLD))
|
||||
.cloned()
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(friend_rows(&after), friend_rows(&before));
|
||||
}
|
||||
|
||||
/// A third participant of the shared Match took "Ami#FIX": Riot lists the Match for them too.
|
||||
/// The Friend played champion 77 and placed 2nd.
|
||||
fn stranger_takes_the_riot_id(champion: u32, placement: u8) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
duo_world(&db);
|
||||
let before = dump(&db);
|
||||
let theirs = payload(
|
||||
"EUW1_4",
|
||||
1750,
|
||||
champion,
|
||||
"Champion",
|
||||
placement,
|
||||
true,
|
||||
1_004_000_000,
|
||||
);
|
||||
let stranger = Account {
|
||||
puuid: "stranger".into(),
|
||||
game_name: "Ami".into(),
|
||||
tag_line: "FIX".into(),
|
||||
};
|
||||
let tracker = open(
|
||||
&db,
|
||||
FakeHistory::new(stranger, under("stranger", vec![theirs])),
|
||||
);
|
||||
|
||||
let report = tracker.import_friend(FRIEND_OLD, &mut |_| {}).unwrap();
|
||||
|
||||
assert_eq!(report.account.puuid, FRIEND_OLD);
|
||||
assert_eq!(tracker.replaced_puuid(FRIEND_OLD), None);
|
||||
assert_eq!(dump(&db), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stranger_of_the_same_match_taking_a_friends_riot_id_does_not_take_the_friend() {
|
||||
stranger_takes_the_riot_id(50, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opponent_on_the_friends_champion_does_not_take_the_friend_either() {
|
||||
stranger_takes_the_riot_id(77, 1);
|
||||
}
|
||||
|
||||
/// Riot answers the sync with this history instead: the proof it allows fails, nothing moves
|
||||
/// and the sync goes on with a second Account.
|
||||
fn sync_without_proof(history: FakeHistory) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("arena.db");
|
||||
old_world(&db);
|
||||
let before = dump(&db);
|
||||
let tracker = open(&db, history);
|
||||
|
||||
sync(&tracker);
|
||||
|
||||
assert_eq!(tracker.replaced_puuid(SELF_PUUID), None);
|
||||
let after = dump(&db);
|
||||
assert!(before.iter().all(|row| after.contains(row)));
|
||||
let mut puuids = puuids(&tracker);
|
||||
puuids.sort();
|
||||
assert_eq!(puuids, [NEW, SELF_PUUID]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proof_match_riot_does_not_have_proves_nothing() {
|
||||
let history = new_key(NEW, old_matches());
|
||||
history.fail_match_with(Some(SourceError::NotFound));
|
||||
sync_without_proof(history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proof_match_that_cannot_be_read_proves_nothing() {
|
||||
let mut matches = old_matches();
|
||||
matches.pop();
|
||||
let history = new_key(NEW, matches);
|
||||
history.add_unreadable("EUW1_4", 1_004_000_000, "not a Match");
|
||||
sync_without_proof(history);
|
||||
}
|
||||
@@ -212,7 +212,8 @@ fn a_match_that_cannot_be_delivered_or_read_does_not_block_the_others() {
|
||||
progress.last(),
|
||||
Some(&SyncProgress {
|
||||
fetched: 5,
|
||||
to_fetch: 5
|
||||
to_fetch: 5,
|
||||
..Default::default()
|
||||
})
|
||||
);
|
||||
let again = sync(&tracker);
|
||||
@@ -247,6 +248,7 @@ fn progress_goes_from_nothing_fetched_to_everything_fetched() {
|
||||
.map(|fetched| SyncProgress {
|
||||
fetched,
|
||||
to_fetch: 6,
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(progress, want);
|
||||
@@ -257,7 +259,8 @@ fn progress_goes_from_nothing_fetched_to_everything_fetched() {
|
||||
progress,
|
||||
[SyncProgress {
|
||||
fetched: 0,
|
||||
to_fetch: 0
|
||||
to_fetch: 0,
|
||||
..Default::default()
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -19,5 +19,5 @@ The relay (`crates/relay`) is a request in, a request out: `/{routing value}{Rio
|
||||
|
||||
- When the relay is down, imports stop; what is stored stays readable.
|
||||
- The relay sees each player's address and Riot IDs in transit; it logs only the type of call, the status and the duration.
|
||||
- A PUUID depends on the key's Riot application: switching to the production key changes every stored one (#150).
|
||||
- A PUUID depends on the key's Riot application: switching to the production key changes every stored one. A sync and a Friend's import first ask Riot for the PUUID of the Riot ID, and move the stored Account to it only on proof: a stored published Match is listed for the new PUUID and the new PUUID has the same champion and Placement in it (the same participant, so not a mere co-participant of that Match). Without proof nothing changes. The follower's look-ups of a Match by id during a session do not check; they recover at the next sync (#150).
|
||||
- Not built yet: a cache of Matches (if the quota is reached), Riot's per-method limits (its 429 is respected).
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Défi et Statistiques
|
||||
|
||||
L’appli s’ouvre sur **Défi** : la bannière du Défi de la Saison, puis les cartes de vos champions. À côté des onglets, le sélecteur de **Compte** liste les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client) en premier, et choisit le Compte que montrent **Défi**, **Statistiques** et **Parties** (les Comptes sous « Vos Comptes », vos Amis sous « Amis »). Pour un autre Compte, la bannière commence par « Défi de Pseudo · », et la Progression officielle et l’animation de fin de Partie sont réservées au Compte actif. Le filtre **Tous** revient à chaque changement de Compte ; le tri et le thème restent les mêmes. L’appli revient sur le Compte actif quand une Sélection ou une Partie en cours commence, et à la fin d’une Partie suivie. Pour l’analyse détaillée (courbe des champions validés, Placements, Tentatives, tableau des champions, avec les sélecteurs de Saison et de Format), cliquez l’icône de courbe **Statistiques**, dans le coin inférieur droit de la bannière (une bulle la nomme au survol). La page porte **‹ Défi** en haut à gauche, qui ramène au Défi ; l’onglet **Défi** de la barre du haut y ramène aussi. Au clavier, Tab atteint l’icône et le retour, Entrée ou Espace les active. Survolez l’anneau de la bannière : la graduation visée s’allume et la bannière présente ce champion (« X · validé le 12 nov. · 3 Tentatives », « X · 2 Parties · meilleur Placement 3ᵉ » ou « X · jamais joué ») ; elle revient à son état habituel quand vous quittez l’anneau.
|
||||
L’appli s’ouvre sur **Défi** : la bannière du Défi de la Saison, puis les cartes de vos champions. À côté des onglets, le sélecteur de **Compte** liste les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client) en premier, et choisit le Compte que montrent **Défi**, **Statistiques** et **Parties** (les Comptes sous « Vos Comptes », vos Amis sous « Amis »). Pour un autre Compte, la bannière commence par « Défi de Pseudo · », et la Progression officielle et l’animation de fin de Partie sont réservées au Compte actif. Le filtre **Tous** revient à chaque changement de Compte ; le tri et le thème restent les mêmes. L’appli revient sur le Compte actif quand une Sélection ou une Partie en cours commence, et à la fin d’une Partie suivie. Pour l’analyse détaillée (courbe des champions validés, Placements, Tentatives, tableau des champions, avec les sélecteurs de Saison et de Format), cliquez l’icône de courbe **Statistiques**, dans le coin inférieur droit de la bannière (une bulle la nomme au survol). La page porte **‹ Défi** en haut à gauche, qui ramène au Défi ; l’onglet **Défi** de la barre du haut y ramène aussi. Au clavier, Tab atteint l’icône et le retour, Entrée ou Espace les active. La première fois, l’import de l’historique de votre Compte se voit de la même façon : la ligne en haut à droite compte les Parties (« Import en cours : n / N Parties ») et, à partir de 10 Parties, un arc se remplit autour de l’anneau ; si Riot demande d’attendre (quota atteint), l’arc s’arrête et la ligne dit « Quota Riot atteint : reprise dans 12 s », puis l’import reprend tout seul. Survolez l’anneau de la bannière : la graduation visée s’allume et la bannière présente ce champion (« X · validé le 12 nov. · 3 Tentatives », « X · 2 Parties · meilleur Placement 3ᵉ » ou « X · jamais joué ») ; elle revient à son état habituel quand vous quittez l’anneau.
|
||||
|
||||
Au début d’une Sélection des champions Arena, l’onglet **Sélection** apparaît à droite de **Défi** et **Parties** et l’appli l’affiche d’elle-même, où que vous soyez. Il montre les Champions de l’Enclume et « Autres champions ». Pendant la sélection, l’onglet **Défi** montre l’accueil habituel (et son icône **Statistiques**) ; revenez sur **Sélection** quand vous voulez, la main y est posée. Les bans et les choix des alliés ne vous ramènent pas sur **Sélection**. À la fin de la sélection, l’onglet disparaît et l’appli affiche le Défi, ou **En partie** si la partie est lancée.
|
||||
|
||||
@@ -10,13 +10,13 @@ Au lancement d’une Partie Arena, y compris quand l’appli démarre ou retrouv
|
||||
|
||||
## Amis
|
||||
|
||||
Pour consulter le Défi d’un autre joueur, ouvrez le sélecteur de Compte, choisissez **Ajouter un ami…** tout en bas, saisissez son Riot ID sous la forme `Pseudo#TAG` et appuyez sur Entrée (Échap ou **Annuler** referme le champ). Il doit jouer dans la même région que vous. Si le Compte est déjà l’un des vôtres ou un Ami, il est simplement sélectionné. Votre ami n’a rien à installer : ses Parties Arena viennent de l’API Riot, par le service d’Arena Tracker. À l’ajout, tout son historique disponible est importé en arrière-plan, la Saison en cours d’abord et après les besoins de votre Compte actif ; son Défi se remplit au fur et à mesure, et la ligne en haut à droite affiche « Import de Pseudo : n / N Parties ». Ensuite, seules ses nouvelles Parties sont récupérées, quand vous le choisissez dans le sélecteur ou que vous appuyez sur **Actualiser** pendant que son Défi est affiché ; l’appli ne le fait jamais d’elle-même. Si l’import est interrompu, il reprend de la même façon sans refaire ce qui est enregistré. Un Ami qui se connecte au client sur votre PC reste un Ami, suivi comme votre Compte actif.
|
||||
Pour consulter le Défi d’un autre joueur, ouvrez le sélecteur de Compte, choisissez **Ajouter un ami…** tout en bas, saisissez son Riot ID sous la forme `Pseudo#TAG` et appuyez sur Entrée (Échap ou **Annuler** referme le champ). Il doit jouer dans la même région que vous. Si le Compte est déjà l’un des vôtres ou un Ami, il est simplement sélectionné. Votre ami n’a rien à installer : ses Parties Arena viennent de l’API Riot, par le service d’Arena Tracker. À l’ajout, tout son historique disponible est importé en arrière-plan, la Saison en cours d’abord et après les besoins de votre Compte actif ; son Défi se remplit au fur et à mesure, et la ligne en haut à droite affiche « Import de Pseudo : n / N Parties ». Si l’import porte sur 10 Parties ou plus et que le Compte de votre ami est affiché, un arc fin se remplit autour de l’anneau de la bannière, de midi vers la droite, et disparaît à la fin. Si Riot demande d’attendre (quota atteint), l’arc s’arrête et la ligne dit « Quota Riot atteint : reprise dans 12 s », décomptée chaque seconde, puis l’import reprend tout seul. Ensuite, seules ses nouvelles Parties sont récupérées, quand vous le choisissez dans le sélecteur ou que vous appuyez sur **Actualiser** pendant que son Défi est affiché ; l’appli ne le fait jamais d’elle-même. Si l’import est interrompu, il reprend de la même façon sans refaire ce qui est enregistré. Un Ami qui se connecte au client sur votre PC reste un Ami, suivi comme votre Compte actif. Quand Riot change l’identifiant technique (PUUID) d’un Compte ou d’un Ami, par exemple avec une nouvelle clé, Arena Tracker le retrouve par une de ses Parties enregistrées et garde son historique ; sans cette preuve (Riot ID changé, Parties trop anciennes), rien n’est modifié ni supprimé : le Riot ID est alors importé comme un second Compte, et l’ancien peut être supprimé dans **Paramètres** (voir « Supprimer un Compte ou un Ami »).
|
||||
|
||||
## Parties
|
||||
|
||||
L’onglet **Parties** liste vos Parties enregistrées, de la plus récente à la plus ancienne, pour le Compte choisi dans le sélecteur de la barre du haut (le Compte connecté au client au démarrage). Chaque ligne montre le champion, la date et l’heure, et le Placement, en or pour un top 1, en vert pour une autre Victoire, en rouge sinon. Au-dessus de la liste, des filtres se combinent : la **Saison** (la Saison actuelle par défaut, ou toutes les Saisons s’il n’y en a pas) et le **Format**, les mêmes sélecteurs que sur **Statistiques** : en changer sur une page le change sur l’autre ; le **Placement** (**Tous**, **Top 1** ou **Victoires**, les Parties que le jeu compte comme gagnées) ; et une recherche de champion, comme sur l’accueil (nom, abréviation connue comme « TF », sans tenir compte des accents ni des majuscules). Le Placement et la recherche sont gardés tant que l’appli reste ouverte. Si aucune Partie ne correspond, la liste le dit et le récapitulatif reste vide. À l’ouverture, la Partie la plus récente que les filtres laissent est choisie et son récapitulatif s’affiche à côté : les équipes rangées par Placement, votre ligne encadrée d’or, et pour chaque joueur son Riot ID, son niveau, son K/D/A, ses objets, ses améliorations et ses dégâts aux champions (une barre comparée au meilleur de la Partie, partagée entre physiques, magiques et bruts, le total à côté). Les objets et les améliorations montrent leur icône dans une case, leur nom dans la bulle de survol, toujours en français, quelle que soit la langue du client (les objets viennent de Data Dragon, les améliorations de CommunityDragon) ; sans eux (première ouverture hors ligne, objet très récent), une icône neutre et « Objet n » ou « Amélioration n ». Survoler un objet ou une amélioration, dans le récapitulatif ou dans **Dégâts observés dans les récaps de mort**, affiche une bulle avec son nom et sa description ; un « ? » marque une valeur que le jeu calcule pendant la Partie, et « Description indisponible » une description que le catalogue n’a pas. Ces noms, descriptions et icônes sont gardés sur le disque : ils restent lisibles hors ligne. L’appli regarde si le jeu a changé de patch à son lancement et à chaque ouverture du client, jamais en continu, et ne télécharge de nouveau que dans ce cas ; au premier téléchargement, les icônes apparaissent au fur et à mesure ; si CommunityDragon n’a pas encore le nouveau patch, les noms précédents restent jusqu’à la vérification suivante. Cliquez une autre Partie, ou parcourez la liste avec les flèches haut et bas. Cliquez la ligne d’un joueur (ou atteignez-la avec Tab, puis Entrée ou Espace) pour déplier ses détails, en barres avec leur valeur à côté : dégâts aux champions et reçus (une barre partagée entre physiques, magiques et bruts), puis dégâts atténués, soins et boucliers sur les alliés, or gagné et dépensé, contrôle (une barre par valeur, pleine pour le meilleur joueur de la Partie) ; recliquez pour les replier. Les totaux sont ceux de Riot, tels quels. Une valeur que Riot ne donne pas s’affiche « Indisponible ». Sous ces valeurs, la section **Dégâts observés dans les récaps de mort** détaille, par objet et par amélioration du joueur (puis « Autres effets »), les dégâts que les récaps de mort des champions éliminés lui attribuent : c’est la seule source de dégâts par effet, si bien que les dégâts infligés à un champion qui survit n’y figurent jamais et que le total de la Partie par effet reste indisponible. Les récaps sont récupérés chez Riot une fois par Partie, à la fin d’une Partie suivie ou à la première ouverture d’une Partie plus ancienne ; une Partie provisoire affiche « En attente », une Partie dont Riot refuse les récaps « Indisponible », et en cas d’échec passager le bouton **Réessayer** les redemande. Une bannière, la même que celle du Défi (Saison, compteur, anneau), surmonte la liste et le récapitulatif : son illustration est le champion de la Partie choisie, dont la graduation est allumée sur l’anneau. Dans une fenêtre étroite, la liste et ses filtres s’ouvrent avec le bouton **Parties** au-dessus du récapitulatif. Si la Partie affichée n’est plus laissée par un filtre, la première Partie de la liste prend sa place.
|
||||
|
||||
À la fin d’une Partie Arena, dès que le client donne son résultat, l’appli affiche **Parties** sur cette Partie (marquée « Provisoire » jusqu’à sa publication par Riot), où que vous soyez, Paramètres compris. Le Placement repasse à **Tous** et la recherche se vide pour qu’elle apparaisse. Si la Saison ou le Format choisis l’écartent, ils reviennent à la Saison de la Partie (toutes les Saisons si aucune ne la contient) et à tous les Formats (sur **Statistiques** aussi). La fenêtre ne passe pas au premier plan et ne vous prend pas le focus : réduite ou cachée dans la zone de notification, elle le reste. L’animation de fin de Partie (la comète d’un top 1, le compteur qui monte) joue alors sur la bannière de **Parties** ; en revenant sur le Défi, vous le trouvez dans son état final, sans la revoir. Changez ensuite d’onglet librement, rien ne vous ramène sur **Parties**. Si le client ne donne pas de résultat, **En partie** reste jusqu’au retour au salon, puis l’appli affiche le Défi. Pour afficher le Défi plutôt que **Parties** à la fin d’une Partie, désactivez **Ouvrir le récapitulatif en fin de Partie** dans les Paramètres : la Partie reste dans la liste.
|
||||
À la fin d’une Partie Arena, dès que le client donne son résultat, l’appli affiche **Parties** sur cette Partie (marquée « Provisoire » jusqu’à sa publication par Riot), où que vous soyez, Paramètres compris. Le Placement repasse à **Tous** et la recherche se vide pour qu’elle apparaisse. Si la Saison ou le Format choisis l’écartent, ils reviennent à la Saison de la Partie (toutes les Saisons si aucune ne la contient) et à tous les Formats (sur **Statistiques** aussi). Comme à l’entrée en sélection, la fenêtre passe au premier plan, même réduite ou cachée dans la zone de notification, sans vous prendre le focus ; elle y passe aussi quand l’appli affiche le Défi en fin de Partie. L’animation de fin de Partie (la comète d’un top 1, le compteur qui monte) joue alors sur la bannière de **Parties** ; en revenant sur le Défi, vous le trouvez dans son état final, sans la revoir. Changez ensuite d’onglet librement, rien ne vous ramène sur **Parties**. Si le client ne donne pas de résultat, **En partie** reste jusqu’au retour au salon, puis l’appli affiche le Défi. Pour afficher le Défi plutôt que **Parties** à la fin d’une Partie, désactivez **Ouvrir le récapitulatif en fin de Partie** dans les Paramètres : la Partie reste dans la liste.
|
||||
|
||||
## Installer
|
||||
|
||||
|
||||
+4
-4
@@ -15,7 +15,7 @@ L’identité « L’Anneau » (itération « La Bannière ») habille ensuite c
|
||||
1. À chaque ouverture, « Tous » est sélectionné. La grille présente tous les champions, y compris ceux jamais joués et ceux déjà validés. La recherche par nom et les filtres « Restants » et « Validés » permettent de réduire la grille.
|
||||
2. La bannière ouvre l’accueil. Elle porte l’anneau, un titre-compteur « N / total champions validés » surmonté de la Saison (précédée de « Défi de Pseudo · » pour un Compte autre que le Compte actif), et deux lignes : « Dernier champion validé : X, le … » et « Dernière Partie : … ». La seconde est permanente : elle se calcule à partir des Parties enregistrées, pas des seules Parties suivies pendant la session. Le titre « Défi de saison » disparaît. Le total reste celui du Défi quand on recherche un champion, filtre la grille ou passe en sélection. La section « Identité » décrit la bannière et l’anneau.
|
||||
3. Lorsqu’aucune préférence de tri n’a encore été enregistrée, les champions sont classés par points de maîtrise décroissants. Le joueur peut choisir A–Z. Le même choix s’applique aux deux écrans et à toutes leurs sections de cartes, puis à la prochaine ouverture. L’anneau n’est pas une section de cartes : c’est une jauge à l’ordre fixe, qui ne suit pas le tri choisi.
|
||||
4. **Compte.** Un seul sélecteur de Compte, à côté des onglets dans la barre du haut, choisit le Compte que montrent « Défi » (bannière, anneau, grille, fiches), « Statistiques » et « Parties » : il liste, sous « Vos Comptes », les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client, ou le dernier connu quand il est fermé) en premier, puis, sous « Amis » (seulement s’il y en a), les Amis ; sa dernière entrée, seule, est « Ajouter un ami… ». L’appli démarre sur le Compte actif et y revient à l’entrée dans une phase (sélection, Partie en cours), où le sélecteur est grisé, et quand une Partie suivie s’ouvre en fin de Partie. Un autre Compte rétablit « Tous » dans le filtre de l’accueil et dans celui de « Statistiques » ; le tri et le thème sont communs à tous les Comptes. Ses statistiques sont calculées une fois, hors du thread d’interface. La Progression officielle et les animations de fin de Partie ne concernent que le Compte actif. **Amis.** Un Ami est un Compte ajouté par son Riot ID pour consulter son Défi ; ses Parties viennent de l’API Riot, par le service d’Arena Tracker, il n’a rien à installer. « Ajouter un ami… » laisse le Compte affiché sélectionné et ouvre sous l’en-tête un champ « Pseudo#TAG » (avec « Annuler » ; Échap le ferme aussi), validé par Entrée : la recherche tourne hors du thread d’interface, à basse priorité, « Recherche du Compte… » l’indique et Entrée est ignorée en attendant. Un refus s’affiche à côté du champ, qui garde son texte : Riot ID mal formé (« Saisissez un Riot ID de la forme Pseudo#TAG. »), « Aucun Compte ne porte ce Riot ID. », « Ce Compte joue dans une autre région. », ou le message d’un échec passager (service indisponible, réseau). Un Compte déjà connu (le vôtre ou un Ami) est simplement sélectionné. Une fois l’Ami ajouté, il est sélectionné et son Défi s’affiche. L’import de son historique Arena disponible tourne en arrière-plan, à basse priorité, après les requêtes du Compte actif, en attendant le `Retry-After` du service quand son quota est plein : la Saison en cours d’abord, puis les autres ; le Défi se remplit au fur et à mesure (rechargé au plus une fois par seconde) et la ligne d’état de l’en-tête dit « Import de Pseudo : n / N Parties » (« Import de Pseudo… » pendant la recherche des Parties) ; ses points de maîtrise sont récupérés à la fin. Une erreur de l’import s’affiche en une ligne d’alerte sans masquer les données enregistrées, et l’import d’un Ami supprimé s’arrête sans rien dire. Ensuite seules les nouvelles Parties sont récupérées, quand on choisit l’Ami dans le sélecteur ou avec « Actualiser » pendant qu’il est affiché (qui n’actualise alors que lui) : jamais à intervalle régulier ni au lancement. Un import interrompu reprend à l’une de ces deux occasions, sans réimporter les Parties déjà enregistrées. Un seul import tourne à la fois ; la demande faite pendant l’un attend sa fin, la dernière gagne. Un Ami qui se connecte au client sur ce PC reste un Ami, sous « Amis » : l’appli le suit alors comme tout Compte actif (le premier de son groupe), ses Parties en direct comprises, et « Actualiser » est celle du suivi.
|
||||
4. **Compte.** Un seul sélecteur de Compte, à côté des onglets dans la barre du haut, choisit le Compte que montrent « Défi » (bannière, anneau, grille, fiches), « Statistiques » et « Parties » : il liste, sous « Vos Comptes », les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client, ou le dernier connu quand il est fermé) en premier, puis, sous « Amis » (seulement s’il y en a), les Amis ; sa dernière entrée, seule, est « Ajouter un ami… ». L’appli démarre sur le Compte actif et y revient à l’entrée dans une phase (sélection, Partie en cours), où le sélecteur est grisé, et quand une Partie suivie s’ouvre en fin de Partie. Un autre Compte rétablit « Tous » dans le filtre de l’accueil et dans celui de « Statistiques » ; le tri et le thème sont communs à tous les Comptes. Ses statistiques sont calculées une fois, hors du thread d’interface. La Progression officielle et les animations de fin de Partie ne concernent que le Compte actif. **Amis.** Un Ami est un Compte ajouté par son Riot ID pour consulter son Défi ; ses Parties viennent de l’API Riot, par le service d’Arena Tracker, il n’a rien à installer. « Ajouter un ami… » laisse le Compte affiché sélectionné et ouvre sous l’en-tête un champ « Pseudo#TAG » (avec « Annuler » ; Échap le ferme aussi), validé par Entrée : la recherche tourne hors du thread d’interface, à basse priorité, « Recherche du Compte… » l’indique et Entrée est ignorée en attendant. Un refus s’affiche à côté du champ, qui garde son texte : Riot ID mal formé (« Saisissez un Riot ID de la forme Pseudo#TAG. »), « Aucun Compte ne porte ce Riot ID. », « Ce Compte joue dans une autre région. », ou le message d’un échec passager (service indisponible, réseau). Un Compte déjà connu (le vôtre ou un Ami) est simplement sélectionné. Une fois l’Ami ajouté, il est sélectionné et son Défi s’affiche. L’import de son historique Arena disponible tourne en arrière-plan, à basse priorité, après les requêtes du Compte actif, en attendant le `Retry-After` du service quand son quota est plein : la Saison en cours d’abord, puis les autres ; le Défi se remplit au fur et à mesure (rechargé au plus une fois par seconde) et la ligne d’état de l’en-tête dit « Import de Pseudo : n / N Parties » (« Import de Pseudo… » pendant la recherche des Parties), ou « Quota Riot atteint : reprise dans 12 s » (décomptée chaque seconde) tant que l’import attend le quota Riot, puis l’import reprend ; un arc se remplit autour de l’anneau (section « Identité ») quand il porte sur 10 Parties ou plus ; ses points de maîtrise sont récupérés à la fin. Une erreur de l’import s’affiche en une ligne d’alerte sans masquer les données enregistrées, et l’import d’un Ami supprimé s’arrête sans rien dire. Ensuite seules les nouvelles Parties sont récupérées, quand on choisit l’Ami dans le sélecteur ou avec « Actualiser » pendant qu’il est affiché (qui n’actualise alors que lui) : jamais à intervalle régulier ni au lancement. Un import interrompu reprend à l’une de ces deux occasions, sans réimporter les Parties déjà enregistrées. Un seul import tourne à la fois ; la demande faite pendant l’un attend sa fin, la dernière gagne. Un Ami qui se connecte au client sur ce PC reste un Ami, sous « Amis » : l’appli le suit alors comme tout Compte actif (le premier de son groupe), ses Parties en direct comprises, et « Actualiser » est celle du suivi.
|
||||
|
||||
### Carte de champion
|
||||
|
||||
@@ -60,7 +60,7 @@ Cette section décrit l’identité « L’Anneau ». [La page de référence](p
|
||||
|
||||
**Bannière de sélection.** Elle ouvre l’onglet « Sélection » pendant une sélection Arena ; « Défi » garde la bannière d’accueil. Son surtitre porte le compteur, son titre est « Sélection des champions », et sa ligne indique « Champions de l’Enclume · k à valider et disponibles ». Seules les graduations des Champions de l’Enclume y restent vives. L’illustration suit la carte survolée ; au repos, c’est celle du premier Champion de l’Enclume à valider et disponible. La barre du haut n’affiche pas d’autre indicateur de sélection que l’onglet « Sélection ».
|
||||
|
||||
**Anneau.** Une graduation par champion du Défi, dans un ordre fixe : d’abord les validés, dans l’ordre de leur Premier top 1 en tournant depuis midi, puis les champions joués, puis ceux jamais joués, ces deux derniers groupes par points de maîtrise décroissants (A–Z tant que les points sont inconnus, comme les cartes). Il ne suit pas le tri choisi. Survoler la couronne vise la graduation la plus proche par l’angle, pas au pixel près (dans une bande qui déborde un peu les graduations, à l’intérieur comme à l’extérieur) : elle s’allume comme au survol d’une carte, l’illustration de la bannière passe en fondu sur ce champion (sans fondu quand les animations Windows sont coupées) et la première ligne de la bannière devient la sienne, son nom en gras : « X · validé le 12 nov. · 3 Tentatives » (« · du premier coup » pour une seule), « X · 2 Parties · meilleur Placement 3ᵉ » (« 1 Partie » au singulier ; sans Placement connu, la fin est omise) ou « X · jamais joué », selon les chiffres de la Saison, tous Formats. Le titre ne change pas ; la seconde ligne (« Dernière Partie : … ») est masquée sans que rien ne bouge. En quittant la couronne, la bannière revient à l’état de repos de l’écran affiché (« Défi », « Sélection », « En partie »), et il en va de même partout où l’anneau est affiché. Pendant l’animation de fin de Partie, le survol de l’anneau est ignoré. Règle n° 1 : rien n’est redessiné tant que la graduation visée ne change pas, hors de la couronne il n’y a aucun travail, et un balayage rapide ne décode jamais plus de deux illustrations à la fois, la dernière graduation visée l’emportant.
|
||||
**Anneau.** Une graduation par champion du Défi, dans un ordre fixe : d’abord les validés, dans l’ordre de leur Premier top 1 en tournant depuis midi, puis les champions joués, puis ceux jamais joués, ces deux derniers groupes par points de maîtrise décroissants (A–Z tant que les points sont inconnus, comme les cartes). Il ne suit pas le tri choisi. Survoler la couronne vise la graduation la plus proche par l’angle, pas au pixel près (dans une bande qui déborde un peu les graduations, à l’intérieur comme à l’extérieur) : elle s’allume comme au survol d’une carte, l’illustration de la bannière passe en fondu sur ce champion (sans fondu quand les animations Windows sont coupées) et la première ligne de la bannière devient la sienne, son nom en gras : « X · validé le 12 nov. · 3 Tentatives » (« · du premier coup » pour une seule), « X · 2 Parties · meilleur Placement 3ᵉ » (« 1 Partie » au singulier ; sans Placement connu, la fin est omise) ou « X · jamais joué », selon les chiffres de la Saison, tous Formats. Le titre ne change pas ; la seconde ligne (« Dernière Partie : … ») est masquée sans que rien ne bouge. En quittant la couronne, la bannière revient à l’état de repos de l’écran affiché (« Défi », « Sélection », « En partie »), et il en va de même partout où l’anneau est affiché. Pendant l’animation de fin de Partie, le survol de l’anneau est ignoré. Règle n° 1 : rien n’est redessiné tant que la graduation visée ne change pas, hors de la couronne il n’y a aucun travail, et un balayage rapide ne décode jamais plus de deux illustrations à la fois, la dernière graduation visée l’emportant. **Arc d’import (#140).** Pendant l’import des Parties du Compte affiché (le vôtre, au premier lancement par exemple, ou celui d’un Ami), un arc fin entoure les graduations : il part de midi et se remplit dans le sens horaire en proportion de « Parties récupérées / Parties à récupérer », le reste du cercle restant tracé plus discrètement. Il n’apparaît qu’à partir de 10 Parties à récupérer (une synchronisation de 1 ou 2 Parties ne le fait pas clignoter), jamais pour l’import d’un autre Compte que celui affiché, sur toutes les bannières qui portent l’anneau (« Défi », « Parties », « En partie »), et disparaît à la fin de l’import, réussi ou en erreur. Il n’est jamais animé : l’anneau est redessiné quand l’arc apparaît ou disparaît et, au plus une fois par seconde, quand le compte change.
|
||||
|
||||
**Illustration.** La bannière montre une fenêtre d’environ 80 % de la largeur du splash du champion, centrée sur lui (voir les décisions d’implémentation pour le cadrage). Elle passe d’une illustration à l’autre par un fondu.
|
||||
|
||||
@@ -85,7 +85,7 @@ Pour une Saison, présenter d’abord la courbe cumulée des champions validés,
|
||||
L’onglet permanent « Parties », à droite de « Défi » dans la barre du haut, liste les Parties enregistrées du Compte choisi dans la barre du haut (le Compte actif au démarrage), de la plus récente à la plus ancienne, filtrées par Saison, Format, Placement et champion (voir « Filtres »). « Défi » n’est allumé que sur « Défi » et « Statistiques », « Parties » sur sa page. On y passe avec le voile des transitions.
|
||||
|
||||
- **Sélection.** Ouvrir l’onglet à la main choisit la Partie la plus récente de celles que les filtres laissent : le choix précédent n’est pas gardé d’une ouverture à l’autre. Un clic ou les flèches haut et bas choisissent une autre Partie, Entrée confirme ; son Récapitulatif de partie s’affiche à côté. Pendant une synchronisation, la Partie choisie le reste tant qu’elle est listée et que les filtres la laissent.
|
||||
- **Ouverture en fin de Partie.** À l’arrivée du bloc de fin d’une Partie Arena suivie (sa Partie provisoire), l’appli affiche « Parties » avec cette Partie choisie et son récapitulatif, d’où que l’on soit (« Défi », « Statistiques », le récapitulatif d’une autre Partie) ; « Paramètres » se ferme, comme à l’entrée en sélection (« la phase décide »). Le Placement revient à « Tous » et la recherche se vide pour qu’elle soit listée ; si la Saison ou le Format choisis (ceux de « Statistiques », les mêmes sélecteurs) l’écartent, ils reviennent à la Saison de la Partie (toutes les Saisons si aucune ne la contient) et à « Tous les Formats », « Statistiques » se recalculant en conséquence en arrière-plan, pour que la nouvelle Partie soit celle qui est choisie ; s’ils la gardent, ils ne bougent pas. Tant que la liste relue ne la contient pas, aucun autre récapitulatif ne s’affiche. La fenêtre n’est jamais mise au premier plan et ne prend pas le focus : réduite ou cachée dans la zone de notification, elle le reste, et la bascule s’y fait sans voile. Le bloc est enregistré en base dès son arrivée, sans attendre une synchronisation en cours, avec le Compte connecté à ce moment : la Partie provisoire est de ce Compte, même si un autre se connecte avant sa conversion. Un bloc dont rien ne dit le mode (ni mode, ni file, ni partie vue en cours) est gardé ; seul un bloc d’un autre mode est écarté. Le texte du bloc, gardé tel que reçu tant que la Partie provisoire peut en avoir besoin (bloc pas encore converti, ou converti et toujours provisoire), est effacé de la base dès qu’il ne sert plus : bloc d’une Partie qui n’est pas Arena, ou Partie publiée par Riot. Un bloc qui ne se convertit pas est relu toutes les 20 s pendant la fenêtre d’attente de la Partie (environ 30 minutes), puis seulement après une synchronisation réussie (adoption d’un Compte, par exemple), et abandonné au bout de 7 jours (son texte reste alors). Ensuite rien ne ramène sur « Parties » : la correction de la Partie publiée, une relecture ou une synchronisation ne déplacent pas le joueur. Quand le client quitte une Partie Arena sans bloc, l’appli affiche le Défi, d’où que l’on soit. La fin de chaque Partie ne décide qu’une fois : la sortie de partie qui suit un bloc ne déplace rien, mais un bloc arrivé après la sortie ouvre encore son récapitulatif. Une Partie trouvée seulement chez Riot ne déplace rien, et pendant une sélection Arena rien ne bascule. « En partie » reste affiché jusqu’au bloc ou au retour au salon : une sortie de partie sans bloc n’affiche le Défi qu’au retour au salon (voir « Pendant une Partie en cours »). Le réglage « Ouvrir le récapitulatif en fin de Partie » des Paramètres, activé par défaut et enregistré, coupe cette ouverture : l’appli affiche le Défi, et la Partie est dans l’historique. Une Partie qu’aucune Saison ne contient s’ouvre aussi, sans rien apporter au Défi. L’animation de fin de Partie garde ses règles, mais joue sur « Parties » : elle attend que l’écran soit visible et que la nouvelle Partie soit choisie ; réglage désactivé, elle joue sur « Défi ».
|
||||
- **Ouverture en fin de Partie.** À l’arrivée du bloc de fin d’une Partie Arena suivie (sa Partie provisoire), l’appli affiche « Parties » avec cette Partie choisie et son récapitulatif, d’où que l’on soit (« Défi », « Statistiques », le récapitulatif d’une autre Partie) ; « Paramètres » se ferme, comme à l’entrée en sélection (« la phase décide »). Le Placement revient à « Tous » et la recherche se vide pour qu’elle soit listée ; si la Saison ou le Format choisis (ceux de « Statistiques », les mêmes sélecteurs) l’écartent, ils reviennent à la Saison de la Partie (toutes les Saisons si aucune ne la contient) et à « Tous les Formats », « Statistiques » se recalculant en conséquence en arrière-plan, pour que la nouvelle Partie soit celle qui est choisie ; s’ils la gardent, ils ne bougent pas. Tant que la liste relue ne la contient pas, aucun autre récapitulatif ne s’affiche. Comme à l’entrée en sélection, la fenêtre passe au premier plan sans prendre le focus, même réduite ou cachée dans la zone de notification, et la bascule s’y fait sans voile ; il en va de même quand la fin de Partie affiche le Défi (réglage désactivé, ou sortie sans bloc). Le bloc est enregistré en base dès son arrivée, sans attendre une synchronisation en cours, avec le Compte connecté à ce moment : la Partie provisoire est de ce Compte, même si un autre se connecte avant sa conversion. Un bloc dont rien ne dit le mode (ni mode, ni file, ni partie vue en cours) est gardé ; seul un bloc d’un autre mode est écarté. Le texte du bloc, gardé tel que reçu tant que la Partie provisoire peut en avoir besoin (bloc pas encore converti, ou converti et toujours provisoire), est effacé de la base dès qu’il ne sert plus : bloc d’une Partie qui n’est pas Arena, ou Partie publiée par Riot. Un bloc qui ne se convertit pas est relu toutes les 20 s pendant la fenêtre d’attente de la Partie (environ 30 minutes), puis seulement après une synchronisation réussie (adoption d’un Compte, par exemple), et abandonné au bout de 7 jours (son texte reste alors). Ensuite rien ne ramène sur « Parties » : la correction de la Partie publiée, une relecture ou une synchronisation ne déplacent pas le joueur. Quand le client quitte une Partie Arena sans bloc, l’appli affiche le Défi, d’où que l’on soit. La fin de chaque Partie ne décide qu’une fois : la sortie de partie qui suit un bloc ne déplace rien, mais un bloc arrivé après la sortie ouvre encore son récapitulatif. Une Partie trouvée seulement chez Riot ne déplace rien, et pendant une sélection Arena rien ne bascule. « En partie » reste affiché jusqu’au bloc ou au retour au salon : une sortie de partie sans bloc n’affiche le Défi qu’au retour au salon (voir « Pendant une Partie en cours »). Le réglage « Ouvrir le récapitulatif en fin de Partie » des Paramètres, activé par défaut et enregistré, coupe cette ouverture : l’appli affiche le Défi, et la Partie est dans l’historique. Une Partie qu’aucune Saison ne contient s’ouvre aussi, sans rien apporter au Défi. L’animation de fin de Partie garde ses règles, mais joue sur « Parties » : elle attend que l’écran soit visible et que la nouvelle Partie soit choisie ; réglage désactivé, elle joue sur « Défi ».
|
||||
- **Filtres.** Une rangée au-dessus de la liste (dans la colonne de la liste : derrière le bouton « Parties » dans une fenêtre étroite) : les sélecteurs de Saison et de Format, un contrôle segmenté de Placement « Tous · Top 1 · Victoires » et un champ de recherche de champion. Les filtres se combinent. Saison et Format sont les sélecteurs de « Statistiques », avec le même état : choisir l’un sur une page le change sur l’autre (et, comme sur « Statistiques », la Saison choisie est celle du Défi affiché sur « Défi »). Par défaut la Saison actuelle, ou « Toutes les Saisons » quand il n’y en a pas, comme sur « Statistiques ». Une Partie est de la Saison dont la période contient son début. « Top 1 » garde les Parties de Placement 1 ; « Victoires » celles que le jeu compte comme gagnées (Win : le top 3 en Arena 3x6). La recherche est celle de l’accueil (nom, identifiant Data Dragon, alias connus ; sans casse ni accents), avec son propre champ. Placement et recherche ne sont pas ceux de « Statistiques » et sont gardés tant que l’appli tourne, sans être enregistrés ; ils reviennent à « Tous » et à vide au lancement. Le filtrage se fait sur les Parties déjà chargées, sans nouvelle lecture de la base : seules les lignes gardées sont écrites dans la liste. Si la Partie choisie est écartée, la première Partie gardée est choisie et son récapitulatif s’affiche ; s’il n’en reste aucune, la liste dit « Aucune Partie ne correspond aux filtres » et le récapitulatif est vide. Les filtres restent affichés pour être changés.
|
||||
- **Compte.** Le sélecteur de Compte de la barre du haut est actif sur cette page (grisé pendant une phase) : choisir un autre Compte remplace la liste aussitôt, sans jamais mélanger les Parties de deux Comptes, choisit la plus récente et replie le joueur déplié. Un changement de Compte dans le client fait de même quand le Compte actif est affiché, c’est-à-dire quand aucun autre Compte n’est choisi.
|
||||
- **Ligne de la liste.** Portrait et nom du champion, date et heure de début (heure de Windows, « 15 nov. 2026 · 18:29 »), Placement (« 1ᵉʳ », « 2ᵉ »…) coloré selon le résultat : or pour un top 1, vert pour une autre Victoire, rouge sinon, et « Provisoire » pour une Partie provisoire. Pas de Format dans la ligne.
|
||||
@@ -95,7 +95,7 @@ L’onglet permanent « Parties », à droite de « Défi » dans la barre du ha
|
||||
- **Dégâts observés dans les récaps de mort.** Sous les cinq rangées des détails d’un joueur, une section titrée « Dégâts observés dans les récaps de mort ». Seule la chronologie Match‑V5 donne des dégâts par effet, et seulement ceux qu’un champion reçoit avant de mourir : chaque entrée de récap de mort est comptée une seule fois, pour le joueur qui l’a infligée et son effet. Les dégâts infligés à un champion qui survit ne sont jamais attribués ; le total de la Partie par effet est indisponible, ce que la section dit une fois, en gris (« Le total de la Partie par effet est indisponible : seuls les dégâts subis avant une élimination sont détaillés. Les dégâts infligés à un champion qui survit ne sont jamais attribués. »). Une ligne par objet ou amélioration du joueur reconnu (icône et nom du catalogue, comme dans le récapitulatif, total des dégâts, puis les types qui ont infligé quelque chose, « Physiques 120 · Magiques 80 »), du plus au moins dommageable, puis « Autres effets » (attaques de base, sorts du champion, effets qui ne sont pas un objet ou une amélioration de sa fin de Partie). La correspondance est automatique quand le nom de l’effet est l’`augmentNameId` d’une amélioration du joueur (sans tenir compte de la casse) ; les objets, et les améliorations dont le nom diffère, passent par une table d’exceptions tenue à la main (`death_recap/exceptions.tsv` du cœur) ; elle est refaite à chaque lecture, si bien qu’un catalogue renouvelé ou une exception ajoutée s’applique aux Parties déjà récupérées. États de la section : « En attente » pour une Partie provisoire (pas de chronologie, rien n’est demandé) ; « Chargement… » pendant la requête ; « Indisponible » quand Riot refuse la chronologie de cette Partie (403, retenu : elle n’est plus redemandée) ; un bouton « Réessayer » avec un message en cas d’échec passager (réseau, service indisponible), qui redemande ; « Aucun dégât observé » quand aucune entrée ne nomme ce joueur. La chronologie est récupérée une fois par Partie : en arrière-plan, à basse priorité, dès qu’une nouvelle Partie suivie est publiée ; à la première ouverture du récapitulatif pour une Partie plus ancienne, sans jamais rattraper l’historique en masse ni pendant une synchronisation. Seules les entrées des récaps de mort sont gardées en base, jamais la chronologie. Les requêtes passent par le service et respectent `Retry-After`. Le récapitulatif ouvert se relit quand la récupération en arrière-plan de sa Partie se termine. Une même chronologie n’est jamais demandée deux fois à la fois : une Partie publiée pendant que son récapitulatif est ouvert (ou ouverte alors qu’elle est en file) attend la récupération en cours. Un récap de mort mis en correspondance avec un ancien catalogue (récupération en cours quand les données du jeu changent) est relu avec le catalogue courant. La page ne lit qu’un récap de mort à la fois : pendant une lecture, seule la dernière demandée attend (une demande à Riot pour la même Partie n’est pas perdue), et quitter l’écran l’oublie ; parcourir la liste quand Riot est lent ne lance pas un thread par Partie.
|
||||
- **Valeurs absentes.** Une valeur que la source ne donne pas s’affiche « Indisponible », en gris ; 0 seulement si la source donne 0. Dans une Partie provisoire, dont la source est le bloc de fin de partie du client, l’absence s’affiche « En attente ».
|
||||
- **Disposition.** La bannière du Défi est en haut (#110) : la Saison (« Défi de Pseudo · » pour un autre Compte), le compteur, les lignes « Dernier champion validé » et « Dernière Partie », l’icône « Statistiques » dans le coin inférieur droit et l’anneau, sur l’illustration du champion de la Partie choisie dans la liste, dont la graduation est allumée comme celle du champion joué sur « En partie » ; l’illustration passe en fondu quand le choix change. Sans Partie choisie (liste vide, filtres qui n’en gardent aucune), ni illustration ni graduation allumée. Dans une fenêtre basse, la colonne défile sous la bannière : la liste et le récapitulatif gardent au moins 240 px. Dessous, la liste (≈ 320 px, défilante, sous sa rangée de filtres) et le récapitulatif (défilant) côte à côte. Sous ≈ 900 px de large, la liste passe derrière un bouton « Parties » à chevron qui l’ouvre par-dessus le récapitulatif ; choisir une Partie la referme.
|
||||
- **Synchronisation.** Le bandeau, la ligne d’état et le bouton « Actualiser » de la barre de titre restent ceux des autres pages. Les Parties déjà connues restent consultables pendant la synchronisation et après un échec, qui s’affiche en une ligne au-dessus.
|
||||
- **Synchronisation.** Le bandeau, la ligne d’état et le bouton « Actualiser » de la barre de titre restent ceux des autres pages. Les Parties déjà connues restent consultables pendant la synchronisation et après un échec, qui s’affiche en une ligne au-dessus. Quand le quota de l’API Riot est atteint, l’import attend la fin de l’attente demandée par Riot : l’arc de l’anneau reste figé et la ligne d’état dit « Quota Riot atteint : reprise dans 12 s », décomptée chaque seconde (pour le Compte comme pour un Ami, celle de l’import du Compte passant avant), puis la ligne d’import (« Import en cours : n / N Parties », « Import de Pseudo : n / N Parties ») revient à la reprise. Un seul minuteur, démarré pour l’attente, redessine cette ligne ; il n’y en a aucun hors d’une attente.
|
||||
- **États vides.** Sans Compte, « Compte indisponible » ; sans Partie, « Aucune Partie enregistrée » ; Parties enregistrées mais aucune gardée par les filtres, « Aucune Partie ne correspond aux filtres » sous les filtres.
|
||||
- **Règle n° 1.** La liste est la seule partie de l’écran à état propre (sélection, défilement, survol) : une vue en cache, dont seules les lignes visibles sont construites, et que le reste de la page redessiné ne redessine pas. La liste est lue en arrière-plan à l’ouverture de l’écran, puis quand les Parties enregistrées changent pendant qu’il est affiché ; caché, il est seulement marqué à relire, et il ne l’est que si les Parties enregistrées ont changé entre-temps (ou qu’une lecture a été coupée ou a échoué) : rouvrir l’écran sans changement ne relit pas la base, et choisit de nouveau la Partie la plus récente gardée. Un récapitulatif qui n’a pas pu être décodé l’est de nouveau quand la liste est relue ou que l’écran se rouvre. Un seul décodage de récapitulatif à la fois, un résultat périmé est jeté. Rien ne tourne au repos, et les portraits sont rendus en quittant l’écran.
|
||||
|
||||
|
||||
+1
-1
@@ -74,6 +74,6 @@ The identity (ring, banner, animations; `docs/interface.md`) follows the same ru
|
||||
- **The end of a followed Match is drawn over the cached ring, the cached grid and the banner** (#89). The comet, the flaring tick and the bouncing crown are a function of the page's render in a layer over the ring (`Ring::match_layer`): the ring is not drawn again, and the comet and the tick are built at each frame only while the animation runs, unlike the ring's own shapes, built once per set of ticks; the crown is the ring's own, moved. The card that changes is drawn over its grid like a lifted card at rest (`card_lift.rs`), and stays in the grid until the animation ends even if the filter leaves it out. With the pointer on the grid, nothing moves under it: the grid of the new statistics (order, cards, filter) is prepared when they arrive, and the pointer leaving only puts it in place. The banner's counter rolls in painted over its place in the title, and the splash of the champion validé settles in with the banner's own decode. The animation is fixed when it starts (tick, duration) and reads no statistics at each frame; each frame is asked for by the page's render while it runs, and none after. Structural tests check that it draws neither the grid nor the ring again, tessellates no crown, builds no card, recomputes no statistics and asks for no frame at rest, and that leaving a grid it held still sorts nothing and builds no card.
|
||||
- **Two splashes decoded at most**: the one shown and the one replacing it. All splashes are downloaded in the background, at low priority, after the card portraits, and kept on disk.
|
||||
- During champ select, the Anvil grid is cached at the height of its card rows. The capture replay checks that a splash fade builds no cards and that traversing the hand and « Autres champions » keeps at most two decoded splashes. The latest hovered card takes over when the current fade finishes.
|
||||
- **The ring is a cached view**, laid out from its style alone. A structural test guards it: hovering a card, scrolling the grid or an animation on another part does not render the ring; only a change of what it shows (the champions' state, their order, the selection) or its own animation does. Its gain is checked at the next release benchmark.
|
||||
- **The ring is a cached view**, laid out from its style alone. A structural test guards it: hovering a card, scrolling the grid or an animation on another part does not render the ring; only a change of what it shows (the champions' state, their order, the selection, the import's arc: when it appears or disappears, and its count at most once a second) or its own animation does. The arc's circle is built once per size and its done part once per progress, and a hover tessellates only the lit tick, during an import too. The Riot quota countdown draws the status line, never the ring. Its gain is checked at the next release benchmark.
|
||||
- **The « Parties » list is a cached view** (`MatchList`, `crates/app/src/page/matches/list.rs`), which owns its selection, scroll and hover. The page drawn again (the recap arriving, the veil) does not draw it: a structural test in `crates/app/src/page/tests/matches.rs` checks that its render count does not move. Its gain is checked at the next release benchmark.
|
||||
- The « Parties » recap owns its scroll area and image cache. The match-end animation test checks that advancing the banner by one frame reuses the ready recap. Check the frame-time gain with a full recap at the next release benchmark.
|
||||
Reference in new issue
Block a user