Repository navigation
feat: add optional IHttpClientHintsFeature middleware, enforce 100% coverage - #22
Merged
Merged
Conversation
app.UseHttpClientHintsFeature() registers IHttpClientHintsFeature in HttpContext.Features for every request. The feature exposes View and Snapshot, which return the same values as GetClientHintsView() and GetClientHints(). The middleware does not need AddHttpClientHints() or UseHttpClientHints(), and applications that do not call it are not affected. Closes #2
The middleware stays async, so a synchronous exception of the next middleware still results in a faulted task and AsyncLocal changes of the next middleware do not flow back to the caller. New tests cover both and the use of configuration values changed after construction. The file is now UTF-8 instead of ISO-8859-1. Adds middleware benchmarks.
Assert-CodeCoverage.ps1 now fails if MyCSharp.HttpClientHints or MyCSharp.HttpClientHints.AspNetCore is missing from the report or below the threshold. The threshold is 100% in CI, the Justfile, and the script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #2.
This PR adds
IHttpClientHintsFeatureand an optional middleware,app.UseHttpClientHintsFeature(), that registers the feature inHttpContext.Featuresfor every request. Middleware and handlers after it can read the Client Hints withHttpContext.Features.Get<IHttpClientHintsFeature>(). Applications that do not callUseHttpClientHintsFeature()are not affected.The PR also raises the coverage requirement from 90% to 100% for each package, and the Accept-CH middleware now reads the response headers once. The version goes from 3.2 to 3.3.
Changes
Library (
MyCSharp.HttpClientHints.AspNetCore)IHttpClientHintsFeature(public, new)Viewis the same ashttpContext.GetClientHintsView().Snapshotis the same ashttpContext.GetClientHints(), including the instance that is cached for the request.HttpClientHintsFeature(internal sealed, new): the default implementation.HttpContext, so it has the minimum object size of 24 B on x64.ViewandSnapshotcall the existing extension methods and compute nothing up front.UseHttpClientHintsFeature()(public, new) andHttpClientHintsFeatureMiddleware(internal sealed, new)Accept-CHis configured.AddHttpClientHints()norUseHttpClientHints().app.Use(...)and needs no reflection.HttpClientHintsRequestMiddlewarecontext.Response.Headersonce instead of twice. Its behavior does not change: it staysasyncand reads the configuration on every request.©in the header comment was broken.HttpClientHintsOptions,HttpClientHintsMiddlewareConfig, andAddHttpClientHints()are unchanged.Tests
HttpClientHintsFeatureTestscovers:AddHttpClientHints(), and together withUseHttpClientHints().UseHttpClientHints()alone does not register the feature.Viewreads the current headers.Snapshotis the instance thatGetClientHints()returns, also when it was created before the registration.Snapshotkeeps its values, whileSnapshot.Headersshows later header changes.HttpClientHintsRequestMiddlewareTestspin down existing behavior of the Accept-CH middleware:AsyncLocalchanges of the next middleware do not flow back to the caller.CI and tooling
build-and-test.yml, theJustfile, and the default ofeng/Assert-CodeCoverage.ps1.-RequiredPackages, with both packages as default. It fails when a package is missing from the report or below the threshold. Before, a report with onlyMyCSharp.HttpClientHintspassed with 100%.Benchmarks
HttpClientHintsMiddlewareBenchmarksruns pipelines built withApplicationBuilder:UseHttpClientHints()alone.UseHttpClientHintsFeature()alone.View.Mobile.Documentation and sample
Snapshot.Headersshows later header changes.MyCSharp.HttpClientHints.AspNetCorementions the middleware.app.UseHttpClientHintsFeature()and reads the snapshot from the feature.Notes for reviewers
AddHttpClientHints(): Applications that do not use the feature pay nothing, not even a flag check per request. The Accept-CH middleware keeps its behavior, and the feature also works in applications that do not sendAccept-CH.Accept-CH: Browsers send some Client Hints, such asSec-CH-UA,Sec-CH-UA-Mobile, andSec-CH-UA-Platform, without being asked.UseHttpClientHints(), the pipeline takes about 19 ns more thanUseHttpClientHints()alone.Features.Setchanges the revision of the feature collection, soHttpContextlooks up the features it has cached again. These numbers come from a reusedDefaultHttpContext. In a separate test with Kestrel on .NET 11, the registration allocated 24 B or 112 B per request, depending on whether Kestrel reused its request object. The README states both.async: It returns the task of the next middleware directly, like many middlewares in ASP.NET Core. If the next middleware throws synchronously, the exception propagates fromInvokeAsyncinstead of as a faulted task. It is a new middleware, so no existing caller depends on the other behavior.asyncon purpose: Returning the task of the next middleware directly would save 118 B per request when the rest of the pipeline completes asynchronously. Measured with a copy of the middleware: 96 B instead of 214 B. It would also change two observable behaviors: a synchronous exception of the next middleware would propagate fromInvokeAsyncinstead of as a faulted task, andAsyncLocalchanges of the next middleware would flow back to the caller. That would need a separate decision, so this PR leaves it out. The new tests fail if one of the two behaviors changes.IHttpClientHintsFeatureregistered earlier. Applications that need their own implementation register it afterUseHttpClientHintsFeature().HttpContext, so it must not be kept beyond the request.Testing
dotnet build -c Release: 0 warnings, 0 errors, withTreatWarningsAsErrorsenabled.dotnet test -c Release --no-build --results-directory TestResults --results-directory-layout per-module -- --coverage --coverage-output-format cobertura: 296 tests passed onnet8.0,net9.0,net10.0, andnet11.0../eng/Assert-CodeCoverage.ps1 -ResultsDirectory TestResults: 100.00% line and branch coverage forMyCSharp.HttpClientHintsand forMyCSharp.HttpClientHints.AspNetCore.MyCSharp.HttpClientHints.AspNetCorepackage.dotnet format --verify-no-changes: no changes.net11.0, requested withcurl:Sec-CH-UA-Platform: "Windows"andSec-CH-UA-Mobile: ?0, it returns HTTP 200 withAccept-CHandAccept-CH-Lifetime. The page shows"Windows"next toWindowsandFalsefor mobile, read fromIHttpClientHintsFeature.Snapshot.Benchmark
AMD Ryzen 9 9950X, Windows 10 x64, .NET SDK 11.0.100, .NET 11.0.0, BenchmarkDotNet 0.16.0-preview.2,
--iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6. Both tables are in the README.UseHttpClientHints()UseHttpClientHintsFeature()UseHttpClientHintsFeature()and readView.MobileAccept-CH middleware compared with a copy of the version on
main, measured side by side in one session:mainTask.Yield)With the asynchronous next middleware,
Task.Yielddominates the time and both versions are within the noise.This PR does not change the code that the "Reading Client Hints" benchmarks run. Their new results differ from the ones on
mainby at most 1.1 ns or 2.6% per benchmark, which is variation between the two runs.Reproduce
dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6