169 lines
8.1 KiB
C#
169 lines
8.1 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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 <c>192.0.2.1</c> (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.
|
|
/// </summary>
|
|
public sealed class GrpcConnectTimeoutTests
|
|
{
|
|
private const string BlackHole = "http://192.0.2.1:8083";
|
|
|
|
/// <summary>A <c>ConnectTimeout</c> firing on the subchannel is a provably-unsent connect failure.</summary>
|
|
[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));
|
|
}
|
|
|
|
/// <summary>The option defaults to 5 s and is validated positive.</summary>
|
|
[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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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<RpcException>(() => 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}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// With the deadline shorter than the connect timeout, the call ends DeadlineExceeded while the
|
|
/// channel is still connecting — recognised as a connect-phase deadline.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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<RpcException>(() => 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");
|
|
}
|
|
|
|
/// <summary>A deadline on a non-connecting state (a plain server-side deadline) is not connect-phase.</summary>
|
|
[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));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SitePair_ConnectPhaseDeadlineOnNodeA_FlipsToNodeB()
|
|
{
|
|
using var provider = new SitePairChannelProvider(
|
|
new NoKeyProvider(),
|
|
Options.Create(new CommunicationOptions()),
|
|
NullLogger<SitePairChannelProvider>.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<RpcException>(() => 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"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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<GrpcCentralTransport>.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
|
|
{
|
|
/// <inheritdoc />
|
|
public ValueTask<string> GetAsync(string siteId, CancellationToken ct) => new("k");
|
|
/// <inheritdoc />
|
|
public void Invalidate(string siteId) { }
|
|
}
|
|
}
|