diff --git a/docs/requirements/Component-Communication.md b/docs/requirements/Component-Communication.md index 87077a2d..21984871 100644 --- a/docs/requirements/Component-Communication.md +++ b/docs/requirements/Component-Communication.md @@ -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. - **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. ## Failover Behavior diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs index 00795858..270bd208 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs @@ -19,7 +19,7 @@ namespace ZB.MOM.WW.ScadaBridge.Communication.Grpc; /// Creates a StreamRelayActor per subscription to bridge Akka domain events /// through a Channel<T> to the gRPC response stream. /// -public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase +public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase, IDisposable { private readonly ISiteStreamSubscriber _streamSubscriber; private ActorSystem? _actorSystem; @@ -38,6 +38,19 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase // true, never reset (the server is single-lifetime per host). private volatile bool _shuttingDown; 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? _isActiveNode; + private Timer? _activeRoleWatchdog; + + /// How often the active-role watchdog re-checks the gate while streams are open. + internal static readonly TimeSpan DefaultActiveRoleCheckInterval = TimeSpan.FromSeconds(2); // Ask timeout is 30 s. The ingest actor's repo // 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. @@ -142,12 +155,111 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase /// the gRPC server can be created by DI before the actor system exists. /// /// The initialized Akka actor system. - public void SetReady(ActorSystem actorSystem) + public void SetReady(ActorSystem actorSystem) => SetReady(actorSystem, isActiveNode: null); + + /// + /// Marks the server ready and installs the active-node gate (COMM-2): while + /// returns false, and + /// refuse with , and a + /// watchdog ends every open stream with 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. + /// + /// The initialized Akka actor system. + /// + /// Returns whether this node is the active node for its site + /// (ActiveNodeEvaluator.SelfIsOldestUp(cluster, "site-{SiteId}")); null disables the gate. + /// + /// Watchdog cadence; defaults to . + public void SetReady(ActorSystem actorSystem, Func? isActiveNode, TimeSpan? activeRoleCheckInterval = null) { _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; } + /// + /// 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. + /// + 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; + } + } + + /// + /// Watchdog body (COMM-2): when the node is no longer the active node, ends every open + /// stream so its client sees 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. + /// + /// The number of streams this call ended. + 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; + } + + /// + public void Dispose() + { + _activeRoleWatchdog?.Dispose(); + GC.SuppressFinalize(this); + } + /// /// Hands the site-local (the same /// SqliteAuditWriter singleton that backs @@ -322,6 +434,14 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase if (_shuttingDown) 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 // 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 @@ -513,6 +633,16 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase : null, 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) { // Normal cancellation (client disconnect or duplicate replacement) @@ -787,5 +917,16 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase /// /// Tracks a single active stream so cleanup only removes its own entry. /// - private sealed record StreamEntry(CancellationTokenSource Cts); + /// + /// A class, not a record: _activeStreams.TryRemove(KeyValuePair) must match by + /// reference, and is mutable. + /// + private sealed class StreamEntry(CancellationTokenSource cts) + { + /// The stream's cancellation source. + public CancellationTokenSource Cts { get; } = cts; + + /// Set by the active-role watchdog before it cancels the stream (COMM-2). + public volatile bool LostActiveRole; + } } diff --git a/src/ZB.MOM.WW.ScadaBridge.Host/Actors/AkkaHostedService.cs b/src/ZB.MOM.WW.ScadaBridge.Host/Actors/AkkaHostedService.cs index f45f9c17..51c4c2fa 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Host/Actors/AkkaHostedService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Host/Actors/AkkaHostedService.cs @@ -1433,7 +1433,15 @@ akka {{ { 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 // ready at the same point as the streaming server — the actor graph exists and the local diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteStreamGrpcServerTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteStreamGrpcServerTests.cs index daca7c56..1e685bec 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteStreamGrpcServerTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteStreamGrpcServerTests.cs @@ -158,6 +158,116 @@ public class SiteStreamGrpcServerTests : TestKit Assert.Equal(0, server.ActiveStreamCount); } + // --- Active-node gate (COMM-2) --- + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Comm2_StandbyNode_RefusesSubscriptionsWithUnavailable() + { + using var server = CreateServer(); + server.SetReady(Sys, isActiveNode: () => false, activeRoleCheckInterval: TimeSpan.FromHours(1)); + + var writer = Substitute.For>(); + var instanceEx = await Assert.ThrowsAsync( + () => 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( + () => 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(), Arg.Any()); + _subscriber.DidNotReceive().SubscribeSiteAlarms(Arg.Any()); + } + + /// COMM-2: a gate that throws (cluster going away) refuses rather than accepts. + /// A task that represents the asynchronous operation. + [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(() => server.SubscribeInstance( + MakeRequest("corr-throws"), Substitute.For>(), CreateMockContext())); + Assert.Equal(StatusCode.Unavailable, ex.StatusCode); + } + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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>(); + 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(() => streamTask); + Assert.Equal(StatusCode.Unavailable, ex.StatusCode); + Assert.Equal(0, server.ActiveStreamCount); + _subscriber.Received().RemoveSubscriber(Arg.Any()); + } + + /// COMM-2: the watchdog timer itself (not just a direct call) ends the stream. + /// A task that represents the asynchronous operation. + [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>(), CreateMockContext())); + await WaitForConditionAsync(() => server.ActiveStreamCount == 1); + + Volatile.Write(ref active, false); + var ex = await Assert.ThrowsAsync(() => streamTask.WaitAsync(TimeSpan.FromSeconds(10))); + Assert.Equal(StatusCode.Unavailable, ex.StatusCode); + } + + /// COMM-2: a client cancel on an active node still ends quietly (no Unavailable). + /// A task that represents the asynchronous operation. + [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>(), CreateMockContext(cts.Token))); + await WaitForConditionAsync(() => server.ActiveStreamCount == 1); + + cts.Cancel(); + await streamTask; + Assert.Equal(0, server.ActiveStreamCount); + } + // --- Site-shutdown ordering --- /// Verifies that cancelling all streams cancels the active streams and refuses new ones.