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
5 changes: 5 additions & 0 deletions .github/workflows/ordered-report-aot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,10 @@ jobs:
$queue = Join-Path $env:RUNNER_TEMP "ordered-aot"
& $exe $queue success
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$rejectedQueue = Join-Path $env:RUNNER_TEMP "ordered-aot-rejected"
& $exe $rejectedQueue terminal
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $exe $rejectedQueue inspect
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $exe $queue success
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,27 @@ is busy, times out or is cancelled after the transaction commits, `ReportAsync`
throw while the event remains queued; retry delivery with `ReplayAsync`, not by
submitting a new report. Persistence failures before commit cannot be replayed.

#### Terminal rejection quarantine (additional opt-in)

Only after verifying the target service supports the newer `ReportTerminalConflict`
contract (not just ordered events), pass `terminalRejectionConfirmed: true` to
`OrderedUpdateReporter` in **every** writer and replay process sharing the store.
Upgrade all processes first: older versions do not respect the quarantine. Never enable
this based on HTTP success or an untrusted endpoint. By default terminal rejection still
stops the entire queue. Other conflicts, HTTP errors, malformed replies and transient
failures always stop replay and retain the original event.

With the extra opt-in, a confirmed terminal rejection is atomically retained in the
same database with its original JSON, event identity, sequence and reason. Later events
for that `(type, recordId)` remain pending and are never sent ahead of it; unrelated
records can proceed. Replay reports an error while any quarantine remains, even if
other records were delivered. Inspect `await reporter.GetQuarantinedAsync()` and alert
an operator; protect these payloads as sensitive. After investigating and correcting
the cause, `await reporter.RetryQuarantinedAsync(id)` restores the exact event to its
original queue position; call `ReplayAsync` to retry it. A terminal record cannot be
reopened; a genuinely new attempt requires a new server record ID. Quarantine does
not fix legacy flows that report Success before a later launch Failure.

## 🙏 Thanks

<div align="center">
Expand Down
18 changes: 18 additions & 0 deletions src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,19 @@ internal async Task SendJsonAsync(string json, CancellationToken token)
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
using var document = JsonDocument.Parse(content);
var root = document.RootElement;
if (response.StatusCode == System.Net.HttpStatusCode.OK &&
root.ValueKind == JsonValueKind.Object &&
root.TryGetProperty("code", out var terminalCode) && terminalCode.ValueKind == JsonValueKind.Number &&
terminalCode.TryGetInt32(out var terminalValue) && terminalValue == 400 &&
root.TryGetProperty("body", out var terminalBody) && terminalBody.ValueKind == JsonValueKind.False &&
root.TryGetProperty("errorCode", out var terminalError) && terminalError.ValueKind == JsonValueKind.String &&
terminalError.GetString() == "ReportTerminalConflict")
throw new ReportTerminalConflictException();
if (root.ValueKind == JsonValueKind.Object &&
root.TryGetProperty("errorCode", out var unexpectedTerminal) &&
unexpectedTerminal.ValueKind == JsonValueKind.String &&
unexpectedTerminal.GetString() == "ReportTerminalConflict")
throw new InvalidOperationException("The terminal rejection response is malformed.");
if (root.ValueKind == JsonValueKind.Object &&
root.TryGetProperty("errorCode", out var errorCode) &&
errorCode.ValueKind == JsonValueKind.String &&
Expand All @@ -249,4 +262,9 @@ internal async Task SendJsonAsync(string json, CancellationToken token)
!root.TryGetProperty("body", out var body) || body.ValueKind != JsonValueKind.True)
throw new InvalidOperationException("The report endpoint did not confirm business success.");
}

internal sealed class ReportTerminalConflictException : InvalidOperationException
{
public ReportTerminalConflictException() : base("The report endpoint rejected a terminal record transition.") { }
}
}
134 changes: 127 additions & 7 deletions src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
Expand All @@ -22,6 +23,7 @@ public sealed class OrderedUpdateReporter : IUpdateReporter
private readonly string _identity;
private readonly HttpUpdateReporter _sender;
private readonly TimeSpan _lockTimeout;
private readonly bool _terminalRejectionConfirmed;

/// <summary>
/// Creates an ordered reporter. The operator must confirm that the endpoint supports
Expand All @@ -30,6 +32,13 @@ public sealed class OrderedUpdateReporter : IUpdateReporter
/// </summary>
public OrderedUpdateReporter(string directory, HttpClient client, string reportUrl,
string namespaceIdentity, bool protocolConfirmed, TimeSpan? lockTimeout = null)
: this(directory, client, reportUrl, namespaceIdentity, protocolConfirmed, false, lockTimeout)
{
}

/// <summary>Creates a reporter with explicit confirmation of the terminal rejection protocol.</summary>
public OrderedUpdateReporter(string directory, HttpClient client, string reportUrl,
string namespaceIdentity, bool protocolConfirmed, bool terminalRejectionConfirmed, 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));
Expand All @@ -43,6 +52,7 @@ public OrderedUpdateReporter(string directory, HttpClient client, string reportU
_identity = Identity(reportUrl, namespaceIdentity);
_sender = new HttpUpdateReporter(client, reportUrl);
_lockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30);
_terminalRejectionConfirmed = terminalRejectionConfirmed;
if (_lockTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(lockTimeout));
}

Expand Down Expand Up @@ -105,22 +115,70 @@ public async Task ReplayAsync(CancellationToken token = default)

private async Task ReplayLockedAsync(SqliteConnection connection, CancellationToken token)
{
if (!_terminalRejectionConfirmed && HasQuarantine(connection))
throw new InvalidOperationException("Quarantined reports require explicit terminal rejection protocol confirmation.");
while (true)
{
token.ThrowIfCancellationRequested();
long id;
string payload;
long id = 0;
string? payload = null;
UpdateReport? report = null;
var blocked = false;
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT id, payload FROM outbox ORDER BY id LIMIT 1;";
command.CommandText = "SELECT id, payload FROM outbox ORDER BY id;";
using (var reader = command.ExecuteReader())
{
if (!reader.Read()) return;
id = reader.GetInt64(0);
payload = reader.GetString(1);
while (reader.Read())
{
var candidate = reader.GetString(1);
var parsed = JsonSerializer.Deserialize(candidate, UpdateReportJsonContext.Default.UpdateReport)
?? throw new InvalidDataException("A queued report is null.");
if (parsed.RecordId <= 0 || (parsed.Type != 1 && parsed.Type != 2) ||
parsed.EventId == null || parsed.EventId == Guid.Empty || parsed.Sequence == null || parsed.Sequence <= 0)
throw new InvalidDataException("A queued ordered report is invalid.");
if (IsBlocked(connection, parsed.Type, parsed.RecordId))
{
blocked = true;
continue;
}
id = reader.GetInt64(0);
payload = candidate;
report = parsed;
break;
}
}
}
if (payload == null)
{
if (blocked || HasQuarantine(connection))
throw new InvalidOperationException("Ordered reports are quarantined; operator review is required.");
return;
}
try
{
await _sender.SendJsonAsync(payload, token).ConfigureAwait(false);
}
catch (HttpUpdateReporter.ReportTerminalConflictException) when (_terminalRejectionConfirmed)
{
using (var transaction = connection.BeginTransaction())
{
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = @"INSERT INTO quarantine (id, type, record_id, payload, reason)
VALUES ($id, $type, $record, $payload, 'ReportTerminalConflict');
DELETE FROM outbox WHERE id = $id;";
command.Parameters.AddWithValue("$id", id);
command.Parameters.AddWithValue("$type", report!.Type);
command.Parameters.AddWithValue("$record", report.RecordId);
command.Parameters.AddWithValue("$payload", payload);
command.ExecuteNonQuery();
}
transaction.Commit();
}
continue;
}
await _sender.SendJsonAsync(payload, token).ConfigureAwait(false);
using (var command = connection.CreateCommand())
{
command.CommandText = "DELETE FROM outbox WHERE id = $id;";
Expand All @@ -130,6 +188,62 @@ private async Task ReplayLockedAsync(SqliteConnection connection, CancellationTo
}
}
}
/// <summary>Returns quarantined reports for operator inspection. Payloads may contain sensitive diagnostics.</summary>
public async Task<IReadOnlyList<QuarantinedUpdateReport>> GetQuarantinedAsync(CancellationToken token = default)
{
using (await AcquireLockAsync(token).ConfigureAwait(false))
using (var connection = Open())
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT id, payload, reason FROM quarantine ORDER BY id;";
using (var reader = command.ExecuteReader())
{
var result = new List<QuarantinedUpdateReport>();
while (reader.Read()) result.Add(new QuarantinedUpdateReport(reader.GetInt64(0), reader.GetString(1), reader.GetString(2)));
return result;
}
}
}

/// <summary>Moves an inspected event back to its original place in the outbox for an explicit retry.</summary>
public async Task RetryQuarantinedAsync(long id, CancellationToken token = default)
{
using (await AcquireLockAsync(token).ConfigureAwait(false))
using (var connection = Open())
using (var transaction = connection.BeginTransaction())
{
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = "INSERT INTO outbox (id, payload) SELECT id, payload FROM quarantine WHERE id = $id;";
command.Parameters.AddWithValue("$id", id);
if (command.ExecuteNonQuery() != 1) throw new InvalidOperationException("Quarantined report not found.");
command.CommandText = "DELETE FROM quarantine WHERE id = $id;";
if (command.ExecuteNonQuery() != 1) throw new InvalidDataException("Quarantined report changed.");
}
transaction.Commit();
}
}

private static bool IsBlocked(SqliteConnection connection, int type, int recordId)
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT EXISTS(SELECT 1 FROM quarantine WHERE type = $type AND record_id = $record);";
command.Parameters.AddWithValue("$type", type);
command.Parameters.AddWithValue("$record", recordId);
return (long)command.ExecuteScalar()! != 0;
}
}

private static bool HasQuarantine(SqliteConnection connection)
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT EXISTS(SELECT 1 FROM quarantine);";
return (long)command.ExecuteScalar()! != 0;
}
}

private SqliteConnection Open()
{
Expand Down Expand Up @@ -157,10 +271,13 @@ private SqliteConnection Open()
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);
CREATE TABLE IF NOT EXISTS quarantine (id INTEGER PRIMARY KEY, type INTEGER NOT NULL,
record_id INTEGER NOT NULL, payload TEXT NOT NULL, reason 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;
Expand Down Expand Up @@ -206,4 +323,7 @@ private static string Identity(string endpoint, string scope)
return Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(value)));
}
}

/// <summary>A rejected report retained for operator review. The JSON is the original wire payload.</summary>
public sealed record QuarantinedUpdateReport(long Id, string Payload, string Reason);
}
Loading
Loading