diff --git a/.github/workflows/ordered-report-aot.yml b/.github/workflows/ordered-report-aot.yml index 6eddbe22..328f0027 100644 --- a/.github/workflows/ordered-report-aot.yml +++ b/.github/workflows/ordered-report-aot.yml @@ -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 } diff --git a/README.md b/README.md index 3e838a5e..c4559b17 100644 --- a/README.md +++ b/README.md @@ -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
diff --git a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs index 4f61202e..aa51e357 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs @@ -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 && @@ -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.") { } + } } diff --git a/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs index 737085d4..94f9f597 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http; @@ -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; /// /// Creates an ordered reporter. The operator must confirm that the endpoint supports @@ -30,6 +32,13 @@ public sealed class OrderedUpdateReporter : IUpdateReporter /// public OrderedUpdateReporter(string directory, HttpClient client, string reportUrl, string namespaceIdentity, bool protocolConfirmed, TimeSpan? lockTimeout = null) + : this(directory, client, reportUrl, namespaceIdentity, protocolConfirmed, false, lockTimeout) + { + } + + /// Creates a reporter with explicit confirmation of the terminal rejection protocol. + 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)); @@ -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)); } @@ -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;"; @@ -130,6 +188,62 @@ private async Task ReplayLockedAsync(SqliteConnection connection, CancellationTo } } } + /// Returns quarantined reports for operator inspection. Payloads may contain sensitive diagnostics. + public async Task> 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(); + while (reader.Read()) result.Add(new QuarantinedUpdateReport(reader.GetInt64(0), reader.GetString(1), reader.GetString(2))); + return result; + } + } + } + + /// Moves an inspected event back to its original place in the outbox for an explicit retry. + 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() { @@ -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; @@ -206,4 +323,7 @@ private static string Identity(string endpoint, string scope) return Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(value))); } } + + /// A rejected report retained for operator review. The JSON is the original wire payload. + public sealed record QuarantinedUpdateReport(long Id, string Payload, string Reason); } diff --git a/tests/CoreTest/Download/OrderedUpdateReporterTests.cs b/tests/CoreTest/Download/OrderedUpdateReporterTests.cs index b0d9c79f..2133a959 100644 --- a/tests/CoreTest/Download/OrderedUpdateReporterTests.cs +++ b/tests/CoreTest/Download/OrderedUpdateReporterTests.cs @@ -61,6 +61,67 @@ await Assert.ThrowsAsync(() => Assert.Equal(handler.Bodies[1], handler.Bodies[2]); } + [Fact] + public async Task TerminalRejectionIsOptInAndPreservesPerRecordOrderingAcrossRestart() + { + var handler = new Handler { TerminalRecord = 10 }; + var legacy = Create(handler); + await Assert.ThrowsAnyAsync(() => legacy.ReportAsync(new UpdateReport(10, 3))); + Assert.Empty(await legacy.GetQuarantinedAsync()); + var reporter = Create(handler, true); + await Assert.ThrowsAsync(() => reporter.ReplayAsync()); + var quarantined = Assert.Single(await Create(handler, true).GetQuarantinedAsync()); + Assert.Equal(handler.Bodies[0], quarantined.Payload); + Assert.Equal("ReportTerminalConflict", quarantined.Reason); + await Assert.ThrowsAsync(() => reporter.ReportAsync(new UpdateReport(10, 2))); + await Assert.ThrowsAsync(() => reporter.ReportAsync(new UpdateReport(11, 3))); + Assert.Equal(new[] { 10, 10, 11 }, handler.Bodies.Select(RecordId)); + await Assert.ThrowsAsync(() => legacy.ReplayAsync()); + handler.TerminalRecord = null; + await reporter.RetryQuarantinedAsync(quarantined.Id); + await Create(handler, true).ReplayAsync(); + Assert.Equal(new[] { 10, 10, 11, 10, 10 }, handler.Bodies.Select(RecordId)); + Assert.Equal(quarantined.Payload, handler.Bodies[3]); + Assert.Equal(2, Sequence(handler.Bodies[4])); + Assert.Empty(await reporter.GetQuarantinedAsync()); + } + + [Theory] + [InlineData("{\"code\":400,\"body\":false,\"errorCode\":\"Conflict\"}", 200)] + [InlineData("{\"code\":200,\"body\":true,\"errorCode\":\"ReportTerminalConflict\"}", 200)] + [InlineData("{\"code\":400,\"body\":false,\"errorCode\":\"ReportTerminalConflict\"}", 409)] + [InlineData("{\"code\":400,\"body\":false,\"errorCode\":\"Other\"}", 200)] + public async Task OtherResponsesNeverQuarantine(string body, int status) + { + var handler = new Handler { ResponseBody = body, ResponseStatus = status }; + var reporter = Create(handler, true); + await Assert.ThrowsAnyAsync(() => reporter.ReportAsync(new UpdateReport(10, 3))); + Assert.Empty(await reporter.GetQuarantinedAsync()); + handler.ResponseBody = null; + handler.ResponseStatus = 200; + await reporter.ReplayAsync(); + Assert.Equal(handler.Bodies[0], handler.Bodies[1]); + } + + [Fact] + public async Task QuarantineSurvivesProcessRestartAndOtherRecordIsDelivered() + { + using (var worker = StartWorker("terminal")) + { + await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(60)); + Assert.Equal(0, worker.ExitCode); + } + using (var worker = StartWorker("inspect")) + { + await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(60)); + Assert.Equal(0, worker.ExitCode); + } + var handler = new Handler(); + await Assert.ThrowsAsync(() => Create(handler, true).ReportAsync(new UpdateReport(11, 3))); + Assert.Equal(11, RecordId(Assert.Single(handler.Bodies))); + Assert.Single(await Create(handler, true).GetQuarantinedAsync()); + } + [Fact] public async Task ConcurrentProcessesAllocateUniqueSequences() { @@ -152,8 +213,9 @@ await Task.WhenAll(Enumerable.Range(0, 12).Select(async _ => 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 OrderedUpdateReporter Create(Handler handler, bool terminalConfirmed = false) => + new(_directory, new HttpClient(handler, false), "https://example.test/report", "tenant/database", true, + terminalRejectionConfirmed: terminalConfirmed); private Process StartWorker(string mode) { @@ -167,6 +229,7 @@ private Process StartWorker(string mode) 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(); + private static int RecordId(string body) => JsonDocument.Parse(body).RootElement.GetProperty("recordId").GetInt32(); public void Dispose() { @@ -178,6 +241,9 @@ private sealed class Handler : HttpMessageHandler public bool Fail { get; set; } public bool AcceptBeforeFailure { get; set; } public bool Conflict { get; set; } + public int? TerminalRecord { get; set; } + public string? ResponseBody { get; set; } + public int ResponseStatus { get; set; } = 200; public List Bodies { get; } = []; public HashSet Applied { get; } = []; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) @@ -189,11 +255,13 @@ protected override async Task SendAsync(HttpRequestMessage json.RootElement.TryGetProperty("eventId", out var eventId)) Applied.Add(eventId.GetGuid()); if (Fail) throw new HttpRequestException("lost response"); - return new HttpResponseMessage(HttpStatusCode.OK) + return new HttpResponseMessage((HttpStatusCode)ResponseStatus) { - Content = new StringContent(Conflict + Content = new StringContent(ResponseBody ?? (TerminalRecord == json.RootElement.GetProperty("recordId").GetInt32() + ? "{\"code\":400,\"errorCode\":\"ReportTerminalConflict\",\"body\":false}" + : Conflict ? "{\"code\":400,\"errorCode\":\"Conflict\",\"body\":false}" - : "{\"code\":200,\"body\":true}") + : "{\"code\":200,\"body\":true}")) }; } } diff --git a/tests/ReportWorker/Program.cs b/tests/ReportWorker/Program.cs index efd1a059..9030b002 100644 --- a/tests/ReportWorker/Program.cs +++ b/tests/ReportWorker/Program.cs @@ -12,11 +12,21 @@ 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); + var reporter = new OrderedUpdateReporter(args[0], client, "https://example.test/report", "tenant/database", true, + terminalRejectionConfirmed: args[1] == "terminal" || args[1] == "inspect"); + if (args[1] == "inspect") + { + var quarantined = await reporter.GetQuarantinedAsync(); + return quarantined.Count == 1 && quarantined[0].Reason == "ReportTerminalConflict" ? 0 : 1; + } try { await reporter.ReportAsync(new UpdateReport(10, 3)); } + catch (InvalidOperationException) when (args[1] == "terminal") + { + return (await reporter.GetQuarantinedAsync()).Count == 1 ? 0 : 1; + } catch (HttpRequestException) { return 0; @@ -39,6 +49,8 @@ protected override async Task SendAsync(HttpRequestMessage await Task.Delay(Timeout.InfiniteTimeSpan, token); } if (mode == "offline") throw new HttpRequestException("offline"); + if (mode == "terminal") + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"code\":400,\"body\":false,\"errorCode\":\"ReportTerminalConflict\"}") }; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"code\":200,\"body\":true}") }; } }