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
8 changes: 4 additions & 4 deletions wpf/QuotaFloat.Wpf.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
<AssemblyName>QuotaFloat.Wpf</AssemblyName>
<RootNamespace>QuotaFloat.Wpf</RootNamespace>
<ApplicationIcon>Assets\QuoteFloat.ico</ApplicationIcon>
<Version>1.1.2</Version>
<AssemblyVersion>1.1.2.0</AssemblyVersion>
<FileVersion>1.1.2.0</FileVersion>
<InformationalVersion>1.1.2</InformationalVersion>
<Version>1.1.3</Version>
<AssemblyVersion>1.1.3.0</AssemblyVersion>
<FileVersion>1.1.3.0</FileVersion>
<InformationalVersion>1.1.3</InformationalVersion>
Comment thread
keida marked this conversation as resolved.
Resolved
<ApplicationManifest>app.manifest</ApplicationManifest>
<DebugType>embedded</DebugType>
<Deterministic>true</Deterministic>
Expand Down
147 changes: 120 additions & 27 deletions wpf/Services/QuotaRefreshCoordinator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ public sealed class QuotaRefreshCoordinator : IDisposable
private readonly object sync = new();
private readonly CancellationTokenSource lifetime = new();
private readonly TimeSpan maximumBackoff;
private TaskCompletionSource<bool> successfulRefresh = NewRefreshSignal();
private long successfulRefreshGeneration;
private Task<QuotaDisplayState>? inFlight;
private QuotaSnapshot? safeSnapshot;
private DateTimeOffset? lastFreshAt;
Expand All @@ -34,33 +36,76 @@ public int ActiveRequests

public Task<QuotaDisplayState> RefreshAsync(CancellationToken cancellationToken = default)
{
CancellationTokenSource? linked;
TaskCompletionSource<QuotaDisplayState>? completion;
Task<QuotaDisplayState> task;
lock (sync)
{
ObjectDisposedException.ThrowIf(disposed, this);
if (inFlight is not null)
task = GetOrStartRefreshLocked(out linked, out completion);
}

StartRefresh(linked, completion);
return AwaitWithCancellation(task, cancellationToken);
}

private Task<QuotaDisplayState> GetOrStartRefreshLocked(
out CancellationTokenSource? linked,
out TaskCompletionSource<QuotaDisplayState>? completion)
{
ObjectDisposedException.ThrowIf(disposed, this);
if (inFlight is not null)
{
linked = null;
completion = null;
return inFlight;
}

linked = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
inFlight = completion.Task;
return inFlight;
}

private void StartRefresh(CancellationTokenSource? linked, TaskCompletionSource<QuotaDisplayState>? completion)
{
if (linked is not null && completion is not null)
{
_ = CompleteRefreshAsync(linked, completion);
}
}

private async Task CompleteRefreshAsync(CancellationTokenSource linked, TaskCompletionSource<QuotaDisplayState> completion)
{
try
{
var result = await RefreshCoreAsync(linked).ConfigureAwait(false);
ClearInFlight(completion.Task);
completion.TrySetResult(result);
}
catch (OperationCanceledException exception)
{
ClearInFlight(completion.Task);
completion.TrySetCanceled(exception.CancellationToken);
}
catch (Exception exception)
{
ClearInFlight(completion.Task);
completion.TrySetException(exception);
}
finally
{
linked.Dispose();
}
}

private void ClearInFlight(Task<QuotaDisplayState> completed)
{
lock (sync)
{
if (ReferenceEquals(inFlight, completed))
{
return AwaitWithCancellation(inFlight, cancellationToken);
inFlight = null;
}

var linked = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
var task = RefreshCoreAsync(linked);
inFlight = task;
_ = task.ContinueWith(
completed =>
{
linked.Dispose();
lock (sync)
{
if (ReferenceEquals(inFlight, completed))
{
inFlight = null;
}
}
},
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
return AwaitWithCancellation(task, cancellationToken);
}
}

Expand All @@ -73,14 +118,55 @@ public async Task RunAutoRefreshAsync(Func<TimeSpan> intervalProvider, Cancellat
{
var failureCount = 0;
TimeSpan? serverRetryAfter = null;
long observedSuccessGeneration = 0;
while (!cancellationToken.IsCancellationRequested && !lifetime.IsCancellationRequested)
{
var delay = Backoff(intervalProvider(), failureCount, serverRetryAfter);
serverRetryAfter = null;
try
{
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
var result = await RefreshAsync(cancellationToken).ConfigureAwait(false);
var configuredInterval = intervalProvider();
TimeSpan delay;
Task resetSchedule;
lock (sync)
{
if (successfulRefreshGeneration != observedSuccessGeneration)
{
observedSuccessGeneration = successfulRefreshGeneration;
failureCount = 0;
serverRetryAfter = null;
}

delay = Backoff(configuredInterval, failureCount, serverRetryAfter);
serverRetryAfter = null;
resetSchedule = successfulRefresh.Task;
}

using var delayCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var delayTask = Task.Delay(delay, delayCancellation.Token);
var completedDelay = await Task.WhenAny(delayTask, resetSchedule).ConfigureAwait(false);
if (completedDelay != delayTask)
{
delayCancellation.Cancel();
try { await delayTask.ConfigureAwait(false); }
catch (OperationCanceledException) { }
continue;
}

await delayTask.ConfigureAwait(false);
CancellationTokenSource? linked;
TaskCompletionSource<QuotaDisplayState>? completion;
Task<QuotaDisplayState> refreshTask;
lock (sync)
{
if (successfulRefreshGeneration != observedSuccessGeneration)
{
continue;
Comment thread
keida marked this conversation as resolved.
Resolved
}

refreshTask = GetOrStartRefreshLocked(out linked, out completion);
}

StartRefresh(linked, completion);
var result = await AwaitWithCancellation(refreshTask, cancellationToken).ConfigureAwait(false);
if (IsTerminalAutoStatus(result.Status))
{
break;
Expand Down Expand Up @@ -143,6 +229,10 @@ private async Task<QuotaDisplayState> RefreshCoreAsync(CancellationTokenSource l
lastFreshAt = snapshot.UpdatedAt;
var status = result.Status == "partial" ? QuotaUiStatus.Partial : QuotaUiStatus.Fresh;
next = new(status, safeSnapshot, null, lastFreshAt, null, false, 0, source.SessionGeneration);
successfulRefreshGeneration++;
var resetSchedule = successfulRefresh;
successfulRefresh = NewRefreshSignal();
resetSchedule.TrySetResult(true);
}
else
{
Expand Down Expand Up @@ -226,6 +316,9 @@ private static bool HasRenderableWindow(QuotaSnapshot snapshot) =>
private static bool IsTerminalAutoStatus(QuotaUiStatus status) =>
status is QuotaUiStatus.SignedOut or QuotaUiStatus.SessionChanged;

private static TaskCompletionSource<bool> NewRefreshSignal() =>
new(TaskCreationOptions.RunContinuationsAsynchronously);

private static QuotaUiStatus MapFailure(string status) => status.ToLowerInvariant() switch
{
"signedout" => QuotaUiStatus.SignedOut,
Expand Down
2 changes: 1 addition & 1 deletion wpf/app.manifest
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.1.2.0" name="QuotaFloat.Wpf.app" />
<assemblyIdentity version="1.1.3.0" name="QuotaFloat.Wpf.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
Expand Down
87 changes: 87 additions & 0 deletions wpf/tests/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO;
using System.Diagnostics;
using System.Text.Json;
using QuotaFloat;
using QuotaFloat.Wpf.Interaction;
Expand All @@ -15,6 +16,42 @@ void Check(bool condition, string label)
if (!condition) failures.Add(label);
}

async Task VerifyManualRefreshBackoffReset()
{
var normalRefreshInterval = TimeSpan.FromMilliseconds(700);
using var source = new ManualRefreshBackoffSource();
using var coordinator = new QuotaRefreshCoordinator(source, TimeSpan.FromSeconds(5));
using var cancellation = new CancellationTokenSource();
coordinator.StateChanged += state =>
{
if (state.Status == QuotaUiStatus.Offline && !state.IsRefreshing)
source.FirstAutoFailureCompleted.TrySetResult(true);
};
var autoLoop = coordinator.RunAutoRefreshAsync(() => normalRefreshInterval, cancellation.Token);
await source.FirstAutoCall.Task.WaitAsync(TimeSpan.FromSeconds(5));
await source.FirstAutoFailureCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5));
var manualResult = await coordinator.RefreshAsync();
var manualSuccessAt = Stopwatch.GetTimestamp();
var nextAutoCallAt = await source.ThirdCall.Task.WaitAsync(TimeSpan.FromSeconds(5));
var elapsed = Stopwatch.GetElapsedTime(manualSuccessAt, nextAutoCallAt);
Console.WriteLine($"REFRESH-BACKOFF-RESET: normalMs={normalRefreshInterval.TotalMilliseconds:F0}; manualToNextAutoMs={elapsed.TotalMilliseconds:F1}; calls={source.CallCount}; maxActive={source.MaxActive}");
Check(manualResult.Status == QuotaUiStatus.Fresh && source.CallCount == 3 &&
elapsed >= TimeSpan.FromMilliseconds(500) && elapsed <= TimeSpan.FromMilliseconds(1100),
$"manual success rebases pending auto retry to normal interval (elapsed {elapsed.TotalMilliseconds:F1}ms)");
Check(source.MaxActive == 1, "manual refresh during auto backoff keeps source concurrency at one");
cancellation.Cancel();
await autoLoop;
}

if (args.Length == 1 && args[0] == "--refresh-backoff-reset")
{
await VerifyManualRefreshBackoffReset();
foreach (var failure in failures) Console.WriteLine($"FAIL: {failure}");
if (failures.Count > 0) return 1;
Console.WriteLine("PASS: manual refresh rebases the pending auto interval; MaxActive=1");
return 0;
}

QuotaSnapshot? Parse(string usage, string credits = "{}")
{
using var usageDocument = JsonDocument.Parse(usage);
Expand Down Expand Up @@ -167,6 +204,8 @@ void Check(bool condition, string label)
await rateLimitBackoffCoordinator.RunAutoRefreshAsync(() => TimeSpan.FromMilliseconds(20), rateLimitCancellation.Token);
Check(rateLimitBackoffSource.CallCount >= 2 && rateLimitBackoffSource.CallCount <= 4, "rate-limit retry remains bounded");

await VerifyManualRefreshBackoffReset();

foreach (var interval in PreferenceStore.ApprovedRefreshIntervals)
{
Check(PreferenceStore.NearestRefreshInterval(interval) == interval, $"approved refresh interval {interval}s remains exact");
Expand Down Expand Up @@ -404,3 +443,51 @@ public async Task<QuotaResult> FetchAsync(CancellationToken cancellationToken)

public void Dispose() { }
}

sealed class ManualRefreshBackoffSource : IQuotaSource
{
private int calls;
private int active;
private int maxActive;

public TaskCompletionSource<bool> FirstAutoCall { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource<bool> FirstAutoFailureCompleted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource<long> ThirdCall { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public int CallCount => Volatile.Read(ref calls);
public int MaxActive => Volatile.Read(ref maxActive);
public long SessionGeneration => 1;

public Task<QuotaResult> FetchAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var call = Interlocked.Increment(ref calls);
var timestamp = Stopwatch.GetTimestamp();
var nowActive = Interlocked.Increment(ref active);
UpdateMaximum(nowActive);
try
{
if (call == 1)
{
FirstAutoCall.TrySetResult(true);
return Task.FromResult(new QuotaResult(null, "offline"));
}

if (call == 3) ThirdCall.TrySetResult(timestamp);
var snapshot = new QuotaSnapshot("Plus", new QuotaWindow(72, DateTimeOffset.UtcNow.AddHours(1), 18000, "5h"),
new QuotaWindow(38, DateTimeOffset.UtcNow.AddDays(2), 604800, "Weekly"), 1, Array.Empty<DateTimeOffset>(), DateTimeOffset.UtcNow);
return Task.FromResult(new QuotaResult(snapshot, "ok"));
}
finally { Interlocked.Decrement(ref active); }
}

public void Dispose() { }

private void UpdateMaximum(int value)
{
while (true)
{
var current = Volatile.Read(ref maxActive);
if (value <= current || Interlocked.CompareExchange(ref maxActive, value, current) == current) return;
}
}
}