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
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

<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 @@ -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)
{
Expand All @@ -162,4 +152,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);
Comment on lines +65 to +66
}

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);
}
}
}
}
151 changes: 151 additions & 0 deletions tests/CoreTest/Download/PersistentUpdateReporterTests.cs
Original file line number Diff line number Diff line change
@@ -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<Exception>(() => 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<HttpRequestException>(() => Create(handler).ReportAsync(new UpdateReport(1, 3)));
await Assert.ThrowsAsync<HttpRequestException>(() => 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<HttpRequestException>(() => 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<HttpRequestException>(() => Create(handler).ReportAsync(new UpdateReport(i, 3)));
});
await Task.WhenAll(tasks);
Comment on lines +62 to +67
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<InvalidOperationException>(() => 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<InvalidDataException>(() => 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<HttpUpdateReporter>(bootstrap.UpdateReporter<HttpUpdateReporter>().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<OperationCanceledException>(() =>
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<TestBootstrap, IStrategy>
{
public IUpdateReporter? ResolveReporter() => ResolveExtension<IUpdateReporter>();
public override Task<TestBootstrap> LaunchAsync() => Task.FromResult(this);
}

public void Dispose()
{
if (Directory.Exists(_directory)) Directory.Delete(_directory, true);
}

private sealed class Handler(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
{
public Func<HttpRequestMessage, HttpResponseMessage> Respond { get; set; } = respond;
public List<int> Statuses { get; } = [];

protected override async Task<HttpResponseMessage> 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);
}
}
}
Loading