Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO;
using System.Net.Http;
using FourFoldAccountManager.Core.Data;
using FourFoldAccountManager.Core.Tracking;
using FourFoldAccountManager.Desktop.Services;
Expand Down Expand Up @@ -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<string, ClassProfileSnapshot>
{
["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<IReadOnlyList<RankingEntry>> GetRankingAsync(CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<RankingEntry>>([]);
Offline ? throw new HttpRequestException() : Task.FromResult<IReadOnlyList<RankingEntry>>(ranking);

public Task<PlayerProgressSnapshot> GetProfileAsync(int playerId, CancellationToken cancellationToken) =>
Task.FromResult(snapshot);
Offline ? throw new HttpRequestException() : Task.FromResult(snapshot);
}
}
26 changes: 13 additions & 13 deletions src/FourFoldAccountManager.Desktop/Services/PlayerProfileService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,15 @@ public async Task<PlayerProfileReadResult> 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<RankingEntry> ranking;
Expand All @@ -48,20 +52,20 @@ public async Task<PlayerProfileReadResult> 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;
Expand All @@ -79,12 +83,12 @@ public async Task<PlayerProfileReadResult> 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))
Expand Down Expand Up @@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> VerifyPlayerAsync(int playerId, string username)
{
var result = await _profileService.ReadAsync(Guid.NewGuid(), username, playerId, CancellationToken.None);
Expand Down Expand Up @@ -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);
}
Expand All @@ -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();
}
Expand Down
Loading