Skip to content
Draft
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
36 changes: 36 additions & 0 deletions .github/workflows/ordered-report-aot.yml
Original file line number Diff line number Diff line change
@@ -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 }
47 changes: 42 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 20 additions & 0 deletions src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ public enum UpdateStatus { Updating = 1, Success = 2, Failure = 3 }
/// </remarks>
public record UpdateReport(int RecordId, int Status = 1, int Type = 1)
{
/// <summary>Optional idempotency key, paired with <see cref="Sequence"/>.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public Guid? EventId { get; init; }

/// <summary>Optional positive sequence for the record, paired with <see cref="EventId"/>.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public long? Sequence { get; init; }

/// <summary>Optional failure category, matching the server's diagnostic contract.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public FailureCategory? Category { get; init; }
Expand Down Expand Up @@ -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);
Expand All @@ -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 ||
Expand Down
209 changes: 209 additions & 0 deletions src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs
Original file line number Diff line number Diff line change
@@ -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;

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

/// <summary>
/// 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.
/// </summary>
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));
}

/// <summary>Atomically allocates an event and sequence, commits the payload, then replays.</summary>
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);
}

/// <summary>Replays committed events in order, stopping on the first unconfirmed response.</summary>
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<FileStream> 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)));
}
}
}
2 changes: 2 additions & 0 deletions src/GeneralUpdate.Core/GeneralUpdate.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.10" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.1.13" />
<!-- IsExternalInit is built-in for net8.0+ (C# 9 records) -->
<Compile Remove="Configuration\IsExternalInit.cs" Condition="'$(TargetFramework)' != 'netstandard2.0'" />

Expand Down
1 change: 1 addition & 0 deletions tests/CoreTest/CoreTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

<ItemGroup>
<ProjectReference Include="..\..\src\GeneralUpdate.Core\GeneralUpdate.Core.csproj" />
<ProjectReference Include="..\ReportWorker\ReportWorker.csproj" />
</ItemGroup>

</Project>
Loading
Loading