Repository navigation
feat: add decoded Client Hints values, enforce 90% coverage - #20
Merged
Merged
Conversation
- Decode the RFC 9651 strings of Sec-CH-UA-Platform, Sec-CH-UA-Platform-Version, Sec-CH-UA-Arch, and Sec-CH-UA-Model in Platform, PlatformVersion, Architecture, and Model - Add RawPlatform, RawPlatformVersion, RawArchitecture, and RawModel to HttpClientHintsView and the HttpClientHints record - Bump the version to 4.0 and add an upgrade guide to the README - Collect code coverage in CI and fail below 90% line or branch coverage - Add a raw-read benchmark and update the README benchmark results
- Platform, PlatformVersion, Architecture, and Model return the header values as sent again, as in 3.x, so the change is no longer breaking - Add DecodedPlatform, DecodedPlatformVersion, DecodedArchitecture, and DecodedModel to HttpClientHints and HttpClientHintsView; they decode on every access and store nothing - Move the decoder to the public HttpClientHintsInterpreter.DecodeStructuredString - Remove the Raw* properties and set the version to 3.2 instead of 4.0 - Replace the upgrade guide with a "Decoded values" README section - Benchmark decoded reads with ReadDecodedViewProperties
- README: explain GetClientHints and GetClientHintsView, list the headers each option requests, and use Sec-CH-UA-Full-Version-List as the Additional example instead of Sec-CH-UA-Bitness, which Architecture already requests - README: show DecodeStructuredString for Sec-CH-UA-Bitness, show the install command for both packages, fix a typo - Sample: show header values next to their decoded values, decode Sec-CH-UA-Bitness, request Sec-CH-UA-Full-Version-List, and remove the empty template columns
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
This PR does two things:
DecodedPlatform,DecodedPlatformVersion,DecodedArchitecture, andDecodedModeltoHttpClientHintsandHttpClientHintsView. Browsers send these Client Hints as quoted HTTP Structured Field strings, such asSec-CH-UA-Platform: "Windows". The new properties returnWindowsinstead of"Windows". They decode on every access and store nothing.Platform,PlatformVersion,Architecture, andModelkeep returning the header values as sent, so the change is not breaking. The version goes from 3.1 to 3.2.The first commit made
Platformand the other three properties return decoded values and addedRaw*properties for the original values, as a breaking 4.0 change. The second commit replaces that approach with the one described here. Please use "Squash and merge", so that thefeat!commit message of the first commit does not end up inmain.Changes
Library
HttpClientHintsInterpreter.DecodeStructuredString(MyCSharp.HttpClientHints, new)Decodes a header value that is an sf-string (RFC 9651 § 4.2.5). It is public, like
IsMobile, so that applications without ASP.NET Core can use it.nullnull"Windows"Windows""string.Empty"Model \"Pro\" \\ Edition"Model "Pro" \ Edition"Windows"(leading or trailing SP or HTAB)WindowsWindows(unquoted)"Windows(unterminated)null"a\qb"(escape other than\"or\\)null"Modèle","a<TAB>b","a<DEL>b"(character outside%x20-7E)null"Windows";a=1(parameters)nullIt allocates nothing for unquoted values and for a quoted empty value. It allocates a
StringBuilderonly if the value contains an escape.HttpClientHintsrecord (MyCSharp.HttpClientHints)DecodedPlatform,DecodedPlatformVersion,DecodedArchitecture, andDecodedModel. Each one callsDecodeStructuredStringon the matching positional property.Decoded*properties.HttpClientHintsView(MyCSharp.HttpClientHints.AspNetCore)Decoded*properties, computed from the header values on every access.BuildSnapshot()is unchanged and still allocates only the record.Decoded*properties allocate the decoded string of a quoted value. The remarks state which reads allocate.Version
version.jsongoes from 3.1 to 3.2.Tests
DecodeStructuredString_ShouldReturnExpectedResult_ForGivenInputcovers 21 header values: missing, empty, whitespace-only, unquoted, quoted empty, a typical quoted value, leading and trailing whitespace, inner whitespace, both escapes, the character range boundaries!#[]~, a lone", an unterminated value, trailing text, a trailing backslash, an invalid escape, two strings, a tab, DEL, a non-ASCII character, and parameters.DecodeStructuredString_ReturnsTheSameInstance_ForUnquotedValueschecks that unquoted values are not copied.HttpClientHintsTestscheck that the record decodes all four properties, returnsnullfor missing and malformed values, followswithexpressions, and that reading aDecoded*property does not affect equality or the hash code."Windows","19.0.0","x86","") and check that the default properties keep the quotes and theDecoded*properties remove them, for the view, for the snapshot, and for the cached snapshot of anHttpContext.CI and tooling
build-and-test.ymlcollects Cobertura coverage in the existing test run (--coverage --coverage-output-format cobertura). A new step,Check code coverage, fails the build when the merged line or branch coverage is below 90%. The Cobertura reports are uploaded with the TRX files.eng/Assert-CodeCoverage.ps1reads the merged Cobertura report thatdotnet testwrites and compares its line and branch rates with-Threshold(default 90).Microsoft.Testing.Extensions.CodeCoveragehas no threshold option of its own.just test-covdeletes old results, collects coverage for the default target framework, and runs the same check.just ciruns it as before.Benchmarks
ReadDecodedViewPropertiesreads the same four view properties asReadViewProperties, but usesDecodedPlatformandDecodedArchitecture.Documentation
Decoded*properties decode on every access.GetClientHints(), which returns a record that is cached for the request, andGetClientHintsView(), which reads the current headers without allocating. The new section refers to both types, and the README did not mention the view before.Additionalexample now requestsSec-CH-UA-Full-Version-Listinstead ofSec-CH-UA-Bitness.Architecturealready requestsSec-CH-UA-Bitness, so the old example sent it twice inAccept-CH, andFullVersionListstayednullbecause nothing requested its header. The section also shows how to decodeSec-CH-UA-BitnesswithDecodeStructuredString.dotnet add packagecommand. A typo is fixed ("experimental").Sample
Sec-CH-UA-Bitnessdecoded withDecodeStructuredString.HttpContext.GetClientHints()instead of building a new record from the headers.Sec-CH-UA-Full-Version-Listinstead of requestingSec-CH-UA-Bitnessa second time."afterSec-CH-UA-Full-Version-Listare removed.Notes for reviewers
Platform == "\"Windows\""would silently evaluate tofalse. It would also make every snapshot more expensive, even when nobody reads the decoded values. The first commit measured 232 B instead of 88 B and 97 ns instead of 59 ns for a snapshot with all Client Hints.EqualsandGetHashCodeinclude all instance fields, including private ones. A cache field would make two otherwise equal snapshots unequal, depending on whether a decoded value was read. Awithexpression also copies all fields, sohints with { Platform = "\"Linux\"" }would return a stale cachedWindows. Computed properties avoid both problems. A test covers each case.ToString()output changes: The synthesizedToString()of a record prints all public properties, so it now also prints the fourDecoded*values and decodes them for that call.Platformstill returns the value with quotes. The XML docs ofPlatformand the other three properties point to the matchingDecoded*property."Windows";a=1is a valid RFC 9651 Item, but the decoded value isnull. Browsers do not send parameters on these headers, and supporting them would need a full parameter parser. The README and XML docs state this, and tests cover it.null, so non-compliant clients still produce a value. Leading and trailing HTAB is trimmed in addition to SP, matching HTTP's optional whitespace around field values.Testing
dotnet build -c Release: 0 warnings, 0 errors, withTreatWarningsAsErrorsenabled.dotnet test -c Release --no-build --results-directory TestResults --results-directory-layout per-module -- --report-trx --coverage --coverage-output-format cobertura: 244 tests passed, 61 per target framework onnet8.0,net9.0,net10.0, andnet11.0(37 inHttpClientHints.UnitTests, 24 inHttpClientHints.AspNetCore.UnitTests)../eng/Assert-CodeCoverage.ps1 -ResultsDirectory TestResults -Threshold 90on that run: 100.00% line coverage and 100.00% branch coverage.just test-cov: 100.00% line and branch coverage onnet11.0.dotnet format --verify-no-changes: no changes.net11.0, requested withcurland browser-like Client Hints: the page shows"Windows"next toWindows,"19.0.0"next to19.0.0,"x86"next tox86,"64"next to64, and""next to an empty decoded model. The response sendsAccept-CH: User-Agent, Sec-CH-UA, Sec-CH-UA-Platform, Sec-CH-UA-Platform-Version, Sec-CH-UA-Arch, Sec-CH-UA-Bitness, Sec-CH-UA-Model, Sec-CH-UA-Mobile, Sec-CH-UA-Full-Version-List, with each header once.Benchmark
The "3.1" column is the benchmark output in the README on
main, measured for #19. The "This PR" column was measured for this PR. Both runs used the same machine and settings: AMD Ryzen 9 9950X, Windows 10 x64, .NET SDK 11.0.100, .NET 11.0.0, BenchmarkDotNet 0.16.0-preview.2. The two versions were not measured side by side in one session.This PR does not change the code that the existing five scenarios run, so their differences are variation between the two runs. In the new scenario, decoding
"Windows"and"x86"adds about 18 ns and allocates the two decoded strings: 40 B forWindowsand 32 B forx86on x64. BenchmarkDotNet reported a bimodal distribution forReadViewPropertiesin this run.Reproduce
dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6Raw benchmark output, .NET 11, this PR