fix(comm): site stream server refuses/ends subscriptions on a non-active node with Unavailable (COMM-2, WP4 task 4.2)

This commit is contained in:
Joseph Doherty
2026-12-03 09:44:08 -05:00
parent 34527374ec
commit 8a4b466a03
4 changed files with 264 additions and 4 deletions
@@ -441,6 +441,7 @@ Disconnect is detected at the **transport layer**, never via an application-leve
- **In-flight command/control messages (gRPC call + deadline)**: When a connection drops while a request is in flight (e.g., a deployment sent but no response received), the gRPC call fails or hits its deadline and the caller receives a failure. There is **no automatic retry or buffering at central** — the engineer sees the failure in the UI and re-initiates the action. This is consistent with the design principle that central does not buffer messages. An in-progress deployment whose round-trip exceeds the timeout (default 120 s at `CommunicationService.DeployInstanceAsync`) surfaces as `DeploymentStatus.Failed` to the caller. - **In-flight command/control messages (gRPC call + deadline)**: When a connection drops while a request is in flight (e.g., a deployment sent but no response received), the gRPC call fails or hits its deadline and the caller receives a failure. There is **no automatic retry or buffering at central** — the engineer sees the failure in the UI and re-initiates the action. This is consistent with the design principle that central does not buffer messages. An in-progress deployment whose round-trip exceeds the timeout (default 120 s at `CommunicationService.DeployInstanceAsync`) surfaces as `DeploymentStatus.Failed` to the caller.
- **Debug streams (gRPC)**: Any gRPC stream interruption is detected by the HTTP/2 keepalive PING (~25 s) and triggers reconnection logic in the `DebugStreamBridgeActor`. The bridge actor attempts to reconnect to the other site node endpoint (NodeB if NodeA failed, or vice versa), with up to 3 retries and 5-second backoff. If all retries fail, the consumer is notified via `OnStreamTerminated` and the bridge actor is stopped. Events during the reconnection gap are lost (acceptable for real-time debug view). On successful reconnection, the consumer can request a fresh snapshot to re-sync state. - **Debug streams (gRPC)**: Any gRPC stream interruption is detected by the HTTP/2 keepalive PING (~25 s) and triggers reconnection logic in the `DebugStreamBridgeActor`. The bridge actor attempts to reconnect to the other site node endpoint (NodeB if NodeA failed, or vice versa), with up to 3 retries and 5-second backoff. If all retries fail, the consumer is notified via `OnStreamTerminated` and the bridge actor is stopped. Events during the reconnection gap are lost (acceptable for real-time debug view). On successful reconnection, the consumer can request a fresh snapshot to re-sync state.
- **Only the active site node serves streams (COMM-2, 2026-12).** The site stream hub is node-local — Instance Actors, and therefore every attribute/alarm event, exist only on the active node (oldest Up member of the `site-{SiteId}` role, `ActiveNodeEvaluator.SelfIsOldestUp`). `SiteStreamGrpcServer` therefore refuses `SubscribeInstance`/`SubscribeSite` with **`Unavailable`** on a node that is not active, and a watchdog (2 s) ends every open stream with **`Unavailable`** once the node loses the active role. Both consumers treat `Unavailable` as a stream error and flip NodeA↔NodeB, so after a failover — and in the steady state after any NodeA restart, where NodeA rejoins as standby — the Alarm Summary aggregator and Debug View land on the node that produces events. Before this a subscription to a healthy standby succeeded (headers flushed, keepalives passed) and never delivered an event; nothing errored, so the consumer never flipped and `IsLive` stayed true. The ending deliberately uses an error status, not OK: a graceful completion does not flip the node (below). The reconciliation/trace pulls on the same service are not gated — they read node-local stores and must answer on either node.
- **Graceful end of stream is NOT a fault, but it IS a reconnect trigger.** When the site's `GrpcMaxStreamLifetime` (4 h) elapses — and on a graceful site shutdown — the server ends the RPC with status **OK**, so the client's read loop simply finishes with no exception. `SiteStreamGrpcClient` reports that through a dedicated `onCompleted` callback, distinct from `onError`, and both consuming actors treat it as a reconnect trigger that **does not spend (or refund) the error-retry budget** and does **not** flip the node — the peer that closed cleanly is healthy. `SiteAlarmAggregatorActor` marks the stream down and lets the periodic reconcile tick reopen it (which also re-seeds); `DebugStreamBridgeActor` reopens on the same endpoint after `ReconnectDelay`. Both stamp the stream generation on the callback so a completion racing out of an already-replaced stream is ignored, and both observe the subscription `Task` itself so a fault escaping the subscribe call can never go unobserved. Without the `onCompleted` leg an OK completion was invisible to the reconnect logic and the stream stayed silently dead until the central process restarted. - **Graceful end of stream is NOT a fault, but it IS a reconnect trigger.** When the site's `GrpcMaxStreamLifetime` (4 h) elapses — and on a graceful site shutdown — the server ends the RPC with status **OK**, so the client's read loop simply finishes with no exception. `SiteStreamGrpcClient` reports that through a dedicated `onCompleted` callback, distinct from `onError`, and both consuming actors treat it as a reconnect trigger that **does not spend (or refund) the error-retry budget** and does **not** flip the node — the peer that closed cleanly is healthy. `SiteAlarmAggregatorActor` marks the stream down and lets the periodic reconcile tick reopen it (which also re-seeds); `DebugStreamBridgeActor` reopens on the same endpoint after `ReconnectDelay`. Both stamp the stream generation on the callback so a completion racing out of an already-replaced stream is ignored, and both observe the subscription `Task` itself so a fault escaping the subscribe call can never go unobserved. Without the `onCompleted` leg an OK completion was invisible to the reconnect logic and the stream stayed silently dead until the central process restarted.
## Failover Behavior ## Failover Behavior
@@ -19,7 +19,7 @@ namespace ZB.MOM.WW.ScadaBridge.Communication.Grpc;
/// Creates a StreamRelayActor per subscription to bridge Akka domain events /// Creates a StreamRelayActor per subscription to bridge Akka domain events
/// through a Channel<T> to the gRPC response stream. /// through a Channel<T> to the gRPC response stream.
/// </summary> /// </summary>
public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase, IDisposable
{ {
private readonly ISiteStreamSubscriber _streamSubscriber; private readonly ISiteStreamSubscriber _streamSubscriber;
private ActorSystem? _actorSystem; private ActorSystem? _actorSystem;
@@ -38,6 +38,19 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase
// true, never reset (the server is single-lifetime per host). // true, never reset (the server is single-lifetime per host).
private volatile bool _shuttingDown; private volatile bool _shuttingDown;
private long _actorCounter; private long _actorCounter;
// Active-node gate (COMM-2). The site stream hub is node-local — Instance Actors, and so
// every event, exist only on the ACTIVE node — so a subscription accepted by a standby
// is a live-looking stream that never carries an event. When the host supplies the gate
// (ActiveNodeEvaluator.SelfIsOldestUp for the site role), Subscribe* refuses with
// Unavailable on a non-active node and the watchdog ends every open stream with
// Unavailable once the node loses the active role; both surface on central's stream
// client as an error, which flips it to the other node. Null = no gate (tests composing
// the server in isolation, and hosts that predate the gate).
private Func<bool>? _isActiveNode;
private Timer? _activeRoleWatchdog;
/// <summary>How often the active-role watchdog re-checks the gate while streams are open.</summary>
internal static readonly TimeSpan DefaultActiveRoleCheckInterval = TimeSpan.FromSeconds(2);
// Ask timeout is 30 s. The ingest actor's repo // Ask timeout is 30 s. The ingest actor's repo
// calls take under 100 ms in steady state; a generous timeout absorbs a slow // calls take under 100 ms in steady state; a generous timeout absorbs a slow
// MSSQL connection without surfacing as a gRPC failure on a healthy site. // MSSQL connection without surfacing as a gRPC failure on a healthy site.
@@ -142,12 +155,111 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase
/// the gRPC server can be created by DI before the actor system exists. /// the gRPC server can be created by DI before the actor system exists.
/// </summary> /// </summary>
/// <param name="actorSystem">The initialized Akka actor system.</param> /// <param name="actorSystem">The initialized Akka actor system.</param>
public void SetReady(ActorSystem actorSystem) public void SetReady(ActorSystem actorSystem) => SetReady(actorSystem, isActiveNode: null);
/// <summary>
/// Marks the server ready and installs the active-node gate (COMM-2): while
/// <paramref name="isActiveNode"/> returns false, <see cref="SubscribeInstance"/> and
/// <see cref="SubscribeSite"/> refuse with <see cref="StatusCode.Unavailable"/>, and a
/// watchdog ends every open stream with <see cref="StatusCode.Unavailable"/> once the node
/// stops being active. Central's stream clients treat both as a stream error and flip to
/// the other site node, so a viewer always lands on the node whose Instance Actors produce
/// events. Only the two subscription RPCs are gated — the reconciliation/trace pulls read
/// node-local stores and must keep answering on either node.
/// </summary>
/// <param name="actorSystem">The initialized Akka actor system.</param>
/// <param name="isActiveNode">
/// Returns whether this node is the active node for its site
/// (<c>ActiveNodeEvaluator.SelfIsOldestUp(cluster, "site-{SiteId}")</c>); null disables the gate.
/// </param>
/// <param name="activeRoleCheckInterval">Watchdog cadence; defaults to <see cref="DefaultActiveRoleCheckInterval"/>.</param>
public void SetReady(ActorSystem actorSystem, Func<bool>? isActiveNode, TimeSpan? activeRoleCheckInterval = null)
{ {
_actorSystem = actorSystem; _actorSystem = actorSystem;
_isActiveNode = isActiveNode;
if (isActiveNode is not null && _activeRoleWatchdog is null)
{
var interval = activeRoleCheckInterval ?? DefaultActiveRoleCheckInterval;
_activeRoleWatchdog = new Timer(_ => EndStreamsIfNotActive(), null, interval, interval);
}
_ready = true; _ready = true;
} }
/// <summary>
/// Evaluates the active-node gate for a NEW subscription. A gate that throws (the cluster
/// extension going away during shutdown) counts as "not active" — refusing is the safe
/// answer, since the client simply tries the other node.
/// </summary>
private bool IsActiveForNewSubscription()
{
var gate = _isActiveNode;
if (gate is null) return true;
try
{
return gate();
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Active-node gate threw; refusing the stream subscription");
return false;
}
}
/// <summary>
/// Watchdog body (COMM-2): when the node is no longer the active node, ends every open
/// stream so its client sees <see cref="StatusCode.Unavailable"/> and flips to the other
/// node. A gate that throws leaves the streams alone (an open stream is only ended on a
/// definite "not active"). Returns the number of streams ended; exposed for tests.
/// </summary>
/// <returns>The number of streams this call ended.</returns>
internal int EndStreamsIfNotActive()
{
var gate = _isActiveNode;
if (gate is null || _activeStreams.IsEmpty || _shuttingDown) return 0;
bool active;
try
{
active = gate();
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Active-node gate threw in the stream watchdog; leaving streams open");
return 0;
}
if (active) return 0;
var ended = 0;
foreach (var entry in _activeStreams.Values)
{
entry.LostActiveRole = true;
try
{
entry.Cts.Cancel();
ended++;
}
catch (ObjectDisposedException)
{
// Its own handler already finished — nothing to end.
}
}
if (ended > 0)
{
_logger.LogInformation(
"This site node is no longer the active node; ended {Count} stream(s) with Unavailable so central reconnects to the active node",
ended);
}
return ended;
}
/// <inheritdoc />
public void Dispose()
{
_activeRoleWatchdog?.Dispose();
GC.SuppressFinalize(this);
}
/// <summary> /// <summary>
/// Hands the site-local <see cref="ISiteAuditQueue"/> (the same /// Hands the site-local <see cref="ISiteAuditQueue"/> (the same
/// <c>SqliteAuditWriter</c> singleton that backs <see cref="IAuditWriter"/> /// <c>SqliteAuditWriter</c> singleton that backs <see cref="IAuditWriter"/>
@@ -322,6 +434,14 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase
if (_shuttingDown) if (_shuttingDown)
throw new RpcException(new GrpcStatus(StatusCode.Unavailable, "Server shutting down")); throw new RpcException(new GrpcStatus(StatusCode.Unavailable, "Server shutting down"));
// COMM-2: a standby node's hub carries no events (Instance Actors run only on the
// active node), so accepting here would hand central a stream that looks live and is
// silent forever. Refuse; central's client treats Unavailable as a stream error and
// flips to the other node.
if (!IsActiveForNewSubscription())
throw new RpcException(new GrpcStatus(StatusCode.Unavailable,
"Not the active node for this site; subscribe to the other site node"));
// correlation_id arrives off the wire on a public gRPC // correlation_id arrives off the wire on a public gRPC
// endpoint and is used (below) to compose an Akka actor name. Akka actor names // endpoint and is used (below) to compose an Akka actor name. Akka actor names
// have a restricted character set — a id containing '/', whitespace, or other // have a restricted character set — a id containing '/', whitespace, or other
@@ -513,6 +633,16 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase
: null, : null,
streamCts.Token); streamCts.Token);
} }
catch (OperationCanceledException)
when (entry.LostActiveRole && !context.CancellationToken.IsCancellationRequested)
{
// COMM-2: ended by the active-role watchdog. End with Unavailable, NOT a graceful
// OK — central's clients deliberately do not flip nodes on a graceful completion
// (that is the 4h lifetime / clean shutdown path), so only an error status moves
// them to the node that is now active.
throw new RpcException(new GrpcStatus(StatusCode.Unavailable,
"This site node is no longer the active node; reconnect to the other site node"));
}
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
// Normal cancellation (client disconnect or duplicate replacement) // Normal cancellation (client disconnect or duplicate replacement)
@@ -787,5 +917,16 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase
/// <summary> /// <summary>
/// Tracks a single active stream so cleanup only removes its own entry. /// Tracks a single active stream so cleanup only removes its own entry.
/// </summary> /// </summary>
private sealed record StreamEntry(CancellationTokenSource Cts); /// <remarks>
/// A class, not a record: <c>_activeStreams.TryRemove(KeyValuePair)</c> must match by
/// reference, and <see cref="LostActiveRole"/> is mutable.
/// </remarks>
private sealed class StreamEntry(CancellationTokenSource cts)
{
/// <summary>The stream's cancellation source.</summary>
public CancellationTokenSource Cts { get; } = cts;
/// <summary>Set by the active-role watchdog before it cancels the stream (COMM-2).</summary>
public volatile bool LostActiveRole;
}
} }
@@ -1433,7 +1433,15 @@ akka {{
{ {
grpcServer?.SetOperationTrackingStore(siteTrackingStore); grpcServer?.SetOperationTrackingStore(siteTrackingStore);
} }
grpcServer?.SetReady(_actorSystem!); // COMM-2: only the active node (oldest Up member of THIS site's role — where the
// DeploymentManager singleton and so every Instance Actor runs) accepts stream
// subscriptions; a standby refuses with Unavailable and ends its streams on losing the
// role, so central's stream clients flip to the node that actually produces events.
var streamActorSystem = _actorSystem!;
grpcServer?.SetReady(
streamActorSystem,
() => ZB.MOM.WW.ScadaBridge.Communication.ClusterState.ActiveNodeEvaluator.SelfIsOldestUp(
Cluster.Get(streamActorSystem), siteRole));
// Site command plane: hand the shared dispatcher to the gRPC command service and flip it // Site command plane: hand the shared dispatcher to the gRPC command service and flip it
// ready at the same point as the streaming server — the actor graph exists and the local // ready at the same point as the streaming server — the actor graph exists and the local
@@ -158,6 +158,116 @@ public class SiteStreamGrpcServerTests : TestKit
Assert.Equal(0, server.ActiveStreamCount); Assert.Equal(0, server.ActiveStreamCount);
} }
// --- Active-node gate (COMM-2) ---
/// <summary>
/// COMM-2 regression: a standby site node's stream hub carries no events, so it must refuse
/// both subscription RPCs with Unavailable (which central's clients treat as a stream error
/// and flip to the other node) instead of handing back a live-looking silent stream.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Comm2_StandbyNode_RefusesSubscriptionsWithUnavailable()
{
using var server = CreateServer();
server.SetReady(Sys, isActiveNode: () => false, activeRoleCheckInterval: TimeSpan.FromHours(1));
var writer = Substitute.For<IServerStreamWriter<SiteStreamEvent>>();
var instanceEx = await Assert.ThrowsAsync<RpcException>(
() => server.SubscribeInstance(MakeRequest("corr-standby-1"), writer, CreateMockContext()));
Assert.Equal(StatusCode.Unavailable, instanceEx.StatusCode);
Assert.Contains("active node", instanceEx.Status.Detail, StringComparison.OrdinalIgnoreCase);
var siteEx = await Assert.ThrowsAsync<RpcException>(
() => server.SubscribeSite(new SiteStreamRequest { CorrelationId = "corr-standby-2" }, writer, CreateMockContext()));
Assert.Equal(StatusCode.Unavailable, siteEx.StatusCode);
Assert.Equal(0, server.ActiveStreamCount);
_subscriber.DidNotReceive().Subscribe(Arg.Any<string>(), Arg.Any<IActorRef>());
_subscriber.DidNotReceive().SubscribeSiteAlarms(Arg.Any<IActorRef>());
}
/// <summary>COMM-2: a gate that throws (cluster going away) refuses rather than accepts.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Comm2_GateThrows_RefusesSubscription()
{
using var server = CreateServer();
server.SetReady(Sys, isActiveNode: () => throw new InvalidOperationException("cluster gone"),
activeRoleCheckInterval: TimeSpan.FromHours(1));
var ex = await Assert.ThrowsAsync<RpcException>(() => server.SubscribeInstance(
MakeRequest("corr-throws"), Substitute.For<IServerStreamWriter<SiteStreamEvent>>(), CreateMockContext()));
Assert.Equal(StatusCode.Unavailable, ex.StatusCode);
}
/// <summary>
/// COMM-2 regression: when the node loses the active role, the watchdog ends every open
/// stream with Unavailable (NOT a graceful OK — central does not flip nodes on OK), and the
/// server-side state is cleaned up.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Comm2_LosingActiveRole_EndsOpenStreamsWithUnavailable()
{
var active = true;
using var server = CreateServer();
server.SetReady(Sys, isActiveNode: () => Volatile.Read(ref active), activeRoleCheckInterval: TimeSpan.FromHours(1));
var writer = Substitute.For<IServerStreamWriter<SiteStreamEvent>>();
var streamTask = Task.Run(() => server.SubscribeSite(
new SiteStreamRequest { CorrelationId = "corr-active-1" }, writer, CreateMockContext()));
await WaitForConditionAsync(() => server.ActiveStreamCount == 1);
// Still active: the watchdog leaves the stream alone.
Assert.Equal(0, server.EndStreamsIfNotActive());
Assert.Equal(1, server.ActiveStreamCount);
Volatile.Write(ref active, false);
Assert.Equal(1, server.EndStreamsIfNotActive());
var ex = await Assert.ThrowsAsync<RpcException>(() => streamTask);
Assert.Equal(StatusCode.Unavailable, ex.StatusCode);
Assert.Equal(0, server.ActiveStreamCount);
_subscriber.Received().RemoveSubscriber(Arg.Any<IActorRef>());
}
/// <summary>COMM-2: the watchdog timer itself (not just a direct call) ends the stream.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Comm2_Watchdog_EndsStreamOnItsOwnTick()
{
var active = true;
using var server = CreateServer();
server.SetReady(Sys, isActiveNode: () => Volatile.Read(ref active), activeRoleCheckInterval: TimeSpan.FromMilliseconds(50));
var streamTask = Task.Run(() => server.SubscribeInstance(
MakeRequest("corr-watchdog"), Substitute.For<IServerStreamWriter<SiteStreamEvent>>(), CreateMockContext()));
await WaitForConditionAsync(() => server.ActiveStreamCount == 1);
Volatile.Write(ref active, false);
var ex = await Assert.ThrowsAsync<RpcException>(() => streamTask.WaitAsync(TimeSpan.FromSeconds(10)));
Assert.Equal(StatusCode.Unavailable, ex.StatusCode);
}
/// <summary>COMM-2: a client cancel on an active node still ends quietly (no Unavailable).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Comm2_ActiveNode_ClientCancel_EndsWithoutError()
{
using var server = CreateServer();
server.SetReady(Sys, isActiveNode: () => true, activeRoleCheckInterval: TimeSpan.FromHours(1));
var cts = new CancellationTokenSource();
var streamTask = Task.Run(() => server.SubscribeInstance(
MakeRequest("corr-active-cancel"), Substitute.For<IServerStreamWriter<SiteStreamEvent>>(), CreateMockContext(cts.Token)));
await WaitForConditionAsync(() => server.ActiveStreamCount == 1);
cts.Cancel();
await streamTask;
Assert.Equal(0, server.ActiveStreamCount);
}
// --- Site-shutdown ordering --- // --- Site-shutdown ordering ---
/// <summary>Verifies that cancelling all streams cancels the active streams and refuses new ones.</summary> /// <summary>Verifies that cancelling all streams cancels the active streams and refuses new ones.</summary>