diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 2211b5d6..d79bd9e0 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -75,7 +75,9 @@ paths, timeouts, queue sizes, enum values, or protocol values are invalid. }, "Protocol": { "WorkerProtocolVersion": 1, - "MaxGrpcMessageBytes": 16777216 + "MaxGrpcMessageBytes": 16777216, + "Http2KeepAlivePingDelaySeconds": 60, + "Http2KeepAlivePingTimeoutSeconds": 10 }, "Galaxy": { "ConnectionString": "Server=localhost;Database=ZB;Integrated Security=True;TrustServerCertificate=True;Encrypt=False;", @@ -440,8 +442,12 @@ is **not yet available**. |--------|---------|-------------| | `MxGateway:Protocol:WorkerProtocolVersion` | `1` | Worker IPC protocol version expected by the gateway and worker. This must match `GatewayContractInfo.WorkerProtocolVersion`. | | `MxGateway:Protocol:MaxGrpcMessageBytes` | `16777216` | Public gRPC max send and receive message size in bytes. The same default is used by official clients. The validator allows values from `1024` through `268435456`, and requires `MxGateway:Worker:MaxMessageBytes` to exceed this by at least the 64 KiB worker-frame envelope reserve and by no more than twice that reserve, so a `DrainEvents` reply budgeted at the pipe maximum still fits this send cap (see the Worker options). | +| `MxGateway:Protocol:Http2KeepAlivePingDelaySeconds` | `60` | Seconds an HTTP/2 connection may go without receiving a frame before the gateway sends a keepalive PING (Kestrel `Limits.Http2.KeepAlivePingDelay`). `0` turns server pings off. Must be between `0` and `86400`. Without server pings, a client that vanished without closing its connection (power loss, a firewall or NAT idle drop) keeps its `StreamEvents` call open on a quiet session indefinitely: the session's subscriber slot stays taken, so the client's own resume is refused with `ResourceExhausted` (`EventSubscriberAlreadyActive`), and the session and its x86 worker are never swept. With pings, the dead peer is detected within the delay plus the timeout and the subscriber detaches. | +| `MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds` | `10` | Seconds the gateway waits for any frame after a keepalive PING before it closes the connection (Kestrel `Limits.Http2.KeepAlivePingTimeout`). Must be between `1` and `3600`. | -The protocol option is exposed for diagnostics and explicit deployment +Client keepalive pings need no server setting. Kestrel has no minimum client-ping interval (unlike grpc-core and grpc-go servers, it never answers frequent pings with `GOAWAY`/`ENHANCE_YOUR_CALM`), it answers pings with or without an active call, and a received ping resets the connection's idle keep-alive timeout. The official clients ping every 30 s with a 10 s timeout, also while no call is active, which keeps an idle connection open and detects a dead gateway from the client side. + +The worker protocol version option is exposed for diagnostics and explicit deployment configuration, not for compatibility negotiation. A mismatch fails validation at startup. diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs index 2acd8fcc..67bd806e 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs @@ -714,6 +714,19 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase 86400) + { + builder.Add( + "MxGateway:Protocol:Http2KeepAlivePingDelaySeconds must be between 0 (disabled) and 86400."); + } + + if (options.Http2KeepAlivePingTimeoutSeconds is < 1 or > 3600) + { + builder.Add("MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds must be between 1 and 3600."); + } } // The worker-frame (pipe) maximum must stay above the public gRPC cap by the envelope-overhead diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/ProtocolOptions.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/ProtocolOptions.cs index 5a983f5c..8f6e9558 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/ProtocolOptions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/ProtocolOptions.cs @@ -3,7 +3,7 @@ using ZB.MOM.WW.MxGateway.Contracts; namespace ZB.MOM.WW.MxGateway.Server.Configuration; /// -/// Configuration options for the worker protocol version. +/// Configuration options for the worker protocol version and the public gRPC (HTTP/2) transport. /// public sealed class ProtocolOptions { @@ -14,4 +14,21 @@ public sealed class ProtocolOptions /// Gets or sets the maximum gRPC message size in bytes. public int MaxGrpcMessageBytes { get; init; } = 16 * 1024 * 1024; + + /// + /// Gets or sets how long an HTTP/2 connection may be idle (no frames received) before the + /// gateway sends a keepalive PING, in seconds. 0 disables server pings. Maps to + /// Kestrel's Limits.Http2.KeepAlivePingDelay. Without it a client that vanished + /// without a FIN or RST (power loss, a firewall or NAT idle drop) holds its + /// StreamEvents call, its session and its worker until a write times out, which on a + /// quiet session may be never. + /// + public int Http2KeepAlivePingDelaySeconds { get; init; } = 60; + + /// + /// Gets or sets how long the gateway waits for any frame after sending a keepalive PING + /// before it closes the connection, in seconds. Maps to Kestrel's + /// Limits.Http2.KeepAlivePingTimeout. + /// + public int Http2KeepAlivePingTimeoutSeconds { get; init; } = 10; } diff --git a/src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs b/src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs index 312ef0f8..ffa60325 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs @@ -110,6 +110,9 @@ public static class GatewayApplication builder.AddZbSerilog(o => o.ServiceName = "mxgateway"); builder.Services.AddGatewayConfiguration(builder.Configuration); + builder.Services.AddSingleton< + Microsoft.Extensions.Options.IConfigureOptions, + GatewayKestrelKeepAliveConfiguration>(); builder.Services.AddZbSecrets(builder.Configuration, "Secrets"); builder.Services.AddSqliteAuthStore(builder.Configuration); builder.Services.AddGatewayGrpcAuthorization(); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Grpc/GatewayKestrelKeepAliveConfiguration.cs b/src/ZB.MOM.WW.MxGateway.Server/Grpc/GatewayKestrelKeepAliveConfiguration.cs new file mode 100644 index 00000000..84c5f7b8 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Grpc/GatewayKestrelKeepAliveConfiguration.cs @@ -0,0 +1,63 @@ +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.MxGateway.Server.Configuration; + +namespace ZB.MOM.WW.MxGateway.Server.Grpc; + +/// +/// Applies the gateway's HTTP/2 keepalive policy (MxGateway:Protocol:Http2KeepAlive*) to +/// Kestrel (SES-005). +/// +/// +/// +/// Kestrel's HTTP/2 keepalive ping is off unless configured. A client that disappears +/// without closing its connection (host power loss, a firewall or NAT idle drop, a pulled +/// cable) is otherwise noticed only when a write times out at the TCP layer, and a quiet +/// session writes nothing: its StreamEvents call stays open, the session's single +/// subscriber slot stays taken — so the real client's resume is refused with +/// EventSubscriberAlreadyActive — and the session and its x86 worker are never +/// swept. With the ping on, a dead peer is detected within the delay plus the timeout, +/// the call's token fires, and the subscriber detaches. +/// +/// +/// Kestrel has no minimum-client-ping-interval policy (no equivalent of grpc-core's +/// GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS): it answers every client +/// PING and never sends GOAWAY/ENHANCE_YOUR_CALM for ping rate, with or without +/// an active call. A received PING also resets the connection's idle keep-alive timeout, +/// so client keepalive pings (the official clients send one every 30 s, also with no call +/// active) keep an otherwise idle connection open. There is therefore nothing to configure +/// on the server side for client pings. +/// +/// +/// The section is bound straight from configuration rather than through +/// IOptions<GatewayOptions>: Kestrel resolves its options while the server is +/// constructed, and reading the validated gateway options there would surface any +/// configuration error from inside Kestrel's construction instead of as the +/// OptionsValidationException startup validation reports. +/// +/// +/// The application configuration holding MxGateway:Protocol. +public sealed class GatewayKestrelKeepAliveConfiguration(IConfiguration configuration) + : IConfigureOptions +{ + /// The configuration section the keepalive options bind from. + public const string SectionName = "MxGateway:Protocol"; + + /// + public void Configure(KestrelServerOptions options) + { + ArgumentNullException.ThrowIfNull(options); + ProtocolOptions protocol = configuration.GetSection(SectionName).Get() ?? new ProtocolOptions(); + + // Out-of-range values are rejected by GatewayOptionsValidator at startup; the guards here + // only keep Kestrel's own setters from throwing before that validation reports. + options.Limits.Http2.KeepAlivePingDelay = protocol.Http2KeepAlivePingDelaySeconds > 0 + ? TimeSpan.FromSeconds(protocol.Http2KeepAlivePingDelaySeconds) + : TimeSpan.MaxValue; + if (protocol.Http2KeepAlivePingTimeoutSeconds > 0) + { + options.Limits.Http2.KeepAlivePingTimeout = TimeSpan.FromSeconds(protocol.Http2KeepAlivePingTimeoutSeconds); + } + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/appsettings.json b/src/ZB.MOM.WW.MxGateway.Server/appsettings.json index 93489ca4..d440e6e2 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/appsettings.json +++ b/src/ZB.MOM.WW.MxGateway.Server/appsettings.json @@ -90,7 +90,9 @@ }, "Protocol": { "WorkerProtocolVersion": 1, - "MaxGrpcMessageBytes": 16777216 + "MaxGrpcMessageBytes": 16777216, + "Http2KeepAlivePingDelaySeconds": 60, + "Http2KeepAlivePingTimeoutSeconds": 10 }, "Galaxy": { "ConnectionString": "Server=localhost;Database=ZB;Integrated Security=True;TrustServerCertificate=True;Encrypt=False;", diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs index cfeebb46..44fc7d80 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs @@ -1330,6 +1330,35 @@ public sealed class GatewayOptionsValidatorTests Assert.True(result.Succeeded); } + /// SES-005: the HTTP/2 keepalive knobs are range-checked; a delay of 0 (off) is valid. + /// Configured ping delay. + /// Configured ping timeout. + /// Whether validation should pass. + [Theory] + [InlineData(60, 10, true)] + [InlineData(0, 10, true)] + [InlineData(86400, 3600, true)] + [InlineData(-1, 10, false)] + [InlineData(86401, 10, false)] + [InlineData(60, 0, false)] + [InlineData(60, 3601, false)] + public void Validate_Http2KeepAlive_IsRangeChecked(int delaySeconds, int timeoutSeconds, bool valid) + { + GatewayOptions options = WithWorkerAndProtocol( + new WorkerOptions(), + new ProtocolOptions + { + Http2KeepAlivePingDelaySeconds = delaySeconds, + Http2KeepAlivePingTimeoutSeconds = timeoutSeconds, + }); + + ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options); + + bool keepAliveFailure = result.Failed + && result.Failures!.Any(f => f.Contains("Http2KeepAlive", StringComparison.Ordinal)); + Assert.Equal(!valid, keepAliveFailure); + } + /// /// Verifies that a worker-frame maximum equal to the gRPC cap (zero headroom) fails validation: /// a maximally-sized accepted gRPC payload would not fit one worker frame once wrapped in a diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/GatewayKestrelKeepAliveTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/GatewayKestrelKeepAliveTests.cs new file mode 100644 index 00000000..c28c71c6 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/GatewayKestrelKeepAliveTests.cs @@ -0,0 +1,122 @@ +using System.Net; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.MxGateway.Server.Grpc; +using ZB.MOM.WW.MxGateway.Tests.TestSupport; + +namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Grpc; + +/// +/// SES-005: the gateway configures Kestrel's HTTP/2 keepalive from MxGateway:Protocol, and +/// Kestrel tolerates the official clients' keepalive pings (every 30 s, also with no call active). +/// +public sealed class GatewayKestrelKeepAliveTests +{ + /// The defaults are the D7 policy: server ping after 60 s idle, 10 s timeout. + [Fact] + public void Configure_WithDefaults_AppliesSixtySecondDelayAndTenSecondTimeout() + { + KestrelServerOptions kestrel = new(); + + new GatewayKestrelKeepAliveConfiguration(Config()).Configure(kestrel); + + Assert.Equal(TimeSpan.FromSeconds(60), kestrel.Limits.Http2.KeepAlivePingDelay); + Assert.Equal(TimeSpan.FromSeconds(10), kestrel.Limits.Http2.KeepAlivePingTimeout); + } + + /// Configured values are applied; a delay of 0 turns server pings off. + [Fact] + public void Configure_WithZeroDelay_DisablesServerPings() + { + KestrelServerOptions kestrel = new(); + new GatewayKestrelKeepAliveConfiguration(Config( + ("MxGateway:Protocol:Http2KeepAlivePingDelaySeconds", "0"), + ("MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds", "25"))) + .Configure(kestrel); + + Assert.Equal(TimeSpan.MaxValue, kestrel.Limits.Http2.KeepAlivePingDelay); + Assert.Equal(TimeSpan.FromSeconds(25), kestrel.Limits.Http2.KeepAlivePingTimeout); + } + + /// The real gateway host wires the configuration into its Kestrel options. + /// A task that represents the asynchronous operation. + [Fact] + public async Task GatewayHost_ConfiguresKestrelKeepAlive() + { + await using WebApplication app = TestGatewayHost.Build("--MxGateway:Protocol:Http2KeepAlivePingDelaySeconds=45"); + + KestrelServerOptions kestrel = app.Services.GetRequiredService>().Value; + + Assert.Equal(TimeSpan.FromSeconds(45), kestrel.Limits.Http2.KeepAlivePingDelay); + Assert.Equal(TimeSpan.FromSeconds(10), kestrel.Limits.Http2.KeepAlivePingTimeout); + } + + /// + /// Kestrel accepts client keepalive pings on a connection with no active call without a + /// GOAWAY, and the pings keep the idle connection open past Kestrel's idle keep-alive + /// timeout: the second request reuses the first request's connection. A client that does + /// not ping is the control — its idle connection is closed and the second request lands on a + /// new one, so the test can tell the two apart. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ClientPingsWithNoActiveCall_AreAcceptedAndKeepTheIdleConnectionOpen() + { + WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.UseKestrel(options => + { + options.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(2); + options.Listen(IPAddress.Loopback, 0, listen => listen.Protocols = HttpProtocols.Http2); + }); + await using WebApplication app = builder.Build(); + app.MapGet("/connection", (HttpContext context) => context.Connection.Id); + await app.StartAsync(); + string address = app.Services.GetRequiredService().Features.Get()!.Addresses.First(); + + Task<(string First, string Second)> pinging = TwoRequestsAcrossIdleGapAsync(address, ping: true); + Task<(string First, string Second)> silent = TwoRequestsAcrossIdleGapAsync(address, ping: false); + (string pingFirst, string pingSecond) = await pinging; + (string silentFirst, string silentSecond) = await silent; + + Assert.Equal(pingFirst, pingSecond); + Assert.NotEqual(silentFirst, silentSecond); + await app.StopAsync(); + } + + private static IConfiguration Config(params (string Key, string Value)[] values) + => new ConfigurationBuilder() + .AddInMemoryCollection(values.Select(pair => new KeyValuePair(pair.Key, pair.Value))) + .Build(); + + private static async Task<(string First, string Second)> TwoRequestsAcrossIdleGapAsync(string address, bool ping) + { + using SocketsHttpHandler handler = new() + { + KeepAlivePingDelay = ping ? TimeSpan.FromSeconds(1) : Timeout.InfiniteTimeSpan, + KeepAlivePingTimeout = TimeSpan.FromSeconds(5), + KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, + PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5), + }; + using HttpClient client = new(handler) + { + BaseAddress = new Uri(address), + DefaultRequestVersion = HttpVersion.Version20, + DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact, + Timeout = TimeSpan.FromSeconds(10), + }; + + string first = await client.GetStringAsync("/connection"); + await Task.Delay(TimeSpan.FromSeconds(4.5)); + string second = await client.GetStringAsync("/connection"); + return (first, second); + } +}