From ad77b50c5125a436ab4d4c8a894f6df7235d95b0 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 22 Nov 2026 23:37:51 +0800 Subject: [PATCH] Add opt-in durable update report replay Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 32 ++++ .../Configuration/AbstractBootstrap.cs | 10 ++ .../Download/Reporting/IUpdateReporter.cs | 35 ++-- .../Reporting/PersistentUpdateReporter.cs | 114 +++++++++++++ .../Download/PersistentUpdateReporterTests.cs | 151 ++++++++++++++++++ 5 files changed, 331 insertions(+), 11 deletions(-) create mode 100644 src/GeneralUpdate.Core/Download/Reporting/PersistentUpdateReporter.cs create mode 100644 tests/CoreTest/Download/PersistentUpdateReporterTests.cs diff --git a/README.md b/README.md index 1422742e..ecf9deee 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,38 @@ 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. + ## 🙏 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 7a2029db..bd4299f1 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs @@ -141,17 +141,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) { @@ -162,4 +152,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..f320e108 --- /dev/null +++ b/tests/CoreTest/Download/PersistentUpdateReporterTests.cs @@ -0,0 +1,151 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download.Reporting; +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 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; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(cancellationToken)); + Statuses.Add(json.RootElement.GetProperty("status").GetInt32()); + return Respond(request); + } + } +}