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:
Joseph Doherty
2026-12-03 10:34:51 -05:00
parent d66aa5e9ff
commit afaf6b97d5
9 changed files with 514 additions and 14 deletions
@@ -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;
}