fix(comm): fold post-snapshot debug events into the snapshot and fail fast on a snapshot-request failure (COMM-3, COMM-7, WP4 task 4.3)

This commit is contained in:
Joseph Doherty
2026-12-03 09:47:29 -05:00
parent 8a4b466a03
commit c1db7094eb
4 changed files with 278 additions and 7 deletions
@@ -291,6 +291,37 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers
_snapshotDelivered = true;
});
// Fail-fast reply from the command transport (COMM-7). GrpcSiteTransport answers a
// send it cannot complete (no channel for the site, an immediate RPC error) with
// Status.Failure to the reply target — this actor, for the snapshot request. Before
// the snapshot that is the end of the session: fail it now with the real cause instead
// of waiting out the 30 s snapshot deadline and reporting a generic timeout. After the
// snapshot (e.g. a failed unsubscribe) it is informational only.
Receive<Status.Failure>(failure =>
{
if (_stopped) return;
if (_snapshotDelivered)
{
_log.Debug("Ignoring command-plane failure for {0} after the snapshot: {1}",
_instanceUniqueName, failure.Cause?.Message);
return;
}
_log.Warning("Debug snapshot request for {0} on site {1} failed: {2}",
_instanceUniqueName, _siteIdentifier, failure.Cause?.Message);
Timers.Cancel(SnapshotTimerKey);
CleanupGrpc();
SendUnsubscribe();
_stopped = true;
_preSnapshotBuffer.Clear();
// Hand the cause to DebugStreamService (it intercepts this marker and fails the
// pending StartStreamAsync with it) before the generic termination callback.
_onEvent(new DebugSnapshotRequestFailed(
failure.Cause ?? new InvalidOperationException("The debug snapshot request failed.")));
_onTerminated();
Context.Stop(Self);
});
// Hard snapshot deadline. Nothing else ends a session stuck in the
// buffering phase: the site's reply was lost, so no gRPC error fires, the stream
// keeps delivering events, and stream traffic does not renew the orphan net (which
@@ -577,7 +608,7 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers
/// key via <see cref="string.Concat"/> (e.g. two entries with null AttributePath
/// would otherwise share a key with any entry whose AttributePath is the empty string).
/// </summary>
private static string AttributeKey(AttributeValueChanged a) =>
internal static string AttributeKey(AttributeValueChanged a) =>
string.Concat(
a.InstanceUniqueName ?? string.Empty, KeyDelimiter,
a.AttributePath ?? string.Empty, KeyDelimiter,
@@ -589,7 +620,7 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers
/// reference) are not conflated; empty for computed alarms. Each nullable component is
/// guarded with <c>?? string.Empty</c> to prevent silent key collisions.
/// </summary>
private static string AlarmKey(AlarmStateChanged al) =>
internal static string AlarmKey(AlarmStateChanged al) =>
string.Concat(
al.InstanceUniqueName ?? string.Empty, KeyDelimiter,
al.AlarmName ?? string.Empty, KeyDelimiter,
@@ -862,6 +893,15 @@ internal record ConsumerLivenessTick;
/// </summary>
internal record DebugSnapshotDeadline;
/// <summary>
/// Delivered through the bridge's <c>onEvent</c> callback when the snapshot request failed
/// fast at the command transport (COMM-7). <see cref="DebugStreamService"/> intercepts it and
/// fails the pending <c>StartStreamAsync</c> with <see cref="Cause"/>; it never reaches a
/// consumer.
/// </summary>
/// <param name="Cause">The transport failure.</param>
internal sealed record DebugSnapshotRequestFailed(Exception Cause);
/// <summary>
/// Internal message indicating a gRPC stream error occurred, stamped with the stream
/// generation it came from so a late error out of a cancelled stream can be ignored.
@@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Communication.Actors;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
@@ -138,16 +139,39 @@ public class DebugStreamService : IDisposable
// Capture the initial snapshot via a TaskCompletionSource
var snapshotTcs = new TaskCompletionSource<DebugViewSnapshot>(TaskCreationOptions.RunContinuationsAsynchronously);
// COMM-3: events that follow the snapshot (the bridge flushes its gap-window buffer
// synchronously, right after the snapshot) are HELD here until this method hands the
// snapshot back, then folded into it. Passing them straight to onEvent delivered them
// before the caller had applied the snapshot, so a consumer that replaces its state
// from the snapshot regressed to the older value (the SignalR hub sent
// OnAttributeChanged before OnSnapshot). All three fields are guarded by `gate`.
var gate = new object();
var handedOver = false;
var held = new List<object>();
Action<object> onEventWrapper = evt =>
{
if (evt is DebugViewSnapshot snapshot && !snapshotTcs.Task.IsCompleted)
if (evt is DebugSnapshotRequestFailed failed)
{
snapshotTcs.TrySetResult(snapshot);
// COMM-7: the snapshot request failed fast at the transport — fail the
// pending start with the real cause (onTerminatedWrapper follows).
snapshotTcs.TrySetException(failed.Cause);
return;
}
else
lock (gate)
{
onEvent(evt);
if (!handedOver)
{
if (evt is DebugViewSnapshot snapshot && !snapshotTcs.Task.IsCompleted)
snapshotTcs.TrySetResult(snapshot);
else
held.Add(evt);
return;
}
}
onEvent(evt);
};
Action onTerminatedWrapper = () =>
@@ -185,6 +209,17 @@ public class DebugStreamService : IDisposable
try
{
snapshot = await snapshotTcs.Task.WaitAsync(timeoutCts.Token);
// Hand over (COMM-3): fold every event held since the snapshot into it, then switch
// the wrapper to pass-through. Under the gate, so an event racing this either lands
// in `held` (and is folded) or is delivered after the switch — never both, never
// ahead of the snapshot it postdates.
lock (gate)
{
snapshot = FoldIntoSnapshot(snapshot, held);
held.Clear();
handedOver = true;
}
}
catch (Exception ex)
{
@@ -203,7 +238,7 @@ public class DebugStreamService : IDisposable
$"Timed out waiting for debug snapshot from {instanceUniqueName} on site {siteIdentifier}.");
throw new InvalidOperationException(
$"Debug stream for {instanceUniqueName} on site {siteIdentifier} terminated before a snapshot was received.",
$"Debug stream for {instanceUniqueName} on site {siteIdentifier} terminated before a snapshot was received: {ex.Message}",
ex);
}
@@ -226,6 +261,67 @@ public class DebugStreamService : IDisposable
return new DebugStreamSession(sessionId, snapshot);
}
/// <summary>
/// Folds live events that arrived after <paramref name="snapshot"/> into it (COMM-3): each
/// <see cref="AttributeValueChanged"/>/<see cref="AlarmStateChanged"/> replaces the snapshot
/// row for the same entity (same identity key the bridge's dedup uses) when it is at least as
/// new, or is appended when the snapshot has no row for it. Events are applied in arrival
/// order, so the result is the state as of the last held event.
/// </summary>
/// <param name="snapshot">The snapshot the site returned.</param>
/// <param name="events">Events received after the snapshot, in arrival order.</param>
/// <returns>The snapshot with the events applied (the same instance when there are none).</returns>
internal static DebugViewSnapshot FoldIntoSnapshot(DebugViewSnapshot snapshot, IReadOnlyList<object> events)
{
if (events.Count == 0 || snapshot.InstanceNotFound) return snapshot;
var attributes = snapshot.AttributeValues.ToList();
var alarms = snapshot.AlarmStates.ToList();
var attrIndex = new Dictionary<string, int>();
for (var i = 0; i < attributes.Count; i++)
attrIndex[DebugStreamBridgeActor.AttributeKey(attributes[i])] = i;
var alarmIndex = new Dictionary<string, int>();
for (var i = 0; i < alarms.Count; i++)
alarmIndex[DebugStreamBridgeActor.AlarmKey(alarms[i])] = i;
foreach (var evt in events)
{
switch (evt)
{
case AttributeValueChanged a:
{
var key = DebugStreamBridgeActor.AttributeKey(a);
if (attrIndex.TryGetValue(key, out var i))
{
if (a.Timestamp >= attributes[i].Timestamp) attributes[i] = a;
}
else
{
attrIndex[key] = attributes.Count;
attributes.Add(a);
}
break;
}
case AlarmStateChanged al:
{
var key = DebugStreamBridgeActor.AlarmKey(al);
if (alarmIndex.TryGetValue(key, out var i))
{
if (al.Timestamp >= alarms[i].Timestamp) alarms[i] = al;
}
else
{
alarmIndex[key] = alarms.Count;
alarms.Add(al);
}
break;
}
}
}
return snapshot with { AttributeValues = attributes, AlarmStates = alarms };
}
/// <summary>
/// Re-reads a site's current streaming endpoints for a running session's reconnect.
/// </summary>