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
@@ -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.
/// </summary>
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<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
// 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.
/// </summary>
/// <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;
_isActiveNode = isActiveNode;
if (isActiveNode is not null && _activeRoleWatchdog is null)
{
var interval = activeRoleCheckInterval ?? DefaultActiveRoleCheckInterval;
_activeRoleWatchdog = new Timer(_ => EndStreamsIfNotActive(), null, interval, interval);
}
_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>
/// Hands the site-local <see cref="ISiteAuditQueue"/> (the same
/// <c>SqliteAuditWriter</c> singleton that backs <see cref="IAuditWriter"/>
@@ -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
/// <summary>
/// Tracks a single active stream so cleanup only removes its own entry.
/// </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?.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