fix(sitecalls): Parked is re-openable end to end — operator Retry/Discard reach the site tracking row and central SiteCalls (SCA-1, WP4 task 4.9)

This commit is contained in:
Joseph Doherty
2026-12-03 10:18:43 -05:00
parent 4070f7efca
commit 5c67559a25
12 changed files with 578 additions and 15 deletions
@@ -36,6 +36,19 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Site.Telemetry;
/// </remarks>
public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver
{
/// <summary>
/// Operational status a re-opened (operator-retried) Parked call carries (SCA-1). A
/// <see cref="AuditKind.CachedSubmit"/> packet whose operational status is this value — rather
/// than the initial submit's <c>"Submitted"</c> — tells
/// <see cref="CachedCallTelemetryForwarder"/> to re-open the tracking row instead of
/// inserting one. <c>Attempted</c> is also what central's <c>SiteCalls</c> guard accepts over
/// <c>Parked</c> when newer.
/// </summary>
public const string ReopenedOperationalStatus = "Attempted";
/// <summary>Operational status of an operator-discarded call (SCA-1).</summary>
public const string DiscardedOperationalStatus = "Discarded";
private readonly ICachedCallTelemetryForwarder _forwarder;
private readonly ILogger<CachedCallLifecycleBridge> _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);
}
/// <summary>
/// Operator Retry of a Parked call (SCA-1): one <see cref="AuditKind.CachedSubmit"/> /
/// <see cref="AuditStatus.Submitted"/> row — the call was re-submitted to the retry loop —
/// whose operational half is <see cref="ReopenedOperationalStatus"/> 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.
/// </summary>
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 =>
@@ -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(
@@ -120,4 +120,17 @@ public enum CachedCallAttemptOutcome
/// <summary>Retry budget exhausted — terminal Parked state.</summary>
ParkedMaxRetries,
/// <summary>
/// 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
/// <c>Parked</c> (SCA-1, 2026-12). Additive.
/// </summary>
OperatorRetried,
/// <summary>
/// An operator discarded a PARKED cached call — terminal <c>Discarded</c> state (SCA-1,
/// 2026-12). Not an attempt. Additive.
/// </summary>
OperatorDiscarded,
}
@@ -96,6 +96,30 @@ public interface IOperationTrackingStore
int? httpStatus,
CancellationToken ct = default);
/// <summary>
/// Re-opens a <c>Parked</c> row after an operator Retry re-queued the call (SCA-1): sets
/// <c>Status = Attempted</c>, <c>RetryCount = 0</c>, clears <c>LastError</c>/<c>HttpStatus</c>
/// and <c>TerminalAtUtc</c>, and stamps <c>UpdatedAtUtc</c>, so the attempts and terminal
/// outcome of the retried delivery land on the row again. A row that is not <c>Parked</c>
/// is left untouched.
/// </summary>
/// <param name="id">Operation ID to re-open.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task ReopenParkedAsync(TrackedOperationId id, CancellationToken ct = default);
/// <summary>
/// Records an operator Discard (SCA-1): sets <c>Status = Discarded</c> and stamps
/// <c>TerminalAtUtc</c>/<c>UpdatedAtUtc</c> on a row that is <c>Parked</c> or not yet
/// terminal. Any other terminal row (Delivered, Failed, an earlier Discarded) is left
/// untouched.
/// </summary>
/// <param name="id">Operation ID that was discarded.</param>
/// <param name="lastError">Optional note recorded as the row's last error.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task RecordDiscardedAsync(TrackedOperationId id, string? lastError, CancellationToken ct = default);
/// <summary>
/// Return the latest snapshot for the supplied id, or <c>null</c> when no
/// tracking row exists (purged or never recorded).
@@ -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 ) );";
/// <summary>
@@ -259,6 +259,65 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable,
}, ct).ConfigureAwait(false);
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
public async Task RecordTerminalAsync(
TrackedOperationId id,
@@ -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;
}