fix(comm): key site liveness on central receive time; gRPC connect timeout + connect-phase deadline failover (COMM-4, COMM-5, WP4 task 4.4)
This commit is contained in:
@@ -34,7 +34,10 @@ public interface ICentralHealthAggregator
|
||||
/// shown as "unknown" during the failover window.
|
||||
/// </summary>
|
||||
/// <param name="siteId">The string identifier of the site that sent the heartbeat.</param>
|
||||
/// <param name="receivedAt">The UTC timestamp when the heartbeat was received.</param>
|
||||
/// <param name="receivedAt">
|
||||
/// The UTC time CENTRAL received the heartbeat (its own clock — never the site-stamped
|
||||
/// timestamp, COMM-4). A value in the aggregator's future is clamped to its current time.
|
||||
/// </param>
|
||||
void MarkHeartbeat(string siteId, DateTimeOffset receivedAt);
|
||||
|
||||
/// <summary>Returns a snapshot of all currently tracked site health states.</summary>
|
||||
|
||||
@@ -323,8 +323,12 @@ public class CentralCommunicationActor : ReceiveActor
|
||||
return;
|
||||
}
|
||||
|
||||
// Liveness is keyed on CENTRAL's receive time (COMM-4), never the site-stamped
|
||||
// heartbeat.Timestamp: the offline check compares against central's clock, so a site
|
||||
// clock running X ahead used to stretch the 60 s offline timeout to 60 s + X (a site
|
||||
// without NTP, 30 min fast, read Online for ~31 min after its link dropped).
|
||||
var aggregator = _serviceProvider.GetService<ICentralHealthAggregator>();
|
||||
aggregator?.MarkHeartbeat(heartbeat.SiteId, heartbeat.Timestamp);
|
||||
aggregator?.MarkHeartbeat(heartbeat.SiteId, DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -420,8 +420,18 @@ public sealed class SiteAlarmAggregatorActor : ReceiveActor, IWithTimers
|
||||
_openInFlight = false;
|
||||
_log.Warning(
|
||||
"Site-alarm gRPC stream open for {0} did not report connected, error or completion within {1}; " +
|
||||
"releasing the in-flight guard so the next reconcile tick can reopen",
|
||||
"treating it as a stream error (flip node, count a retry)",
|
||||
_siteIdentifier, _openAttemptTimeout);
|
||||
|
||||
// COMM-5: an attempt that never resolves is a failed attempt — the node did not
|
||||
// accept the subscription. Treat it like a stream error so the aggregator flips to
|
||||
// the other node and spends retry budget; before, it only released the guard and
|
||||
// the next reconcile tick reopened on the SAME node (bumping the generation, so the
|
||||
// cancelled attempt's eventual connect error was discarded as stale) — a black-holed
|
||||
// NodeA was never left. Cancel the stalled attempt first so its late callbacks are
|
||||
// silent (a cancelled attempt reports neither error nor completion).
|
||||
_grpcCts?.Cancel();
|
||||
HandleGrpcError();
|
||||
});
|
||||
|
||||
// Coalesced-publish tick: one publish for a batch of dirtying deltas (N6).
|
||||
|
||||
@@ -134,6 +134,17 @@ public class CommunicationOptions
|
||||
/// <summary>gRPC keepalive ping timeout — stream is considered dead if no response within this period.</summary>
|
||||
public TimeSpan GrpcKeepAlivePingTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>
|
||||
/// TCP connect timeout (<c>SocketsHttpHandler.ConnectTimeout</c>) for every cross-cluster gRPC
|
||||
/// channel — the central→site command pair, the site→central control pair and the site stream
|
||||
/// clients (COMM-5). Without it a peer whose host silently drops SYNs (powered off behind a
|
||||
/// router, firewall drop, WAN black hole) held the connect for the OS TCP timeout (~21 s on
|
||||
/// Windows, ~2 min on Linux), so calls with shorter deadlines ended <c>DeadlineExceeded</c> and
|
||||
/// never failed over. With it the connect fails as <c>Unavailable</c> well inside every call
|
||||
/// deadline. Default 5 s.
|
||||
/// </summary>
|
||||
public TimeSpan GrpcConnectTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Maximum lifetime for a single gRPC stream before the server forces re-establishment.</summary>
|
||||
public TimeSpan GrpcMaxStreamLifetime { get; set; } = TimeSpan.FromHours(4);
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ public sealed class CommunicationOptionsValidator : OptionsValidatorBase<Communi
|
||||
|
||||
builder.RequireThat(options.GrpcKeepAlivePingTimeout > TimeSpan.Zero,
|
||||
$"ScadaBridge:Communication:GrpcKeepAlivePingTimeout must be a positive duration (was {options.GrpcKeepAlivePingTimeout}).");
|
||||
builder.RequireThat(options.GrpcConnectTimeout > TimeSpan.Zero,
|
||||
$"ScadaBridge:Communication:GrpcConnectTimeout must be a positive duration (was {options.GrpcConnectTimeout}).");
|
||||
|
||||
builder.RequireThat(options.GrpcMaxStreamLifetime > TimeSpan.Zero,
|
||||
$"ScadaBridge:Communication:GrpcMaxStreamLifetime must be a positive duration (was {options.GrpcMaxStreamLifetime}).");
|
||||
|
||||
@@ -114,6 +114,7 @@ public sealed class CentralChannelProvider : IDisposable
|
||||
{
|
||||
KeepAlivePingDelay = options.GrpcKeepAlivePingDelay,
|
||||
KeepAlivePingTimeout = options.GrpcKeepAlivePingTimeout,
|
||||
ConnectTimeout = options.GrpcConnectTimeout,
|
||||
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
|
||||
EnableMultipleHttp2Connections = true,
|
||||
},
|
||||
@@ -151,6 +152,18 @@ public sealed class CentralChannelProvider : IDisposable
|
||||
return (idx, _clients[idx]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="error"/> is a <see cref="StatusCode.DeadlineExceeded"/> that expired
|
||||
/// while the endpoint at <paramref name="index"/> was still not accepting a connection
|
||||
/// (COMM-5) — see <see cref="GrpcRetrySafety.IsConnectPhaseDeadline"/>.
|
||||
/// </summary>
|
||||
/// <param name="error">The RPC failure.</param>
|
||||
/// <param name="index">The endpoint index the failed call used.</param>
|
||||
/// <returns><c>true</c> for a connect-phase deadline.</returns>
|
||||
public bool IsConnectPhaseDeadline(RpcException error, int index)
|
||||
=> index >= 0 && index < _channels.Length
|
||||
&& GrpcRetrySafety.IsConnectPhaseDeadline(error, _channels[index]);
|
||||
|
||||
/// <summary>
|
||||
/// Reports that the endpoint at <paramref name="failedIndex"/> refused a connection (an
|
||||
/// <see cref="StatusCode.Unavailable"/> / connect failure). If it is still the current endpoint
|
||||
|
||||
@@ -141,10 +141,12 @@ public sealed class GrpcCentralTransport : ICentralTransport
|
||||
using var call = client.HeartbeatAsync(dto, options);
|
||||
await call.ResponseAsync.ConfigureAwait(false);
|
||||
}
|
||||
catch (RpcException ex) when (IsConnectFailure(ex))
|
||||
catch (RpcException ex) when (IsConnectFailure(ex) || _channels.IsConnectPhaseDeadline(ex, index))
|
||||
{
|
||||
// Nudge the pair so the next call tries the peer, but never fault: a heartbeat
|
||||
// failure must not surface on the site's heartbeat timer path.
|
||||
// failure must not surface on the site's heartbeat timer path. A connect-phase
|
||||
// deadline (COMM-5: black-holed central node) counts too — otherwise a quiet site
|
||||
// whose only traffic is the heartbeat never leaves a dead central-a.
|
||||
_channels.ReportUnavailable(index);
|
||||
_logger.LogDebug(ex, "Heartbeat to central endpoint {Endpoint} was unavailable.", CurrentEndpointSafe());
|
||||
}
|
||||
@@ -213,6 +215,13 @@ public sealed class GrpcCentralTransport : ICentralTransport
|
||||
|
||||
replyTo.Tell(new AkkaStatus.Failure(ex));
|
||||
}
|
||||
catch (RpcException ex) when (_channels.IsConnectPhaseDeadline(ex, index))
|
||||
{
|
||||
// COMM-5: the deadline expired before the endpoint accepted a connection. Move the
|
||||
// pair so the next call tries the peer; the deadline is spent, so no retry here.
|
||||
_channels.ReportUnavailable(index);
|
||||
replyTo.Tell(new AkkaStatus.Failure(ex));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// DeadlineExceeded / Internal / PermissionDenied / a PSK-resolution throw — do NOT
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using Grpc.Core;
|
||||
using Grpc.Net.Client;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Communication.Grpc;
|
||||
|
||||
@@ -31,11 +32,12 @@ public static class GrpcRetrySafety
|
||||
/// <summary>
|
||||
/// True only when the client failed while OPENING a connection, so the request provably never
|
||||
/// left this process (ScadaBridge#136 — the first command to a stopped node of a site pair).
|
||||
/// Two shapes qualify, both <see cref="StatusCode.Unavailable"/> with a
|
||||
/// <see cref="SocketException"/> in the debug-exception chain:
|
||||
/// Two shapes qualify, both <see cref="StatusCode.Unavailable"/>:
|
||||
/// <list type="bullet">
|
||||
/// <item>Grpc.Net.Client's subchannel connect failure (<see cref="SubchannelConnectFailureDetail"/>):
|
||||
/// the balancer never handed the call a connection, whatever the socket error.</item>
|
||||
/// <item>Grpc.Net.Client's subchannel connect failure (<see cref="SubchannelConnectFailureDetail"/>)
|
||||
/// with a <see cref="SocketException"/> or a <see cref="TimeoutException"/> (the
|
||||
/// <c>SocketsHttpHandler.ConnectTimeout</c> firing on a black-holed peer — COMM-5) in the
|
||||
/// debug-exception chain: the balancer never handed the call a connection.</item>
|
||||
/// <item>An <see cref="HttpRequestException"/> classified as a name-resolution or connection
|
||||
/// error whose socket error can only arise before a connection exists (refused, host not
|
||||
/// found, DNS try-again / no-data).</item>
|
||||
@@ -54,10 +56,18 @@ public static class GrpcRetrySafety
|
||||
|
||||
HttpRequestException? http = null;
|
||||
SocketException? socket = null;
|
||||
TimeoutException? connectTimeout = null;
|
||||
for (var e = error.Status.DebugException; e is not null; e = e.InnerException)
|
||||
{
|
||||
http ??= e as HttpRequestException;
|
||||
socket ??= e as SocketException;
|
||||
connectTimeout ??= e as TimeoutException;
|
||||
}
|
||||
|
||||
if (http is null)
|
||||
{
|
||||
return (socket is not null || connectTimeout is not null)
|
||||
&& string.Equals(error.Status.Detail, SubchannelConnectFailureDetail, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
if (socket is null)
|
||||
@@ -65,16 +75,41 @@ public static class GrpcRetrySafety
|
||||
return false;
|
||||
}
|
||||
|
||||
if (http is null)
|
||||
{
|
||||
return string.Equals(error.Status.Detail, SubchannelConnectFailureDetail, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
return http.HttpRequestError is HttpRequestError.NameResolutionError or HttpRequestError.ConnectionError
|
||||
&& socket.SocketErrorCode is SocketError.ConnectionRefused or SocketError.HostNotFound
|
||||
or SocketError.TryAgain or SocketError.NoData;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when a <see cref="StatusCode.DeadlineExceeded"/> ended the call while
|
||||
/// <paramref name="channel"/> was still trying to connect (state <c>Connecting</c> or
|
||||
/// <c>TransientFailure</c>), i.e. the peer never accepted a connection (COMM-5). That is a
|
||||
/// reason to move the channel pair to the other node; it is NOT proof the request was unsent
|
||||
/// for replay purposes, and the spent deadline leaves nothing to retry with anyway. A
|
||||
/// deadline on a connected (<c>Ready</c>) channel is a slow peer and returns false, as does a
|
||||
/// channel that does not expose a connectivity state.
|
||||
/// </summary>
|
||||
/// <param name="error">The RPC failure to inspect.</param>
|
||||
/// <param name="channel">The channel the call ran on.</param>
|
||||
/// <returns><c>true</c> for a deadline that expired in the connect phase.</returns>
|
||||
public static bool IsConnectPhaseDeadline(RpcException error, GrpcChannel channel)
|
||||
{
|
||||
if (error.StatusCode != StatusCode.DeadlineExceeded)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return channel.State is ConnectivityState.Connecting or ConnectivityState.TransientFailure;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Channel built without the subchannel balancer (a custom test handler): unknown.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when a mutation may be replayed on the peer node: the server rejected it before
|
||||
/// dispatch (<see cref="WasNotDispatched"/>), or the client never sent it (<see cref="WasNeverSent"/>).
|
||||
|
||||
@@ -322,6 +322,17 @@ public sealed class SitePairChannelProvider : IDisposable
|
||||
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);
|
||||
@@ -586,6 +597,7 @@ public sealed class SitePairChannelProvider : IDisposable
|
||||
{
|
||||
KeepAlivePingDelay = _options.GrpcKeepAlivePingDelay,
|
||||
KeepAlivePingTimeout = _options.GrpcKeepAlivePingTimeout,
|
||||
ConnectTimeout = _options.GrpcConnectTimeout,
|
||||
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
|
||||
EnableMultipleHttp2Connections = true
|
||||
}
|
||||
|
||||
@@ -92,7 +92,8 @@ public class SiteStreamGrpcClient : IAsyncDisposable, IDisposable
|
||||
{
|
||||
KeepAlivePingDelay = options.GrpcKeepAlivePingDelay,
|
||||
KeepAlivePingTimeout = options.GrpcKeepAlivePingTimeout,
|
||||
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always
|
||||
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
|
||||
ConnectTimeout = options.GrpcConnectTimeout
|
||||
}
|
||||
}.WithMessageLimits().WithSiteCredentials(pskProvider, siteIdentifier, endpoint));
|
||||
_client = new SiteStreamService.SiteStreamServiceClient(_channel);
|
||||
|
||||
@@ -108,6 +108,14 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
|
||||
/// <inheritdoc />
|
||||
public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt)
|
||||
{
|
||||
// Never let a heartbeat stamp land in central's future (COMM-4): the offline check
|
||||
// measures `now - LastHeartbeatAt` on central's clock, so a future stamp silently
|
||||
// extends the offline timeout by the skew. Callers pass central's receive time; this
|
||||
// clamp keeps a skewed caller from reintroducing the drift.
|
||||
var clampNow = _timeProvider.GetUtcNow();
|
||||
if (receivedAt > clampNow)
|
||||
receivedAt = clampNow;
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (!_siteStates.TryGetValue(siteId, out var existing))
|
||||
@@ -151,8 +159,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
|
||||
DateTimeOffset newHeartbeat;
|
||||
if (!existing.IsOnline)
|
||||
{
|
||||
var now = _timeProvider.GetUtcNow();
|
||||
newHeartbeat = receivedAt > now ? receivedAt : now;
|
||||
newHeartbeat = _timeProvider.GetUtcNow();
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user