Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayChannelKeepAliveTests.cs
T

259 lines
12 KiB
C#

using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using Grpc.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Shouldly;
using Xunit;
using ZB.MOM.WW.MxGateway.Client;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
/// #991 G-19 — a gateway connection that dies SILENTLY (host power loss, a firewall dropping the flow: no FIN, no
/// RST) never faulted the driver's <c>StreamEvents</c>: a server stream sends nothing after its request, and the
/// client library's channel has no HTTP/2 keep-alive, so the read waited forever and Galaxy stayed Healthy with
/// stale Good values. The driver's channels now PING; an unanswered PING fails the connection and the stream.
/// Proven here against an in-process gRPC gateway behind a TCP proxy that can be switched to a black hole.
/// </summary>
public sealed class GatewayChannelKeepAliveTests
{
/// <summary>Keep-alive pings at 1 s with a 1 s budget: a black-holed stream faults within a few seconds.</summary>
[Fact]
public async Task A_black_holed_stream_faults_on_the_keep_alive_channel()
{
await using var gateway = await FakeGateway.StartAsync();
await using var proxy = BlackHoleProxy.Start(gateway.Port);
var options = ClientOptions(proxy.Port);
using var channel = GalaxyGatewayChannelFactory.CreateChannel(
options, new GalaxyGatewayOptions(options.Endpoint.ToString(), "k", UseTls: false,
KeepAlivePingDelaySeconds: 1, KeepAlivePingTimeoutSeconds: 1));
await using var client = MxGatewayClient.Create(channel, options);
var outcome = await ReadAcrossBlackHoleAsync(client, proxy, TimeSpan.FromSeconds(15));
outcome.ShouldNotBeNull("the stream must fault once the pings go unanswered");
outcome.ShouldNotBeOfType<EndOfStreamException>("a fault, not a clean end");
}
/// <summary>
/// The control — and the defect: the client library's own channel (no keep-alive) leaves the same black-holed
/// stream waiting. Without this the test above could pass for some other reason (e.g. the proxy closing).
/// </summary>
[Fact]
public async Task Without_keep_alive_a_black_holed_stream_waits_forever()
{
await using var gateway = await FakeGateway.StartAsync();
await using var proxy = BlackHoleProxy.Start(gateway.Port);
var options = ClientOptions(proxy.Port);
await using var client = MxGatewayClient.Create(options);
var outcome = await ReadAcrossBlackHoleAsync(client, proxy, TimeSpan.FromSeconds(5));
outcome.ShouldBeNull("with no pings nothing ever notices the dead connection");
}
/// <summary>The handler carries the pings (policy Always — a stream between events is not an "active request" gap).</summary>
[Fact]
public void The_handler_pings_always_and_zero_disables()
{
var options = ClientOptions(5001);
using var on = GalaxyGatewayChannelFactory.CreateHttpHandler(options, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));
on.KeepAlivePingDelay.ShouldBe(TimeSpan.FromSeconds(15));
on.KeepAlivePingTimeout.ShouldBe(TimeSpan.FromSeconds(10));
on.KeepAlivePingPolicy.ShouldBe(HttpKeepAlivePingPolicy.Always);
on.ConnectTimeout.ShouldBe(options.ConnectTimeout);
var defaults = new GalaxyGatewayOptions("http://x:1", "k");
GalaxyGatewayChannelFactory.KeepAliveDelay(defaults).ShouldBe(TimeSpan.FromSeconds(15));
GalaxyGatewayChannelFactory.KeepAliveTimeout(defaults).ShouldBe(TimeSpan.FromSeconds(10));
GalaxyGatewayChannelFactory.KeepAliveDelay(defaults with { KeepAlivePingDelaySeconds = 0 })
.ShouldBe(Timeout.InfiniteTimeSpan, "0 disables the pings");
}
/// <summary>TLS options mirror the client library: no-validation only when asked for, CA pinning otherwise.</summary>
[Fact]
public void The_handler_mirrors_the_client_tls_settings()
{
var tls = new MxGatewayClientOptions
{
Endpoint = new Uri("https://gw:5001"), ApiKey = "k", UseTls = true, ServerNameOverride = "gw.example",
RequireCertificateValidation = false,
};
using var lax = GalaxyGatewayChannelFactory.CreateHttpHandler(tls, Timeout.InfiniteTimeSpan, TimeSpan.Zero);
lax.SslOptions.TargetHost.ShouldBe("gw.example");
lax.SslOptions.RemoteCertificateValidationCallback.ShouldNotBeNull();
using var strict = GalaxyGatewayChannelFactory.CreateHttpHandler(
new MxGatewayClientOptions
{
Endpoint = tls.Endpoint, ApiKey = "k", UseTls = true, RequireCertificateValidation = true,
}, Timeout.InfiniteTimeSpan, TimeSpan.Zero);
strict.SslOptions.RemoteCertificateValidationCallback.ShouldBeNull("platform validation applies");
using var plain = GalaxyGatewayChannelFactory.CreateHttpHandler(ClientOptions(5001), Timeout.InfiniteTimeSpan, TimeSpan.Zero);
plain.SslOptions.RemoteCertificateValidationCallback.ShouldBeNull();
}
private static MxGatewayClientOptions ClientOptions(int port) => new()
{
Endpoint = new Uri($"http://127.0.0.1:{port}"),
ApiKey = "test-key",
UseTls = false,
ConnectTimeout = TimeSpan.FromSeconds(5),
DefaultCallTimeout = TimeSpan.FromSeconds(5),
};
/// <summary>
/// Opens StreamEvents, takes the first event (the connection is proven live), black-holes the proxy, and waits
/// up to <paramref name="window"/> for the next read to end. Returns the exception it ended with, a sentinel
/// exception for a clean end, or null if it was still waiting when the window closed.
/// </summary>
private static async Task<Exception?> ReadAcrossBlackHoleAsync(MxGatewayClient client, BlackHoleProxy proxy, TimeSpan window)
{
using var cts = new CancellationTokenSource();
var enumerator = client.StreamEventsAsync(new StreamEventsRequest { SessionId = "s1" }, cts.Token)
.GetAsyncEnumerator(cts.Token);
try
{
(await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10))).ShouldBeTrue("the first event proves the stream is live");
proxy.BlackHole();
var next = enumerator.MoveNextAsync().AsTask();
var finished = await Task.WhenAny(next, Task.Delay(window, TestContext.Current.CancellationToken));
if (finished != next) return null;
try
{
return await next ? new InvalidOperationException("an unexpected event arrived") : new EndOfStreamException("completed");
}
catch (Exception ex)
{
return ex;
}
}
finally
{
await cts.CancelAsync();
try { await enumerator.DisposeAsync(); } catch { /* the stream is dead either way */ }
}
}
/// <summary>A gateway whose StreamEvents sends one event and then stays open, silent, until cancelled.</summary>
private sealed class FakeGatewayService : MxAccessGateway.MxAccessGatewayBase
{
public override async Task StreamEvents(
StreamEventsRequest request, IServerStreamWriter<MxEvent> responseStream, ServerCallContext context)
{
await responseStream.WriteAsync(new MxEvent { Family = MxEventFamily.OnDataChange, ItemHandle = 1 });
try { await Task.Delay(Timeout.Infinite, context.CancellationToken); }
catch (OperationCanceledException) { }
}
}
private sealed class FakeGateway(WebApplication app, int port) : IAsyncDisposable
{
public int Port => port;
public static async Task<FakeGateway> StartAsync()
{
var builder = WebApplication.CreateSlimBuilder();
builder.Logging.ClearProviders();
builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0, o => o.Protocols = HttpProtocols.Http2));
builder.Services.AddGrpc();
var app = builder.Build();
app.MapGrpcService<FakeGatewayService>();
await app.StartAsync();
return new FakeGateway(app, new Uri(app.Urls.First()).Port);
}
public async ValueTask DisposeAsync()
{
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try { await app.StopAsync(stop.Token); } catch { /* best effort */ }
await app.DisposeAsync();
}
}
/// <summary>
/// Forwards TCP between client and gateway until <see cref="BlackHole"/>; from then on every byte in either
/// direction is swallowed while both sockets stay open — no FIN, no RST, exactly what a dead host or a
/// dropping firewall looks like to the client.
/// </summary>
private sealed class BlackHoleProxy : IAsyncDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly int _targetPort;
private readonly CancellationTokenSource _cts = new();
private readonly List<Socket> _sockets = [];
private volatile bool _blackHoled;
private Task? _acceptLoop;
private BlackHoleProxy(int targetPort) => _targetPort = targetPort;
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
public static BlackHoleProxy Start(int targetPort)
{
var proxy = new BlackHoleProxy(targetPort);
proxy._listener.Start();
proxy._acceptLoop = Task.Run(proxy.AcceptLoopAsync);
return proxy;
}
public void BlackHole() => _blackHoled = true;
private async Task AcceptLoopAsync()
{
try
{
while (!_cts.IsCancellationRequested)
{
var inbound = await _listener.AcceptSocketAsync(_cts.Token);
var outbound = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await outbound.ConnectAsync(IPAddress.Loopback, _targetPort, _cts.Token);
lock (_sockets) { _sockets.Add(inbound); _sockets.Add(outbound); }
_ = PumpAsync(inbound, outbound);
_ = PumpAsync(outbound, inbound);
}
}
catch (Exception) when (_cts.IsCancellationRequested) { }
catch (ObjectDisposedException) { }
}
private async Task PumpAsync(Socket from, Socket to)
{
var buffer = new byte[16 * 1024];
try
{
while (true)
{
var read = await from.ReceiveAsync(buffer, SocketFlags.None, _cts.Token);
if (read == 0) return;
if (_blackHoled) continue; // swallowed: never delivered, never answered
await to.SendAsync(buffer.AsMemory(0, read), SocketFlags.None, _cts.Token);
}
}
catch (Exception) { /* proxy shutting down */ }
}
public async ValueTask DisposeAsync()
{
await _cts.CancelAsync();
_listener.Stop();
lock (_sockets)
{
foreach (var s in _sockets) { try { s.Dispose(); } catch { /* best effort */ } }
}
if (_acceptLoop is not null) { try { await _acceptLoop; } catch { /* stopped */ } }
_cts.Dispose();
}
}
}