736 lines
33 KiB
C#
736 lines
33 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// Raised when a site has no usable gRPC channel — an unknown site, or a site with neither
|
|
/// <c>GrpcNodeAAddress</c> nor <c>GrpcNodeBAddress</c> configured. <see cref="GrpcSiteTransport"/>
|
|
/// treats this as a known-dead send: it fails the caller's <c>Ask</c> fast with an
|
|
/// <c>Akka.Actor.Status.Failure</c> 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).
|
|
/// </summary>
|
|
public sealed class SiteChannelUnavailableException(string siteId)
|
|
: Exception($"No gRPC channel is configured for site '{siteId}'.")
|
|
{
|
|
/// <summary>The site with no configured channel.</summary>
|
|
public string SiteId { get; } = siteId;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Shared, per-site gRPC channel PAIR provider with sticky failover + failback (design §3.5).
|
|
/// Central holds one <see cref="GrpcChannel"/> 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 / <see cref="StatusCode.Unavailable"/> / 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.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// <b>Retry safety.</b> 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 (<see cref="GrpcRetrySafety.WasNeverSent"/>) 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.
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Addresses.</b> Fed by <see cref="UpdateSite"/>/<see cref="RemoveSite"/> from the single DB
|
|
/// refresh loop (the <c>GrpcNodeAAddress</c>/<c>GrpcNodeBAddress</c> columns). PSK credentials and
|
|
/// the <c>x-scadabridge-site</c> header ride every channel via
|
|
/// <see cref="ControlPlaneCredentials.WithSiteCredentials"/>; removing a site invalidates its
|
|
/// cached key.
|
|
/// </para>
|
|
/// </remarks>
|
|
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);
|
|
|
|
/// <summary>
|
|
/// How long a replaced/removed channel is PARKED before it is disposed. Active calls retain the channel beyond this minimum until completion.
|
|
/// </summary>
|
|
internal static readonly TimeSpan ChannelDisposalGrace = TimeSpan.FromMinutes(5);
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
internal TimeSpan FailbackProbationWindow { get; set; } = TimeSpan.FromMinutes(5);
|
|
|
|
private readonly ISitePskProvider _pskProvider;
|
|
private readonly CommunicationOptions _options;
|
|
private readonly ILogger<SitePairChannelProvider> _logger;
|
|
private readonly Func<string, HttpMessageHandler>? _handlerFactory;
|
|
private readonly Func<GrpcChannel, CancellationToken, Task<bool>> _reachabilityProbe;
|
|
|
|
private readonly ConcurrentDictionary<string, SitePair> _sites = new(StringComparer.Ordinal);
|
|
|
|
/// <summary>
|
|
/// Channels replaced by <see cref="UpdateSite"/> or dropped by <see cref="RemoveSite"/>,
|
|
/// each with the earliest idle disposal instant. Active-call retention can extend that instant.
|
|
/// </summary>
|
|
private readonly ConcurrentQueue<(GrpcChannel Channel, DateTime DisposeAfterUtc)> _graveyard = new();
|
|
private readonly ConcurrentDictionary<GrpcChannel, int> _activeCalls = new();
|
|
|
|
private readonly CancellationTokenSource _shutdown = new();
|
|
private Task? _failbackLoop;
|
|
private readonly object _loopGate = new();
|
|
private volatile bool _disposed;
|
|
private readonly object _lifecycleGate = new();
|
|
|
|
/// <summary>Creates the provider.</summary>
|
|
/// <param name="pskProvider">Resolves each site's preshared key for channel credentials.</param>
|
|
/// <param name="options">Communication options (keepalive settings applied to production channels).</param>
|
|
/// <param name="logger">Logger for failover/failback diagnostics.</param>
|
|
/// <param name="handlerFactory">
|
|
/// Test seam mapping an endpoint to the <see cref="HttpMessageHandler"/> its channel should use
|
|
/// (e.g. an in-process <c>TestServer</c> handler). Null in production, where each channel builds
|
|
/// a keepalive-configured <see cref="SocketsHttpHandler"/>.
|
|
/// </param>
|
|
/// <param name="reachabilityProbe">
|
|
/// Test seam deciding whether a preferred node is READY during a failback sweep. Null in
|
|
/// production, where <see cref="ReadinessProbeAsync"/> issues a real, read-only
|
|
/// <c>ExecuteLifecycle</c> call (review 2026-10-21 03/P-2).
|
|
/// </param>
|
|
public SitePairChannelProvider(
|
|
ISitePskProvider pskProvider,
|
|
IOptions<CommunicationOptions> options,
|
|
ILogger<SitePairChannelProvider> logger,
|
|
Func<string, HttpMessageHandler>? handlerFactory = null,
|
|
Func<GrpcChannel, CancellationToken, Task<bool>>? reachabilityProbe = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(pskProvider);
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
ArgumentNullException.ThrowIfNull(logger);
|
|
|
|
_pskProvider = pskProvider;
|
|
_options = options.Value;
|
|
_logger = logger;
|
|
_handlerFactory = handlerFactory;
|
|
_reachabilityProbe = reachabilityProbe ?? ReadinessProbeAsync;
|
|
}
|
|
|
|
/// <summary>
|
|
/// (Re)builds a site's channel pair from its gRPC node endpoints. A no-op when neither endpoint
|
|
/// changed. Parks (see <see cref="ChannelDisposalGrace"/>) 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.
|
|
/// </summary>
|
|
/// <param name="siteId">Site identifier.</param>
|
|
/// <param name="nodeAEndpoint">NodeA gRPC base address, or null when unconfigured.</param>
|
|
/// <param name="nodeBEndpoint">NodeB gRPC base address, or null when unconfigured.</param>
|
|
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);
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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
|
|
/// <see cref="GrpcEndpointRules"/>, 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.
|
|
/// </summary>
|
|
/// <param name="pair">The site pair (caller holds <c>pair.Gate</c>).</param>
|
|
/// <param name="siteId">Site identifier, for the log.</param>
|
|
/// <param name="endpoint">The new endpoint for this side.</param>
|
|
/// <param name="isA">True for NodeA (<c>GrpcNodeAAddress</c>), false for NodeB.</param>
|
|
/// <param name="channel">The built channel, or null for an unconfigured side.</param>
|
|
/// <returns>True when the replacement may be applied; false to keep the existing side.</returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parks a removed site's channels for deferred disposal (see <see cref="ChannelDisposalGrace"/>)
|
|
/// and invalidates its cached preshared key.
|
|
/// </summary>
|
|
/// <param name="siteId">Site identifier to remove.</param>
|
|
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);
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Runs <paramref name="call"/> 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.
|
|
/// </summary>
|
|
/// <typeparam name="T">The RPC reply type.</typeparam>
|
|
/// <param name="siteId">Target site.</param>
|
|
/// <param name="call">The RPC to run against a given channel.</param>
|
|
/// <param name="ct">Cancellation token.</param>
|
|
/// <param name="retrySafe">Whether repeating this operation is safe after an ambiguous transport failure.</param>
|
|
/// <returns>The RPC reply.</returns>
|
|
/// <exception cref="SiteChannelUnavailableException">The site has no configured channel.</exception>
|
|
public async Task<T> ExecuteAsync<T>(
|
|
string siteId, Func<GrpcChannel, CancellationToken, Task<T>> 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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
/// <param name="siteId">Site identifier.</param>
|
|
/// <param name="ct">Cancellation token.</param>
|
|
/// <returns>True when the site is now (or already) pointed at its preferred node.</returns>
|
|
internal async Task<bool> 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;
|
|
}
|
|
}
|
|
|
|
/// <summary>Test/diagnostic accessor: true when the site currently targets its preferred node (A).</summary>
|
|
/// <param name="siteId">Site identifier.</param>
|
|
/// <returns>True when on NodeA (or when the site is unknown).</returns>
|
|
internal bool IsOnPreferredNode(string siteId)
|
|
=> !_sites.TryGetValue(siteId, out var pair) || pair.CurrentIsA;
|
|
|
|
/// <summary>Starts the background failback loop if not already running. Idempotent.</summary>
|
|
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.
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parks a channel that is no longer reachable through <see cref="_sites"/> instead of
|
|
/// disposing it inline.
|
|
/// <para>
|
|
/// <b>Why deferred.</b> <see cref="ExecuteAsync{T}"/> reads the channel under
|
|
/// <c>pair.Gate</c> but invokes the RPC OUTSIDE it, so an inline
|
|
/// <c>Dispose</c> from the 60 s DB address refresh (or an admin edit) aborted whatever was
|
|
/// in flight — a multi-minute <c>DeployArtifactsCommand</c> included — with
|
|
/// <see cref="ObjectDisposedException"/> or <see cref="StatusCode.Cancelled"/>. Neither is
|
|
/// <see cref="StatusCode.Unavailable"/>, so the cross-node retry deliberately never engaged
|
|
/// and the command simply failed.
|
|
/// </para>
|
|
/// <para>
|
|
/// 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.
|
|
/// </para>
|
|
/// </summary>
|
|
/// <param name="channel">The channel to park; null is ignored.</param>
|
|
private void Park(GrpcChannel? channel)
|
|
{
|
|
if (channel is not null)
|
|
{
|
|
_graveyard.Enqueue((channel, DateTime.UtcNow + ChannelDisposalGrace));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Disposes every parked channel whose grace window has elapsed. Called from the DB refresh
|
|
/// path (<see cref="UpdateSite"/>/<see cref="RemoveSite"/>) and from the failback loop, so a
|
|
/// park always drains even on a provider that never runs a call again.
|
|
/// </summary>
|
|
/// <param name="force">True to ignore idle grace (shutdown and tests); active calls always retain their channels.</param>
|
|
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"); }
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
/// <summary>Test/diagnostic accessor: how many replaced channels are awaiting deferred disposal.</summary>
|
|
internal int ParkedChannelCount => _graveyard.Count;
|
|
|
|
/// <summary>A real call on the preferred node succeeded: a probationary failback is confirmed and the backoff reset.</summary>
|
|
/// <param name="pair">The site pair.</param>
|
|
private static void ConfirmFailback(SitePair pair)
|
|
{
|
|
if (!pair.FailbackOnProbation) return;
|
|
lock (pair.Gate)
|
|
{
|
|
if (pair.FailbackOnProbation && pair.CurrentIsA)
|
|
{
|
|
pair.FailbackOnProbation = false;
|
|
pair.ResetFailback();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Test/diagnostic accessor: the site's current failback backoff (null when the site is unknown).</summary>
|
|
/// <param name="siteId">Site identifier.</param>
|
|
/// <returns>The backoff the next failback probe is (or would be) scheduled with.</returns>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sentinel instance name the readiness probe queries. The leading <c>$</c> makes it an
|
|
/// illegal Akka actor name, which <c>ActorNameRules</c> 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".
|
|
/// </summary>
|
|
internal const string ReadinessProbeInstance = "$scadabridge-failback-probe";
|
|
|
|
/// <summary>
|
|
/// Production failback probe (review 2026-10-21 03/P-2): a real, read-only
|
|
/// <c>ExecuteLifecycle(DeploymentStateQuery)</c> for a sentinel instance, NOT a transport
|
|
/// connect. <c>SiteCommandGrpcService</c> refuses every RPC with a not-dispatched
|
|
/// <see cref="StatusCode.Unavailable"/> 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".
|
|
/// </summary>
|
|
/// <param name="channel">The preferred node's channel.</param>
|
|
/// <param name="ct">Cancellation token.</param>
|
|
/// <returns>True when the node answered a real command.</returns>
|
|
internal static async Task<bool> 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;
|
|
}
|
|
}
|
|
|
|
/// <summary>Disposes every pooled channel and stops the failback sweep and parked-channel disposal.</summary>
|
|
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)
|
|
{
|
|
/// <summary>The site identifier this pair of node channels belongs to.</summary>
|
|
public string SiteId { get; } = siteId;
|
|
public readonly object Gate = new();
|
|
public string? NodeAEndpoint;
|
|
public string? NodeBEndpoint;
|
|
|
|
/// <summary>Last malformed NodeA/NodeB endpoint rejected by <c>UpdateSite</c> (log de-duplication only).</summary>
|
|
public string? RejectedAEndpoint;
|
|
public string? RejectedBEndpoint;
|
|
public GrpcChannel? ChannelA;
|
|
public GrpcChannel? ChannelB;
|
|
|
|
/// <summary>Sticky current node; NodeA is preferred. True = pointing at NodeA.</summary>
|
|
public bool CurrentIsA = true;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public bool FailbackOnProbation;
|
|
|
|
/// <summary>When the current probation began (meaningful only while <see cref="FailbackOnProbation"/>).</summary>
|
|
public DateTime ProbationSinceUtc;
|
|
|
|
/// <summary>The current failback backoff.</summary>
|
|
public TimeSpan Backoff => _backoff;
|
|
|
|
/// <summary>Next time a failback probe is due (while failed over). MaxValue = not scheduled.</summary>
|
|
public DateTime NextProbeUtc = DateTime.MaxValue;
|
|
|
|
private TimeSpan _backoff = InitialBackoff;
|
|
|
|
/// <summary>Sets the failback backoff to <paramref name="delay"/> and schedules the next probe that far ahead.</summary>
|
|
/// <param name="delay">The delay before the next failback probe.</param>
|
|
public void ScheduleFailback(TimeSpan delay)
|
|
{
|
|
_backoff = delay;
|
|
NextProbeUtc = DateTime.UtcNow + _backoff;
|
|
}
|
|
|
|
/// <summary>Doubles the failback backoff (capped at the maximum) and schedules the next probe.</summary>
|
|
public void BumpFailbackBackoff()
|
|
{
|
|
var next = TimeSpan.FromTicks(Math.Min(_backoff.Ticks * 2, MaxBackoff.Ticks));
|
|
_backoff = next;
|
|
NextProbeUtc = DateTime.UtcNow + _backoff;
|
|
}
|
|
|
|
/// <summary>Resets the backoff to its initial value and clears the scheduled failback probe.</summary>
|
|
public void ResetFailback()
|
|
{
|
|
_backoff = InitialBackoff;
|
|
NextProbeUtc = DateTime.MaxValue;
|
|
}
|
|
}
|
|
}
|