From afaf6b97d51b53b4ffa9e3645954abd2316b89eb Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:34:51 -0500 Subject: [PATCH] fix(galaxy): #991 G-19 gateway channels send HTTP/2 keep-alive pings so a silently dead connection faults the event stream --- .../GalaxyDriverOptions.cs | 12 +- .../GalaxyDriver.cs | 70 ++++- .../GalaxyDriverFactoryExtensions.cs | 8 +- .../Runtime/GalaxyGatewayChannelFactory.cs | 117 ++++++++ .../Runtime/GalaxyMxSession.cs | 31 ++- .../GalaxyDriverFactoryTests.cs | 20 ++ .../Runtime/GalaxyDriverShutdownTests.cs | 5 + .../Runtime/GatewayChannelKeepAliveTests.cs | 258 ++++++++++++++++++ ....MOM.WW.OtOpcUa.Driver.Galaxy.Tests.csproj | 7 + 9 files changed, 514 insertions(+), 14 deletions(-) create mode 100644 src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyGatewayChannelFactory.cs create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayChannelKeepAliveTests.cs diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs index df25411f8..729f3de91 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs @@ -129,6 +129,14 @@ public sealed record GalaxyAlarmAckOptions( // legitimate worst case while still failing fast on a wedged worker. // StreamTimeoutSeconds = 0 — unlimited; the StreamEvents RPC must run for the // lifetime of the driver. Set a finite value only for diagnostic runs. +// KeepAlivePingDelaySeconds = 15 / KeepAlivePingTimeoutSeconds = 10 (#991 G-19) — HTTP/2 PING +// frames on every gateway channel, sent even while no call is active. A long-lived +// server stream (StreamEvents, StreamAlarms, WatchDeployEvents) sends nothing after its +// request, so a gateway host that loses power or a firewall that starts dropping the +// flow (no FIN/RST) used to leave the stream waiting forever — Galaxy stayed Healthy +// serving stale Good values. An unanswered ping now fails the connection within +// delay + timeout (~25 s), the stream faults and the reconnect supervisor takes over. +// 0 disables the pings (the .NET default). public sealed record GalaxyGatewayOptions( string Endpoint, string ApiKeySecretRef, @@ -136,7 +144,9 @@ public sealed record GalaxyGatewayOptions( string? CaCertificatePath = null, int ConnectTimeoutSeconds = 10, int DefaultCallTimeoutSeconds = 30, - int StreamTimeoutSeconds = 0); + int StreamTimeoutSeconds = 0, + int KeepAlivePingDelaySeconds = 15, + int KeepAlivePingTimeoutSeconds = 10); /// /// MXAccess-specific knobs the gateway forwards to the worker process. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs index aff2f9a6f..0fc0d0910 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -190,6 +190,40 @@ public sealed class GalaxyDriver // BuildProductionRuntimeAsync entirely. private GalaxyMxSession? _ownedMxSession; private MxGatewayClient? _ownedMxClient; + // #991 G-19: the keep-alive channels the owned clients run on (a client over a caller-owned channel does not + // dispose it), released after their client in the teardown. + private Grpc.Net.Client.GrpcChannel? _ownedMxChannel; + private Grpc.Net.Client.GrpcChannel? _ownedRepositoryChannel; + + /// A gateway channel with this driver's HTTP/2 keep-alive settings (#991 G-19). + private Grpc.Net.Client.GrpcChannel CreateGatewayChannel(MxGatewayClientOptions clientOptions) => + GalaxyGatewayChannelFactory.CreateChannel(clientOptions, _options.Gateway); + + /// + /// The owned repository client (deploy watch, platform / security seeds, lazy discovery), built once per + /// runtime over a keep-alive channel — WatchDeployEvents is a long-lived server stream too. + /// + private async Task EnsureOwnedRepositoryClientAsync(CancellationToken cancellationToken) + { + if (_ownedRepositoryClient is { } existing) return existing; + var clientOptions = await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false); + if (_ownedRepositoryClient is { } raced) return raced; + var channel = CreateGatewayChannel(clientOptions); + try + { + _ownedRepositoryClient = GalaxyRepositoryClient.Create(channel, clientOptions); + } + catch + { + channel.Dispose(); + throw; + } + _ownedRepositoryChannel = channel; + return _ownedRepositoryClient; + } + + /// Test seam: the keep-alive channel the owned gateway client runs on. + internal Grpc.Net.Client.GrpcChannel? OwnedMxChannelForTests => _ownedMxChannel; // PR 4.5 — reconnect supervisor. Reflects in DriverState.Degraded while not Healthy. private ReconnectSupervisor? _supervisor; @@ -776,14 +810,13 @@ public sealed class GalaxyDriver if (!needPlatform && !needSecurity) return; try { - _ownedRepositoryClient ??= GalaxyRepositoryClient.Create( - await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false)); + var repository = await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false); if (needPlatform) { _ownedPlatformSource = - new GatewayGalaxyPlatformSource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize); + new GatewayGalaxyPlatformSource(repository, _options.Repository.DiscoverPageSize); } - if (needSecurity) _ownedSecuritySource = new GatewayGalaxyAttributeSecuritySource(_ownedRepositoryClient); + if (needSecurity) _ownedSecuritySource = new GatewayGalaxyAttributeSecuritySource(repository); } catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { @@ -1085,10 +1118,14 @@ public sealed class GalaxyDriver _ownsRuntime = true; var clientOptions = await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false); - _ownedMxClient = MxGatewayClient.Create(clientOptions); + // #991 G-19: every long-lived gateway client runs over a channel with HTTP/2 keep-alive pings — the alarm + // feed's StreamAlarms on this one, StreamEvents on the session's own (ChannelFactory below). + _ownedMxChannel = CreateGatewayChannel(clientOptions); + _ownedMxClient = MxGatewayClient.Create(_ownedMxChannel, clientOptions); _ownedMxSession = new GalaxyMxSession(_options.MxAccess, _logger) { OpenAndRegisterOverrideForTests = SessionOpenOverrideForTests, + ChannelFactory = CreateGatewayChannel, }; await _ownedMxSession.ConnectAsync(clientOptions, cancellationToken).ConfigureAwait(false); @@ -1261,6 +1298,10 @@ public sealed class GalaxyDriver _ownedRepositoryClient = null; } + // #991 G-19: the keep-alive channels, after the clients built over them (which do not dispose them). + DisposeChannel(ref _ownedMxChannel, "MxClient"); + DisposeChannel(ref _ownedRepositoryChannel, "RepositoryClient"); + if (_ownsRuntime || final) { // Null the seams so the next InitializeAsync rebuilds (production) — injected seams @@ -1280,6 +1321,15 @@ public sealed class GalaxyDriver } } + private void DisposeChannel(ref Grpc.Net.Client.GrpcChannel? channel, string owner) + { + var c = channel; + channel = null; + if (c is null) return; + try { c.Dispose(); } + catch (Exception ex) { _logger.LogWarning(ex, "{Owner} channel dispose failed", owner); } + } + /// /// Reopen callback for : recreate the gw session. After a /// gateway restart the existing session handle is faulted / stale but non-null, so a plain @@ -1820,9 +1870,8 @@ public sealed class GalaxyDriver // Reuse the lazily-built repository client (DiscoverAsync constructs it on demand). // Build under a null-check (not an overwrite) so if BuildDefaultHierarchySourceAsync // later runs it reuses this client rather than leaking the first instance. - _ownedRepositoryClient ??= GalaxyRepositoryClient.Create( - await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false)); - source = new GatewayGalaxyDeployWatchSource(_ownedRepositoryClient); + source = new GatewayGalaxyDeployWatchSource( + await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false)); } // One watcher per driver: a previous one (an InitializeAsync without a ShutdownAsync in @@ -3705,10 +3754,9 @@ public sealed class GalaxyDriver // than always overwriting the field and leaking the first instance. Both paths // produce equivalent clients from the same options. The client-options build is // async now (secret: arm resolves through the shared ISecretResolver). - _ownedRepositoryClient ??= GalaxyRepositoryClient.Create( - await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false)); + var repository = await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false); return new TracedGalaxyHierarchySource( - new GatewayGalaxyHierarchySource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize), + new GatewayGalaxyHierarchySource(repository, _options.Repository.DiscoverPageSize), _options.MxAccess.ClientName); } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs index 9d859ea1b..52b606c2a 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs @@ -106,7 +106,9 @@ public static class GalaxyDriverFactoryExtensions CaCertificatePath: dto.Gateway.CaCertificatePath, ConnectTimeoutSeconds: dto.Gateway.ConnectTimeoutSeconds ?? 10, DefaultCallTimeoutSeconds: dto.Gateway.DefaultCallTimeoutSeconds ?? 30, - StreamTimeoutSeconds: dto.Gateway.StreamTimeoutSeconds ?? 0), + StreamTimeoutSeconds: dto.Gateway.StreamTimeoutSeconds ?? 0, + KeepAlivePingDelaySeconds: dto.Gateway.KeepAlivePingDelaySeconds ?? 15, + KeepAlivePingTimeoutSeconds: dto.Gateway.KeepAlivePingTimeoutSeconds ?? 10), MxAccess: new GalaxyMxAccessOptions( ClientName: dto.MxAccess?.ClientName ?? throw new InvalidOperationException( @@ -199,6 +201,10 @@ public static class GalaxyDriverFactoryExtensions public int? DefaultCallTimeoutSeconds { get; init; } /// Gets or sets the stream timeout in seconds. public int? StreamTimeoutSeconds { get; init; } + /// Gets or sets the HTTP/2 keep-alive ping interval in seconds (0 = no pings; #991 G-19). + public int? KeepAlivePingDelaySeconds { get; init; } + /// Gets or sets how long an unanswered keep-alive ping may wait before the connection fails. + public int? KeepAlivePingTimeoutSeconds { get; init; } } /// MX Access configuration section. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyGatewayChannelFactory.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyGatewayChannelFactory.cs new file mode 100644 index 000000000..98d78db8b --- /dev/null +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyGatewayChannelFactory.cs @@ -0,0 +1,117 @@ +using System.Net.Http; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using Grpc.Net.Client; +using ZB.MOM.WW.MxGateway.Client; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; + +/// +/// #991 G-19 — builds the gRPC channels the driver's long-lived gateway clients run on, with HTTP/2 keep-alive +/// pings. (mxaccessgw client 0.4.0) builds its own +/// with only ConnectTimeout, so pings are off: a server-streaming call +/// (StreamEvents, StreamAlarms, WatchDeployEvents) sends nothing after its request, and a gateway host that loses +/// power — or a firewall that starts silently dropping the flow — never surfaces a TCP error. The stream waited +/// forever, the reconnect supervisor was never told, and Galaxy stayed Healthy serving stale Good values. +/// +/// +/// +/// With the client PINGs the connection every +/// KeepAlivePingDelaySeconds whether or not a call is active, and fails the connection — and every stream on +/// it — when a PING goes unanswered for KeepAlivePingTimeoutSeconds. The stream's fault then reaches the +/// supervisor exactly like a gateway crash. A PING is answered by the peer's HTTP/2 stack itself (mandatory per +/// RFC 9113 §6.7), so this needs nothing from the gateway; Kestrel applies no client-ping rate policy. +/// +/// +/// ⚠️ The TLS settings below MIRROR the client library's own handler (MxGatewayClient.CreateHttpHandler, +/// 0.4.0): CA-pinned custom-root trust with the host-name check kept, RequireCertificateValidation, and +/// ServerNameOverride. Keep them in step if the client's changes — or, better, retire this once the client +/// exposes keep-alive options itself (the cross-repo half of #991 G-19). +/// +/// +internal static class GalaxyGatewayChannelFactory +{ + /// Builds a channel to ' endpoint with keep-alive pings per . + /// The client options (endpoint, TLS, message limits, logging). + /// The driver's gateway options (keep-alive settings). + /// A channel the caller owns and must dispose after the client built over it. + public static GrpcChannel CreateChannel(MxGatewayClientOptions options, GalaxyGatewayOptions gateway) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(gateway); + options.Validate(); + return GrpcChannel.ForAddress(options.Endpoint, new GrpcChannelOptions + { + HttpHandler = CreateHttpHandler(options, KeepAliveDelay(gateway), KeepAliveTimeout(gateway)), + DisposeHttpClient = true, + LoggerFactory = options.LoggerFactory, + MaxReceiveMessageSize = options.MaxGrpcMessageBytes, + MaxSendMessageSize = options.MaxGrpcMessageBytes, + }); + } + + /// The ping interval; infinite (no pings) when not positive. + internal static TimeSpan KeepAliveDelay(GalaxyGatewayOptions gateway) => + gateway.KeepAlivePingDelaySeconds > 0 ? TimeSpan.FromSeconds(gateway.KeepAlivePingDelaySeconds) : Timeout.InfiniteTimeSpan; + + /// How long an unanswered ping may wait; the .NET default (20 s) when not positive. + internal static TimeSpan KeepAliveTimeout(GalaxyGatewayOptions gateway) => + gateway.KeepAlivePingTimeoutSeconds > 0 ? TimeSpan.FromSeconds(gateway.KeepAlivePingTimeoutSeconds) : TimeSpan.FromSeconds(20); + + /// + /// The handler: the client library's connect-timeout + TLS behaviour, plus keep-alive pings when + /// is finite. + /// + /// The client options. + /// Ping interval; = no pings. + /// Unanswered-ping budget. + /// The configured handler. + internal static SocketsHttpHandler CreateHttpHandler( + MxGatewayClientOptions options, TimeSpan keepAlivePingDelay, TimeSpan keepAlivePingTimeout) + { + var handler = new SocketsHttpHandler + { + ConnectTimeout = options.ConnectTimeout, + }; + if (keepAlivePingDelay != Timeout.InfiniteTimeSpan) + { + handler.KeepAlivePingDelay = keepAlivePingDelay; + handler.KeepAlivePingTimeout = keepAlivePingTimeout; + handler.KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always; + } + + if (!options.UseTls) return handler; + + handler.SslOptions = new SslClientAuthenticationOptions(); + if (!string.IsNullOrWhiteSpace(options.ServerNameOverride)) + { + handler.SslOptions.TargetHost = options.ServerNameOverride; + } + + if (!string.IsNullOrWhiteSpace(options.CaCertificatePath)) + { + var trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath); + handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, _, errors) => + { + if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) return false; + if (certificate is null) return false; + + using var customChain = new X509Chain(); + customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + customChain.ChainPolicy.CustomTrustStore.Add(trustedRoot); + customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; + var toValidate = certificate as X509Certificate2 + ?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert)); + return customChain.Build(toValidate); + }; + } + else if (!options.RequireCertificateValidation) + { + handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true; + } + + return handler; + } +} diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyMxSession.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyMxSession.cs index 75550740a..d8d2e794e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyMxSession.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyMxSession.cs @@ -26,7 +26,15 @@ public sealed class GalaxyMxSession : IAsyncDisposable // Owned gateway client + session — populated when ConnectAsync runs. Tests can leave // them null and exercise the surface via injected IGalaxyDataReader fakes. private MxGatewayClient? _ownedClient; + private Grpc.Net.Client.GrpcChannel? _ownedChannel; private MxGatewaySession? _session; + + /// + /// Optional channel builder (#991 G-19). When set, the owned client runs over the channel it returns (the + /// driver supplies one with HTTP/2 keep-alive pings); the session disposes it after the client. Null = the + /// client library builds its own channel. + /// + internal Func? ChannelFactory { get; init; } private int _serverHandle; private bool _connected; private bool _disposed; @@ -88,7 +96,17 @@ public sealed class GalaxyMxSession : IAsyncDisposable } else { - _ownedClient = MxGatewayClient.Create(clientOptions); + // #991 G-19: over a driver-built channel with HTTP/2 keep-alive pings when one is supplied — the + // client's own handler has none, so a silently dead gateway never faulted StreamEvents. + if (ChannelFactory is { } channelFactory) + { + _ownedChannel = channelFactory(clientOptions); + _ownedClient = MxGatewayClient.Create(_ownedChannel, clientOptions); + } + else + { + _ownedClient = MxGatewayClient.Create(clientOptions); + } _session = await _ownedClient.OpenSessionAsync(cancellationToken: cancellationToken).ConfigureAwait(false); _serverHandle = await _session.RegisterAsync(_options.ClientName, cancellationToken).ConfigureAwait(false); } @@ -209,5 +227,16 @@ public sealed class GalaxyMxSession : IAsyncDisposable catch (Exception ex) { _logger.LogWarning(ex, "GalaxyMxSession client dispose failed (best-effort)"); } _ownedClient = null; } + + if (_ownedChannel is not null) + { + // A client created over a caller-owned channel does not dispose it. + try { _ownedChannel.Dispose(); } + catch (Exception ex) { _logger.LogWarning(ex, "GalaxyMxSession channel dispose failed (best-effort)"); } + _ownedChannel = null; + } } + + /// Test seam: the driver-built channel the owned client runs on, or null. + internal Grpc.Net.Client.GrpcChannel? OwnedChannelForTests => _ownedChannel; } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverFactoryTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverFactoryTests.cs index 99568a20b..77208e69d 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverFactoryTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverFactoryTests.cs @@ -41,6 +41,26 @@ public sealed class GalaxyDriverFactoryTests driver.Options.Reconnect.ReplayOnSessionLost.ShouldBeTrue(); } + /// #991 G-19: keep-alive pings default on (15 s / 10 s) and both knobs bind, 0 included. + [Fact] + public void CreateInstance_BindsKeepAliveKnobs_DefaultingOn() + { + var defaults = GalaxyDriverFactoryExtensions.CreateInstance("g", MinimalConfig).Options.Gateway; + defaults.KeepAlivePingDelaySeconds.ShouldBe(15); + defaults.KeepAlivePingTimeoutSeconds.ShouldBe(10); + + const string json = """ + { + "Gateway": { "Endpoint": "https://mxgw.test:5001", "ApiKeySecretRef": "galaxy:apiKey", + "KeepAlivePingDelaySeconds": 0, "KeepAlivePingTimeoutSeconds": 5 }, + "MxAccess": { "ClientName": "OtOpcUa-A" } + } + """; + var gw = GalaxyDriverFactoryExtensions.CreateInstance("g", json).Options.Gateway; + gw.KeepAlivePingDelaySeconds.ShouldBe(0); + gw.KeepAlivePingTimeoutSeconds.ShouldBe(5); + } + /// lmxopcua#749: the AlarmAck fallback section binds; absent means no fallback. [Fact] public void CreateInstance_BindsAlarmAckFallback() diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverShutdownTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverShutdownTests.cs index 6c2b45481..efc09419a 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverShutdownTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverShutdownTests.cs @@ -319,6 +319,8 @@ public sealed class GalaxyDriverShutdownTests await driver.InitializeAsync("{}", CancellationToken.None); opens.ShouldBe(1); var client = driver.OwnedMxClientForTests.ShouldNotBeNull(); + // #991 G-19: the owned client runs over the driver's keep-alive channel, which the teardown must release. + var channel = driver.OwnedMxChannelForTests.ShouldNotBeNull(); var session = driver.OwnedMxSessionForTests.ShouldNotBeNull(); session.IsConnected.ShouldBeTrue(); driver.SupervisorForTests.ShouldNotBeNull(); @@ -333,6 +335,9 @@ public sealed class GalaxyDriverShutdownTests await Should.ThrowAsync(() => client.OpenSessionAsync(cancellationToken: CancellationToken.None), "the owned gateway channel must be disposed"); driver.OwnedMxClientForTests.ShouldBeNull(); + driver.OwnedMxChannelForTests.ShouldBeNull(); + await Should.ThrowAsync(() => channel.ConnectAsync(CancellationToken.None), + "the keep-alive channel must be disposed with its client (a client over a caller-owned channel does not)"); driver.OwnedMxSessionForTests.ShouldBeNull(); driver.SupervisorForTests.ShouldBeNull(); driver.ProbeWatcherForTests.ShouldBeNull(); diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayChannelKeepAliveTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayChannelKeepAliveTests.cs new file mode 100644 index 000000000..d0958703a --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayChannelKeepAliveTests.cs @@ -0,0 +1,258 @@ +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; + +/// +/// #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 StreamEvents: 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. +/// +public sealed class GatewayChannelKeepAliveTests +{ + /// Keep-alive pings at 1 s with a 1 s budget: a black-holed stream faults within a few seconds. + [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("a fault, not a clean end"); + } + + /// + /// 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). + /// + [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"); + } + + /// The handler carries the pings (policy Always — a stream between events is not an "active request" gap). + [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"); + } + + /// TLS options mirror the client library: no-validation only when asked for, CA pinning otherwise. + [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), + }; + + /// + /// Opens StreamEvents, takes the first event (the connection is proven live), black-holes the proxy, and waits + /// up to 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. + /// + private static async Task 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 */ } + } + } + + /// A gateway whose StreamEvents sends one event and then stays open, silent, until cancelled. + private sealed class FakeGatewayService : MxAccessGateway.MxAccessGatewayBase + { + public override async Task StreamEvents( + StreamEventsRequest request, IServerStreamWriter 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 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(); + 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(); + } + } + + /// + /// Forwards TCP between client and gateway until ; 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. + /// + 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 _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(); + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.csproj b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.csproj index 39628bce8..9e0754867 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.csproj +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.csproj @@ -34,6 +34,13 @@ + + + + + +