using System.Net; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Logging; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Host.Grpc; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; /// /// H2 review 10: the origin's history session of an HTTP/2 connection must be cleared when Kestrel closes that /// connection. A real in-process Kestrel HTTP/2 (cleartext, loopback) host proves the close hook fires on a stream's /// HttpContext — the path uses. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")] public sealed class GrpcDataHistoryKestrelChannelTests { [Fact] public async Task Closing_the_client_connection_clears_its_history_session() { var ct = TestContext.Current.CancellationToken; var sessions = new OriginHistorySessions(TimeProvider.System); var caller = new DataAuthenticatedContext("peer", "key", "v1", null, 1); var cancellable = false; var builder = WebApplication.CreateSlimBuilder(); builder.Logging.ClearProviders(); builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0, o => o.Protocols = HttpProtocols.Http2)); await using var app = builder.Build(); app.MapGet("/probe", (HttpContext http) => { var channel = DataConnectionGrpcService.ChannelOf(http); cancellable = channel.Closed.CanBeCanceled; sessions.Get(caller, channel, 4); return Results.Ok(channel.ChannelId); }); await app.StartAsync(ct); var address = app.Urls.Single(); var client = new HttpClient(new SocketsHttpHandler()) { DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact }; (await client.GetAsync(address + "/probe", ct)).StatusCode.ShouldBe(HttpStatusCode.OK); (await client.GetAsync(address + "/probe", ct)).StatusCode.ShouldBe(HttpStatusCode.OK); cancellable.ShouldBeTrue("Kestrel exposes IConnectionLifetimeFeature.ConnectionClosed on an HTTP/2 stream"); sessions.Count.ShouldBe(1, "two requests on one HTTP/2 connection share one session"); client.Dispose(); // closes the TCP/HTTP2 connection var until = DateTime.UtcNow.AddSeconds(15); while (sessions.Count != 0 && DateTime.UtcNow < until) await Task.Delay(20, ct); sessions.Count.ShouldBe(0, "the connection close cleared the session"); await app.StopAsync(ct); } }