fix(galaxy): #991 G-19 gateway channels send HTTP/2 keep-alive pings so a silently dead connection faults the event stream
This commit is contained in:
@@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// MXAccess-specific knobs the gateway forwards to the worker process.
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A gateway channel with this driver's HTTP/2 keep-alive settings (#991 G-19).</summary>
|
||||
private Grpc.Net.Client.GrpcChannel CreateGatewayChannel(MxGatewayClientOptions clientOptions) =>
|
||||
GalaxyGatewayChannelFactory.CreateChannel(clientOptions, _options.Gateway);
|
||||
|
||||
/// <summary>
|
||||
/// The owned repository client (deploy watch, platform / security seeds, lazy discovery), built once per
|
||||
/// runtime over a keep-alive channel — <c>WatchDeployEvents</c> is a long-lived server stream too.
|
||||
/// </summary>
|
||||
private async Task<GalaxyRepositoryClient> 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;
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the keep-alive channel the owned gateway client runs on.</summary>
|
||||
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); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reopen callback for <see cref="ReconnectSupervisor"/>: 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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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; }
|
||||
/// <summary>Gets or sets the stream timeout in seconds.</summary>
|
||||
public int? StreamTimeoutSeconds { get; init; }
|
||||
/// <summary>Gets or sets the HTTP/2 keep-alive ping interval in seconds (0 = no pings; #991 G-19).</summary>
|
||||
public int? KeepAlivePingDelaySeconds { get; init; }
|
||||
/// <summary>Gets or sets how long an unanswered keep-alive ping may wait before the connection fails.</summary>
|
||||
public int? KeepAlivePingTimeoutSeconds { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>MX Access configuration section.</summary>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-19 — builds the gRPC channels the driver's long-lived gateway clients run on, with HTTP/2 keep-alive
|
||||
/// pings. <see cref="MxGatewayClient.Create(MxGatewayClientOptions)"/> (mxaccessgw client 0.4.0) builds its own
|
||||
/// <see cref="SocketsHttpHandler"/> with only <c>ConnectTimeout</c>, 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// With <see cref="HttpKeepAlivePingPolicy.Always"/> the client PINGs the connection every
|
||||
/// <c>KeepAlivePingDelaySeconds</c> whether or not a call is active, and fails the connection — and every stream on
|
||||
/// it — when a PING goes unanswered for <c>KeepAlivePingTimeoutSeconds</c>. 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// ⚠️ The TLS settings below MIRROR the client library's own handler (<c>MxGatewayClient.CreateHttpHandler</c>,
|
||||
/// 0.4.0): CA-pinned custom-root trust with the host-name check kept, <c>RequireCertificateValidation</c>, and
|
||||
/// <c>ServerNameOverride</c>. 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).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class GalaxyGatewayChannelFactory
|
||||
{
|
||||
/// <summary>Builds a channel to <paramref name="options"/>' endpoint with keep-alive pings per <paramref name="gateway"/>.</summary>
|
||||
/// <param name="options">The client options (endpoint, TLS, message limits, logging).</param>
|
||||
/// <param name="gateway">The driver's gateway options (keep-alive settings).</param>
|
||||
/// <returns>A channel the caller owns and must dispose after the client built over it.</returns>
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The ping interval; infinite (no pings) when not positive.</summary>
|
||||
internal static TimeSpan KeepAliveDelay(GalaxyGatewayOptions gateway) =>
|
||||
gateway.KeepAlivePingDelaySeconds > 0 ? TimeSpan.FromSeconds(gateway.KeepAlivePingDelaySeconds) : Timeout.InfiniteTimeSpan;
|
||||
|
||||
/// <summary>How long an unanswered ping may wait; the .NET default (20 s) when not positive.</summary>
|
||||
internal static TimeSpan KeepAliveTimeout(GalaxyGatewayOptions gateway) =>
|
||||
gateway.KeepAlivePingTimeoutSeconds > 0 ? TimeSpan.FromSeconds(gateway.KeepAlivePingTimeoutSeconds) : TimeSpan.FromSeconds(20);
|
||||
|
||||
/// <summary>
|
||||
/// The handler: the client library's connect-timeout + TLS behaviour, plus keep-alive pings when
|
||||
/// <paramref name="keepAlivePingDelay"/> is finite.
|
||||
/// </summary>
|
||||
/// <param name="options">The client options.</param>
|
||||
/// <param name="keepAlivePingDelay">Ping interval; <see cref="Timeout.InfiniteTimeSpan"/> = no pings.</param>
|
||||
/// <param name="keepAlivePingTimeout">Unanswered-ping budget.</param>
|
||||
/// <returns>The configured handler.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal Func<MxGatewayClientOptions, Grpc.Net.Client.GrpcChannel>? 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the driver-built channel the owned client runs on, or null.</summary>
|
||||
internal Grpc.Net.Client.GrpcChannel? OwnedChannelForTests => _ownedChannel;
|
||||
}
|
||||
|
||||
@@ -41,6 +41,26 @@ public sealed class GalaxyDriverFactoryTests
|
||||
driver.Options.Reconnect.ReplayOnSessionLost.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>#991 G-19: keep-alive pings default on (15 s / 10 s) and both knobs bind, 0 included.</summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#749: the AlarmAck fallback section binds; absent means no fallback.</summary>
|
||||
[Fact]
|
||||
public void CreateInstance_BindsAlarmAckFallback()
|
||||
|
||||
+5
@@ -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<ObjectDisposedException>(() => client.OpenSessionAsync(cancellationToken: CancellationToken.None),
|
||||
"the owned gateway channel must be disposed");
|
||||
driver.OwnedMxClientForTests.ShouldBeNull();
|
||||
driver.OwnedMxChannelForTests.ShouldBeNull();
|
||||
await Should.ThrowAsync<ObjectDisposedException>(() => 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();
|
||||
|
||||
+258
@@ -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;
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
@@ -34,6 +34,13 @@
|
||||
<!-- Client package: only the Skip-gated live alarm-feed smoke (GatewayGalaxyAlarmFeedLiveTests)
|
||||
constructs a real MxGatewayClient. Unit tests use the fake stream-factory seam. -->
|
||||
<PackageReference Include="ZB.MOM.WW.MxGateway.Client" />
|
||||
<!-- #991 G-19: an in-process gRPC gateway behind a black-holing TCP proxy proves the keep-alive channel
|
||||
faults a silently dead StreamEvents (and that the client library's own channel does not). -->
|
||||
<PackageReference Include="Grpc.AspNetCore" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user