diff --git a/src/FourFoldAccountManager.Desktop.Tests/Services/XpTrackerSnapshotTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Services/XpTrackerSnapshotTests.cs index 5678f99..557bba1 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Services/XpTrackerSnapshotTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Services/XpTrackerSnapshotTests.cs @@ -1,4 +1,5 @@ using System.IO; +using System.Net.Http; using FourFoldAccountManager.Core.Data; using FourFoldAccountManager.Core.Tracking; using FourFoldAccountManager.Desktop.Services; @@ -33,12 +34,62 @@ public async Task LatestSnapshotAppearsOnlyAfterASuccessfulFetch() Assert.Null(tracker.GetLatestSnapshot(Guid.NewGuid())); } - private sealed class FixedTransport(PlayerProgressSnapshot snapshot) : IPlayerProfileTransport + [Fact] + public async Task AFailedReadAfterARenameDoesNotPairTheOldPlayerIdWithTheNewUsername() + { + var transport = new FixedTransport(Snapshot("Login"), new RankingEntry("Login", 7)); + await using var tracker = new XpTrackerCoordinator(new LocalDataPaths(_root), _ => Task.CompletedTask, + new PlayerProfileService(transport)) { ProfileRetryDelay = TimeSpan.Zero }; + var accountId = Guid.NewGuid(); + tracker.Start(accountId, "Login", null); + Poll(tracker); + Assert.Equal(7, Assert.Single(tracker.GetActiveLeaderboardProfiles()).PlayerId); + + transport.Offline = true; + tracker.Start(accountId, "Ranked", null); + Poll(tracker); + + Assert.Empty(tracker.GetActiveLeaderboardProfiles()); + } + + [Fact] + public async Task ALinkedPlayerIsStillTrackedAfterTheFirstReadFails() + { + // The ranking is empty, so only the linked id can find this player. + var snapshot = Snapshot("Player"); + var transport = new FixedTransport(snapshot) { Offline = true }; + await using var tracker = new XpTrackerCoordinator(new LocalDataPaths(_root), _ => Task.CompletedTask, + new PlayerProfileService(transport)) { ProfileRetryDelay = TimeSpan.Zero }; + var accountId = Guid.NewGuid(); + tracker.Start(accountId, "Player", 42); + await tracker.PollOnceAsync(CancellationToken.None); + + transport.Offline = false; + await tracker.PollOnceAsync(CancellationToken.None); + + Assert.Same(snapshot, tracker.GetLatestSnapshot(accountId)); + } + + private static PlayerProgressSnapshot Snapshot(string username) => + new(username, "Warrior", new Dictionary + { + ["Warrior"] = new(2, 5, 30, null) { ClassName = "Warrior" } + }, []); + + // Start and GetActiveLeaderboardProfiles must run on the thread that created the tracker, and an awaited + // poll may resume on another one, so this blocks on the poll instead. + private static void Poll(XpTrackerCoordinator tracker) => + Task.Run(() => tracker.PollOnceAsync(CancellationToken.None)).GetAwaiter().GetResult(); + + private sealed class FixedTransport(PlayerProgressSnapshot snapshot, params RankingEntry[] ranking) + : IPlayerProfileTransport { + public bool Offline { get; set; } + public Task> GetRankingAsync(CancellationToken cancellationToken) => - Task.FromResult>([]); + Offline ? throw new HttpRequestException() : Task.FromResult>(ranking); public Task GetProfileAsync(int playerId, CancellationToken cancellationToken) => - Task.FromResult(snapshot); + Offline ? throw new HttpRequestException() : Task.FromResult(snapshot); } } diff --git a/src/FourFoldAccountManager.Desktop/Services/PlayerProfileService.cs b/src/FourFoldAccountManager.Desktop/Services/PlayerProfileService.cs index a476a5e..f2da13f 100644 --- a/src/FourFoldAccountManager.Desktop/Services/PlayerProfileService.cs +++ b/src/FourFoldAccountManager.Desktop/Services/PlayerProfileService.cs @@ -29,11 +29,15 @@ public async Task ReadAsync( username = username?.Trim(); if (string.IsNullOrWhiteSpace(username)) { - return Failure(PlayerProfileReadStatus.MissingUsername, "Add a ranking username to read the public profile.", accountId); + return Failure(PlayerProfileReadStatus.MissingUsername, "Add a ranking username to read the public profile."); } var cached = GetCached(accountId); var resolvedId = playerId is > 0 ? playerId : cached?.PlayerId; + // A player's id survives a rename, so the cached id is still the one to try under a new username. Until + // that read succeeds it is unchecked for the new name, so a failed read must not hand it back. + var lastGood = string.Equals(cached?.Snapshot.Username.Trim(), username, StringComparison.OrdinalIgnoreCase) + ? cached : null; if (resolvedId is null) { IReadOnlyList ranking; @@ -48,20 +52,20 @@ public async Task ReadAsync( catch { return Failure(PlayerProfileReadStatus.RankingUnavailable, - "Ranking data is unavailable; link a profile or try again.", accountId); + "Ranking data is unavailable; link a profile or try again."); } var identity = RankingIdentityResolver.Resolve(username, ranking); if (identity.Status == IdentityResolutionStatus.Ambiguous) { return Failure(PlayerProfileReadStatus.Ambiguous, - "Multiple ranking matches found; link the exact player profile.", accountId); + "Multiple ranking matches found; link the exact player profile."); } if (identity.Status != IdentityResolutionStatus.Matched) { return Failure(PlayerProfileReadStatus.NotInTop200, - "Player is not in the top 200; link the player profile.", accountId); + "Player is not in the top 200; link the player profile."); } resolvedId = identity.PlayerId; @@ -79,12 +83,12 @@ public async Task ReadAsync( catch (InvalidDataException) { return Failure(PlayerProfileReadStatus.MalformedProfile, - "The public profile is incomplete or malformed; try again later.", accountId, cached); + "The public profile is incomplete or malformed; try again later.", lastGood); } catch { return Failure(PlayerProfileReadStatus.ProfileUnavailable, - "The public profile could not be refreshed; showing the last successful read.", accountId, cached); + "The public profile could not be refreshed; showing the last successful read.", lastGood); } if (!string.Equals(snapshot.Username.Trim(), username, StringComparison.OrdinalIgnoreCase)) @@ -121,15 +125,11 @@ public void Invalidate(Guid accountId) } } - private PlayerProfileReadResult Failure( + private static PlayerProfileReadResult Failure( PlayerProfileReadStatus status, string message, - Guid accountId, - CachedProfile? cached = null) - { - cached ??= GetCached(accountId); - return new PlayerProfileReadResult(status, cached?.PlayerId, cached?.Snapshot, message); - } + CachedProfile? lastGood = null) => + new(status, lastGood?.PlayerId, lastGood?.Snapshot, message); private sealed record CachedProfile(int PlayerId, PlayerProgressSnapshot Snapshot); } diff --git a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs index caf8e8f..60c8110 100644 --- a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs +++ b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs @@ -57,6 +57,9 @@ internal XpTrackerCoordinator( public PlayerProfileService ProfileService => _profileService; + // Tests shorten the pause before the one retry of a failed profile read. + internal TimeSpan ProfileRetryDelay { get; init; } = TimeSpan.FromSeconds(5); + public async Task VerifyPlayerAsync(int playerId, string username) { var result = await _profileService.ReadAsync(Guid.NewGuid(), username, playerId, CancellationToken.None); @@ -220,7 +223,7 @@ result.Status is PlayerProfileReadStatus.RankingUnavailable or PlayerProfileReadStatus.ProfileUnavailable or PlayerProfileReadStatus.MalformedProfile) { account.CanRetryProfileRead = false; - await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); + await Task.Delay(ProfileRetryDelay, cancellationToken); if (!_active.TryGetValue(account.Id, out current) || !ReferenceEquals(current, account)) return; result = await _profileService.ReadAsync(account.Id, account.Username, playerId, cancellationToken); } @@ -242,7 +245,8 @@ result.Status is PlayerProfileReadStatus.RankingUnavailable or } else { - account.PlayerId = result.PlayerId; + // A failed read can supply an id the account lacks, but never clears or replaces one. + account.PlayerId ??= result.PlayerId; account.Status = "Stale; could not refresh player data"; account.Session.MarkFetchFailed(); }