From 9e5083dbf547d79503294c9c6e37b1988c911b6e Mon Sep 17 00:00:00 2001 From: BEN ABT Date: Sat, 21 Nov 2026 15:10:47 +0100 Subject: [PATCH] perf: faster client hints cache, move tests to Microsoft.Testing.Platform - Cache the HttpContext snapshot under a private object key instead of the string "__HttpClientHints" - Read headers in HttpClientHintsView through one GetFirstValue helper - Use a list pattern in HttpClientHintsInterpreter.IsMobile - Drop the Microsoft.Extensions.Primitives package dependency for net11.0 - Build with the stable .NET SDK 11.0.100 and LangVersion 14/15 - Run tests on Microsoft.Testing.Platform with xunit.v3 4, TRX and coverage - Validate PRs in one job across net8.0 to net11.0 - Rework the benchmark scenarios and show the current results in the README --- .github/workflows/build-and-test.yml | 4 +- .github/workflows/pr-validation.yml | 26 +--- Directory.Build.props | 34 +---- Directory.Packages.props | 44 ++----- Justfile | 10 +- README.md | 54 ++++---- global.json | 7 +- .../HttpClientHintBenchmarks.cs | 116 ++++++------------ .../HttpClientHints.Benchmarks.csproj | 10 -- perf/HttpClientHints.Benchmarks/Program.cs | 4 +- ...tpClientHints.Samples.AspNetCoreMvc.csproj | 1 + .../HttpClientHintsHttpContextExtensions.cs | 9 +- .../HttpClientHintsView.cs | 27 ++-- src/HttpClientHints/HttpClientHints.csproj | 2 +- .../HttpClientHintsInterpreter.cs | 14 +-- ...tpClientHintsHttpContextExtensionsTests.cs | 35 ++++++ .../HttpClientHintsRegistrationTests.cs | 19 +-- .../HttpClientHintsInterpreterTests.cs | 4 + 18 files changed, 169 insertions(+), 251 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 6b6617f..46a717c 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -68,13 +68,13 @@ jobs: run: dotnet build --configuration ${{ inputs.configuration }} --no-restore /p:Version=${{ steps.nbgv.outputs.SemVer2 }} - name: Test - run: dotnet test --configuration ${{ inputs.configuration }} --no-build --verbosity normal --logger "trx;LogFileName=test-results.trx" + run: dotnet test --configuration ${{ inputs.configuration }} --no-build --results-directory TestResults --results-directory-layout per-module -- --report-trx - name: Upload test results if: always() && inputs.upload-test-results uses: actions/upload-artifact@v6 with: - name: test-results-${{ inputs.dotnet-version }} + name: test-results path: '**/TestResults/**/*.trx' - name: Pack NuGet packages diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml index 7b9dd63..79b527b 100644 --- a/.github/workflows/pr-validation.yml +++ b/.github/workflows/pr-validation.yml @@ -10,30 +10,8 @@ permissions: pull-requests: read jobs: - validate-dotnet-8: - name: Test on .NET 8.0 + validate: + name: Test on .NET 8, 9, 10 and 11 uses: ./.github/workflows/build-and-test.yml with: - dotnet-version: '8.0.x' - upload-test-results: true - - validate-dotnet-9: - name: Test on .NET 9.0 - uses: ./.github/workflows/build-and-test.yml - with: - dotnet-version: '9.0.x' - upload-test-results: true - - validate-dotnet-10: - name: Test on .NET 10.0 - uses: ./.github/workflows/build-and-test.yml - with: - dotnet-version: '10.0.x' - upload-test-results: true - - validate-dotnet-11: - name: Test on .NET 11.0 - uses: ./.github/workflows/build-and-test.yml - with: - dotnet-version: '11.0.x' upload-test-results: true diff --git a/Directory.Build.props b/Directory.Build.props index 9e99e11..147166a 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -36,7 +36,8 @@ - preview + 14.0 + 15.0 embedded enable en-US @@ -83,24 +84,9 @@ - - - - - all - runtime; build; native; contentfiles; analyzers - + + - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - @@ -116,18 +102,6 @@ all runtime; build; native; contentfiles; analyzers - - all - runtime; build; native; contentfiles; analyzers - - - all - runtime; build; native; contentfiles; analyzers - - - all - runtime; build; native; contentfiles; analyzers - all runtime; build; native; contentfiles; analyzers diff --git a/Directory.Packages.props b/Directory.Packages.props index 3fc4d18..7652e96 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,55 +6,27 @@ - - + - - - - - all - runtime; build; native; contentfiles; analyzers - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + + - - all - runtime; build; native; contentfiles; analyzers - - - all - runtime; build; native; contentfiles; analyzers - - - all - runtime; build; native; contentfiles; analyzers - - + all runtime; build; native; contentfiles; analyzers - + all runtime; build; native; contentfiles; analyzers - + all runtime; build; native; contentfiles; analyzers - + all runtime; build; native; contentfiles; analyzers diff --git a/Justfile b/Justfile index 31efb0a..22184d4 100644 --- a/Justfile +++ b/Justfile @@ -5,7 +5,7 @@ set shell := ["pwsh", "-c"] # ===== Configurable defaults ===== CONFIG := "Debug" -TFM := "net10.0" +TFM := "net11.0" BENCH_PRJ := "perf/HttpClientHints.Benchmarks/HttpClientHints.Benchmarks.csproj" # ===== Default / Help ===== @@ -43,14 +43,14 @@ format-check: dotnet format --verify-no-changes --verbosity minimal test *ARGS: - dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" --nologo --verbosity minimal {{ARGS}} + dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" {{ARGS}} test-cov: - dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" --nologo --verbosity minimal /p:CollectCoverage=true /p:CoverletOutputFormat="cobertura,lcov,opencover" /p:CoverletOutput="./TestResults/coverage/coverage" + dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" --results-directory-layout per-module -- --coverage --coverage-output-format cobertura test-filter QUERY: - dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" --nologo --verbosity minimal --filter "{{QUERY}}" + dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" -- --filter-query "{{QUERY}}" # ===== Packaging / Release ===== pack *ARGS: @@ -64,7 +64,7 @@ publish-sc RID *ARGS: # ===== Benchmarks ===== bench *ARGS: - dotnet run --configuration Release --project "{{BENCH_PRJ}}" --framework "{{TFM}}" {{ARGS}} + dotnet run --configuration Release --project "{{BENCH_PRJ}}" --framework "{{TFM}}" -- {{ARGS}} # ===== Housekeeping ===== clean-artifacts: diff --git a/README.md b/README.md index 561c63a..8f76df7 100644 --- a/README.md +++ b/README.md @@ -82,40 +82,40 @@ HttpClientHints clientHints = HttpClientHintsHttpContextExtensions.GetClientHint clientHints.Headers.TryGetValue("Sec-CH-UA-Bitness", out StringValues bitness); ``` -## Benchmark +## Build and test + +Use the .NET 11 SDK to build the solution. Both NuGet packages target .NET 8, 9, 10, and 11. The .NET 11 build uses `Microsoft.Extensions.Primitives` from the shared runtime. Install the corresponding runtimes to run the full test suite. ```shell -BenchmarkDotNet v0.15.2, Windows 10 (10.0.19045.6216/22H2/2022Update) +dotnet build -c Release +dotnet test -c Release --no-build +``` + +## Benchmark + +``` +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 -.NET SDK 10.0.100-preview.7.25380.108 - [Host] : .NET 10.0.0 (10.0.25.38108), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI - .NET 10.0 : .NET 10.0.0 (10.0.25.38108), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI - .NET 8.0 : .NET 8.0.19 (8.0.1925.36514), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI - .NET 9.0 : .NET 9.0.8 (9.0.825.36511), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI - - -| Method | Job | Runtime | Mean | Error | StdDev | Gen0 | Allocated | -|------------------------------------------------------- |---------- |---------- |----------:|---------:|---------:|-------:|----------:| -| 'View: read few properties (no alloc)' | .NET 8.0 | .NET 8.0 | 31.26 ns | 0.403 ns | 0.377 ns | - | - | -| 'View: read few properties (no alloc)' | .NET 9.0 | .NET 9.0 | 34.50 ns | 0.328 ns | 0.307 ns | - | - | -| 'View: read few properties (no alloc)' | .NET 10.0 | .NET 10.0 | 21.71 ns | 0.397 ns | 0.371 ns | - | - | -| | | | | | | | | -| 'View: BuildSnapshot (alloc 1)' | .NET 8.0 | .NET 8.0 | 70.83 ns | 1.058 ns | 0.884 ns | 0.0052 | 88 B | -| 'View: BuildSnapshot (alloc 1)' | .NET 9.0 | .NET 9.0 | 67.35 ns | 0.462 ns | 0.409 ns | - | - | -| 'View: BuildSnapshot (alloc 1)' | .NET 10.0 | .NET 10.0 | 44.59 ns | 0.599 ns | 0.561 ns | - | - | -| | | | | | | | | -| 'Extension: GetClientHints(headers) (alloc 1)' | .NET 8.0 | .NET 8.0 | 70.32 ns | 0.872 ns | 0.816 ns | 0.0052 | 88 B | -| 'Extension: GetClientHints(headers) (alloc 1)' | .NET 9.0 | .NET 9.0 | 67.24 ns | 0.506 ns | 0.473 ns | - | - | -| 'Extension: GetClientHints(headers) (alloc 1)' | .NET 10.0 | .NET 10.0 | 46.50 ns | 0.254 ns | 0.212 ns | - | - | -| | | | | | | | | -| 'Extension: GetClientHints(context) (alloc 1, cached)' | .NET 8.0 | .NET 8.0 | 111.04 ns | 0.767 ns | 0.718 ns | 0.0052 | 88 B | -| 'Extension: GetClientHints(context) (alloc 1, cached)' | .NET 9.0 | .NET 9.0 | 114.79 ns | 2.304 ns | 2.155 ns | 0.0052 | 88 B | -| 'Extension: GetClientHints(context) (alloc 1, cached)' | .NET 10.0 | .NET 10.0 | 98.26 ns | 1.429 ns | 1.267 ns | 0.0052 | 88 B | +Memory: 61,64 GB Total, 31,83 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 + +IterationCount=15 IterationTime=200ms LaunchCount=2 +WarmupCount=6 ``` +| Method | Mean | Error | StdDev | Gen0 | Allocated | +|-------------------------------------- |----------:|----------:|----------:|-------:|----------:| +| ReadViewProperties | 18.688 ns | 0.2959 ns | 0.4337 ns | - | - | +| GetClientHintsFromHeaders | 58.697 ns | 0.7625 ns | 1.1176 ns | 0.0051 | 88 B | +| GetClientHintsFromHeadersWithoutHints | 51.311 ns | 0.8545 ns | 1.2255 ns | 0.0052 | 88 B | +| GetClientHintsFromContextUncached | 76.252 ns | 2.8269 ns | 4.0542 ns | 0.0050 | 88 B | +| GetClientHintsFromContextCached | 6.174 ns | 0.1132 ns | 0.1623 ns | - | - | + ## Samples -- [ASP.NET Core MVC Sample](./samples/MyCSharp.HttpClientHints.Samples.AspNetCoreMvc/) +- [ASP.NET Core MVC Sample](./samples/HttpClientHints.Samples.AspNetCoreMvc/) ## Maintained diff --git a/global.json b/global.json index ef31c07..269797b 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,10 @@ { "sdk": { - "version": "11.0.100-preview.2.26159.112" + "version": "11.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + }, + "test": { + "runner": "Microsoft.Testing.Platform" } } diff --git a/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs b/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs index 279208b..7fe1055 100644 --- a/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs +++ b/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs @@ -1,106 +1,70 @@ // Copyright © https://myCSharp.de - all rights reserved using BenchmarkDotNet.Attributes; -using BenchmarkDotNet.Jobs; -using BenchmarkDotNet.Order; -using BenchmarkDotNet.Configs; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Primitives; +using Microsoft.AspNetCore.Http.Features; using MyCSharp.HttpClientHints.AspNetCore; +using ClientHints = MyCSharp.HttpClientHints.HttpClientHints; namespace HttpClientHints.Benchmarks; -/// -/// Benchmarks for comparing zero-allocation view vs. snapshot materialization and legacy extension. -/// [MemoryDiagnoser] -[SimpleJob(RuntimeMoniker.Net80)] -[SimpleJob(RuntimeMoniker.Net90)] -[SimpleJob(RuntimeMoniker.Net10_0)] -[Orderer(SummaryOrderPolicy.Method, MethodOrderPolicy.Declared)] -[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByMethod)] public class HttpClientHintBenchmarks { + private readonly HeaderDictionary _headersWithoutHints = new() { ["User-Agent"] = "Mozilla/5.0" }; private HeaderDictionary _headers = null!; - private DefaultHttpContext _httpContext = null!; + private DefaultHttpContext _uncachedContext = null!; + private DefaultHttpContext _cachedContext = null!; [GlobalSetup] public void Setup() { - HeaderDictionary headers = new(); - // representative set of headers - headers["User-Agent"] = new StringValues("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"); - headers["Sec-CH-UA"] = new StringValues("\"Chromium\";v=\"127\", \"Not;A=Brand\";v=\"99\"\"Chrome\";v=\"127\""); - headers["Sec-CH-UA-Platform"] = new StringValues("\"Windows\""); - headers["Sec-CH-UA-Platform-Version"] = new StringValues("\"15.0.0\""); - headers["Sec-CH-UA-Arch"] = new StringValues("\"x86\""); - headers["Sec-CH-UA-Full-Version-List"] = new StringValues("\"Chromium\";v=\"127.0.6533.72\", \"Not;A=Brand\";v=\"99.0.0.0\", \"Chrome\";v=\"127.0.6533.72\""); - headers["Sec-CH-UA-Model"] = new StringValues("\"\""); - headers["Sec-CH-UA-Mobile"] = new StringValues("?0"); - - _headers = headers; - _httpContext = new DefaultHttpContext(); - _httpContext.Request.Headers.Clear(); - foreach (KeyValuePair kvp in headers) + _headers = new HeaderDictionary { - _httpContext.Request.Headers[kvp.Key] = kvp.Value; - } - } - - [Benchmark(Description = "View: read few properties (no alloc)")] - public int View_Read_Properties() - { - HttpClientHintsView view = _headers.GetClientHintsView(); - // touch several properties to simulate typical usage - string ua = view.UA; - string platform = view.Platform; - string arch = view.Architecture; - bool? mobile = view.Mobile; + ["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", + ["Sec-CH-UA"] = "\"Chromium\";v=\"131\", \"Not;A=Brand\";v=\"99\", \"Google Chrome\";v=\"131\"", + ["Sec-CH-UA-Platform"] = "\"Windows\"", + ["Sec-CH-UA-Platform-Version"] = "\"15.0.0\"", + ["Sec-CH-UA-Arch"] = "\"x86\"", + ["Sec-CH-UA-Full-Version-List"] = "\"Chromium\";v=\"131.0.6778.85\", \"Google Chrome\";v=\"131.0.6778.85\"", + ["Sec-CH-UA-Model"] = "\"\"", + ["Sec-CH-UA-Mobile"] = "?0" + }; - int hash = 17; - hash = (hash * 31) + (ua?.Length ?? 0); - hash = (hash * 31) + (platform?.Length ?? 0); - hash = (hash * 31) + (arch?.Length ?? 0); - hash = (hash * 31) + (mobile.HasValue ? (mobile.Value ? 1 : 2) : 3); - return hash; + _uncachedContext = CreateContext(); + _cachedContext = CreateContext(); } - [Benchmark(Description = "View: BuildSnapshot (alloc 1)")] - public int View_BuildSnapshot() + [Benchmark] + public int ReadViewProperties() { HttpClientHintsView view = _headers.GetClientHintsView(); - MyCSharp.HttpClientHints.HttpClientHints snapshot = view.BuildSnapshot(); - int hash = 17; - hash = (hash * 31) + (snapshot.UA?.Length ?? 0); - hash = (hash * 31) + (snapshot.Platform?.Length ?? 0); - hash = (hash * 31) + (snapshot.Architecture?.Length ?? 0); - hash = (hash * 31) + (snapshot.Mobile.HasValue ? (snapshot.Mobile.Value ? 1 : 2) : 3); - return hash; + return (view.UA?.Length ?? 0) + (view.Platform?.Length ?? 0) + + (view.Architecture?.Length ?? 0) + (view.Mobile == false ? 1 : 0); } - [Benchmark(Description = "Extension: GetClientHints(headers) (alloc 1)")] - public int Extension_GetClientHints_FromHeaders() + [Benchmark] + public ClientHints GetClientHintsFromHeaders() => _headers.GetClientHints(); + + [Benchmark] + public ClientHints GetClientHintsFromHeadersWithoutHints() => _headersWithoutHints.GetClientHints(); + + [Benchmark] + public ClientHints GetClientHintsFromContextUncached() { - MyCSharp.HttpClientHints.HttpClientHints hints = _headers.GetClientHints(); - int hash = 17; - hash = (hash * 31) + (hints.UA?.Length ?? 0); - hash = (hash * 31) + (hints.Platform?.Length ?? 0); - hash = (hash * 31) + (hints.Architecture?.Length ?? 0); - hash = (hash * 31) + (hints.Mobile.HasValue ? (hints.Mobile.Value ? 1 : 2) : 3); - return hash; + _uncachedContext.Items.Clear(); + return _uncachedContext.GetClientHints(); } - [Benchmark(Description = "Extension: GetClientHints(context) (alloc 1, cached)")] - public int Extension_GetClientHints_FromHttpContext() + [Benchmark] + public ClientHints GetClientHintsFromContextCached() => _cachedContext.GetClientHints(); + + private DefaultHttpContext CreateContext() { - // clear cache to measure allocation consistently - _httpContext.Items.Remove("__HttpClientHints"); - MyCSharp.HttpClientHints.HttpClientHints hints = _httpContext.GetClientHints(); - int hash = 17; - hash = (hash * 31) + (hints.UA?.Length ?? 0); - hash = (hash * 31) + (hints.Platform?.Length ?? 0); - hash = (hash * 31) + (hints.Architecture?.Length ?? 0); - hash = (hash * 31) + (hints.Mobile.HasValue ? (hints.Mobile.Value ? 1 : 2) : 3); - return hash; + FeatureCollection features = new(); + features.Set(new HttpRequestFeature { Headers = _headers }); + DefaultHttpContext context = new(features); + _ = context.GetClientHints(); + return context; } } diff --git a/perf/HttpClientHints.Benchmarks/HttpClientHints.Benchmarks.csproj b/perf/HttpClientHints.Benchmarks/HttpClientHints.Benchmarks.csproj index 6a85e98..002cbbb 100644 --- a/perf/HttpClientHints.Benchmarks/HttpClientHints.Benchmarks.csproj +++ b/perf/HttpClientHints.Benchmarks/HttpClientHints.Benchmarks.csproj @@ -2,7 +2,6 @@ Exe - disable @@ -11,17 +10,8 @@ $(MSBuildProjectName) - - $(DefineConstants);OS_WIN - - - - $(NoWarn);CS8002 - - - diff --git a/perf/HttpClientHints.Benchmarks/Program.cs b/perf/HttpClientHints.Benchmarks/Program.cs index d4b6f17..0dda352 100644 --- a/perf/HttpClientHints.Benchmarks/Program.cs +++ b/perf/HttpClientHints.Benchmarks/Program.cs @@ -1,7 +1,5 @@ // Copyright © https://myCSharp.de - all rights reserved -using System.Reflection; using BenchmarkDotNet.Running; -// dotnet run -c Release --framework net80 net90 --runtimes net90 -BenchmarkSwitcher.FromAssembly(Assembly.GetExecutingAssembly()).Run(args); +BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); diff --git a/samples/HttpClientHints.Samples.AspNetCoreMvc/HttpClientHints.Samples.AspNetCoreMvc.csproj b/samples/HttpClientHints.Samples.AspNetCoreMvc/HttpClientHints.Samples.AspNetCoreMvc.csproj index 75901c6..673fe61 100644 --- a/samples/HttpClientHints.Samples.AspNetCoreMvc/HttpClientHints.Samples.AspNetCoreMvc.csproj +++ b/samples/HttpClientHints.Samples.AspNetCoreMvc/HttpClientHints.Samples.AspNetCoreMvc.csproj @@ -2,6 +2,7 @@ $(NoWarn);1591 + false diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs index 5366bc7..73b056b 100644 --- a/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs @@ -12,7 +12,7 @@ public static class HttpClientHintsHttpContextExtensions /// /// The cache key used to store the client hints in the HttpContext.Items dictionary. /// - private const string ClientHintsCacheKey = "__HttpClientHints"; + private static readonly object s_clientHintsCacheKey = new(); /// /// Retrieves the from the current HTTP context. @@ -21,15 +21,14 @@ public static class HttpClientHintsHttpContextExtensions /// An instance of populated with the relevant header values. public static HttpClientHints GetClientHints(this HttpContext context) { - // Check if client hints are already cached for this request - if (context.Items.TryGetValue(ClientHintsCacheKey, out object? cached) && cached is HttpClientHints hints) + IDictionary items = context.Items; + if (items.TryGetValue(s_clientHintsCacheKey, out object? cached) && cached is HttpClientHints hints) { return hints; } - // Create and cache new client hints HttpClientHints newHints = context.Request.Headers.GetClientHints(); - context.Items[ClientHintsCacheKey] = newHints; + items[s_clientHintsCacheKey] = newHints; return newHints; } diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs index eb191d3..a4e1ac5 100644 --- a/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs @@ -17,52 +17,47 @@ namespace MyCSharp.HttpClientHints.AspNetCore; /// public readonly struct HttpClientHintsView(IHeaderDictionary headers) { - private static string? FirstOrNull(in StringValues values) => values.Count > 0 ? values[0] : null; - /// Gets the raw headers. public IHeaderDictionary Headers => headers; /// User-Agent public string? UserAgent - => FirstOrNull(headers.TryGetValue("User-Agent", out StringValues v) ? v : default); + => GetFirstValue("User-Agent"); /// Sec-CH-UA public string? UA - => FirstOrNull(headers.TryGetValue("Sec-CH-UA", out StringValues v) ? v : default); + => GetFirstValue("Sec-CH-UA"); /// Sec-CH-UA-Platform public string? Platform - => FirstOrNull(headers.TryGetValue("Sec-CH-UA-Platform", out StringValues v) ? v : default); + => GetFirstValue("Sec-CH-UA-Platform"); /// Sec-CH-UA-Platform-Version public string? PlatformVersion - => FirstOrNull(headers.TryGetValue("Sec-CH-UA-Platform-Version", out StringValues v) ? v : default); + => GetFirstValue("Sec-CH-UA-Platform-Version"); /// Sec-CH-UA-Arch public string? Architecture - => FirstOrNull(headers.TryGetValue("Sec-CH-UA-Arch", out StringValues v) ? v : default); + => GetFirstValue("Sec-CH-UA-Arch"); /// Sec-CH-UA-Model public string? Model - => FirstOrNull(headers.TryGetValue("Sec-CH-UA-Model", out StringValues v) ? v : default); + => GetFirstValue("Sec-CH-UA-Model"); /// Sec-CH-UA-Full-Version-List public string? FullVersionList - => FirstOrNull(headers.TryGetValue("Sec-CH-UA-Full-Version-List", out StringValues v) ? v : default); + => GetFirstValue("Sec-CH-UA-Full-Version-List"); /// Sec-CH-UA-Mobile mapped to nullable bool. public bool? Mobile - { - get - { - headers.TryGetValue("Sec-CH-UA-Mobile", out StringValues v); - return HttpClientHintsInterpreter.IsMobile(FirstOrNull(v)); - } - } + => HttpClientHintsInterpreter.IsMobile(GetFirstValue("Sec-CH-UA-Mobile")); /// /// Materializes a snapshot record of the current values. This allocates one object. /// public HttpClientHints BuildSnapshot() => new(UserAgent, Platform, PlatformVersion, Architecture, Model, FullVersionList, UA, Mobile, headers); + + private string? GetFirstValue(string key) + => headers.TryGetValue(key, out StringValues values) && values.Count > 0 ? values[0] : null; } diff --git a/src/HttpClientHints/HttpClientHints.csproj b/src/HttpClientHints/HttpClientHints.csproj index 0459f39..0a321c6 100644 --- a/src/HttpClientHints/HttpClientHints.csproj +++ b/src/HttpClientHints/HttpClientHints.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/HttpClientHints/HttpClientHintsInterpreter.cs b/src/HttpClientHints/HttpClientHintsInterpreter.cs index 87540b4..ef8d77d 100644 --- a/src/HttpClientHints/HttpClientHintsInterpreter.cs +++ b/src/HttpClientHints/HttpClientHintsInterpreter.cs @@ -21,16 +21,16 @@ public static class HttpClientHintsInterpreter /// public static bool? IsMobile(string? mobileHeaderValue) { - if (string.Equals(mobileHeaderValue, "?1", StringComparison.Ordinal)) + if (mobileHeaderValue is not ['?', char flag]) { - return true; + return null; } - if (string.Equals(mobileHeaderValue, "?0", StringComparison.Ordinal)) + return flag switch { - return false; - } - - return null; + '1' => true, + '0' => false, + _ => null + }; } } diff --git a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs index 405b4b3..44687e1 100644 --- a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs +++ b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs @@ -105,4 +105,39 @@ public void GetClientHints_ReturnsCorrectMobileValue_WhenMobileHeaderIsNull() // Assert Assert.Null(clientHints.Mobile); } + + [Fact] + public void GetClientHintsView_UsesOnlyTheFirstValue() + { + HeaderDictionary headers = new() + { + ["Sec-CH-UA"] = new StringValues(["first", "second"]), + ["Sec-CH-UA-Mobile"] = new StringValues(["?0", "?1"]), + ["Sec-CH-UA-Platform"] = new StringValues([null, "fallback"]), + ["Sec-CH-UA-Model"] = new StringValues(string.Empty) + }; + + HttpClientHintsView view = headers.GetClientHintsView(); + + Assert.Equal("first", view.UA); + Assert.False(view.Mobile); + Assert.Null(view.Platform); + Assert.Equal(string.Empty, view.Model); + } + + [Fact] + public void GetClientHints_ReusesSnapshotForTheSameContext() + { + DefaultHttpContext context = new(); + context.Request.Headers["Sec-CH-UA"] = "original"; + context.Items["__HttpClientHints"] = "application data"; + + HttpClientHints snapshot = context.GetClientHints(); + context.Request.Headers["Sec-CH-UA"] = "updated"; + + Assert.Equal("original", snapshot.UA); + Assert.Same(snapshot, context.GetClientHints()); + Assert.Equal("updated", context.GetClientHintsView().UA); + Assert.Equal("application data", context.Items["__HttpClientHints"]); + } } diff --git a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsRegistrationTests.cs b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsRegistrationTests.cs index a47c53b..cabb72b 100644 --- a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsRegistrationTests.cs +++ b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsRegistrationTests.cs @@ -1,9 +1,9 @@ // Copyright © https://myCSharp.de - all rights reserved using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using NSubstitute; using Xunit; namespace MyCSharp.HttpClientHints.AspNetCore.UnitTests; @@ -105,16 +105,19 @@ public void AddHttpClientHints_AllHeadersDisabled_RegistersNoHeaders() } [Fact] - public void UseHttpClientHints_ReturnsApplicationBuilder() + public async Task UseHttpClientHints_AddsMiddlewareAndReturnsApplicationBuilder() { - // Arrange - IApplicationBuilder appBuilder = Substitute.For(); + ServiceCollection services = new(); + services.AddHttpClientHints(); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + ApplicationBuilder appBuilder = new(serviceProvider); - // Act IApplicationBuilder result = appBuilder.UseHttpClientHints(); + appBuilder.Run(static _ => Task.CompletedTask); + DefaultHttpContext context = new(); + await appBuilder.Build()(context); - // Assert - Assert.NotNull(result); - Assert.Same(appBuilder, result); // Ensure the same instance is returned + Assert.Same(appBuilder, result); + Assert.Contains("Sec-CH-UA", context.Response.Headers["Accept-CH"].ToString(), StringComparison.Ordinal); } } diff --git a/tests/HttpClientHints.UnitTests/HttpClientHintsInterpreterTests.cs b/tests/HttpClientHints.UnitTests/HttpClientHintsInterpreterTests.cs index 236658f..9f2e769 100644 --- a/tests/HttpClientHints.UnitTests/HttpClientHintsInterpreterTests.cs +++ b/tests/HttpClientHints.UnitTests/HttpClientHintsInterpreterTests.cs @@ -14,6 +14,10 @@ public class HttpClientHintsInterpreterTests [InlineData(null, null)] [InlineData("unknown", null)] [InlineData("", null)] + [InlineData("?", null)] + [InlineData("?2", null)] + [InlineData("?10", null)] + [InlineData("!1", null)] public void IsMobile_ShouldReturnExpectedResult_ForGivenInput(string? input, bool? expectedResult) { // Act