using System.Collections.Concurrent; using Grpc.Core; using Grpc.Net.Client; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ZB.MOM.WW.ScadaBridge.Commons.Messages.Deployment; using ZB.MOM.WW.ScadaBridge.Commons.Validation; namespace ZB.MOM.WW.ScadaBridge.Communication.Grpc; /// /// Raised when a site has no usable gRPC channel — an unknown site, or a site with neither /// GrpcNodeAAddress nor GrpcNodeBAddress configured. /// treats this as a known-dead send: it fails the caller's Ask fast with an /// Akka.Actor.Status.Failure wrapping this exception instead of warning and dropping /// the message, so the caller does not burn its full Ask timeout on a failure already known at send /// time (central still never buffers). /// public sealed class SiteChannelUnavailableException(string siteId) : Exception($"No gRPC channel is configured for site '{siteId}'.") { /// The site with no configured channel. public string SiteId { get; } = siteId; } /// /// Shared, per-site gRPC channel PAIR provider with sticky failover + failback (design §3.5). /// Central holds one per site node (NodeA/NodeB) rather than one channel /// with re-dial logic; NodeA is the preferred node (config order). Every call goes to the current /// sticky channel; on connect failure / / readiness rejection /// it flips to the other node and stays there. A background readiness probe (a real read-only RPC) /// returns to the preferred node once it answers again; the backoff (1 s → doubling → 60 s cap) is /// reset only after a real call on the preferred node succeeds. /// /// /// /// Retry safety. Unavailable can mean a lost response after application. Only explicitly /// retry-safe operations, a server-owned not-started trailer, or a connect-phase failure that /// provably never sent the request () permit replay on the peer. /// Ambiguous mutations fail with Aborted / OUTCOME_UNKNOWN; the next independent call uses the /// peer. Deadlines are never replayed. Readiness rejection remains safe before actor dispatch. /// /// /// Addresses. Fed by / from the single DB /// refresh loop (the GrpcNodeAAddress/GrpcNodeBAddress columns). PSK credentials and /// the x-scadabridge-site header ride every channel via /// ; removing a site invalidates its /// cached key. /// /// public sealed class SitePairChannelProvider : IDisposable { private static readonly TimeSpan InitialBackoff = TimeSpan.FromSeconds(1); private static readonly TimeSpan MaxBackoff = TimeSpan.FromSeconds(60); private static readonly TimeSpan FailbackSweepInterval = TimeSpan.FromSeconds(1); /// /// How long a replaced/removed channel is PARKED before it is disposed. Active calls retain the channel beyond this minimum until completion. /// internal static readonly TimeSpan ChannelDisposalGrace = TimeSpan.FromMinutes(5); /// /// How long a probe-driven failback stays on probation without a confirming real call; a /// NodeA failure after this window is treated as a fresh failover (backoff restarts at the /// initial value). Settable per instance for tests. /// internal TimeSpan FailbackProbationWindow { get; set; } = TimeSpan.FromMinutes(5); private readonly ISitePskProvider _pskProvider; private readonly CommunicationOptions _options; private readonly ILogger _logger; private readonly Func? _handlerFactory; private readonly Func> _reachabilityProbe; private readonly ConcurrentDictionary _sites = new(StringComparer.Ordinal); /// /// Channels replaced by or dropped by , /// each with the earliest idle disposal instant. Active-call retention can extend that instant. /// private readonly ConcurrentQueue<(GrpcChannel Channel, DateTime DisposeAfterUtc)> _graveyard = new(); private readonly ConcurrentDictionary _activeCalls = new(); private readonly CancellationTokenSource _shutdown = new(); private Task? _failbackLoop; private readonly object _loopGate = new(); private volatile bool _disposed; private readonly object _lifecycleGate = new(); /// Creates the provider. /// Resolves each site's preshared key for channel credentials. /// Communication options (keepalive settings applied to production channels). /// Logger for failover/failback diagnostics. /// /// Test seam mapping an endpoint to the its channel should use /// (e.g. an in-process TestServer handler). Null in production, where each channel builds /// a keepalive-configured . /// /// /// Test seam deciding whether a preferred node is READY during a failback sweep. Null in /// production, where issues a real, read-only /// ExecuteLifecycle call (review 2026-10-21 03/P-2). /// public SitePairChannelProvider( ISitePskProvider pskProvider, IOptions options, ILogger logger, Func? handlerFactory = null, Func>? reachabilityProbe = null) { ArgumentNullException.ThrowIfNull(pskProvider); ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(logger); _pskProvider = pskProvider; _options = options.Value; _logger = logger; _handlerFactory = handlerFactory; _reachabilityProbe = reachabilityProbe ?? ReadinessProbeAsync; } /// /// (Re)builds a site's channel pair from its gRPC node endpoints. A no-op when neither endpoint /// changed. Parks (see ) and rebuilds a channel whose endpoint /// changed, and resets stickiness to the preferred node when the pair is (re)created. Called on /// the DB refresh tick. /// /// Site identifier. /// NodeA gRPC base address, or null when unconfigured. /// NodeB gRPC base address, or null when unconfigured. public void UpdateSite(string siteId, string? nodeAEndpoint, string? nodeBEndpoint) { lock (_lifecycleGate) { ObjectDisposedException.ThrowIf(_disposed, this); ArgumentException.ThrowIfNullOrWhiteSpace(siteId); SweepGraveyard(); var pair = _sites.GetOrAdd(siteId, id => new SitePair(id)); lock (pair.Gate) { var changedA = !string.Equals(pair.NodeAEndpoint, nodeAEndpoint, StringComparison.Ordinal); var changedB = !string.Equals(pair.NodeBEndpoint, nodeBEndpoint, StringComparison.Ordinal); // Build every replacement BEFORE parking anything (review 2026-10-21 03/R-1): a // malformed address used to throw out of BuildChannel after the old channel was // already parked, leaving pair.ChannelA pointing at a channel the graveyard would // dispose — every later call then failed with ObjectDisposedException (not // Unavailable, so no failover) — and the throw escaped into the refresh actor. // A side whose new endpoint cannot be built keeps its old channel AND old endpoint. GrpcChannel? newA = null, newB = null; if (changedA && !TryBuildReplacement(pair, siteId, nodeAEndpoint, isA: true, out newA)) { changedA = false; } if (changedB && !TryBuildReplacement(pair, siteId, nodeBEndpoint, isA: false, out newB)) { changedB = false; } if (!changedA && !changedB) { return; } if (changedA) { Park(pair.ChannelA); pair.ChannelA = newA; pair.NodeAEndpoint = nodeAEndpoint; } if (changedB) { Park(pair.ChannelB); pair.ChannelB = newB; pair.NodeBEndpoint = nodeBEndpoint; } // Addresses changed — return to the preferred node and reset failback backoff. pair.CurrentIsA = pair.ChannelA is not null; pair.FailbackOnProbation = false; pair.ResetFailback(); _logger.LogInformation( "gRPC channel pair for site {TargetSiteId} refreshed (nodeA={HasA}, nodeB={HasB})", siteId, pair.ChannelA is not null, pair.ChannelB is not null); } } } /// /// Builds the replacement channel for one side of a pair whose endpoint changed. A null/blank /// endpoint is a valid "unconfigured" (null channel). A malformed endpoint — validated with /// , and any channel-construction throw besides — is rejected: /// logged at Error naming the site and column (once per distinct rejected value, so the 60 s /// refresh does not repeat it every tick) and the caller keeps the side's existing channel. /// /// The site pair (caller holds pair.Gate). /// Site identifier, for the log. /// The new endpoint for this side. /// True for NodeA (GrpcNodeAAddress), false for NodeB. /// The built channel, or null for an unconfigured side. /// True when the replacement may be applied; false to keep the existing side. private bool TryBuildReplacement(SitePair pair, string siteId, string? endpoint, bool isA, out GrpcChannel? channel) { channel = null; if (string.IsNullOrWhiteSpace(endpoint)) { SetRejected(pair, isA, null); return true; } var field = isA ? "GrpcNodeAAddress" : "GrpcNodeBAddress"; Exception? buildError = null; if (GrpcEndpointRules.TryValidate(endpoint, allowEmpty: false, out var error)) { try { channel = BuildChannel(endpoint, siteId); SetRejected(pair, isA, null); return true; } catch (Exception ex) { buildError = ex; error = ex.Message; } } if (!string.Equals(isA ? pair.RejectedAEndpoint : pair.RejectedBEndpoint, endpoint, StringComparison.Ordinal)) { _logger.LogError(buildError, "Site {TargetSiteId} {Field} '{Endpoint}' is not a usable gRPC endpoint ({Error}); keeping the " + "previous channel ({Previous}) for that node until the address is corrected", siteId, field, endpoint, error, (isA ? pair.NodeAEndpoint : pair.NodeBEndpoint) ?? "none"); SetRejected(pair, isA, endpoint); } return false; } private static void SetRejected(SitePair pair, bool isA, string? endpoint) { if (isA) pair.RejectedAEndpoint = endpoint; else pair.RejectedBEndpoint = endpoint; } /// /// Parks a removed site's channels for deferred disposal (see ) /// and invalidates its cached preshared key. /// /// Site identifier to remove. public void RemoveSite(string siteId) { lock (_lifecycleGate) { ObjectDisposedException.ThrowIf(_disposed, this); if (string.IsNullOrWhiteSpace(siteId)) { return; } SweepGraveyard(); if (_sites.TryRemove(siteId, out var pair)) { lock (pair.Gate) { Park(pair.ChannelA); Park(pair.ChannelB); pair.ChannelA = null; pair.ChannelB = null; } _pskProvider.Invalidate(siteId); _logger.LogInformation("gRPC channel pair for site {TargetSiteId} removed", siteId); } } } /// /// Runs against the site's current sticky channel, failing over to the /// other node only for a retry-safe operation or proven pre-dispatch rejection. An ambiguous /// mutation returns OUTCOME_UNKNOWN. Ensures the background failback loop is running. /// /// The RPC reply type. /// Target site. /// The RPC to run against a given channel. /// Cancellation token. /// Whether repeating this operation is safe after an ambiguous transport failure. /// The RPC reply. /// The site has no configured channel. public async Task ExecuteAsync( string siteId, Func> call, CancellationToken ct, bool retrySafe = false) { ArgumentException.ThrowIfNullOrWhiteSpace(siteId); ArgumentNullException.ThrowIfNull(call); EnsureFailbackLoop(); if (!_sites.TryGetValue(siteId, out var pair)) { throw new SiteChannelUnavailableException(siteId); } GrpcChannel primary; GrpcChannel? secondary; bool primaryIsA; lock (pair.Gate) { primaryIsA = pair.CurrentIsA; primary = (primaryIsA ? pair.ChannelA : pair.ChannelB) ?? pair.ChannelA ?? pair.ChannelB ?? throw new SiteChannelUnavailableException(siteId); // Recompute which node `primary` actually is (the current side may be null). primaryIsA = ReferenceEquals(primary, pair.ChannelA); secondary = primaryIsA ? pair.ChannelB : pair.ChannelA; _activeCalls.AddOrUpdate(primary, 1, (_, count) => count + 1); if (secondary is not null) _activeCalls.AddOrUpdate(secondary, 1, (_, count) => count + 1); } try { var result = await call(primary, ct).ConfigureAwait(false); if (primaryIsA) ConfirmFailback(pair); return result; } catch (RpcException ex) when (secondary is not null && GrpcRetrySafety.IsConnectPhaseDeadline(ex, primary)) { // COMM-5: the deadline expired while the node was still not accepting a connection // (black-holed host, deadline shorter than the connect timeout). Move the pair so the // next call goes to the other node; the spent deadline leaves nothing to retry with. FlipTo(pair, toIsA: !primaryIsA); _logger.LogWarning( "Site {TargetSiteId} node {FromNode} did not accept a connection before the call deadline; next calls go to node {ToNode}", siteId, primaryIsA ? "A" : "B", primaryIsA ? "B" : "A"); throw; } catch (RpcException ex) when (ex.StatusCode == StatusCode.Unavailable) { if (secondary is not null) FlipTo(pair, toIsA: !primaryIsA); // ScadaBridge#136: a connect-phase failure (refused / unresolvable — the stopped node of // a pair) provably never sent the request, so a mutation fails over within this call // just like an explicit pre-dispatch rejection. Anything that may have been delivered // stays OUTCOME_UNKNOWN and is never replayed. if (!retrySafe && !GrpcRetrySafety.ProvablyNotApplied(ex)) throw GrpcRetrySafety.OutcomeUnknown(ex); if (secondary is null) throw; // Only reads/idempotent operations or a provably unapplied request may replay. _logger.LogWarning( "Site {TargetSiteId} node {FromNode} unavailable; failing over to node {ToNode}", siteId, primaryIsA ? "A" : "B", primaryIsA ? "B" : "A"); try { return await call(secondary, ct).ConfigureAwait(false); } catch (RpcException retryError) when (retryError.StatusCode == StatusCode.Unavailable && !retrySafe && !GrpcRetrySafety.ProvablyNotApplied(retryError)) { throw GrpcRetrySafety.OutcomeUnknown(retryError); } } finally { _activeCalls.AddOrUpdate(primary, 0, (_, count) => count - 1); if (secondary is not null) _activeCalls.AddOrUpdate(secondary, 0, (_, count) => count - 1); if (_disposed) SweepGraveyard(force: true); } } /// /// Probes a site's preferred node (NodeA) and, if reachable, returns stickiness to it. The /// background loop calls this per due site; tests call it to drive failback deterministically. /// /// Site identifier. /// Cancellation token. /// True when the site is now (or already) pointed at its preferred node. internal async Task TryFailbackAsync(string siteId, CancellationToken ct) { if (!_sites.TryGetValue(siteId, out var pair)) { return false; } GrpcChannel? preferred; lock (pair.Gate) { if (pair.CurrentIsA || pair.ChannelA is null) { return true; // already on preferred (or no preferred channel to fail back to) } preferred = pair.ChannelA; } var reachable = await _reachabilityProbe(preferred, ct).ConfigureAwait(false); lock (pair.Gate) { if (reachable) { // Return to A on PROBATION (review 2026-10-21 03/P-2): the backoff is kept, not // reset, until a real call on A succeeds (ConfirmFailback). If A rejects the next // call anyway, FlipTo doubles the backoff instead of restarting it at 1 s, so a // node that answers the probe but not real traffic is retried ever less often. pair.CurrentIsA = true; pair.FailbackOnProbation = true; pair.ProbationSinceUtc = DateTime.UtcNow; pair.NextProbeUtc = DateTime.MaxValue; _logger.LogInformation("Site {TargetSiteId} preferred node A ready again; failing back", siteId); return true; } pair.BumpFailbackBackoff(); return false; } } /// Test/diagnostic accessor: true when the site currently targets its preferred node (A). /// Site identifier. /// True when on NodeA (or when the site is unknown). internal bool IsOnPreferredNode(string siteId) => !_sites.TryGetValue(siteId, out var pair) || pair.CurrentIsA; /// Starts the background failback loop if not already running. Idempotent. public void EnsureFailbackLoop() { if (_failbackLoop is not null || _disposed) { return; } lock (_loopGate) { if (_failbackLoop is null && !_disposed) { _failbackLoop = Task.Run(() => FailbackLoopAsync(_shutdown.Token)); } } } private async Task FailbackLoopAsync(CancellationToken ct) { using var timer = new PeriodicTimer(FailbackSweepInterval); try { while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) { SweepGraveyard(); var now = DateTime.UtcNow; foreach (var kvp in _sites) { var pair = kvp.Value; bool due; lock (pair.Gate) { due = !pair.CurrentIsA && pair.ChannelA is not null && now >= pair.NextProbeUtc; } if (due) { try { await TryFailbackAsync(kvp.Key, ct).ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception ex) { _logger.LogDebug(ex, "Failback probe for site {TargetSiteId} faulted", kvp.Key); } } } } } catch (OperationCanceledException) { // Shutting down. } } /// /// Parks a channel that is no longer reachable through instead of /// disposing it inline. /// /// Why deferred. reads the channel under /// pair.Gate but invokes the RPC OUTSIDE it, so an inline /// Dispose from the 60 s DB address refresh (or an admin edit) aborted whatever was /// in flight — a multi-minute DeployArtifactsCommand included — with /// or . Neither is /// , so the cross-node retry deliberately never engaged /// and the command simply failed. /// /// /// Active calls retain both selected channels until completion, including the retry channel. /// The grace is only an idle-channel minimum; dynamic WaitForAttribute deadlines can exceed it. /// /// /// The channel to park; null is ignored. private void Park(GrpcChannel? channel) { if (channel is not null) { _graveyard.Enqueue((channel, DateTime.UtcNow + ChannelDisposalGrace)); } } /// /// Disposes every parked channel whose grace window has elapsed. Called from the DB refresh /// path (/) and from the failback loop, so a /// park always drains even on a provider that never runs a call again. /// /// True to ignore idle grace (shutdown and tests); active calls always retain their channels. internal void SweepGraveyard(bool force = false) { lock (_lifecycleGate) { var now = DateTime.UtcNow; var count = _graveyard.Count; // Visit each parked channel once: an occupied channel must not starve later entries. for (var i = 0; i < count && _graveyard.TryDequeue(out var parked); i++) { if ((!force && now < parked.DisposeAfterUtc) || _activeCalls.GetValueOrDefault(parked.Channel) > 0) { _graveyard.Enqueue(parked); continue; } _activeCalls.TryRemove(parked.Channel, out _); try { parked.Channel.Dispose(); } catch (Exception ex) { _logger.LogDebug(ex, "Disposing a parked gRPC channel faulted"); } } } } /// Test/diagnostic accessor: how many replaced channels are awaiting deferred disposal. internal int ParkedChannelCount => _graveyard.Count; /// A real call on the preferred node succeeded: a probationary failback is confirmed and the backoff reset. /// The site pair. private static void ConfirmFailback(SitePair pair) { if (!pair.FailbackOnProbation) return; lock (pair.Gate) { if (pair.FailbackOnProbation && pair.CurrentIsA) { pair.FailbackOnProbation = false; pair.ResetFailback(); } } } /// Test/diagnostic accessor: the site's current failback backoff (null when the site is unknown). /// Site identifier. /// The backoff the next failback probe is (or would be) scheduled with. internal TimeSpan? GetFailbackBackoff(string siteId) { if (!_sites.TryGetValue(siteId, out var pair)) return null; lock (pair.Gate) return pair.Backoff; } private void FlipTo(SitePair pair, bool toIsA) { lock (pair.Gate) { pair.CurrentIsA = toIsA; if (!toIsA) { // Probation is time-boxed: a site quiet for longer than FailbackProbationWindow // after a probe-driven failback (no real call to confirm it) is treated as // confirmed, so a fresh NodeA failure much later starts at InitialBackoff again // instead of inheriting a stale, grown backoff. if (pair.FailbackOnProbation && DateTime.UtcNow - pair.ProbationSinceUtc < FailbackProbationWindow) { // A failed us again right after a probe-driven failback: it is not really // ready yet — grow the backoff rather than restarting it. pair.FailbackOnProbation = false; pair.BumpFailbackBackoff(); } else { // Failed over off the preferred node → schedule the first failback probe. pair.FailbackOnProbation = false; pair.ScheduleFailback(InitialBackoff); } } else { pair.FailbackOnProbation = false; pair.ResetFailback(); } } } private GrpcChannel BuildChannel(string endpoint, string siteId) { var channelOptions = new GrpcChannelOptions { HttpHandler = _handlerFactory is not null ? _handlerFactory(endpoint) : new SocketsHttpHandler { KeepAlivePingDelay = _options.GrpcKeepAlivePingDelay, KeepAlivePingTimeout = _options.GrpcKeepAlivePingTimeout, ConnectTimeout = _options.GrpcConnectTimeout, KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, EnableMultipleHttp2Connections = true } }.WithMessageLimits().WithSiteCredentials(_pskProvider, siteId, endpoint); return GrpcChannel.ForAddress(endpoint, channelOptions); } /// /// Sentinel instance name the readiness probe queries. The leading $ makes it an /// illegal Akka actor name, which ActorNameRules rejects for every real instance, so it /// can never collide with one. The site-side DeploymentStateQuery path (dispatcher → /// DeploymentManagerActor → a parameterised SQLite lookup) never validates or materialises /// the name, so the probe simply reads "not deployed". /// internal const string ReadinessProbeInstance = "$scadabridge-failback-probe"; /// /// Production failback probe (review 2026-10-21 03/P-2): a real, read-only /// ExecuteLifecycle(DeploymentStateQuery) for a sentinel instance, NOT a transport /// connect. SiteCommandGrpcService refuses every RPC with a not-dispatched /// until the site has finished bring-up, so a node that is /// Up but still warming (minutes on a large site) now reads as NOT ready — a TCP/HTTP2 connect /// succeeded there and failed every command back to it each sweep. The query reads one /// (absent) row from the site's deployed-config store; it is idempotent and side-effect free. /// Any reply is "ready"; any failure, including the readiness rejection, is "not ready". /// /// The preferred node's channel. /// Cancellation token. /// True when the node answered a real command. internal static async Task ReadinessProbeAsync(GrpcChannel channel, CancellationToken ct) { try { var request = SiteCommandDtoMapper.ToLifecycleRequest(new DeploymentStateQueryRequest( "failback-probe-" + Guid.NewGuid().ToString("N"), ReadinessProbeInstance, DateTimeOffset.UtcNow)); var client = new SiteCommandService.SiteCommandServiceClient(channel); await client.ExecuteLifecycleAsync( request, deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: ct).ResponseAsync.ConfigureAwait(false); return true; } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } catch { return false; } } /// Disposes every pooled channel and stops the failback sweep and parked-channel disposal. public void Dispose() { lock (_lifecycleGate) { if (_disposed) return; _disposed = true; foreach (var pair in _sites.Values) { lock (pair.Gate) { Park(pair.ChannelA); Park(pair.ChannelB); pair.ChannelA = null; pair.ChannelB = null; } } _sites.Clear(); } _shutdown.Cancel(); try { _failbackLoop?.Wait(TimeSpan.FromSeconds(2)); } catch { /* shutdown is best effort; active calls retain their channels */ } _shutdown.Dispose(); SweepGraveyard(force: true); } private sealed class SitePair(string siteId) { /// The site identifier this pair of node channels belongs to. public string SiteId { get; } = siteId; public readonly object Gate = new(); public string? NodeAEndpoint; public string? NodeBEndpoint; /// Last malformed NodeA/NodeB endpoint rejected by UpdateSite (log de-duplication only). public string? RejectedAEndpoint; public string? RejectedBEndpoint; public GrpcChannel? ChannelA; public GrpcChannel? ChannelB; /// Sticky current node; NodeA is preferred. True = pointing at NodeA. public bool CurrentIsA = true; /// /// True between a probe-driven failback and the first successful real call on NodeA; while /// set, the backoff is kept so a renewed failure doubles it. /// public bool FailbackOnProbation; /// When the current probation began (meaningful only while ). public DateTime ProbationSinceUtc; /// The current failback backoff. public TimeSpan Backoff => _backoff; /// Next time a failback probe is due (while failed over). MaxValue = not scheduled. public DateTime NextProbeUtc = DateTime.MaxValue; private TimeSpan _backoff = InitialBackoff; /// Sets the failback backoff to and schedules the next probe that far ahead. /// The delay before the next failback probe. public void ScheduleFailback(TimeSpan delay) { _backoff = delay; NextProbeUtc = DateTime.UtcNow + _backoff; } /// Doubles the failback backoff (capped at the maximum) and schedules the next probe. public void BumpFailbackBackoff() { var next = TimeSpan.FromTicks(Math.Min(_backoff.Ticks * 2, MaxBackoff.Ticks)); _backoff = next; NextProbeUtc = DateTime.UtcNow + _backoff; } /// Resets the backoff to its initial value and clears the scheduled failback probe. public void ResetFailback() { _backoff = InitialBackoff; NextProbeUtc = DateTime.MaxValue; } } }