diff --git a/.github/workflows/ordered-report-aot.yml b/.github/workflows/ordered-report-aot.yml
new file mode 100644
index 00000000..6eddbe22
--- /dev/null
+++ b/.github/workflows/ordered-report-aot.yml
@@ -0,0 +1,36 @@
+name: Ordered report Native AOT
+
+on:
+ pull_request:
+ workflow_dispatch:
+
+jobs:
+ publish-and-run:
+ strategy:
+ matrix:
+ include:
+ - os: windows-latest
+ rid: win-x64
+ executable: ReportWorker.exe
+ - os: ubuntu-latest
+ rid: linux-x64
+ executable: ReportWorker
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-dotnet@v5
+ with:
+ dotnet-version: '10.0.x'
+ - name: Test outbox
+ run: dotnet test tests/CoreTest/CoreTest.csproj -c Release --filter "FullyQualifiedName~OrderedUpdateReporterTests"
+ - name: Publish Native AOT
+ run: dotnet publish tests/ReportWorker/ReportWorker.csproj -c Release -f net10.0 -r ${{ matrix.rid }} -p:PublishAot=true -p:TargetFrameworks=net10.0 -o aot-out
+ - name: Run native outbox
+ shell: pwsh
+ run: |
+ $exe = Join-Path $PWD "aot-out" "${{ matrix.executable }}"
+ $queue = Join-Path $env:RUNNER_TEMP "ordered-aot"
+ & $exe $queue success
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ & $exe $queue success
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
diff --git a/README.md b/README.md
index 7eb0e281..3e838a5e 100644
--- a/README.md
+++ b/README.md
@@ -125,11 +125,48 @@ a server-supported event ID/idempotency contract. Ordering applies only to repor
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.
+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.
+
+### Ordered idempotent reports (separate opt-in)
+
+`OrderedUpdateReporter` uses the GeneralSpace ordered-event protocol, but is **disabled
+by default** and separate from the legacy file queue. Enable it only after an operator
+confirms the deployed service supports both `eventId` and `sequence`; an ordinary
+success response is not evidence because older servers ignore unknown fields.
+
+```csharp
+var reporter = new OrderedUpdateReporter(
+ queueDirectory, httpClient, reportUrl,
+ namespaceIdentity: "stable-tenant-and-server-database-id",
+ protocolConfirmed: true);
+await reporter.ReplayAsync(cancellationToken);
+bootstrap.UpdateReporter(reporter);
+```
+
+The host must replay on startup and periodically, monitor errors and storage, and
+register the same reporter in each reporting process. It must ensure that **all**
+writers for a server database's `(type, recordId)` use this one database on the same
+machine and the same exact endpoint and namespace identity; no legacy, independent,
+multi-machine or restored-old-copy writers may write those records. The namespace must
+identify the tenant and actual server database, not an ephemeral token or hostname.
+URLs and credentials are not stored, but a hash binding the exact URL and namespace is
+stored to reject accidental reconfiguration. The host must prevent redirects, retargeting,
+and authentication changes that could send to a different tenant or database.
+
+The private directory must be on a local filesystem supporting SQLite locking and
+durable flushes, with access restricted to trusted processes. Protect the database,
+rollback journal, lock file, and backups: report payloads may contain sensitive
+diagnostics. SQLite transactionally commits the record counter, GUID, and complete
+payload before sending. A lost response or crash replays the same event; a business
+conflict or other failure stops replay without deleting it. Keep the database and
+counters even when the queue is empty. Deleting, rolling back or cloning the database,
+or using network filesystems, invalidates the ordering guarantee. Hardware and filesystem
+durability still apply. The SQLite native dependency must be available for the target RID.
+Enqueue transactions do not hold the delivery lock during HTTP requests. If delivery
+is busy, times out or is cancelled after the transaction commits, `ReportAsync` can
+throw while the event remains queued; retry delivery with `ReplayAsync`, not by
+submitting a new report. Persistence failures before commit cannot be replayed.
## 🙏 Thanks
diff --git a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
index 8e0b668d..4f61202e 100644
--- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
+++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
@@ -72,6 +72,14 @@ public enum UpdateStatus { Updating = 1, Success = 2, Failure = 3 }
///
public record UpdateReport(int RecordId, int Status = 1, int Type = 1)
{
+ /// Optional idempotency key, paired with .
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ public Guid? EventId { get; init; }
+
+ /// Optional positive sequence for the record, paired with .
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ public long? Sequence { get; init; }
+
/// Optional failure category, matching the server's diagnostic contract.
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public FailureCategory? Category { get; init; }
@@ -215,6 +223,13 @@ public async Task SendAsync(UpdateReport report, CancellationToken token = defau
throw new InvalidOperationException("A report URL is required.");
var json = JsonSerializer.Serialize(report, UpdateReportJsonContext.Default.UpdateReport);
+ await SendJsonAsync(json, token).ConfigureAwait(false);
+ }
+
+ internal async Task SendJsonAsync(string json, CancellationToken token)
+ {
+ if (string.IsNullOrWhiteSpace(_reportUrl))
+ throw new InvalidOperationException("A report URL is required.");
using var request = new HttpRequestMessage(HttpMethod.Post, _reportUrl);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
await HttpClientProvider.ApplyAuthAsync(request, token).ConfigureAwait(false);
@@ -223,6 +238,11 @@ public async Task SendAsync(UpdateReport report, CancellationToken token = defau
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("errorCode", out var errorCode) &&
+ errorCode.ValueKind == JsonValueKind.String &&
+ errorCode.GetString() == "Conflict")
+ throw new InvalidOperationException("The report endpoint reported an event or sequence conflict.");
if (root.ValueKind != JsonValueKind.Object ||
!root.TryGetProperty("code", out var code) || code.ValueKind != JsonValueKind.Number ||
!code.TryGetInt32(out var value) || value != 200 ||
diff --git a/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs
new file mode 100644
index 00000000..737085d4
--- /dev/null
+++ b/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs
@@ -0,0 +1,209 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Net.Http;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using GeneralUpdate.Core.JsonContext;
+using Microsoft.Data.Sqlite;
+
+namespace GeneralUpdate.Core.Download.Reporting;
+
+///
+/// Opt-in, single-host outbox for an explicitly authorized ordered-report protocol.
+/// All writers for the same server record namespace must share the same local database.
+///
+public sealed class OrderedUpdateReporter : IUpdateReporter
+{
+ private readonly string _directory;
+ private readonly string _identity;
+ private readonly HttpUpdateReporter _sender;
+ private readonly TimeSpan _lockTimeout;
+
+ ///
+ /// Creates an ordered reporter. The operator must confirm that the endpoint supports
+ /// the event ID and sequence protocol and that namespaceIdentity identifies the stable
+ /// tenant and server database namespace. A successful POST is not capability detection.
+ ///
+ public OrderedUpdateReporter(string directory, HttpClient client, string reportUrl,
+ string namespaceIdentity, bool protocolConfirmed, TimeSpan? lockTimeout = null)
+ {
+ if (!protocolConfirmed) throw new InvalidOperationException("The ordered-report protocol must be explicitly confirmed.");
+ if (string.IsNullOrWhiteSpace(directory)) throw new ArgumentException("A private local directory is required.", nameof(directory));
+ if (client == null) throw new ArgumentNullException(nameof(client));
+ if (!Uri.TryCreate(reportUrl, UriKind.Absolute, out var uri) ||
+ (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
+ throw new ArgumentException("An absolute HTTP report URL is required.", nameof(reportUrl));
+ if (string.IsNullOrWhiteSpace(namespaceIdentity))
+ throw new ArgumentException("A stable tenant and database namespace identity is required.", nameof(namespaceIdentity));
+ _directory = Path.GetFullPath(directory);
+ _identity = Identity(reportUrl, namespaceIdentity);
+ _sender = new HttpUpdateReporter(client, reportUrl);
+ _lockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30);
+ if (_lockTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(lockTimeout));
+ }
+
+ /// Atomically allocates an event and sequence, commits the payload, then replays.
+ public async Task ReportAsync(UpdateReport report, CancellationToken token = default)
+ {
+ if (report == null) throw new ArgumentNullException(nameof(report));
+ if (report.EventId != null || report.Sequence != null)
+ throw new ArgumentException("The outbox allocates event IDs and sequences.", nameof(report));
+ if (report.RecordId <= 0 || (report.Type != 1 && report.Type != 2))
+ throw new ArgumentException("A positive record ID and supported record type are required.", nameof(report));
+
+ Directory.CreateDirectory(_directory);
+ using (var connection = Open())
+ {
+ token.ThrowIfCancellationRequested();
+ using (var transaction = connection.BeginTransaction())
+ {
+ using (var update = connection.CreateCommand())
+ {
+ update.Transaction = transaction;
+ update.CommandText = @"INSERT INTO counters (type, record_id, sequence) VALUES ($type, $record, 1)
+ ON CONFLICT(type, record_id) DO UPDATE SET sequence = sequence + 1
+ WHERE sequence < 9223372036854775807;";
+ update.Parameters.AddWithValue("$type", report.Type);
+ update.Parameters.AddWithValue("$record", report.RecordId);
+ if (update.ExecuteNonQuery() != 1) throw new InvalidOperationException("Report sequence exhausted.");
+ }
+ long sequence;
+ using (var read = connection.CreateCommand())
+ {
+ read.Transaction = transaction;
+ read.CommandText = "SELECT sequence FROM counters WHERE type = $type AND record_id = $record;";
+ read.Parameters.AddWithValue("$type", report.Type);
+ read.Parameters.AddWithValue("$record", report.RecordId);
+ sequence = (long)read.ExecuteScalar()!;
+ }
+ var payload = JsonSerializer.Serialize(report with { EventId = Guid.NewGuid(), Sequence = sequence },
+ UpdateReportJsonContext.Default.UpdateReport);
+ using (var insert = connection.CreateCommand())
+ {
+ insert.Transaction = transaction;
+ insert.CommandText = "INSERT INTO outbox (payload) VALUES ($payload);";
+ insert.Parameters.AddWithValue("$payload", payload);
+ insert.ExecuteNonQuery();
+ }
+ transaction.Commit();
+ }
+ }
+ await ReplayAsync(token).ConfigureAwait(false);
+ }
+
+ /// Replays committed events in order, stopping on the first unconfirmed response.
+ public async Task ReplayAsync(CancellationToken token = default)
+ {
+ using (await AcquireLockAsync(token).ConfigureAwait(false))
+ using (var connection = Open())
+ await ReplayLockedAsync(connection, token).ConfigureAwait(false);
+ }
+
+ private async Task ReplayLockedAsync(SqliteConnection connection, CancellationToken token)
+ {
+ while (true)
+ {
+ token.ThrowIfCancellationRequested();
+ long id;
+ string payload;
+ using (var command = connection.CreateCommand())
+ {
+ command.CommandText = "SELECT id, payload FROM outbox ORDER BY id LIMIT 1;";
+ using (var reader = command.ExecuteReader())
+ {
+ if (!reader.Read()) return;
+ id = reader.GetInt64(0);
+ payload = reader.GetString(1);
+ }
+ }
+ await _sender.SendJsonAsync(payload, token).ConfigureAwait(false);
+ using (var command = connection.CreateCommand())
+ {
+ command.CommandText = "DELETE FROM outbox WHERE id = $id;";
+ command.Parameters.AddWithValue("$id", id);
+ if (command.ExecuteNonQuery() != 1)
+ throw new InvalidDataException("The queued report changed during delivery.");
+ }
+ }
+ }
+
+ private SqliteConnection Open()
+ {
+ var builder = new SqliteConnectionStringBuilder
+ {
+ DataSource = Path.Combine(_directory, "ordered-reports.db"),
+ Mode = SqliteOpenMode.ReadWriteCreate,
+ Pooling = false
+ };
+ var connection = new SqliteConnection(builder.ToString());
+ try
+ {
+ connection.Open();
+ using (var command = connection.CreateCommand())
+ {
+ command.CommandText = "PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL;";
+ command.ExecuteNonQuery();
+ }
+ using (var transaction = connection.BeginTransaction())
+ {
+ using (var command = connection.CreateCommand())
+ {
+ command.Transaction = transaction;
+ command.CommandText = @"CREATE TABLE IF NOT EXISTS metadata (id INTEGER PRIMARY KEY CHECK(id = 1), identity TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS counters (type INTEGER NOT NULL, record_id INTEGER NOT NULL,
+ sequence INTEGER NOT NULL, PRIMARY KEY(type, record_id));
+ CREATE TABLE IF NOT EXISTS outbox (id INTEGER PRIMARY KEY AUTOINCREMENT, payload TEXT NOT NULL);
+ INSERT OR IGNORE INTO metadata (id, identity) VALUES (1, $identity);";
+ command.Parameters.AddWithValue("$identity", _identity);
+ command.ExecuteNonQuery();
+ }
+ using (var command = connection.CreateCommand())
+ {
+ command.Transaction = transaction;
+ command.CommandText = "SELECT identity FROM metadata WHERE id = 1;";
+ if (!string.Equals(command.ExecuteScalar() as string, _identity, StringComparison.Ordinal))
+ throw new InvalidOperationException("The ordered outbox belongs to a different endpoint or namespace.");
+ }
+ transaction.Commit();
+ }
+ return connection;
+ }
+ catch
+ {
+ connection.Dispose();
+ throw;
+ }
+ }
+
+ private async Task AcquireLockAsync(CancellationToken token)
+ {
+ Directory.CreateDirectory(_directory);
+ var started = Stopwatch.StartNew();
+ while (true)
+ {
+ token.ThrowIfCancellationRequested();
+ try
+ {
+ return new FileStream(Path.Combine(_directory, "ordered-reports.lock"), FileMode.OpenOrCreate,
+ FileAccess.ReadWrite, FileShare.None);
+ }
+ catch (IOException) when (started.Elapsed < _lockTimeout)
+ {
+ await Task.Delay(TimeSpan.FromMilliseconds(100), token).ConfigureAwait(false);
+ }
+ }
+ }
+
+ private static string Identity(string endpoint, string scope)
+ {
+ using (var hash = SHA256.Create())
+ {
+ var value = endpoint.Length + ":" + endpoint + scope.Length + ":" + scope;
+ return Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(value)));
+ }
+ }
+}
diff --git a/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj b/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj
index e6161552..3cc6750b 100644
--- a/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj
+++ b/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj
@@ -38,6 +38,8 @@
+
+
diff --git a/tests/CoreTest/CoreTest.csproj b/tests/CoreTest/CoreTest.csproj
index 99d514db..82ed96f4 100644
--- a/tests/CoreTest/CoreTest.csproj
+++ b/tests/CoreTest/CoreTest.csproj
@@ -21,6 +21,7 @@
+
\ No newline at end of file
diff --git a/tests/CoreTest/Download/OrderedUpdateReporterTests.cs b/tests/CoreTest/Download/OrderedUpdateReporterTests.cs
new file mode 100644
index 00000000..b0d9c79f
--- /dev/null
+++ b/tests/CoreTest/Download/OrderedUpdateReporterTests.cs
@@ -0,0 +1,200 @@
+using System.Diagnostics;
+using System.Net;
+using System.Text.Json;
+using GeneralUpdate.Core.Download.Reporting;
+using Microsoft.Data.Sqlite;
+
+namespace CoreTest.Download;
+
+public sealed class OrderedUpdateReporterTests : IDisposable
+{
+ private readonly string _directory = Path.Combine(Path.GetTempPath(), "gu-ordered-" + Guid.NewGuid());
+
+ [Fact]
+ public async Task ReplaysExactEventAfterLostResponseAndKeepsCountersAfterDrain()
+ {
+ var handler = new Handler { Fail = true, AcceptBeforeFailure = true };
+ var reporter = Create(handler);
+ await Assert.ThrowsAsync(() => reporter.ReportAsync(new UpdateReport(10, 3)
+ {
+ Category = FailureCategory.Apply, Phase = "Apply", Message = "Apply failed."
+ }));
+ handler.Fail = false;
+ await Create(handler).ReplayAsync();
+ await Create(handler).ReportAsync(new UpdateReport(10, 2));
+ await Create(handler).ReportAsync(new UpdateReport(10, 1, 2));
+ Assert.Equal(handler.Bodies[0], handler.Bodies[1]);
+ Assert.Equal(new long[] { 1, 1, 2, 1 }, handler.Bodies.Select(Sequence));
+ Assert.Equal(EventId(handler.Bodies[0]), EventId(handler.Bodies[1]));
+ Assert.Equal(3, handler.Applied.Count);
+ Assert.NotEqual(EventId(handler.Bodies[1]), EventId(handler.Bodies[2]));
+ Assert.DoesNotContain("example.test", File.ReadAllText(Path.Combine(_directory, "ordered-reports.db")));
+ }
+
+ [Fact]
+ public async Task LegacySenderDoesNotAddProtocolFields()
+ {
+ var handler = new Handler();
+ await new HttpUpdateReporter(new HttpClient(handler, false), "https://example.test/report")
+ .SendAsync(new UpdateReport(10));
+ using var json = JsonDocument.Parse(Assert.Single(handler.Bodies));
+ Assert.False(json.RootElement.TryGetProperty("eventId", out _));
+ Assert.False(json.RootElement.TryGetProperty("sequence", out _));
+ }
+
+ [Fact]
+ public async Task AuthorizationIdentityAndConflictFailClosed()
+ {
+ var handler = new Handler();
+ using var client = new HttpClient(handler, false);
+ Assert.Throws(() => new OrderedUpdateReporter(_directory, client, "https://example.test/report", "tenant/database", false));
+ await Create(handler).ReportAsync(new UpdateReport(10));
+ await Assert.ThrowsAsync(() =>
+ new OrderedUpdateReporter(_directory, client, "https://example.test/report", "different tenant", true).ReplayAsync());
+ Assert.Single(handler.Bodies);
+
+ handler.Conflict = true;
+ var error = await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(10)));
+ Assert.Contains("conflict", error.Message);
+ handler.Conflict = false;
+ await Create(handler).ReplayAsync();
+ Assert.Equal(handler.Bodies[1], handler.Bodies[2]);
+ }
+
+ [Fact]
+ public async Task ConcurrentProcessesAllocateUniqueSequences()
+ {
+ var workers = Enumerable.Range(0, 6).Select(_ => StartWorker("offline")).ToArray();
+ foreach (var worker in workers)
+ {
+ await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(90));
+ Assert.Equal(0, worker.ExitCode);
+ worker.Dispose();
+ }
+ var handler = new Handler();
+ await Create(handler).ReplayAsync();
+ Assert.Equal(Enumerable.Range(1, 6).Select(i => (long)i), handler.Bodies.Select(Sequence));
+ Assert.Equal(6, handler.Bodies.Select(EventId).Distinct().Count());
+ }
+
+ [Fact]
+ public async Task KilledProcessReplaysCommittedPayload()
+ {
+ using var worker = StartWorker("hold");
+ try
+ {
+ Assert.Equal("committed", await worker.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(60)));
+ }
+ finally
+ {
+ if (!worker.HasExited) worker.Kill(entireProcessTree: true);
+ await worker.WaitForExitAsync();
+ }
+ var handler = new Handler();
+ await Create(handler).ReplayAsync();
+ await Create(handler).ReportAsync(new UpdateReport(10, 2));
+ Assert.Equal(new long[] { 1, 2 }, handler.Bodies.Select(Sequence));
+ }
+
+ [Fact]
+ public async Task SlowDeliveryDoesNotBlockAnotherProcessFromCommitting()
+ {
+ using var first = StartWorker("hold");
+ Process? second = null;
+ try
+ {
+ Assert.Equal("committed", await first.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(60)));
+ second = StartWorker("offline");
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
+ while (true)
+ {
+ timeout.Token.ThrowIfCancellationRequested();
+ using var connection = new SqliteConnection(new SqliteConnectionStringBuilder
+ {
+ DataSource = Path.Combine(_directory, "ordered-reports.db"),
+ Mode = SqliteOpenMode.ReadOnly,
+ Pooling = false
+ }.ToString());
+ connection.Open();
+ using var command = connection.CreateCommand();
+ command.CommandText = "SELECT COUNT(*) FROM outbox;";
+ if ((long)command.ExecuteScalar()! == 2) break;
+ await Task.Delay(100, timeout.Token);
+ }
+ Assert.False(first.HasExited);
+ }
+ finally
+ {
+ if (!first.HasExited) first.Kill(entireProcessTree: true);
+ await first.WaitForExitAsync();
+ if (second != null)
+ {
+ if (!second.HasExited) second.Kill(entireProcessTree: true);
+ await second.WaitForExitAsync();
+ second.Dispose();
+ }
+ }
+ var handler = new Handler();
+ await Create(handler).ReplayAsync();
+ Assert.Equal(new long[] { 1, 2 }, handler.Bodies.Select(Sequence));
+ }
+
+ [Fact]
+ public async Task ConcurrentInstancesAllocatePerRecord()
+ {
+ var handler = new Handler { Fail = true };
+ await Task.WhenAll(Enumerable.Range(0, 12).Select(async _ =>
+ await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(10, 3)))));
+ handler.Fail = false;
+ handler.Bodies.Clear();
+ await Create(handler).ReplayAsync();
+ Assert.Equal(Enumerable.Range(1, 12).Select(i => (long)i), handler.Bodies.Select(Sequence));
+ Assert.Equal(12, handler.Bodies.Select(EventId).Distinct().Count());
+ }
+
+ private OrderedUpdateReporter Create(Handler handler) =>
+ new(_directory, new HttpClient(handler, false), "https://example.test/report", "tenant/database", true);
+
+ private Process StartWorker(string mode)
+ {
+ var testAssembly = typeof(OrderedUpdateReporterTests).Assembly.Location;
+ var start = new ProcessStartInfo("dotnet") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
+ foreach (var arg in new[] { "exec", "--runtimeconfig", Path.ChangeExtension(testAssembly, ".runtimeconfig.json"),
+ "--depsfile", Path.ChangeExtension(testAssembly, ".deps.json"), typeof(ReportWorker.Marker).Assembly.Location, _directory, mode })
+ start.ArgumentList.Add(arg);
+ return Process.Start(start)!;
+ }
+
+ private static long Sequence(string body) => JsonDocument.Parse(body).RootElement.GetProperty("sequence").GetInt64();
+ private static Guid EventId(string body) => JsonDocument.Parse(body).RootElement.GetProperty("eventId").GetGuid();
+
+ public void Dispose()
+ {
+ if (Directory.Exists(_directory)) Directory.Delete(_directory, true);
+ }
+
+ private sealed class Handler : HttpMessageHandler
+ {
+ public bool Fail { get; set; }
+ public bool AcceptBeforeFailure { get; set; }
+ public bool Conflict { get; set; }
+ public List Bodies { get; } = [];
+ public HashSet Applied { get; } = [];
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token)
+ {
+ var body = await request.Content!.ReadAsStringAsync(token);
+ Bodies.Add(body);
+ using var json = JsonDocument.Parse(body);
+ if ((!Fail || AcceptBeforeFailure) && !Conflict &&
+ json.RootElement.TryGetProperty("eventId", out var eventId))
+ Applied.Add(eventId.GetGuid());
+ if (Fail) throw new HttpRequestException("lost response");
+ return new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent(Conflict
+ ? "{\"code\":400,\"errorCode\":\"Conflict\",\"body\":false}"
+ : "{\"code\":200,\"body\":true}")
+ };
+ }
+ }
+}
diff --git a/tests/ReportWorker/Program.cs b/tests/ReportWorker/Program.cs
new file mode 100644
index 00000000..efd1a059
--- /dev/null
+++ b/tests/ReportWorker/Program.cs
@@ -0,0 +1,45 @@
+using System.Net;
+using System.Text.Json;
+using GeneralUpdate.Core.Download.Reporting;
+
+namespace ReportWorker;
+
+public sealed class Marker;
+
+internal static class Program
+{
+ private static async Task Main(string[] args)
+ {
+ if (args.Length != 2) return 2;
+ using var client = new HttpClient(new Handler(args[1]));
+ var reporter = new OrderedUpdateReporter(args[0], client, "https://example.test/report", "tenant/database", true);
+ try
+ {
+ await reporter.ReportAsync(new UpdateReport(10, 3));
+ }
+ catch (HttpRequestException)
+ {
+ return 0;
+ }
+ return 0;
+ }
+
+ private sealed class Handler(string mode) : HttpMessageHandler
+ {
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token)
+ {
+ using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(token));
+ if (json.RootElement.GetProperty("eventId").GetGuid() == Guid.Empty ||
+ json.RootElement.GetProperty("sequence").GetInt64() <= 0)
+ throw new InvalidDataException("Invalid ordered report.");
+ if (mode == "hold")
+ {
+ Console.WriteLine("committed");
+ await Console.Out.FlushAsync();
+ await Task.Delay(Timeout.InfiniteTimeSpan, token);
+ }
+ if (mode == "offline") throw new HttpRequestException("offline");
+ return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"code\":200,\"body\":true}") };
+ }
+ }
+}
diff --git a/tests/ReportWorker/ReportWorker.csproj b/tests/ReportWorker/ReportWorker.csproj
new file mode 100644
index 00000000..601478a7
--- /dev/null
+++ b/tests/ReportWorker/ReportWorker.csproj
@@ -0,0 +1,11 @@
+
+
+ Exe
+ net10.0
+ enable
+ enable
+
+
+
+
+