fix(grpc): configure Kestrel HTTP/2 keepalive (60 s ping, 10 s timeout) under MxGateway:Protocol (SES-005, #253)
This commit is contained in:
@@ -714,6 +714,19 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
|
||||
builder.Add(
|
||||
$"MxGateway:Protocol:MaxGrpcMessageBytes must be between {MinimumMaxMessageBytes} and {MaximumMaxMessageBytes}.");
|
||||
}
|
||||
|
||||
// Kestrel rejects a non-positive ping delay or timeout, so 0 is the explicit "off" for the
|
||||
// delay only; the timeout must always be a real bound.
|
||||
if (options.Http2KeepAlivePingDelaySeconds is < 0 or > 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
|
||||
|
||||
@@ -3,7 +3,7 @@ using ZB.MOM.WW.MxGateway.Contracts;
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration options for the worker protocol version.
|
||||
/// Configuration options for the worker protocol version and the public gRPC (HTTP/2) transport.
|
||||
/// </summary>
|
||||
public sealed class ProtocolOptions
|
||||
{
|
||||
@@ -14,4 +14,21 @@ public sealed class ProtocolOptions
|
||||
|
||||
/// <summary>Gets or sets the maximum gRPC message size in bytes.</summary>
|
||||
public int MaxGrpcMessageBytes { get; init; } = 16 * 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets how long an HTTP/2 connection may be idle (no frames received) before the
|
||||
/// gateway sends a keepalive PING, in seconds. <c>0</c> disables server pings. Maps to
|
||||
/// Kestrel's <c>Limits.Http2.KeepAlivePingDelay</c>. Without it a client that vanished
|
||||
/// without a FIN or RST (power loss, a firewall or NAT idle drop) holds its
|
||||
/// <c>StreamEvents</c> call, its session and its worker until a write times out, which on a
|
||||
/// quiet session may be never.
|
||||
/// </summary>
|
||||
public int Http2KeepAlivePingDelaySeconds { get; init; } = 60;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <c>Limits.Http2.KeepAlivePingTimeout</c>.
|
||||
/// </summary>
|
||||
public int Http2KeepAlivePingTimeoutSeconds { get; init; } = 10;
|
||||
}
|
||||
|
||||
@@ -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<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>,
|
||||
GatewayKestrelKeepAliveConfiguration>();
|
||||
builder.Services.AddZbSecrets(builder.Configuration, "Secrets");
|
||||
builder.Services.AddSqliteAuthStore(builder.Configuration);
|
||||
builder.Services.AddGatewayGrpcAuthorization();
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Applies the gateway's HTTP/2 keepalive policy (<c>MxGateway:Protocol:Http2KeepAlive*</c>) to
|
||||
/// Kestrel (SES-005).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// 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 <c>StreamEvents</c> call stays open, the session's single
|
||||
/// subscriber slot stays taken — so the real client's resume is refused with
|
||||
/// <c>EventSubscriberAlreadyActive</c> — 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Kestrel has no minimum-client-ping-interval policy (no equivalent of grpc-core's
|
||||
/// <c>GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS</c>): it answers every client
|
||||
/// PING and never sends <c>GOAWAY</c>/<c>ENHANCE_YOUR_CALM</c> 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The section is bound straight from configuration rather than through
|
||||
/// <c>IOptions<GatewayOptions></c>: 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
|
||||
/// <c>OptionsValidationException</c> startup validation reports.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="configuration">The application configuration holding <c>MxGateway:Protocol</c>.</param>
|
||||
public sealed class GatewayKestrelKeepAliveConfiguration(IConfiguration configuration)
|
||||
: IConfigureOptions<KestrelServerOptions>
|
||||
{
|
||||
/// <summary>The configuration section the keepalive options bind from.</summary>
|
||||
public const string SectionName = "MxGateway:Protocol";
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Configure(KestrelServerOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ProtocolOptions protocol = configuration.GetSection(SectionName).Get<ProtocolOptions>() ?? 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;",
|
||||
|
||||
@@ -1330,6 +1330,35 @@ public sealed class GatewayOptionsValidatorTests
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
|
||||
/// <summary>SES-005: the HTTP/2 keepalive knobs are range-checked; a delay of 0 (off) is valid.</summary>
|
||||
/// <param name="delaySeconds">Configured ping delay.</param>
|
||||
/// <param name="timeoutSeconds">Configured ping timeout.</param>
|
||||
/// <param name="valid">Whether validation should pass.</param>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// SES-005: the gateway configures Kestrel's HTTP/2 keepalive from <c>MxGateway:Protocol</c>, and
|
||||
/// Kestrel tolerates the official clients' keepalive pings (every 30 s, also with no call active).
|
||||
/// </summary>
|
||||
public sealed class GatewayKestrelKeepAliveTests
|
||||
{
|
||||
/// <summary>The defaults are the D7 policy: server ping after 60 s idle, 10 s timeout.</summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>Configured values are applied; a delay of 0 turns server pings off.</summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>The real gateway host wires the configuration into its Kestrel options.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GatewayHost_ConfiguresKestrelKeepAlive()
|
||||
{
|
||||
await using WebApplication app = TestGatewayHost.Build("--MxGateway:Protocol:Http2KeepAlivePingDelaySeconds=45");
|
||||
|
||||
KestrelServerOptions kestrel = app.Services.GetRequiredService<IOptions<KestrelServerOptions>>().Value;
|
||||
|
||||
Assert.Equal(TimeSpan.FromSeconds(45), kestrel.Limits.Http2.KeepAlivePingDelay);
|
||||
Assert.Equal(TimeSpan.FromSeconds(10), kestrel.Limits.Http2.KeepAlivePingTimeout);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<IServer>().Features.Get<IServerAddressesFeature>()!.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<string, string?>(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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user