using Grpc.Core; using Grpc.Net.Client; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using ZB.MOM.WW.ScadaBridge.Communication.Grpc; namespace ZB.MOM.WW.ScadaBridge.Communication.Tests.Grpc; /// /// COMM-5: a black-holed peer (SYNs silently dropped) must surface as a failover-worthy error /// well inside a call deadline, not as a DeadlineExceeded that never moves the channel pair. /// The live cases dial 192.0.2.1 (TEST-NET-1, never routed). On a host with a default /// route the SYN is dropped (the black-hole shape); on a host without one the connect fails /// fast with a socket error instead — every assertion here holds for either, since both are /// failover-worthy. /// public sealed class GrpcConnectTimeoutTests { private const string BlackHole = "http://192.0.2.1:8083"; /// A ConnectTimeout firing on the subchannel is a provably-unsent connect failure. [Fact] public void SubchannelConnectTimeout_IsNeverSent() { var ex = new RpcException(new Status(StatusCode.Unavailable, GrpcRetrySafety.SubchannelConnectFailureDetail, new TimeoutException("A connection could not be established within the configured ConnectTimeout.", new OperationCanceledException()))); Assert.True(GrpcRetrySafety.WasNeverSent(ex)); Assert.True(GrpcRetrySafety.ProvablyNotApplied(ex)); } /// The option defaults to 5 s and is validated positive. [Fact] public void GrpcConnectTimeout_DefaultsToFiveSeconds_AndMustBePositive() { Assert.Equal(TimeSpan.FromSeconds(5), new CommunicationOptions().GrpcConnectTimeout); var result = new CommunicationOptionsValidator().Validate(null, new CommunicationOptions { GrpcConnectTimeout = TimeSpan.Zero }); Assert.True(result.Failed); Assert.Contains("GrpcConnectTimeout", result.FailureMessage); } /// /// With the connect timeout shorter than the deadline, a black-holed peer fails Unavailable /// and provably unsent — so the pair fails over even for a mutation. /// /// A task that represents the asynchronous operation. [Fact] public async Task BlackHoledPeer_WithConnectTimeout_FailsUnavailableAndNeverSent() { using var channel = GrpcChannel.ForAddress(BlackHole, new GrpcChannelOptions { HttpHandler = new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromMilliseconds(500) }, }); var client = new SiteStreamService.SiteStreamServiceClient(channel); var ex = await Assert.ThrowsAsync(() => client.PullAuditEventsAsync( new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddSeconds(10)).ResponseAsync); Assert.Equal(StatusCode.Unavailable, ex.StatusCode); Assert.True(GrpcRetrySafety.WasNeverSent(ex), $"expected a never-sent connect failure, got: {ex.Status.DebugException}"); } /// /// With the deadline shorter than the connect timeout, the call ends DeadlineExceeded while the /// channel is still connecting — recognised as a connect-phase deadline. /// /// A task that represents the asynchronous operation. [Fact] public async Task BlackHoledPeer_DeadlineBeforeConnectTimeout_IsAConnectPhaseDeadline() { using var channel = GrpcChannel.ForAddress(BlackHole, new GrpcChannelOptions { HttpHandler = new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) }, }); var client = new SiteStreamService.SiteStreamServiceClient(channel); var ex = await Assert.ThrowsAsync(() => client.PullAuditEventsAsync( new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddMilliseconds(400)).ResponseAsync); if (ex.StatusCode == StatusCode.DeadlineExceeded) Assert.True(GrpcRetrySafety.IsConnectPhaseDeadline(ex, channel)); else Assert.True(GrpcRetrySafety.WasNeverSent(ex), "no default route: the connect fails fast instead"); } /// A deadline on a non-connecting state (a plain server-side deadline) is not connect-phase. [Fact] public void NonDeadlineStatuses_AreNotConnectPhaseDeadlines() { using var channel = GrpcChannel.ForAddress(BlackHole); Assert.False(GrpcRetrySafety.IsConnectPhaseDeadline( new RpcException(new Status(StatusCode.Unavailable, "x")), channel)); // A fresh channel that never attempted a connection is Idle, not connecting. Assert.False(GrpcRetrySafety.IsConnectPhaseDeadline( new RpcException(new Status(StatusCode.DeadlineExceeded, "")), channel)); } /// /// SitePairChannelProvider: a connect-phase DeadlineExceeded on node A moves the pair to node B /// (before COMM-5 only Unavailable did, so a black-holed NodeA kept every command). /// /// A task that represents the asynchronous operation. [Fact] public async Task SitePair_ConnectPhaseDeadlineOnNodeA_FlipsToNodeB() { using var provider = new SitePairChannelProvider( new NoKeyProvider(), Options.Create(new CommunicationOptions()), NullLogger.Instance, handlerFactory: _ => new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) }, reachabilityProbe: (_, _) => Task.FromResult(false)); provider.UpdateSite("site-1", BlackHole, "http://localhost:15399"); var ex = await Assert.ThrowsAsync(() => provider.ExecuteAsync("site-1", (channel, ct) => new SiteStreamService.SiteStreamServiceClient(channel) .PullAuditEventsAsync(new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddMilliseconds(400), cancellationToken: ct).ResponseAsync, CancellationToken.None, retrySafe: false)); // Either shape moves the pair: a connect-phase deadline (black hole) or a fast connect // failure (no default route). Assert.True(ex.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Unavailable or StatusCode.Aborted, $"unexpected {ex.StatusCode}"); Assert.False(provider.IsOnPreferredNode("site-1")); } /// /// GrpcCentralTransport: a heartbeat that times out against a black-holed central-a moves the /// pair to central-b (before COMM-5 a quiet site whose only traffic is the heartbeat never left /// a dead central-a and read Offline at central). /// /// A task that represents the asynchronous operation. [Fact] public async Task CentralTransport_HeartbeatConnectPhaseDeadline_FlipsToTheOtherCentral() { var options = new CommunicationOptions { HealthReportTimeout = TimeSpan.FromMilliseconds(400) }; using var provider = new CentralChannelProvider( new[] { BlackHole, "http://localhost:15397" }, new NoKeyProvider(), "site-1", options, NullLogger.Instance, handlerFactory: _ => new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) }, backoffBase: TimeSpan.FromMinutes(10), backoffCap: TimeSpan.FromMinutes(10)); var transport = new GrpcCentralTransport(provider, options, NullLogger.Instance); transport.SendHeartbeat( new ZB.MOM.WW.ScadaBridge.Commons.Messages.Health.HeartbeatMessage("site-1", "node-a", true, DateTimeOffset.UtcNow), Akka.Actor.ActorRefs.Nobody); var deadline = DateTime.UtcNow.AddSeconds(10); while (provider.CurrentIndex == 0 && DateTime.UtcNow < deadline) await Task.Delay(50); Assert.Equal(1, provider.CurrentIndex); } private sealed class NoKeyProvider : ISitePskProvider { /// public ValueTask GetAsync(string siteId, CancellationToken ct) => new("k"); /// public void Invalidate(string siteId) { } } }