diff --git a/crates/app/src/page/import_view.rs b/crates/app/src/page/import_view.rs index b9cc58b..c58bd3e 100644 --- a/crates/app/src/page/import_view.rs +++ b/crates/app/src/page/import_view.rs @@ -109,12 +109,14 @@ impl Page { .flatten(); let progress = friend.or_else(|| { let own = self.progress.filter(|p| p.to_fetch >= ARC_FROM)?; - // The Account the follower or the refresh imports is the one signed in to the client. - let signed_in = self.tracker.signed_in_riot_id_folded(); - let imported = (signed_in.and_then(|id| { - (self.accounts.iter()).find(|a| account_riot_id(a).to_lowercase() == *id) - })) - .or(self.active_account())?; + // 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.tracker.signed_in_riot_id_folded() { + Some(id) => { + (self.accounts.iter()).find(|a| account_riot_id(a).to_lowercase() == *id)? + } + None => self.active_account()?, + }; (imported.puuid == *shown).then_some(own) })?; (progress.to_fetch >= ARC_FROM).then_some((progress.fetched, progress.to_fetch)) diff --git a/crates/app/src/page/tests/friends_fixtures.rs b/crates/app/src/page/tests/friends_fixtures.rs index fc2b0b3..cb9421c 100644 --- a/crates/app/src/page/tests/friends_fixtures.rs +++ b/crates/app/src/page/tests/friends_fixtures.rs @@ -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; @@ -90,7 +90,10 @@ impl MatchHistorySource for Riot { let Some(at) = CARL.iter().position(|carl| *carl == id) 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 carl = if self.handles.new_key.load(Ordering::SeqCst) { "Carl2" diff --git a/crates/app/src/page/tests/import_arc.rs b/crates/app/src/page/tests/import_arc.rs index 411a21f..c852da6 100644 --- a/crates/app/src/page/tests/import_arc.rs +++ b/crates/app/src/page/tests/import_arc.rs @@ -5,7 +5,7 @@ use super::banner_fixtures::ring_renders; use super::friends_fixtures::{Handles, tracker}; -use super::page_fixtures::{draw, open_page_with_tracker}; +use super::page_fixtures::{champions, draw, open_page_with_tracker, show, statistics}; use crate::page::Page; use crate::worker::Msg; use arena_tracker_core::SyncProgress; @@ -158,8 +158,12 @@ async fn the_ring_is_drawn_again_only_for_the_arc_and_at_most_once_a_second( ) { let (page, mut window, _) = on_alice(cx).await; let cx = &mut window; + show(&page, cx, statistics(0, 5, champions(5))); draw(cx); let renders = ring_renders(&page, cx); + let tessellations = |page: &Entity, 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); @@ -190,9 +194,30 @@ async fn the_ring_is_drawn_again_only_for_the_arc_and_at_most_once_a_second( assert_eq!(arc(&page, cx), Some((4, 12))); assert_eq!(ring_renders(&page, cx), renders + 2); + // Another tick lit draws the ring again, but tessellates nothing: the arc is kept. + let made = tessellations(&page, cx); + cx.update(|_, cx| { + page.update(cx, |p, cx| { + p.ring.update(cx, |r, cx| r.set_lit(Some(2), cx)) + }) + }); + draw(cx); + assert_eq!(ring_renders(&page, cx), renders + 3); + 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), renders + 3); + assert_eq!(ring_renders(&page, cx), renders + 4); +} + +// 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); } diff --git a/crates/app/src/ring.rs b/crates/app/src/ring.rs index 158b51b..30e999a 100644 --- a/crates/app/src/ring.rs +++ b/crates/app/src/ring.rs @@ -190,6 +190,8 @@ pub struct Ring { progress: Option<(usize, usize)>, /// Made by the paint, for its size; forgotten with the ticks. geometry: Rc>>, + /// The arc's paths, made by the paint for its size and progress. + arc: Rc>>, /// How many times it was drawn: the tests check it stays light. #[cfg(test)] pub(crate) renders: usize, @@ -206,6 +208,7 @@ impl Ring { lit: None, progress: None, geometry: Rc::default(), + arc: Rc::default(), #[cfg(test)] renders: 0, #[cfg(test)] @@ -421,6 +424,7 @@ impl Render for Ring { 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(); @@ -457,9 +461,16 @@ impl Render for Ring { if let Some(path) = &geometry.crown { window.paint_path(moved(path, bounds.origin), crown); } - if let Some(progress) = progress { - arc::paint(frame, progress, rest, crown, window); - } + // Made again only for another size or progress. + let _built = arc::paint( + &mut arcs.borrow_mut(), + bounds, + progress, + (rest, crown), + window, + ); + #[cfg(test)] + tessellations.set(tessellations.get() + usize::from(_built)); // Only the lit tick is tessellated when the pointer changes card. if let Some((index, state)) = lit { let mut path = PathBuilder::fill(); diff --git a/crates/app/src/ring/arc.rs b/crates/app/src/ring/arc.rs index 1093f89..e12ef3d 100644 --- a/crates/app/src/ring/arc.rs +++ b/crates/app/src/ring/arc.rs @@ -5,7 +5,7 @@ use std::f32::consts::TAU; use gpui_kit::*; -use super::{C, Frame}; +use super::{C, Frame, moved}; /// Just outside the ticks, which end at `R2`. const RADIUS: f32 = 256.; @@ -36,28 +36,66 @@ pub(super) fn points(fraction: f32) -> Vec<(f32, f32)> { .collect() } -/// Paints the whole circle in `rest`, then the part done in `done`. -pub(super) fn paint( - frame: Frame, - (fetched, to_fetch): (usize, usize), - rest: Hsla, - done: Hsla, - window: &mut Window, -) { - for (fraction, color) in [(1., rest), (fraction(fetched, to_fetch), done)] { - let mut points = points(fraction).into_iter().map(|(x, y)| frame.point(x, y)); - let Some(first) = points.next() else { continue }; - let mut stroke = PathBuilder::stroke(px(WIDTH * frame.scale)); - stroke.move_to(first); - for at in points { - stroke.line_to(at); - } - if let Ok(path) = stroke.build() { - window.paint_path(path, color); +/// The arc's two paths for one size and one progress, made at the origin and moved where the +/// ring is painted, so a paint for the same ones tessellates nothing. +pub(super) struct Made { + size: Size, + progress: (usize, usize), + /// The whole circle, then the part done. + paths: [Option>; 2], +} + +impl Made { + pub(super) fn new(size: Size, progress: (usize, usize)) -> Made { + let frame = Frame::of(Bounds { + origin: Point::default(), + size, + }); + let stroke = |fraction| { + 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() + }; + Made { + size, + progress, + paths: [stroke(1.), stroke(fraction(progress.0, progress.1))], } } } +/// Paints the arc of `progress` in `bounds`: the whole circle in `rest`, then the part done in +/// `done`; none (and nothing kept) without progress. Tessellates, and says so, only when `made` +/// is not for this size and progress. +pub(super) fn paint( + made: &mut Option, + bounds: Bounds, + progress: Option<(usize, usize)>, + (rest, done): (Hsla, Hsla), + window: &mut Window, +) -> bool { + let Some(progress) = progress else { + *made = None; + return false; + }; + let stale = made + .as_ref() + .is_none_or(|m| (m.size, m.progress) != (bounds.size, progress)); + if stale { + *made = Some(Made::new(bounds.size, progress)); + } + for (path, color) in made.iter().flat_map(|m| &m.paths).zip([rest, done]) { + if let Some(path) = path { + window.paint_path(moved(path, bounds.origin), color); + } + } + stale +} + #[cfg(test)] mod tests { use super::{C, RADIUS, WIDTH, fraction, points}; diff --git a/crates/core/src/tracker/friends.rs b/crates/core/src/tracker/friends.rs index 5773c94..a89a67f 100644 --- a/crates/core/src/tracker/friends.rs +++ b/crates/core/src/tracker/friends.rs @@ -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}; @@ -157,10 +158,11 @@ impl Tracker { let mut account = self.stored_account(puuid)?; // Before any request that carries the stored PUUID: a new key may have changed it. gate(); - match with_retry(|| { - self.history - .resolve_account(&account.game_name, &account.tag_line) - }) { + let resolved = told(SyncProgress::default(), on_progress, |on_wait| { + let resolve = || (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. diff --git a/crates/core/src/tracker/rekey.rs b/crates/core/src/tracker/rekey.rs index 847e6e0..02239c3 100644 --- a/crates/core/src/tracker/rekey.rs +++ b/crates/core/src/tracker/rekey.rs @@ -1,15 +1,16 @@ //! 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 player, never on the Riot ID -//! alone; without proof nothing changes. +//! 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, synced_until_key, - with_retry, + OVERLAP_S, PAGE_SIZE, Tracker, friends::platform_key, mastery::mastery_key, + payload::decode_match, synced_until_key, with_retry, }; -use crate::error::Error; +use crate::error::{Error, SourceError}; use crate::follow::{account_riot_id, same_riot_id}; use crate::journal::short; use crate::model::Account; @@ -23,8 +24,7 @@ impl Tracker { } /// Moves every stored Account with the Riot ID of `resolved` (what Riot answers now) to its - /// PUUID, when a stored published Match of the old one is among those of the new one. - /// `gate` runs before the request of the proof. + /// PUUID, when the proof holds (`is_same_player`). `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(); @@ -38,7 +38,9 @@ impl Tracker { Ok(()) } - /// Whether the newest published Match stored for `old` is listed for `new` too. + /// Whether a published Match stored for `old` is listed for `new` too, and `new` played the + /// same champion in it: anyone who shared the Match would pass the first, and a champion is + /// played by one player only in an Arena Match. fn is_same_player(&self, old: &str, new: &str, gate: &dyn Fn()) -> Result { let newest: Option<(u32, i64)> = self .db() @@ -58,7 +60,19 @@ impl Tracker { (self.history).match_ids_when(new, queue_id, 0, PAGE_SIZE, since_s, gate) })?; let stored = self.match_ids_stored(old)?; - Ok(listed.iter().any(|id| stored.contains(id))) + 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 == played.champion_id)) } /// Replaces the PUUID everywhere in one transaction; a new PUUID already stored is merged, diff --git a/crates/core/tests/common/history.rs b/crates/core/tests/common/history.rs index 1a9ed26..855dc04 100644 --- a/crates/core/tests/common/history.rs +++ b/crates/core/tests/common/history.rs @@ -54,6 +54,8 @@ pub struct FakeHistory { 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. @@ -94,6 +96,7 @@ impl FakeHistory { 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, @@ -218,6 +221,11 @@ impl FakeHistory { 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; @@ -348,6 +356,7 @@ impl FakeHistory { impl MatchHistorySource for FakeHistory { fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result { 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(); diff --git a/crates/core/tests/follow.rs b/crates/core/tests/follow.rs index e5990fc..8f89d0d 100644 --- a/crates/core/tests/follow.rs +++ b/crates/core/tests/follow.rs @@ -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"] diff --git a/crates/core/tests/follow/key_change.rs b/crates/core/tests/follow/key_change.rs new file mode 100644 index 0000000..bafbe78 --- /dev/null +++ b/crates/core/tests/follow/key_change.rs @@ -0,0 +1,79 @@ +//! Riot's key changes while the app runs: the Account being updated follows its new PUUID. +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: FakeHistory, + new: FakeHistory, + new_key: Arc, +} + +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 { + 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, + ) -> Result, SourceError> { + self.now() + .match_ids(puuid, queue_id, start, count, start_time_s) + } + + fn fetch_match(&self, match_id: &str) -> Result { + 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: FakeHistory::new(recorded_account(), all.clone()), + 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); +} diff --git a/crates/core/tests/import/quota.rs b/crates/core/tests/import/quota.rs index 39e31e5..dc7cc01 100644 --- a/crates/core/tests/import/quota.rs +++ b/crates/core/tests/import/quota.rs @@ -61,3 +61,36 @@ fn an_import_without_a_wait_never_tells_one() { 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]); +} diff --git a/crates/core/tests/import/rekey.rs b/crates/core/tests/import/rekey.rs index 832204f..f3b7a4a 100644 --- a/crates/core/tests/import/rekey.rs +++ b/crates/core/tests/import/rekey.rs @@ -130,8 +130,12 @@ fn an_account_follows_its_new_puuid_with_everything_stored_for_it() { assert_eq!(report.account.puuid, NEW); assert_eq!((report.added, report.stored), (1, 7)); - // Only the Match it did not have and the Provisional one are fetched. - assert_eq!(fetches.load(Ordering::SeqCst), 2); + // 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 = log.try_iter().collect(); assert_eq!(requests[..2], ["account Joueur#EUW", &format!("ids {NEW}")]); @@ -313,7 +317,9 @@ fn a_friend_follows_its_new_puuid_and_stays_a_friend() { old.add_friend("Ami#FIX").unwrap(); old.import_friend(FRIEND_OLD, &mut |_| {}).unwrap(); drop(old); - let history = FakeHistory::new(ami(FRIEND_NEW), under(FRIEND_NEW, matches())); + 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); @@ -321,7 +327,10 @@ fn a_friend_follows_its_new_puuid_and_stays_a_friend() { assert_eq!(report.account, ami(FRIEND_NEW)); assert_eq!((report.added, report.stored), (0, 3)); - assert_eq!(fetches.load(Ordering::SeqCst), 0); + // 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!( @@ -414,3 +423,6 @@ fn a_friend_whose_riot_id_belongs_to_another_stored_account_is_imported_as_itsel assert_eq!(tracker.match_count(FRIEND_OLD).unwrap(), 2); assert!(before.iter().all(|row| dump(&db).contains(row))); } + +#[path = "rekey/identity.rs"] +mod identity; diff --git a/crates/core/tests/import/rekey/identity.rs b/crates/core/tests/import/rekey/identity.rs new file mode 100644 index 0000000..f6fc5c7 --- /dev/null +++ b/crates/core/tests/import/rekey/identity.rs @@ -0,0 +1,85 @@ +//! The proof names the player, 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 game, 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 { + (rows.iter()) + .filter(|r| r.contains(FRIEND_OLD)) + .cloned() + .collect() + }; + assert_eq!(friend_rows(&after), friend_rows(&before)); +} + +#[test] +fn a_stranger_of_the_same_match_taking_a_friends_riot_id_does_not_take_the_friend() { + let dir = tempfile::tempdir().unwrap(); + let db = dir.path().join("arena.db"); + duo_world(&db); + let before = dump(&db); + // A third player of that game took "Ami#FIX": Riot lists the game for them too. + let theirs = payload("EUW1_4", 1750, 50, "Champion", 1, 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); +} diff --git a/docs/adr/0008-riot-calls-go-through-a-relay-holding-the-production-key.md b/docs/adr/0008-riot-calls-go-through-a-relay-holding-the-production-key.md index 23aa6a0..85c78ac 100644 --- a/docs/adr/0008-riot-calls-go-through-a-relay-holding-the-production-key.md +++ b/docs/adr/0008-riot-calls-go-through-a-relay-holding-the-production-key.md @@ -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. Before a request that carries a stored PUUID, the app asks Riot for the PUUID of the Riot ID and moves the stored Account to it only if a stored published Match is among the new PUUID's Matches; without that proof nothing changes (#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 played the same champion in it (so not a mere co-player 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). diff --git a/docs/performance.md b/docs/performance.md index 7ce3170..cbae6e5 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -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, the import's arc: when it appears or disappears, and its count at most once a second) or its own animation does. The Riot quota countdown draws the status line, never the ring. 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 two paths are built once per size and 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.