diff --git a/.github/workflows/report-integration-regression.yml b/.github/workflows/report-integration-regression.yml
new file mode 100644
index 00000000..87834e82
--- /dev/null
+++ b/.github/workflows/report-integration-regression.yml
@@ -0,0 +1,48 @@
+name: Report integration regression
+
+on:
+ push:
+ branches: [justerzhu-persistent-regression-integration]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ report-regression:
+ name: Report regression (${{ matrix.os }})
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [windows-latest, ubuntu-latest]
+ env:
+ REPORT_INTEGRATION_MERGE_SHA: 057da130aab3251342d344e2b60a12dcc8be71ef
+ REPORT_ROUTING_SHA: 623a87ce5112af0dab4d23c457797d23cd419143
+ FAILURE_STAGE_SHA: 66a9403259235dd19c4602ed17a8c51c4615fba0
+ PERSISTENT_REPORT_SHA: ad77b50c5125a436ab4d4c8a894f6df7235d95b0
+ steps:
+ - name: Checkout fixed integration history
+ uses: actions/checkout@v6
+ with:
+ ref: ${{ github.sha }}
+ fetch-depth: 0
+
+ - name: Verify dependency commits
+ shell: bash
+ run: |
+ test "$(git rev-parse "${REPORT_INTEGRATION_MERGE_SHA}^1")" = "${FAILURE_STAGE_SHA}"
+ test "$(git rev-parse "${REPORT_INTEGRATION_MERGE_SHA}^2")" = "${PERSISTENT_REPORT_SHA}"
+ git merge-base --is-ancestor "${REPORT_ROUTING_SHA}" "${REPORT_INTEGRATION_MERGE_SHA}"
+ git merge-base --is-ancestor "${REPORT_INTEGRATION_MERGE_SHA}" HEAD
+
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v5
+ with:
+ dotnet-version: '10.0.x'
+
+ - name: Run cross-PR report regressions
+ run: >-
+ dotnet test tests/CoreTest/CoreTest.csproj
+ --configuration Release
+ --filter "FullyQualifiedName~PersistentUpdateReporterTests|FullyQualifiedName~FailureReportingTests|FullyQualifiedName~ReportRoutingTests"
diff --git a/README.md b/README.md
index 1422742e..7eb0e281 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,43 @@ Special thanks to the authors of the following open source projects for contribu
| 🩺 `generalupdate-troubleshoot` | `/generalupdate-troubleshoot` | 50+ known issues diagnosis |
+## Durable update reports (opt-in)
+
+The default `HttpUpdateReporter` remains best-effort. Hosts that need durable reporting
+can create and register a `PersistentUpdateReporter`, and must replay it on every
+application start (and periodically when connectivity returns):
+
+```csharp
+var sender = new HttpUpdateReporter(httpClient, reportUrl);
+var reporter = new PersistentUpdateReporter(queueDirectory, sender);
+await reporter.ReplayAsync(cancellationToken); // handle and log failures; retry later
+bootstrap.UpdateReporter(reporter);
+```
+
+Use the same writable, local, private queue directory and endpoint across restarts and
+processes, and a separate directory for each endpoint/account. Configure authentication
+and register the reporter again in each reporting process, including the upgrade process;
+neither the URL nor credentials are stored in the queue. Queue
+files contain record IDs and statuses and should be protected and retained by the host.
+The host must arrange periodic retries and monitor disk usage, permissions and errors.
+`ReportAsync` writes before sending and throws if persistence or delivery fails;
+the built-in strategies catch and log reporter exceptions so the update continues.
+
+All statuses are queued to preserve their order, including success after failure.
+Delivery stops at the first unconfirmed report: HTTP success alone is insufficient;
+the response must also have `code: 200` and `body: true`. This is **at-least-once**,
+not exactly-once: a crash or lost response after server acceptance can resend a report,
+and the current server may count a repeated failure again. Safe deduplication requires
+a server-supported event ID/idempotency contract. Ordering applies only to reporters
+sharing this queue, not old clients or independent queues. A report is durable once its
+queue file has been flushed and published; failure before that point cannot be recovered.
+Storage and filesystem durability depend on the host's filesystem and hardware.
+Any future server idempotency fields remain disabled by default. Enable them only after
+trusted capability negotiation or explicit operator confirmation that the target service
+supports the contract; a successful response is not proof because older servers may ignore
+unknown fields. The queue's local file order is not a server sequence or a causal order,
+and its file numbering can restart after the queue drains.
+
## 🙏 Thanks
diff --git a/src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs b/src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs
index 7165d88f..1fbc8fd3 100644
--- a/src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs
+++ b/src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs
@@ -117,11 +117,21 @@ protected T GetOption(Option? option)
///
public TBootstrap UpdateReporter() where T : Download.Reporting.IUpdateReporter, new()
{
+ _instances.Remove(typeof(Download.Reporting.IUpdateReporter));
_extensions[typeof(Download.Reporting.IUpdateReporter)] = typeof(T);
_extensionFactories[typeof(Download.Reporting.IUpdateReporter)] = () => new T();
return (TBootstrap)this;
}
+ /// Registers a configured reporter instance for the update workflow.
+ public TBootstrap UpdateReporter(Download.Reporting.IUpdateReporter reporter)
+ {
+ if (reporter == null) throw new ArgumentNullException(nameof(reporter));
+ _instances[typeof(Download.Reporting.IUpdateReporter)] = reporter;
+ _extensions[typeof(Download.Reporting.IUpdateReporter)] = reporter.GetType();
+ return (TBootstrap)this;
+ }
+
///
/// Registers a custom OS-level strategy implementation (e.g.,
/// , ,
diff --git a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
index 1cda69cc..8e0b668d 100644
--- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
+++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
@@ -195,17 +195,7 @@ public async Task ReportAsync(UpdateReport report, CancellationToken token = def
{
if(string.IsNullOrWhiteSpace(_reportUrl))
return;
-
- var json = JsonSerializer.Serialize(report, UpdateReportJsonContext.Default.UpdateReport);
- using var request = new HttpRequestMessage(HttpMethod.Post, _reportUrl);
- request.Content = new StringContent(json, Encoding.UTF8, "application/json");
-
- // Apply the global authentication provider (if one was set via
- // VersionService.SetDefaultAuthProvider or HttpClientProvider.DefaultAuthProvider)
- // so that report requests carry the same credentials as version validation requests.
- await HttpClientProvider.ApplyAuthAsync(request, token).ConfigureAwait(false);
-
- await _client.SendAsync(request, token).ConfigureAwait(false);
+ await SendAsync(report, token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -216,4 +206,27 @@ public async Task ReportAsync(UpdateReport report, CancellationToken token = def
GeneralTracer.Warn($"Report failed: {ex.Message}");
}
}
+
+ /// Sends a report and throws unless the server confirms both HTTP and business success.
+ public async Task SendAsync(UpdateReport report, CancellationToken token = default)
+ {
+ if (report == null) throw new ArgumentNullException(nameof(report));
+ if (string.IsNullOrWhiteSpace(_reportUrl))
+ throw new InvalidOperationException("A report URL is required.");
+
+ var json = JsonSerializer.Serialize(report, UpdateReportJsonContext.Default.UpdateReport);
+ using var request = new HttpRequestMessage(HttpMethod.Post, _reportUrl);
+ request.Content = new StringContent(json, Encoding.UTF8, "application/json");
+ await HttpClientProvider.ApplyAuthAsync(request, token).ConfigureAwait(false);
+ using var response = await _client.SendAsync(request, token).ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+ var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
+ using var document = JsonDocument.Parse(content);
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object ||
+ !root.TryGetProperty("code", out var code) || code.ValueKind != JsonValueKind.Number ||
+ !code.TryGetInt32(out var value) || value != 200 ||
+ !root.TryGetProperty("body", out var body) || body.ValueKind != JsonValueKind.True)
+ throw new InvalidOperationException("The report endpoint did not confirm business success.");
+ }
}
diff --git a/src/GeneralUpdate.Core/Download/Reporting/PersistentUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/PersistentUpdateReporter.cs
new file mode 100644
index 00000000..6186b754
--- /dev/null
+++ b/src/GeneralUpdate.Core/Download/Reporting/PersistentUpdateReporter.cs
@@ -0,0 +1,114 @@
+using System;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using GeneralUpdate.Core.JsonContext;
+
+namespace GeneralUpdate.Core.Download.Reporting;
+
+///
+/// Opt-in, disk-backed, ordered at-least-once reporting. The host must replay on startup.
+/// Use a separate queue directory for each endpoint and protect it from untrusted writers.
+///
+public sealed class PersistentUpdateReporter : IUpdateReporter
+{
+ private readonly string _directory;
+ private readonly HttpUpdateReporter _sender;
+ private readonly TimeSpan _lockTimeout;
+
+ /// Creates a reporter using the supplied endpoint and queue directory.
+ public PersistentUpdateReporter(string directory, HttpUpdateReporter sender, TimeSpan? lockTimeout = null)
+ {
+ if (string.IsNullOrWhiteSpace(directory)) throw new ArgumentException("A queue directory is required.", nameof(directory));
+ _directory = Path.GetFullPath(directory);
+ _sender = sender ?? throw new ArgumentNullException(nameof(sender));
+ _lockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30);
+ if (_lockTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(lockTimeout));
+ }
+
+ /// Persists the report before attempting to send the ordered queue.
+ public async Task ReportAsync(UpdateReport report, CancellationToken token = default)
+ {
+ if (report == null) throw new ArgumentNullException(nameof(report));
+ using (await AcquireLockAsync(token).ConfigureAwait(false))
+ {
+ var files = PendingFiles();
+ long sequence = files.Length == 0 ? 1 :
+ checked(long.Parse(Path.GetFileNameWithoutExtension(files[files.Length - 1]), CultureInfo.InvariantCulture) + 1);
+ var path = Path.Combine(_directory, sequence.ToString("D20", CultureInfo.InvariantCulture) + ".json");
+ var temp = Path.Combine(_directory, Guid.NewGuid().ToString("N") + ".tmp");
+ try
+ {
+ var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(report, UpdateReportJsonContext.Default.UpdateReport));
+ using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None))
+ {
+ stream.Write(bytes, 0, bytes.Length);
+ stream.Flush(true);
+ }
+ File.Move(temp, path);
+ }
+ finally
+ {
+ if (File.Exists(temp)) File.Delete(temp);
+ }
+ await ReplayLockedAsync(token).ConfigureAwait(false);
+ }
+ }
+
+ /// Retries pending reports in order, stopping and throwing on the first failure.
+ public async Task ReplayAsync(CancellationToken token = default)
+ {
+ using (await AcquireLockAsync(token).ConfigureAwait(false))
+ await ReplayLockedAsync(token).ConfigureAwait(false);
+ }
+
+ private async Task ReplayLockedAsync(CancellationToken token)
+ {
+ foreach (var path in PendingFiles())
+ {
+ token.ThrowIfCancellationRequested();
+ var json = File.ReadAllText(path, Encoding.UTF8);
+ using (var document = JsonDocument.Parse(json))
+ {
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object ||
+ !IsInteger(root, "recordId") || !IsInteger(root, "status") || !IsInteger(root, "type"))
+ throw new InvalidDataException("A queued update report is invalid.");
+ }
+ var report = JsonSerializer.Deserialize(json, UpdateReportJsonContext.Default.UpdateReport)
+ ?? throw new InvalidDataException("A queued update report is null.");
+ await _sender.SendAsync(report, token).ConfigureAwait(false);
+ File.Delete(path);
+ }
+ }
+
+ private string[] PendingFiles() =>
+ Directory.GetFiles(_directory, "*.json").OrderBy(Path.GetFileName, StringComparer.Ordinal).ToArray();
+
+ private static bool IsInteger(JsonElement root, string name) =>
+ root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number &&
+ value.TryGetInt32(out _);
+
+ private async Task AcquireLockAsync(CancellationToken token)
+ {
+ Directory.CreateDirectory(_directory);
+ var started = System.Diagnostics.Stopwatch.StartNew();
+ while (true)
+ {
+ token.ThrowIfCancellationRequested();
+ try
+ {
+ return new FileStream(Path.Combine(_directory, "queue.lock"), FileMode.OpenOrCreate,
+ FileAccess.ReadWrite, FileShare.None);
+ }
+ catch (IOException) when (started.Elapsed < _lockTimeout)
+ {
+ await Task.Delay(TimeSpan.FromMilliseconds(100), token).ConfigureAwait(false);
+ }
+ }
+ }
+}
diff --git a/tests/CoreTest/Download/PersistentUpdateReporterTests.cs b/tests/CoreTest/Download/PersistentUpdateReporterTests.cs
new file mode 100644
index 00000000..24824e9a
--- /dev/null
+++ b/tests/CoreTest/Download/PersistentUpdateReporterTests.cs
@@ -0,0 +1,215 @@
+using System.Net;
+using System.Text;
+using System.Text.Json;
+using GeneralUpdate.Core.Configuration;
+using GeneralUpdate.Core.Download.Reporting;
+using GeneralUpdate.Core.JsonContext;
+using GeneralUpdate.Core.Strategy;
+
+namespace CoreTest.Download;
+
+public sealed class PersistentUpdateReporterTests : IDisposable
+{
+ private readonly string _directory = Path.Combine(Path.GetTempPath(), "gu-report-" + Guid.NewGuid());
+
+ [Theory]
+ [InlineData(500, "{\"code\":200,\"body\":true}")]
+ [InlineData(200, "{\"code\":500,\"body\":true}")]
+ [InlineData(200, "{\"code\":200,\"body\":false}")]
+ [InlineData(200, "{}")]
+ [InlineData(200, "not json")]
+ public async Task RejectedResponseIsPersistedAndReplayed(int status, string body)
+ {
+ var handler = new Handler(_ => new HttpResponseMessage((HttpStatusCode)status) { Content = new StringContent(body) });
+ var reporter = Create(handler);
+ await Assert.ThrowsAnyAsync(() => reporter.ReportAsync(new UpdateReport(10, 3)));
+ Assert.Single(Directory.GetFiles(_directory, "*.json"));
+
+ handler.Respond = _ => Success();
+ await Create(handler).ReplayAsync();
+ Assert.Empty(Directory.GetFiles(_directory, "*.json"));
+ Assert.Equal(new[] { 3, 3 }, handler.Statuses);
+ }
+
+ [Fact]
+ public async Task OfflineThenRestartPreservesTerminalOrder()
+ {
+ var handler = new Handler(_ => throw new HttpRequestException("offline"));
+ await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(1, 3)));
+ await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(1, 2)));
+ Assert.Equal(2, Directory.GetFiles(_directory, "*.json").Length);
+
+ handler.Statuses.Clear();
+ handler.Respond = _ => Success();
+ await Create(handler).ReplayAsync();
+ Assert.Equal(new[] { 3, 2 }, handler.Statuses);
+ await Create(handler).ReplayAsync();
+ Assert.Equal(new[] { 3, 2 }, handler.Statuses);
+ }
+
+ [Fact]
+ public async Task FailureDetailsSurviveRestartAndReplayInOrder()
+ {
+ var reports = new[]
+ {
+ new UpdateReport(41, (int)UpdateStatus.Failure, 2)
+ {
+ Category = FailureCategory.Download,
+ Phase = "Download",
+ ErrorCode = "DOWNLOAD",
+ Message = "Download failed."
+ },
+ new UpdateReport(42, (int)UpdateStatus.Failure, 1)
+ {
+ Category = FailureCategory.Apply,
+ Phase = "Apply",
+ ErrorCode = "APPLY",
+ Message = "Apply failed."
+ }
+ };
+ var handler = new Handler(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
+
+ await Assert.ThrowsAsync(() => Create(handler).ReportAsync(reports[0]));
+ await Assert.ThrowsAsync(() => Create(handler).ReportAsync(reports[1]));
+
+ var queuedJson = string.Join("", Directory.GetFiles(_directory, "*.json").Select(File.ReadAllText));
+ Assert.DoesNotContain("example.test", queuedJson);
+ Assert.DoesNotContain("secret", queuedJson);
+ Assert.Equal(reports, Directory.GetFiles(_directory, "*.json")
+ .OrderBy(Path.GetFileName, StringComparer.Ordinal)
+ .Select(path => JsonSerializer.Deserialize(File.ReadAllText(path), UpdateReportJsonContext.Default.UpdateReport)));
+
+ handler.Bodies.Clear();
+ handler.Statuses.Clear();
+ handler.Respond = _ => Success();
+
+ await Create(handler).ReplayAsync();
+
+ Assert.Empty(Directory.GetFiles(_directory, "*.json"));
+ Assert.Equal(reports.Select(report => report.Status), handler.Statuses);
+ Assert.Equal(reports.Length, handler.Bodies.Count);
+ for (var index = 0; index < reports.Length; index++)
+ {
+ var json = handler.Bodies[index];
+ var replayed = JsonSerializer.Deserialize(json, UpdateReportJsonContext.Default.UpdateReport);
+ Assert.Equal(reports[index], replayed);
+
+ var legacy = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
+ Assert.Equal((reports[index].RecordId, reports[index].Status, reports[index].Type),
+ (legacy!.RecordId, legacy.Status, legacy.Type));
+ }
+ }
+
+ [Fact]
+ public async Task LostAcknowledgementCanDuplicateButCannotSkipFailure()
+ {
+ var handler = new Handler(_ => throw new HttpRequestException("response lost after server accepted"));
+ await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(2, 3)));
+ handler.Respond = _ => Success();
+ await Create(handler).ReplayAsync();
+ Assert.Equal(new[] { 3, 3 }, handler.Statuses);
+ }
+
+ [Fact]
+ public async Task ConcurrentReportersShareQueueAndNeverPersistCredentials()
+ {
+ var handler = new Handler(_ => throw new HttpRequestException("offline"));
+ var tasks = Enumerable.Range(1, 8).Select(async i =>
+ {
+ await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(i, 3)));
+ });
+ await Task.WhenAll(tasks);
+ var files = Directory.GetFiles(_directory, "*.json");
+ Assert.Equal(8, files.Length);
+ foreach (var file in files)
+ {
+ var json = File.ReadAllText(file);
+ Assert.DoesNotContain("example.test", json);
+ Assert.DoesNotContain("secret", json);
+ }
+ handler.Respond = _ => Success();
+ await Create(handler).ReplayAsync();
+ Assert.Empty(Directory.GetFiles(_directory, "*.json"));
+ }
+
+ [Fact]
+ public async Task StrictSenderRejectsUnconfiguredEndpoint()
+ {
+ await Assert.ThrowsAsync(() => new HttpUpdateReporter().SendAsync(new UpdateReport(1)));
+ }
+
+ [Fact]
+ public async Task CorruptQueueStopsWithoutSendingOrDeleting()
+ {
+ Directory.CreateDirectory(_directory);
+ var path = Path.Combine(_directory, "00000000000000000001.json");
+ File.WriteAllText(path, "{}");
+ var handler = new Handler(_ => Success());
+ await Assert.ThrowsAsync(() => Create(handler).ReplayAsync());
+ Assert.True(File.Exists(path));
+ Assert.Empty(handler.Statuses);
+ }
+
+ [Fact]
+ public void BootstrapRegistersConfiguredInstanceAndAllowsReplacement()
+ {
+ var bootstrap = new TestBootstrap();
+ var reporter = Create(new Handler(_ => Success()));
+ Assert.Same(reporter, bootstrap.UpdateReporter(reporter).ResolveReporter());
+ Assert.IsType(bootstrap.UpdateReporter().ResolveReporter());
+ }
+
+ [Fact]
+ public async Task CancellationAfterCommitKeepsReport()
+ {
+ using var cts = new CancellationTokenSource();
+ var handler = new Handler(_ =>
+ {
+ cts.Cancel();
+ throw new OperationCanceledException(cts.Token);
+ });
+ await Assert.ThrowsAnyAsync(() =>
+ Create(handler).ReportAsync(new UpdateReport(1, 3), cts.Token));
+ Assert.Single(Directory.GetFiles(_directory, "*.json"));
+ }
+
+ private PersistentUpdateReporter Create(Handler handler) =>
+ new(_directory, new HttpUpdateReporter(new HttpClient(handler, false), "https://example.test/report?secret=value"));
+
+ private static HttpResponseMessage Success() =>
+ new(HttpStatusCode.OK) { Content = new StringContent("{\"code\":200,\"body\":true}", Encoding.UTF8, "application/json") };
+
+ private sealed class TestBootstrap : AbstractBootstrap
+ {
+ public IUpdateReporter? ResolveReporter() => ResolveExtension();
+ public override Task LaunchAsync() => Task.FromResult(this);
+ }
+
+ public void Dispose()
+ {
+ if (Directory.Exists(_directory)) Directory.Delete(_directory, true);
+ }
+
+ private sealed class Handler(Func respond) : HttpMessageHandler
+ {
+ public Func Respond { get; set; } = respond;
+ public List Statuses { get; } = [];
+ public List Bodies { get; } = [];
+
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ var body = await request.Content!.ReadAsStringAsync(cancellationToken);
+ Bodies.Add(body);
+ using var json = JsonDocument.Parse(body);
+ Statuses.Add(json.RootElement.GetProperty("status").GetInt32());
+ return Respond(request);
+ }
+ }
+
+ private sealed class LegacyReport
+ {
+ public int RecordId { get; set; }
+ public int Status { get; set; }
+ public int Type { get; set; }
+ }
+}