From 5c67559a257406dfaccc55655b3a0456e50a06d9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:18:43 -0500 Subject: [PATCH] =?UTF-8?q?fix(sitecalls):=20Parked=20is=20re-openable=20e?= =?UTF-8?q?nd=20to=20end=20=E2=80=94=20operator=20Retry/Discard=20reach=20?= =?UTF-8?q?the=20site=20tracking=20row=20and=20central=20SiteCalls=20(SCA-?= =?UTF-8?q?1,=20WP4=20task=204.9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/requirements/Component-SiteCallAudit.md | 22 ++- .../Telemetry/CachedCallLifecycleBridge.cs | 49 +++++++ .../Telemetry/CachedCallTelemetryForwarder.cs | 18 +++ .../Services/ICachedCallLifecycleObserver.cs | 13 ++ .../Services/IOperationTrackingStore.cs | 24 +++ .../Repositories/SiteCallAuditRepository.cs | 11 ++ .../Tracking/OperationTrackingStore.cs | 59 ++++++++ .../StoreAndForwardService.cs | 24 +++ .../ParkedReopenCombinedTelemetryTests.cs | 137 ++++++++++++++++++ .../SiteCallAuditRepositoryTests.cs | 104 +++++++++++-- .../Tracking/OperationTrackingStoreTests.cs | 75 ++++++++++ .../CachedCallAttemptEmissionTests.cs | 57 ++++++++ 12 files changed, 578 insertions(+), 15 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Integration/ParkedReopenCombinedTelemetryTests.cs diff --git a/docs/requirements/Component-SiteCallAudit.md b/docs/requirements/Component-SiteCallAudit.md index b087d8ce..be5a09b5 100644 --- a/docs/requirements/Component-SiteCallAudit.md +++ b/docs/requirements/Component-SiteCallAudit.md @@ -101,10 +101,19 @@ never regresses. Within an equal *non-terminal* rank (the `Attempted`/`Skipped` retry phase), the packet with the newest `UpdatedAtUtc` wins — so a retrying call's `RetryCount`/`LastError`/`HttpStatus` stay live instead of freezing at the first `Attempted` write. Equal *terminal* rank stays immutable (a later -`Delivered` never overwrites an earlier `Parked`), equal stamps are an idempotent +`Failed` never overwrites an earlier `Delivered`), equal stamps are an idempotent no-op, and a lower rank is always a no-op — so at-least-once and out-of-order telemetry remain harmless. +**`Parked` is the one re-openable state (SCA-1, 2026-12).** A **strictly newer** +`Attempted`, `Delivered`, `Failed` or `Discarded` packet replaces a `Parked` row +(operator Retry re-opens the call, then its retried outcome arrives; operator +Discard closes it). Only strictly newer — a stale pre-park packet replayed late, +or any `Submitted`/`Forwarded`, leaves it `Parked`; `Delivered`/`Failed`/`Discarded` +stay immutable. Before this a relayed Retry or Discard could never land: the row +stayed `Parked` until the 365-day purge, the Parked KPI counted it forever and the +page kept offering Retry/Discard on it. + From v1.x onward, the `CachedCallTelemetry` message additively carries the `AuditEvent` content alongside the existing operational fields. Central's `AuditLogIngestActor` (Audit Log #23) performs both the immutable `AuditLog` @@ -217,7 +226,16 @@ Parked cached calls live in the owning site's S&F buffer. Operator Retry/Discard from the Central UI is relayed to that site as a `RetryParkedOperation` / `DiscardParkedOperation` command over the command/control channel. The site applies the change and emits telemetry reflecting the new state; central never -mutates the `SiteCalls` row directly. If the site is offline the command fails +mutates the `SiteCalls` row directly. Concretely (SCA-1): the S&F service notifies +the cached-call observer with `OperatorRetried` / `OperatorDiscarded`; the +lifecycle bridge writes one `CachedSubmit`/`Submitted` row (operational status +`Attempted`, no terminal stamp, RetryCount 0) for a Retry or one +`CachedResolve`/`Discarded` row for a Discard; the forwarder re-opens the +site tracking row (`ReopenParkedAsync`: `Attempted`, `TerminalAtUtc` cleared) or +closes it (`RecordDiscardedAsync`), so `Tracking.Status(id)` follows too; the +cached-telemetry drain and the reconciliation pull then carry the newer row to +central, whose guard accepts it over `Parked`. A retried call's later attempts and +outcome land normally because the row is no longer terminal. If the site is offline the command fails fast and the UI surfaces a "site unreachable" message. On a **successful** relay (the site acks `Applied`), `SiteCallAuditActor` emits diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallLifecycleBridge.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallLifecycleBridge.cs index 73e880a1..7203ef2b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallLifecycleBridge.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallLifecycleBridge.cs @@ -36,6 +36,19 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Site.Telemetry; /// public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver { + /// + /// Operational status a re-opened (operator-retried) Parked call carries (SCA-1). A + /// packet whose operational status is this value — rather + /// than the initial submit's "Submitted" — tells + /// to re-open the tracking row instead of + /// inserting one. Attempted is also what central's SiteCalls guard accepts over + /// Parked when newer. + /// + public const string ReopenedOperationalStatus = "Attempted"; + + /// Operational status of an operator-discarded call (SCA-1). + public const string DiscardedOperationalStatus = "Discarded"; + private readonly ICachedCallTelemetryForwarder _forwarder; private readonly ILogger _logger; @@ -70,6 +83,19 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver try { + // SCA-1: operator transitions out of Parked are not attempts — one row each. + if (context.Outcome == CachedCallAttemptOutcome.OperatorRetried) + { + await EmitReopenAsync(context, ct).ConfigureAwait(false); + return; + } + + if (context.Outcome == CachedCallAttemptOutcome.OperatorDiscarded) + { + await EmitResolveAsync(context, ct).ConfigureAwait(false); + return; + } + await EmitAttemptedAsync(context, ct).ConfigureAwait(false); if (IsTerminal(context.Outcome)) @@ -113,6 +139,27 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver await _forwarder.ForwardAsync(packet, ct).ConfigureAwait(false); } + /// + /// Operator Retry of a Parked call (SCA-1): one / + /// row — the call was re-submitted to the retry loop — + /// whose operational half is with no terminal + /// stamp, RetryCount 0 and no error. The forwarder re-opens the tracking row from it, and + /// the cached-telemetry drain carries the re-opened state to central. + /// + private async Task EmitReopenAsync(CachedCallAttemptContext context, CancellationToken ct) + { + var packet = BuildPacket( + context, + kind: AuditKind.CachedSubmit, + status: AuditStatus.Submitted, + operationalStatus: ReopenedOperationalStatus, + terminalAtUtc: null, + lastError: null, + httpStatus: null); + + await _forwarder.ForwardAsync(packet, ct).ConfigureAwait(false); + } + private async Task EmitResolveAsync(CachedCallAttemptContext context, CancellationToken ct) { var (auditStatus, operationalStatus) = TerminalOutcomeToStatuses(context.Outcome); @@ -214,6 +261,8 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver (AuditStatus.Parked, "Parked"), CachedCallAttemptOutcome.ParkedMaxRetries => (AuditStatus.Parked, "Parked"), + CachedCallAttemptOutcome.OperatorDiscarded => + (AuditStatus.Discarded, DiscardedOperationalStatus), // TransientFailure isn't terminal — see IsTerminal — but the switch // is exhaustive so we route it through Failed for safety. CachedCallAttemptOutcome.TransientFailure => diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallTelemetryForwarder.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallTelemetryForwarder.cs index cfb3644a..8286455f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallTelemetryForwarder.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallTelemetryForwarder.cs @@ -174,6 +174,14 @@ public sealed class CachedCallTelemetryForwarder : ICachedCallTelemetryForwarder { switch (audit.Kind) { + case AuditKind.CachedSubmit + when telemetry.Operational.Status == CachedCallLifecycleBridge.ReopenedOperationalStatus: + // SCA-1: an operator re-queued a Parked call — re-open the row + // (clears TerminalAtUtc) so the retried attempts and outcome land. + await _trackingStore.ReopenParkedAsync( + telemetry.Operational.TrackedOperationId, ct).ConfigureAwait(false); + break; + case AuditKind.CachedSubmit: // Enqueue — insert-if-not-exists with the operational // channel as the kind discriminator. RetryCount is fixed @@ -205,6 +213,16 @@ public sealed class CachedCallTelemetryForwarder : ICachedCallTelemetryForwarder ct).ConfigureAwait(false); break; + case AuditKind.CachedResolve + when telemetry.Operational.Status == CachedCallLifecycleBridge.DiscardedOperationalStatus: + // SCA-1: an operator discard closes a Parked row as Discarded (the + // first-write-wins terminal flip below would leave it Parked). + await _trackingStore.RecordDiscardedAsync( + telemetry.Operational.TrackedOperationId, + telemetry.Operational.LastError, + ct).ConfigureAwait(false); + break; + case AuditKind.CachedResolve: // Terminal — first-write-wins on the resolve flip. await _trackingStore.RecordTerminalAsync( diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICachedCallLifecycleObserver.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICachedCallLifecycleObserver.cs index 33d1d0c1..ef110306 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICachedCallLifecycleObserver.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICachedCallLifecycleObserver.cs @@ -120,4 +120,17 @@ public enum CachedCallAttemptOutcome /// Retry budget exhausted — terminal Parked state. ParkedMaxRetries, + + /// + /// An operator re-queued a PARKED cached call (Retry on the Site Calls / Parked Messages + /// page). Not an attempt: the call is back in the retry loop, so its tracking row leaves + /// Parked (SCA-1, 2026-12). Additive. + /// + OperatorRetried, + + /// + /// An operator discarded a PARKED cached call — terminal Discarded state (SCA-1, + /// 2026-12). Not an attempt. Additive. + /// + OperatorDiscarded, } diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingStore.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingStore.cs index d13b5309..822ffbd0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingStore.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingStore.cs @@ -96,6 +96,30 @@ public interface IOperationTrackingStore int? httpStatus, CancellationToken ct = default); + /// + /// Re-opens a Parked row after an operator Retry re-queued the call (SCA-1): sets + /// Status = Attempted, RetryCount = 0, clears LastError/HttpStatus + /// and TerminalAtUtc, and stamps UpdatedAtUtc, so the attempts and terminal + /// outcome of the retried delivery land on the row again. A row that is not Parked + /// is left untouched. + /// + /// Operation ID to re-open. + /// Cancellation token. + /// A task that represents the asynchronous operation. + Task ReopenParkedAsync(TrackedOperationId id, CancellationToken ct = default); + + /// + /// Records an operator Discard (SCA-1): sets Status = Discarded and stamps + /// TerminalAtUtc/UpdatedAtUtc on a row that is Parked or not yet + /// terminal. Any other terminal row (Delivered, Failed, an earlier Discarded) is left + /// untouched. + /// + /// Operation ID that was discarded. + /// Optional note recorded as the row's last error. + /// Cancellation token. + /// A task that represents the asynchronous operation. + Task RecordDiscardedAsync(TrackedOperationId id, string? lastError, CancellationToken ct = default); + /// /// Return the latest snapshot for the supplied id, or null when no /// tracking row exists (purged or never recorded). diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs index 4e829286..5dcac0e3 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs @@ -27,6 +27,9 @@ public class SiteCallAuditRepository : ISiteCallAuditRepository // Monotonic status ordering: // Submitted < Forwarded < Attempted == Skipped < Delivered == Failed == Parked == Discarded. + // One deliberate exception (SCA-1, 2026-12): Parked is re-openable — a STRICTLY NEWER + // Attempted / Delivered / Failed / Discarded replaces a Parked row (operator Retry or + // Discard at the site); see the last clause of MonotonicUpdateSql. // A higher incoming rank always wins. WITHIN an equal NON-terminal rank // (Attempted/Skipped, rank 2 — and the transient Submitted/Forwarded ranks), // the newest UpdatedAtUtc wins so a retrying call's live RetryCount/LastError @@ -324,6 +327,14 @@ WHERE TrackedOperationId = @Id ELSE -1 END) AND @Rank < @TerminalRank + AND UpdatedAtUtc < @UpdatedAtUtc ) + -- SCA-1: Parked is re-openable. An operator Retry re-queues a parked call at the + -- site (Attempted, then the retried outcome) and a Discard closes it (Discarded); + -- both reach central as NEWER packets. Accept them over Parked only — Delivered, + -- Failed and Discarded stay immutable — and only when strictly newer, so a stale + -- pre-park packet replayed late can never reopen the row. + OR ( Status = 'Parked' + AND @Status IN ('Attempted', 'Delivered', 'Failed', 'Discarded') AND UpdatedAtUtc < @UpdatedAtUtc ) );"; /// diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs index ec2e37b4..fe44ddf8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs @@ -259,6 +259,65 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, }, ct).ConfigureAwait(false); } + /// + public async Task ReopenParkedAsync(TrackedOperationId id, CancellationToken ct = default) + { + var now = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); + var idText = id.ToString(); + + await EnqueueAsync($"reopen {idText}", (conn, tx) => + { + using var cmd = conn.CreateCommand(); + cmd.Transaction = tx; + // SCA-1: Parked is re-openable. Only a Parked row moves — every other terminal + // state stays immutable, and a non-terminal row is already in the loop. + cmd.CommandText = """ + UPDATE OperationTracking + SET Status = 'Attempted', + RetryCount = 0, + LastError = NULL, + HttpStatus = NULL, + UpdatedAtUtc = $now, + TerminalAtUtc = NULL + WHERE TrackedOperationId = $id + AND Status = 'Parked'; + """; + cmd.Parameters.AddWithValue("$id", idText); + cmd.Parameters.AddWithValue("$now", now); + + cmd.ExecuteNonQuery(); + }, ct).ConfigureAwait(false); + } + + /// + public async Task RecordDiscardedAsync(TrackedOperationId id, string? lastError, CancellationToken ct = default) + { + var now = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); + var idText = id.ToString(); + + await EnqueueAsync($"discard {idText}", (conn, tx) => + { + using var cmd = conn.CreateCommand(); + cmd.Transaction = tx; + // SCA-1: an operator discard closes a Parked (or still-open) row as Discarded; + // Delivered/Failed/Discarded stay immutable. + cmd.CommandText = """ + UPDATE OperationTracking + SET Status = 'Discarded', + LastError = COALESCE($lastError, LastError), + UpdatedAtUtc = $now, + TerminalAtUtc = $now + WHERE TrackedOperationId = $id + AND (TerminalAtUtc IS NULL OR Status = 'Parked'); + """; + cmd.Parameters.AddWithValue("$id", idText); + cmd.Parameters.AddWithValue("$lastError", (object?)lastError ?? DBNull.Value); + cmd.Parameters.AddWithValue("$now", now); + + cmd.ExecuteNonQuery(); + }, ct).ConfigureAwait(false); + } + /// public async Task RecordTerminalAsync( TrackedOperationId id, diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs index 6d1ebd04..8e6d7d0b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs @@ -1274,6 +1274,17 @@ public class StoreAndForwardService RaiseActivity("Retry", captured.Category, $"Parked message {messageId} moved back to queue"); + + // SCA-1: a re-queued cached call leaves Parked end to end — the observer re-opens the + // site tracking row and emits telemetry so central's SiteCalls row follows. Without it + // the row stayed Parked forever (later attempts were no-ops on a terminal row). + await PostObserverNotification( + captured, + CachedCallAttemptOutcome.OperatorRetried, + lastError: null, + httpStatus: null, + occurredAtUtc: DateTime.UtcNow, + durationMs: null); return true; } @@ -1299,6 +1310,19 @@ public class StoreAndForwardService { RaiseActivity("Discard", message?.Category ?? StoreAndForwardCategory.ExternalSystem, $"Parked message {messageId} discarded"); + + // SCA-1: record the discard on the tracking row (Parked → Discarded) and emit + // telemetry, so Tracking.Status and central's SiteCalls row stop reporting Parked. + if (message is not null) + { + await PostObserverNotification( + message, + CachedCallAttemptOutcome.OperatorDiscarded, + lastError: "Discarded by operator", + httpStatus: null, + occurredAtUtc: DateTime.UtcNow, + durationMs: null); + } } return success; } diff --git a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Integration/ParkedReopenCombinedTelemetryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Integration/ParkedReopenCombinedTelemetryTests.cs new file mode 100644 index 00000000..fb7bbfe8 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Integration/ParkedReopenCombinedTelemetryTests.cs @@ -0,0 +1,137 @@ +using Akka.TestKit.Xunit2; +using Microsoft.EntityFrameworkCore; +using ZB.MOM.WW.Audit; +using ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Integration.Infrastructure; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Integration; +using ZB.MOM.WW.ScadaBridge.Commons.Types; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Entities; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations; + +namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Integration; + +/// +/// SCA-1 end to end: Parked is re-openable. An operator Retry of a parked cached call +/// re-opens the site tracking row and the central SiteCalls row, so the retried delivery's +/// outcome lands on both; an operator Discard closes both as Discarded. Before the fix both +/// stayed Parked forever (site: later writes were no-ops on a terminal row; central: equal +/// terminal rank was immutable). +/// +public class ParkedReopenCombinedTelemetryTests : TestKit, IClassFixture +{ + private readonly MsSqlMigrationFixture _fixture; + + /// Initializes the test with the shared SQL Server migration fixture. + /// The shared MS SQL migration fixture. + public ParkedReopenCombinedTelemetryTests(MsSqlMigrationFixture fixture) => _fixture = fixture; + + private static string NewSiteId() => "test-sca1-" + Guid.NewGuid().ToString("N")[..8]; + + private static CachedCallTelemetry SubmitPacket(TrackedOperationId id, string siteId, DateTime nowUtc) => + new( + Audit: ScadaBridgeAuditEventFactory.Create( + eventId: Guid.NewGuid(), + occurredAtUtc: nowUtc, + channel: AuditChannel.ApiOutbound, + kind: AuditKind.CachedSubmit, + correlationId: id.Value, + sourceSiteId: siteId, + target: "ERP.GetOrder", + status: AuditStatus.Submitted), + Operational: new SiteCallOperational( + id, "ApiOutbound", "ERP.GetOrder", siteId, null, "Submitted", 0, null, null, + nowUtc, nowUtc, null)); + + private static CachedCallAttemptContext Ctx( + TrackedOperationId id, string siteId, CachedCallAttemptOutcome outcome, int retryCount, + string? lastError, DateTime createdUtc, DateTime occurredUtc) => + new(id, "ApiOutbound", "ERP.GetOrder", siteId, outcome, retryCount, lastError, null, + createdUtc, occurredUtc, null, "Plant.Pump42"); + + private static async Task ParkAsync(CombinedTelemetryHarness harness, TrackedOperationId id, string siteId, DateTime t0) + { + await harness.EmitSubmitAsync(SubmitPacket(id, siteId, t0)); + await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.ParkedMaxRetries, 3, "HTTP 500", t0, t0.AddSeconds(30))); + Assert.Equal("Parked", (await harness.TrackingStore.GetStatusAsync(id))!.Status); + } + + /// Retry of a parked call, then a successful delivery: site and central both end Delivered. + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task ParkedThenOperatorRetryThenDelivered_SiteAndCentral_EndDelivered() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var siteId = NewSiteId(); + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 12, 1, 9, 0, 0, DateTimeKind.Utc); + await using var harness = new CombinedTelemetryHarness(_fixture, this); + await ParkAsync(harness, id, siteId, t0); + + await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.OperatorRetried, 0, null, t0, t0.AddMinutes(5))); + await harness.TrackingStore.FlushAsync(); + + var reopened = await harness.TrackingStore.GetStatusAsync(id); + Assert.Equal("Attempted", reopened!.Status); + Assert.Null(reopened.TerminalAtUtc); + + await using (var read = harness.CreateReadContext()) + { + var row = await read.Set().SingleAsync(s => s.TrackedOperationId == id); + Assert.Equal("Attempted", row.Status); + Assert.Null(row.TerminalAtUtc); + } + + await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.Delivered, 1, null, t0, t0.AddMinutes(6))); + + var delivered = await harness.TrackingStore.GetStatusAsync(id); + Assert.Equal("Delivered", delivered!.Status); + Assert.NotNull(delivered.TerminalAtUtc); + + await using (var read = harness.CreateReadContext()) + { + var row = await read.Set().SingleAsync(s => s.TrackedOperationId == id); + Assert.Equal("Delivered", row.Status); + Assert.NotNull(row.TerminalAtUtc); + + // The re-queue is recorded as a second CachedSubmit (Submitted) row. + var submits = await read.Set() + .Where(e => e.SourceSiteId == siteId && e.Kind == AuditKind.CachedSubmit) + .CountAsync(); + Assert.Equal(2, submits); + } + } + + /// Discard of a parked call: site and central both end Discarded. + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task ParkedThenOperatorDiscard_SiteAndCentral_EndDiscarded() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var siteId = NewSiteId(); + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 12, 1, 10, 0, 0, DateTimeKind.Utc); + await using var harness = new CombinedTelemetryHarness(_fixture, this); + await ParkAsync(harness, id, siteId, t0); + + await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.OperatorDiscarded, 3, "Discarded by operator", t0, t0.AddMinutes(5))); + + var site = await harness.TrackingStore.GetStatusAsync(id); + Assert.Equal("Discarded", site!.Status); + Assert.NotNull(site.TerminalAtUtc); + + await using var read = harness.CreateReadContext(); + var row = await read.Set().SingleAsync(s => s.TrackedOperationId == id); + Assert.Equal("Discarded", row.Status); + + var resolves = await read.Set() + .Where(e => e.SourceSiteId == siteId && e.Kind == AuditKind.CachedResolve) + .Select(e => e.Status) + .ToListAsync(); + Assert.Contains(AuditStatus.Discarded, resolves); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/SiteCallAuditRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/SiteCallAuditRepositoryTests.cs index f6a2c6a7..432f5859 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/SiteCallAuditRepositoryTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/SiteCallAuditRepositoryTests.cs @@ -372,33 +372,111 @@ public class SiteCallAuditRepositoryTests : IClassFixture Assert.Equal(0, row.RetryCount); } - /// Verifies that one terminal status cannot overwrite another terminal status. + /// + /// Verifies that one terminal status cannot overwrite another terminal status — except + /// Parked, which is re-openable (SCA-1; see the Parked tests below). + /// /// A task that represents the asynchronous operation. [SkippableFact] public async Task UpsertAsync_TerminalOverTerminal_IsNoOp() { Skip.IfNot(_fixture.Available, _fixture.SkipReason); - // Terminal statuses share rank 3 and are mutually - // exclusive — Delivered cannot overwrite Parked. Note that the - // Delivered packet carries a STRICTLY-NEWER UpdatedAtUtc, yet the row - // stays Parked — the same-rank freshness tiebreaker is scoped to - // NON-terminal ranks (< 3), so terminal immutability is preserved. + // Delivered/Failed/Discarded share rank 3 and are mutually exclusive: a later + // Failed (STRICTLY-NEWER UpdatedAtUtc) cannot overwrite Delivered. The same-rank + // freshness tiebreaker is scoped to NON-terminal ranks (< 3). + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); + await using var context = CreateContext(); + var repo = new SiteCallAuditRepository(context); + + await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 3, lastError: null, updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); + var afterDelivered = await repo.GetAsync(id); + + await repo.UpsertAsync(NewRow(id, status: "Failed", retryCount: 4, lastError: "late", updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5))); + await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 4, lastError: "late", updatedAtUtc: t0.AddMinutes(6), terminal: true, terminalAtUtc: t0.AddMinutes(6))); + var after = await repo.GetAsync(id); + + Assert.NotNull(after); + Assert.Equal("Delivered", after!.Status); + Assert.Equal(afterDelivered!.UpdatedAtUtc, after.UpdatedAtUtc); + } + + /// + /// SCA-1 regression: an operator Retry of a Parked call re-opens it at the site, so a + /// NEWER Attempted and then Delivered must replace the Parked row (it used to stay Parked + /// until the 365-day purge). + /// + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task UpsertAsync_ParkedThenNewerAttemptedThenDelivered_Reopens() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + var id = TrackedOperationId.New(); var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); await using var context = CreateContext(); var repo = new SiteCallAuditRepository(context); await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); - var afterPark = await repo.GetAsync(id); - await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 4, lastError: null, updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5))); - var afterDeliveredAttempt = await repo.GetAsync(id); + await repo.UpsertAsync(NewRow(id, status: "Attempted", retryCount: 0, lastError: null, updatedAtUtc: t0.AddMinutes(5))); + var reopened = await repo.GetAsync(id); + Assert.Equal("Attempted", reopened!.Status); + Assert.Null(reopened.TerminalAtUtc); + Assert.Null(reopened.LastError); - Assert.NotNull(afterDeliveredAttempt); - Assert.Equal("Parked", afterDeliveredAttempt!.Status); - Assert.Equal("parked-reason", afterDeliveredAttempt.LastError); - Assert.Equal(afterPark!.UpdatedAtUtc, afterDeliveredAttempt.UpdatedAtUtc); + await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 1, lastError: null, updatedAtUtc: t0.AddMinutes(6), terminal: true, terminalAtUtc: t0.AddMinutes(6))); + // Fresh context: the first GetAsync left the row tracked, and a raw-SQL upsert does + // not refresh a tracked entity. + await using var readContext = CreateContext(); + var delivered = await new SiteCallAuditRepository(readContext).GetAsync(id); + Assert.Equal("Delivered", delivered!.Status); + Assert.NotNull(delivered.TerminalAtUtc); + } + + /// SCA-1: an operator Discard of a Parked call (newer) closes it as Discarded. + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task UpsertAsync_ParkedThenNewerDiscarded_IsDiscarded() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); + await using var context = CreateContext(); + var repo = new SiteCallAuditRepository(context); + + await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); + await repo.UpsertAsync(NewRow(id, status: "Discarded", retryCount: 3, lastError: "Discarded by operator", updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5))); + + var row = await repo.GetAsync(id); + Assert.Equal("Discarded", row!.Status); + } + + /// + /// SCA-1: Parked is re-opened only by a STRICTLY NEWER Attempted/Delivered/Failed/Discarded — a + /// stale pre-park packet replayed late, or a newer Submitted/Forwarded, leaves it Parked. + /// + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task UpsertAsync_Parked_StaleOrLowRankPacket_StaysParked() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); + await using var context = CreateContext(); + var repo = new SiteCallAuditRepository(context); + + await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); + await repo.UpsertAsync(NewRow(id, status: "Attempted", retryCount: 2, lastError: "old", updatedAtUtc: t0.AddMinutes(-5))); + await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 2, updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); + await repo.UpsertAsync(NewRow(id, status: "Submitted", retryCount: 0, updatedAtUtc: t0.AddMinutes(5))); + + var row = await repo.GetAsync(id); + Assert.Equal("Parked", row!.Status); + Assert.Equal("parked-reason", row.LastError); } /// Verifies that concurrent inserts of the same id leave only one row. diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs index 68389a04..3ee6838c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs @@ -389,6 +389,81 @@ public class OperationTrackingStoreTests : IDisposable Assert.True(snapshot.UpdatedAtUtc >= snapshot.CreatedAtUtc); } + /// + /// SCA-1: a Parked row re-opens on an operator Retry — TerminalAtUtc cleared, RetryCount and + /// error reset — so the retried attempts and outcome land on it again. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReopenParkedAsync_ReopensParkedRow_SoTheRetriedOutcomeLands() + { + var (store, _) = CreateStore(nameof(ReopenParkedAsync_ReopensParkedRow_SoTheRetriedOutcomeLands)); + await using var _store = store; + + var id = TrackedOperationId.New(); + await store.RecordEnqueueAsync(id, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null); + await store.RecordAttemptAsync(id, nameof(AuditStatus.Attempted), 3, "HTTP 500", 500); + await store.RecordTerminalAsync(id, nameof(AuditStatus.Parked), "HTTP 500", 500); + var parked = await store.GetStatusAsync(id); + + await store.ReopenParkedAsync(id); + var reopened = await store.GetStatusAsync(id); + Assert.Equal(nameof(AuditStatus.Attempted), reopened!.Status); + Assert.Null(reopened.TerminalAtUtc); + Assert.Equal(0, reopened.RetryCount); + Assert.Null(reopened.LastError); + Assert.True(reopened.UpdatedAtUtc >= parked!.UpdatedAtUtc); + + await store.RecordAttemptAsync(id, nameof(AuditStatus.Attempted), 1, null, 200); + await store.RecordTerminalAsync(id, nameof(AuditStatus.Delivered), null, 200); + var delivered = await store.GetStatusAsync(id); + Assert.Equal(nameof(AuditStatus.Delivered), delivered!.Status); + Assert.NotNull(delivered.TerminalAtUtc); + } + + /// SCA-1: re-open touches only a Parked row — a Delivered row stays Delivered. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReopenParkedAsync_OnNonParkedTerminalRow_IsNoOp() + { + var (store, _) = CreateStore(nameof(ReopenParkedAsync_OnNonParkedTerminalRow_IsNoOp)); + await using var _store = store; + + var id = TrackedOperationId.New(); + await store.RecordEnqueueAsync(id, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null); + await store.RecordTerminalAsync(id, nameof(AuditStatus.Delivered), null, 200); + + await store.ReopenParkedAsync(id); + + var row = await store.GetStatusAsync(id); + Assert.Equal(nameof(AuditStatus.Delivered), row!.Status); + Assert.NotNull(row.TerminalAtUtc); + } + + /// SCA-1: an operator Discard closes a Parked row as Discarded; Delivered stays immutable. + /// A task that represents the asynchronous operation. + [Fact] + public async Task RecordDiscardedAsync_ClosesParkedRow_ButNotADeliveredOne() + { + var (store, _) = CreateStore(nameof(RecordDiscardedAsync_ClosesParkedRow_ButNotADeliveredOne)); + await using var _store = store; + + var parkedId = TrackedOperationId.New(); + await store.RecordEnqueueAsync(parkedId, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null); + await store.RecordTerminalAsync(parkedId, nameof(AuditStatus.Parked), "HTTP 500", 500); + await store.RecordDiscardedAsync(parkedId, "Discarded by operator"); + var discarded = await store.GetStatusAsync(parkedId); + Assert.Equal(nameof(AuditStatus.Discarded), discarded!.Status); + Assert.NotNull(discarded.TerminalAtUtc); + Assert.Equal("Discarded by operator", discarded.LastError); + + var deliveredId = TrackedOperationId.New(); + await store.RecordEnqueueAsync(deliveredId, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null); + await store.RecordTerminalAsync(deliveredId, nameof(AuditStatus.Delivered), null, 200); + await store.RecordDiscardedAsync(deliveredId, "Discarded by operator"); + Assert.Equal(nameof(AuditStatus.Delivered), (await store.GetStatusAsync(deliveredId))!.Status); + } + /// Verifies that recording an attempt on a terminal row is a no-op. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/CachedCallAttemptEmissionTests.cs b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/CachedCallAttemptEmissionTests.cs index af062880..6420162a 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/CachedCallAttemptEmissionTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/CachedCallAttemptEmissionTests.cs @@ -113,6 +113,63 @@ public class CachedCallAttemptEmissionTests : IAsyncLifetime, IDisposable return trackedId; } + // ── SCA-1: operator transitions out of Parked ── + + private async Task ParkAsync() + { + _service.RegisterDeliveryHandler(StoreAndForwardCategory.ExternalSystem, _ => Task.FromResult(false)); + var id = await EnqueueBufferedAsync(StoreAndForwardCategory.ExternalSystem, "ERP", maxRetries: 5); + await _service.RetryPendingMessagesAsync(); + Assert.Equal(CachedCallAttemptOutcome.PermanentFailure, Assert.Single(_observer.Notifications).Outcome); + _observer.Notifications.Clear(); + return id; + } + + /// + /// SCA-1 regression: an operator Retry of a parked cached call notifies the observer with + /// , so the tracking row re-opens and + /// telemetry carries the change to central (it used to raise an activity only). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task OperatorRetryOfParkedCall_NotifiesOperatorRetried() + { + var id = await ParkAsync(); + + Assert.True(await _service.RetryParkedMessageAsync(id.ToString())); + + var n = Assert.Single(_observer.Notifications); + Assert.Equal(id, n.TrackedOperationId); + Assert.Equal(CachedCallAttemptOutcome.OperatorRetried, n.Outcome); + Assert.Equal(0, n.RetryCount); + Assert.Null(n.LastError); + } + + /// SCA-1 regression: an operator Discard notifies . + /// A task that represents the asynchronous operation. + [Fact] + public async Task OperatorDiscardOfParkedCall_NotifiesOperatorDiscarded() + { + var id = await ParkAsync(); + + Assert.True(await _service.DiscardParkedMessageAsync(id.ToString())); + + var n = Assert.Single(_observer.Notifications); + Assert.Equal(id, n.TrackedOperationId); + Assert.Equal(CachedCallAttemptOutcome.OperatorDiscarded, n.Outcome); + } + + /// A retry/discard of a message that is not parked notifies nothing. + /// A task that represents the asynchronous operation. + [Fact] + public async Task OperatorRetryOfNonParkedCall_NotifiesNothing() + { + var id = await EnqueueBufferedAsync(StoreAndForwardCategory.ExternalSystem, "ERP", maxRetries: 5); + + Assert.False(await _service.RetryParkedMessageAsync(id.ToString())); + Assert.Empty(_observer.Notifications); + } + // ── Per-attempt observer notifications ── /// Verifies that a failed attempt with an HTTP 500 emits attempted telemetry.