diff --git a/wpf/QuotaFloat.Wpf.csproj b/wpf/QuotaFloat.Wpf.csproj
index c25af3a..3fa1b95 100644
--- a/wpf/QuotaFloat.Wpf.csproj
+++ b/wpf/QuotaFloat.Wpf.csproj
@@ -8,10 +8,10 @@
QuotaFloat.Wpf
QuotaFloat.Wpf
Assets\QuoteFloat.ico
- 1.1.2
- 1.1.2.0
- 1.1.2.0
- 1.1.2
+ 1.1.3
+ 1.1.3.0
+ 1.1.3.0
+ 1.1.3
app.manifest
embedded
true
diff --git a/wpf/Services/QuotaRefreshCoordinator.cs b/wpf/Services/QuotaRefreshCoordinator.cs
index b89595f..5718333 100644
--- a/wpf/Services/QuotaRefreshCoordinator.cs
+++ b/wpf/Services/QuotaRefreshCoordinator.cs
@@ -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 successfulRefresh = NewRefreshSignal();
+ private long successfulRefreshGeneration;
private Task? inFlight;
private QuotaSnapshot? safeSnapshot;
private DateTimeOffset? lastFreshAt;
@@ -34,33 +36,76 @@ public int ActiveRequests
public Task RefreshAsync(CancellationToken cancellationToken = default)
{
+ CancellationTokenSource? linked;
+ TaskCompletionSource? completion;
+ Task 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 GetOrStartRefreshLocked(
+ out CancellationTokenSource? linked,
+ out TaskCompletionSource? 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? completion)
+ {
+ if (linked is not null && completion is not null)
+ {
+ _ = CompleteRefreshAsync(linked, completion);
+ }
+ }
+
+ private async Task CompleteRefreshAsync(CancellationTokenSource linked, TaskCompletionSource 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 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);
}
}
@@ -73,14 +118,55 @@ public async Task RunAutoRefreshAsync(Func 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? completion;
+ Task refreshTask;
+ lock (sync)
+ {
+ if (successfulRefreshGeneration != observedSuccessGeneration)
+ {
+ continue;
+ }
+
+ refreshTask = GetOrStartRefreshLocked(out linked, out completion);
+ }
+
+ StartRefresh(linked, completion);
+ var result = await AwaitWithCancellation(refreshTask, cancellationToken).ConfigureAwait(false);
if (IsTerminalAutoStatus(result.Status))
{
break;
@@ -143,6 +229,10 @@ private async Task 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
{
@@ -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 NewRefreshSignal() =>
+ new(TaskCreationOptions.RunContinuationsAsynchronously);
+
private static QuotaUiStatus MapFailure(string status) => status.ToLowerInvariant() switch
{
"signedout" => QuotaUiStatus.SignedOut,
diff --git a/wpf/app.manifest b/wpf/app.manifest
index cb514aa..2940a28 100644
--- a/wpf/app.manifest
+++ b/wpf/app.manifest
@@ -1,6 +1,6 @@
-
+
diff --git a/wpf/tests/Program.cs b/wpf/tests/Program.cs
index 6cbc580..2cdb2c9 100644
--- a/wpf/tests/Program.cs
+++ b/wpf/tests/Program.cs
@@ -1,4 +1,5 @@
using System.IO;
+using System.Diagnostics;
using System.Text.Json;
using QuotaFloat;
using QuotaFloat.Wpf.Interaction;
@@ -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);
@@ -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");
@@ -404,3 +443,51 @@ public async Task FetchAsync(CancellationToken cancellationToken)
public void Dispose() { }
}
+
+sealed class ManualRefreshBackoffSource : IQuotaSource
+{
+ private int calls;
+ private int active;
+ private int maxActive;
+
+ public TaskCompletionSource FirstAutoCall { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public TaskCompletionSource FirstAutoFailureCompleted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public TaskCompletionSource 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 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.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;
+ }
+ }
+}