Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ jobs:

- name: Check code coverage
shell: pwsh
run: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory TestResults -Threshold 90
run: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory TestResults -Threshold 100

- name: Upload test results
if: always() && inputs.upload-test-results
Expand Down
2 changes: 1 addition & 1 deletion Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ CONFIG := "Debug"
TFM := "net11.0"
BENCH_PRJ := "perf/HttpClientHints.Benchmarks/HttpClientHints.Benchmarks.csproj"
COV_DIR := "TestResults/coverage"
COV_MIN := "90"
COV_MIN := "100"

# ===== Default / Help =====
default: help
Expand Down
68 changes: 56 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ app.UseRouting();
...
```

The client hints are not read by a separate dependency injection registration, but as an extension method to the header collection or to the HttpContext object.
The client hints are not read by a separate dependency injection registration, but as an extension method to the header collection or to the HttpContext object. Optionally, a separate middleware also provides them as an `HttpContext` feature, see [HttpContext feature](#httpcontext-feature).

```csharp
using MyCSharp.HttpClientHints.AspNetCore;
Expand All @@ -72,6 +72,35 @@ bool? isMobile = view.Mobile;

Since potentially all client hints are optional, all properties are potentially nullable, which means that the client has not provided this data.

## HttpContext feature

Since 3.3, you can register `IHttpClientHintsFeature` in `HttpContext.Features` with a separate middleware. Add it only if you want to read the Client Hints through the feature:

```csharp
app.UseHttpClientHints();

// Optional: provide IHttpClientHintsFeature in HttpContext.Features
app.UseHttpClientHintsFeature();
```

`UseHttpClientHintsFeature()` does not require `AddHttpClientHints()` or `UseHttpClientHints()`. Every middleware and handler after it can read the Client Hints from the feature:

```csharp
IHttpClientHintsFeature? feature = httpContext.Features.Get<IHttpClientHintsFeature>();
bool? isMobile = feature?.View.Mobile;
```

| Property | Same as |
| --- | --- |
| `View` | `httpContext.GetClientHintsView()` |
| `Snapshot` | `httpContext.GetClientHints()`, including the cached instance |

`Snapshot` keeps the values read on the first access. `Snapshot.Headers` references the request headers, so it shows later changes to them.

The middleware registers the feature for every request, whether or not `Accept-CH` is configured, because browsers send some Client Hints such as `Sec-CH-UA-Mobile` without a request. The registration replaces an `IHttpClientHintsFeature` registered earlier in the pipeline. Register your own implementation after `app.UseHttpClientHintsFeature()`. The feature references the `HttpContext`, so do not keep it beyond the request.

Without `UseHttpClientHintsFeature()`, requests have no additional cost, and `Features.Get<IHttpClientHintsFeature>()` returns `null`. The extension methods work in both cases. With it, the feature is created for every request, even if no handler reads it. In the [benchmark](#benchmark), which reuses one `DefaultHttpContext`, the feature middleware takes about 12 ns and allocates 24 B per request. Together with `UseHttpClientHints()`, the pipeline takes about 19 ns more than `UseHttpClientHints()` alone, because `HttpContext` looks up its cached features again after the registration. The cost depends on the server: in a test with Kestrel on .NET 11, the registration allocated 24 B or 112 B per request, depending on whether Kestrel reused its request object.

## Decoded values

Browsers send `Sec-CH-UA-Platform`, `Sec-CH-UA-Platform-Version`, `Sec-CH-UA-Arch`, and `Sec-CH-UA-Model` as quoted strings, for example `Sec-CH-UA-Platform: "Windows"`. `Platform`, `PlatformVersion`, `Architecture`, and `Model` return these header values as sent, including the quotes. Since 3.2, the matching `Decoded*` properties return the value without quotes and escapes.
Expand Down Expand Up @@ -145,7 +174,7 @@ dotnet build -c Release
dotnet test -c Release --no-build
```

Line and branch coverage must stay at or above 90 %. CI collects coverage on every build and fails below this threshold. Run the same check locally with `just test-cov`, or call `./eng/Assert-CodeCoverage.ps1` after a test run with `--coverage --coverage-output-format cobertura`.
Line and branch coverage of both packages must stay at 100 %. CI collects coverage on every build and fails below this threshold. Run the same check locally with `just test-cov`, or call `./eng/Assert-CodeCoverage.ps1` after a test run with `--coverage --coverage-output-format cobertura`.

## Release

Expand All @@ -161,12 +190,12 @@ The workflow requires a Trusted Publishing policy on NuGet.org for the `MyCSharp

## Benchmark

Reading header values from the view does not allocate, and a snapshot allocates only the record. A `Decoded*` property allocates the decoded string of a quoted value on every access. Run the benchmarks with `dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6`.
Run the benchmarks with `dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6`. Both tables below come from one run of this command.

```
BenchmarkDotNet v0.16.0-preview.2, Windows 10 (10.0.19045.7846/22H2/2022Update)
AMD Ryzen 9 9950X 4.30GHz, 1 CPU, 32 logical and 16 physical cores
Memory: 61,64 GB Total, 31,05 GB Available
Memory: 61,64 GB Total, 35,59 GB Available
.NET SDK 11.0.100
[Host] : .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4
Job-ZRYWOI : .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4
Expand All @@ -175,14 +204,29 @@ IterationCount=15 IterationTime=200ms LaunchCount=2
WarmupCount=6
```

| Method | Mean | Error | StdDev | Gen0 | Allocated |
|-------------------------------------- |----------:|----------:|----------:|-------:|----------:|
| ReadViewProperties | 18.956 ns | 0.3872 ns | 0.5299 ns | - | - |
| ReadDecodedViewProperties | 36.646 ns | 0.5085 ns | 0.6961 ns | 0.0042 | 72 B |
| GetClientHintsFromHeaders | 57.352 ns | 0.4389 ns | 0.6295 ns | 0.0052 | 88 B |
| GetClientHintsFromHeadersWithoutHints | 49.915 ns | 0.7589 ns | 1.1124 ns | 0.0050 | 88 B |
| GetClientHintsFromContextUncached | 71.118 ns | 0.5539 ns | 0.8119 ns | 0.0049 | 88 B |
| GetClientHintsFromContextCached | 6.052 ns | 0.1073 ns | 0.1538 ns | - | - |
### Reading Client Hints

Reading header values from the view does not allocate, and a snapshot allocates only the record. A `Decoded*` property allocates the decoded string of a quoted value on every access.

| Method | Mean | Error | StdDev | Median | Gen0 | Allocated |
|-------------------------------------- |----------:|----------:|----------:|----------:|-------:|----------:|
| ReadViewProperties | 18.471 ns | 0.2174 ns | 0.3118 ns | 18.466 ns | - | - |
| ReadDecodedViewProperties | 36.670 ns | 0.7575 ns | 1.0113 ns | 37.392 ns | 0.0043 | 72 B |
| GetClientHintsFromHeaders | 56.993 ns | 0.5361 ns | 0.7688 ns | 56.722 ns | 0.0051 | 88 B |
| GetClientHintsFromHeadersWithoutHints | 48.849 ns | 0.4774 ns | 0.7146 ns | 48.529 ns | 0.0052 | 88 B |
| GetClientHintsFromContextUncached | 71.006 ns | 0.8836 ns | 1.2386 ns | 70.255 ns | 0.0049 | 88 B |
| GetClientHintsFromContextCached | 6.196 ns | 0.2700 ns | 0.4041 ns | 6.188 ns | - | - |

### Middleware

The middleware benchmarks run pipelines built with `ApplicationBuilder`. They reuse one `DefaultHttpContext`, and the last handler completes synchronously. `UseHttpClientHints()` sets `Accept-CH` and `Accept-CH-Lifetime` and does not allocate in this setup. If a later middleware completes asynchronously, it allocates its async state machine, as in earlier versions. `UseHttpClientHintsFeature()` allocates the 24-byte feature and returns the task of the next middleware directly. Registering the feature changes the revision of the feature collection, so `HttpContext` looks up the features it has cached again. Other servers can allocate more for the registration, see [HttpContext feature](#httpcontext-feature).

| Method | Mean | Error | StdDev | Gen0 | Allocated |
|------------------------------------- |---------:|---------:|---------:|-------:|----------:|
| UseHttpClientHints | 17.60 ns | 0.143 ns | 0.214 ns | - | - |
| UseHttpClientHintsFeature | 12.25 ns | 0.312 ns | 0.458 ns | 0.0014 | 24 B |
| UseHttpClientHintsAndFeature | 36.76 ns | 0.384 ns | 0.526 ns | 0.0013 | 24 B |
| UseHttpClientHintsFeatureAndReadView | 41.71 ns | 0.400 ns | 0.574 ns | 0.0014 | 24 B |

## Samples

Expand Down
37 changes: 32 additions & 5 deletions eng/Assert-CodeCoverage.ps1
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
# Fails when the merged Cobertura report in the results directory is below the coverage threshold.
# Usage: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory ./TestResults -Threshold 90
# Fails when the merged Cobertura report in the results directory is below the coverage threshold
# or does not contain every required package.
# Usage: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory ./TestResults -Threshold 100

[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $ResultsDirectory,

[ValidateRange(0, 100)]
[double] $Threshold = 90
[double] $Threshold = 100,

[ValidateNotNullOrEmpty()]
[string[]] $RequiredPackages = @('MyCSharp.HttpClientHints', 'MyCSharp.HttpClientHints.AspNetCore')
)

$ErrorActionPreference = 'Stop'
Expand All @@ -30,7 +34,30 @@ Write-Host ([string]::Format($invariant, 'Coverage report: {0}', $report.FullNam
Write-Host ([string]::Format($invariant, 'Line coverage: {0:F2} % (minimum {1} %)', $lineRate, $Threshold))
Write-Host ([string]::Format($invariant, 'Branch coverage: {0:F2} % (minimum {1} %)', $branchRate, $Threshold))

if ($lineRate -lt $Threshold -or $branchRate -lt $Threshold) {
Write-Error ([string]::Format($invariant, 'Code coverage is below the minimum of {0} %.', $Threshold))
$failed = $lineRate -lt $Threshold -or $branchRate -lt $Threshold

# A report without one of the packages would otherwise pass with the coverage of the remaining packages.
$packages = @($coverage.coverage.packages.package)
foreach ($name in $RequiredPackages) {
$found = @($packages | Where-Object { $_.name -eq $name })
if ($found.Count -eq 0) {
Write-Host "Package $name`: missing from the coverage report"
$failed = $true
continue
}

foreach ($package in $found) {
$packageLineRate = [double]::Parse($package.'line-rate', $invariant) * 100
$packageBranchRate = [double]::Parse($package.'branch-rate', $invariant) * 100
Write-Host ([string]::Format($invariant, 'Package {0}: line {1:F2} %, branch {2:F2} %', $name, $packageLineRate, $packageBranchRate))

if ($packageLineRate -lt $Threshold -or $packageBranchRate -lt $Threshold) {
$failed = $true
}
}
}

if ($failed) {
Write-Error ([string]::Format($invariant, 'Code coverage is below the minimum of {0} % or a required package is missing.', $Threshold))
exit 1
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright © https://myCSharp.de - all rights reserved

using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using MyCSharp.HttpClientHints.AspNetCore;

namespace HttpClientHints.Benchmarks;

[MemoryDiagnoser]
public class HttpClientHintsMiddlewareBenchmarks
{
private ServiceProvider _serviceProvider = null!;
private RequestDelegate _acceptChPipeline = null!;
private RequestDelegate _featurePipeline = null!;
private RequestDelegate _bothPipeline = null!;
private DefaultHttpContext _context = null!;

[GlobalSetup]
public void Setup()
{
ServiceCollection services = new();
services.AddHttpClientHints(options => options.Lifetime = TimeSpan.FromDays(31));
_serviceProvider = services.BuildServiceProvider();

_acceptChPipeline = BuildPipeline(static app => app.UseHttpClientHints());
_featurePipeline = BuildPipeline(static app => app.UseHttpClientHintsFeature());
_bothPipeline = BuildPipeline(static app => app.UseHttpClientHints().UseHttpClientHintsFeature());

// Every invocation reuses this context. Servers such as Kestrel allocate differently when a feature is registered.
_context = new DefaultHttpContext();
_context.Request.Headers["Sec-CH-UA"] = "\"Chromium\";v=\"131\", \"Not;A=Brand\";v=\"99\", \"Google Chrome\";v=\"131\"";
_context.Request.Headers["Sec-CH-UA-Platform"] = "\"Windows\"";
_context.Request.Headers["Sec-CH-UA-Mobile"] = "?0";
}

[GlobalCleanup]
public void Cleanup() => _serviceProvider.Dispose();

[Benchmark]
public Task UseHttpClientHints() => _acceptChPipeline(_context);

[Benchmark]
public Task UseHttpClientHintsFeature() => _featurePipeline(_context);

[Benchmark]
public Task UseHttpClientHintsAndFeature() => _bothPipeline(_context);

[Benchmark]
public bool? UseHttpClientHintsFeatureAndReadView()
{
_ = _featurePipeline(_context);
return _context.Features.Get<IHttpClientHintsFeature>()!.View.Mobile;
}

private RequestDelegate BuildPipeline(Action<IApplicationBuilder> configure)
{
ApplicationBuilder app = new(_serviceProvider);
configure(app);
app.Run(static _ => Task.CompletedTask);
return app.Build();
}
}
3 changes: 3 additions & 0 deletions samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
// Register Http Client Hints Middleware
app.UseHttpClientHints();

// Optional: provide IHttpClientHintsFeature in HttpContext.Features
app.UseHttpClientHintsFeature();

app.UseRouting();

app.UseAuthorization();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
@using Microsoft.AspNetCore.Http.Features
@using Microsoft.Extensions.Primitives
@using MyCSharp.HttpClientHints
@using MyCSharp.HttpClientHints.AspNetCore
@{
ViewData["Title"] = "Home Page";

HttpClientHints clientHints = Context.GetClientHints();
// Registered by app.UseHttpClientHintsFeature() in Program.cs.
// Context.GetClientHints() returns the same snapshot without the feature.
HttpClientHints clientHints = Context.Features.GetRequiredFeature<IHttpClientHintsFeature>().Snapshot;
clientHints.Headers.TryGetValue("Sec-CH-UA-Bitness", out StringValues bitness);
}

Expand Down
21 changes: 21 additions & 0 deletions src/HttpClientHints.AspNetCore/HttpClientHintsFeature.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright © https://myCSharp.de - all rights reserved

using Microsoft.AspNetCore.Http;

namespace MyCSharp.HttpClientHints.AspNetCore;

/// <summary>
/// Default <see cref="IHttpClientHintsFeature"/> registered by <see cref="HttpClientHintsFeatureMiddleware"/>.
/// </summary>
/// <remarks>
/// The middleware creates one instance per request, so the type holds only the context reference and has the minimum
/// object size. <see cref="View"/> and <see cref="Snapshot"/> use the extension methods and compute nothing up front.
/// </remarks>
internal sealed class HttpClientHintsFeature(HttpContext context) : IHttpClientHintsFeature
{
/// <inheritdoc />
public HttpClientHintsView View => context.GetClientHintsView();

/// <inheritdoc />
public HttpClientHints Snapshot => context.GetClientHints();
}
20 changes: 20 additions & 0 deletions src/HttpClientHints.AspNetCore/HttpClientHintsFeatureMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright © https://myCSharp.de - all rights reserved

using Microsoft.AspNetCore.Http;

namespace MyCSharp.HttpClientHints.AspNetCore;

/// <summary>
/// Registers <see cref="IHttpClientHintsFeature"/> for every request.
/// Added by <see cref="HttpClientHintsRegistration.UseHttpClientHintsFeature"/>.
/// </summary>
internal sealed class HttpClientHintsFeatureMiddleware(RequestDelegate next)
{
public Task InvokeAsync(HttpContext context)
{
context.Features.Set<IHttpClientHintsFeature>(new HttpClientHintsFeature(context));

// Nothing runs after the next middleware, so its task is returned without an async state machine.
return next(context);
}
}
17 changes: 17 additions & 0 deletions src/HttpClientHints.AspNetCore/HttpClientHintsRegistration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,21 @@ public static IApplicationBuilder UseHttpClientHints(this IApplicationBuilder ap

return app;
}

/// <summary>
/// Adds a middleware that registers <see cref="IHttpClientHintsFeature"/> in <c>HttpContext.Features</c> for every request.
/// </summary>
/// <param name="app">The application builder.</param>
/// <returns>The application builder with the middleware added.</returns>
/// <remarks>
/// Middleware and handlers added after this call can read the feature. The middleware does not require
/// <see cref="AddHttpClientHints"/> or <see cref="UseHttpClientHints"/>. It creates the feature for every request,
/// even if no handler reads it, and replaces an <see cref="IHttpClientHintsFeature"/> registered earlier in the pipeline.
/// </remarks>
public static IApplicationBuilder UseHttpClientHintsFeature(this IApplicationBuilder app)
{
app.Use(static next => new HttpClientHintsFeatureMiddleware(next).InvokeAsync);

return app;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright � https://myCSharp.de - all rights reserved
// Copyright © https://myCSharp.de - all rights reserved

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -28,11 +28,12 @@ public async Task InvokeAsync(HttpContext context)
if (_options.HasResponseHeaders)
{
// Set headers directly without additional checks
context.Response.Headers["Accept-CH"] = _options.ResponseHeader;
IHeaderDictionary headers = context.Response.Headers;
headers["Accept-CH"] = _options.ResponseHeader;

if (_options.HasLifetime)
{
context.Response.Headers["Accept-CH-Lifetime"] = _options.LifeTime;
headers["Accept-CH-Lifetime"] = _options.LifeTime;
}
}

Expand Down
35 changes: 35 additions & 0 deletions src/HttpClientHints.AspNetCore/IHttpClientHintsFeature.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright © https://myCSharp.de - all rights reserved

using Microsoft.AspNetCore.Http;

namespace MyCSharp.HttpClientHints.AspNetCore;

/// <summary>
/// Provides the HTTP Client Hints of the current request through <see cref="HttpContext.Features"/>.
/// </summary>
/// <remarks>
/// <see cref="HttpClientHintsRegistration.UseHttpClientHintsFeature"/> adds a middleware that registers this feature
/// for every request. The registration replaces an <see cref="IHttpClientHintsFeature"/> that was registered earlier
/// in the pipeline. To use your own implementation, register it after the middleware. Without registration,
/// <c>HttpContext.Features.Get&lt;IHttpClientHintsFeature&gt;()</c> returns <see langword="null"/>.
/// The extension methods in <see cref="HttpClientHintsHttpContextExtensions"/> work with and without the feature.
/// The default implementation references the <see cref="HttpContext"/>, so do not keep it beyond the request.
/// </remarks>
public interface IHttpClientHintsFeature
{
/// <summary>
/// Gets a view over the current request headers. Same as <see cref="HttpClientHintsHttpContextExtensions.GetClientHintsView(HttpContext)"/>.
/// </summary>
/// <value>A view that reads the current request headers on every property access.</value>
HttpClientHintsView View { get; }

/// <summary>
/// Gets the snapshot of the Client Hints of the request. Same as <see cref="HttpClientHintsHttpContextExtensions.GetClientHints(HttpContext)"/>.
/// </summary>
/// <value>The record that is built on the first access and returned for every further access during the request.</value>
/// <remarks>
/// The properties keep the values read on the first access. <see cref="HttpClientHints.Headers"/> references the
/// request headers themselves, so it shows later changes to the headers.
/// </remarks>
HttpClientHints Snapshot { get; }
}
Loading