Skip to content
Open
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
48 changes: 48 additions & 0 deletions .github/workflows/report-integration-regression.yml
Original file line number Diff line number Diff line change
@@ -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"
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

<div align="center">
Expand Down
10 changes: 10 additions & 0 deletions src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,21 @@ protected T GetOption<T>(Option<T>? option)
/// </remarks>
public TBootstrap UpdateReporter<T>() 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;
}

/// <summary>Registers a configured reporter instance for the update workflow.</summary>
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;
}

/// <summary>
/// Registers a custom OS-level strategy implementation (e.g.,
/// <see cref="Strategy.WindowsStrategy"/>, <see cref="Strategy.LinuxStrategy"/>,
Expand Down
35 changes: 24 additions & 11 deletions src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -216,4 +206,27 @@ public async Task ReportAsync(UpdateReport report, CancellationToken token = def
GeneralTracer.Warn($"Report failed: {ex.Message}");
}
}

/// <summary>Sends a report and throws unless the server confirms both HTTP and business success.</summary>
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.");
}
}
114 changes: 114 additions & 0 deletions src/GeneralUpdate.Core/Download/Reporting/PersistentUpdateReporter.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
public sealed class PersistentUpdateReporter : IUpdateReporter
{
private readonly string _directory;
private readonly HttpUpdateReporter _sender;
private readonly TimeSpan _lockTimeout;

/// <summary>Creates a reporter using the supplied endpoint and queue directory.</summary>
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));
}

/// <summary>Persists the report before attempting to send the ordered queue.</summary>
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);
}
}

/// <summary>Retries pending reports in order, stopping and throwing on the first failure.</summary>
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<FileStream> 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);
}
}
}
}
Loading
Loading