Repository navigation
feat: source-generated regexes, Native AOT, faster detection and real-world test catalog - #104
Draft
BenjaminAbt wants to merge 30 commits into
Draft
BenjaminAbt wants to merge 30 commits into
BenjaminAbt wants to merge 30 commits into
Conversation
…-world test catalog - Replace the 121 runtime-compiled regexes of the public API with [GeneratedRegex], created on first access; the parser keeps its rules in HttpUserAgentRules - Make all packages trimming and Native AOT compatible (IsAotCompatible) and add a Native AOT smoke test with a CI job for net8.0 to net11.0 - Speed up robot and mobile detection with grouped SearchValues, robot anchors and a snapshot check for replaced HttpUserAgentStatics.Robots entries - Add Samsung Internet, Yandex Browser, UC Browser and 27 search engine, SEO and AI crawlers; restore the declared mobile device priority - Add a real-world user agent catalog for tests and benchmarks, enforce 100% line, branch and method coverage - Fix the core cache.size meter, keep Roslyn runtime assets out of tests and apps - Update README and package readmes Closes #3, closes #5, closes #36
Run the validation when a draft is marked as ready for review.
…o Get(HttpContext) - Add IHttpUserAgentParserContextAccessor (extends IHttpUserAgentParserAccessor) with Get() and GetHttpContextUserAgent() for the current request - Add HttpUserAgentParserContextAccessor and AddHttpUserAgentParserContextAccessor(), which registers IHttpContextAccessor and, unless already registered, IHttpUserAgentParserAccessor - Cover both accessors in tests and in the Native AOT smoke test, document both options
- Browser version: read the version from the product token of the
browser only (up to the next space, tab, ';', '(', ')' or ','), so an
empty version no longer takes the version of the next product
("SamsungBrowser/ Chrome/131.0.0.0" is Chrome 131.0.0.0).
- Meters (all packages): create the instruments under a lock and
publish them as one object, so no registration returns before its
instruments exist. The last registered meter is used, the same meter
again is a no-op, calls without a meter share one default meter.
- Robots: replace the pinned raw-reference snapshot with a managed key
reference comparison; replaced values are honored on the fast path.
- .NET 8: use the robot anchor prefilter on all target frameworks.
- Native AOT smoke test: verify meter measurements (MeterListener) and
EventCounters (EventListener, EventSourceSupport) of all packages.
- Docs: catalog counts (48 crawlers, 96 user agents), benchmark results
per runtime, allocation note for untrimmed input, regex culture and
Compiled semantics, meter registration, unbounded ConcurrentDictionary
cache, precise Native AOT statement.
- Browser version: if a token has no version, check the next occurrence
of the same token before the next rule ("Chrome/ Chrome/131.0" is
Chrome 131.0). A separate version token (Version/, MSIE, rv:) only
counts at the start of a token ("Opera/9.80 VendorVersion/120.0" is
Opera 9.80).
- Meters: create the instruments once per meter (ConditionalWeakTable),
so a meter registered again reuses them. The cache.size gauges report
only while their meter is in use; a replaced meter no longer reports
the cache size, and switching back no longer reports it twice.
- MemoryCache: use the user agent string as cache key. The reused
thread-static CacheKey was stored as the key of new entries and
changed by the next call on that thread, so entries were lost between
threads. Keys are ordinal now (Equals ignored case, the hash did not).
- Browser version: later occurrences of a browser token only count at
the start of a token ("ChromeHelper/1 MyChrome/2.0 Firefox/126.0" is
Firefox 126.0); the first occurrence may still continue a word
(HeadlessChrome). A token starts at the beginning or after a space,
tab, ';', '(', ')' or ',' - the delimiters that end a product token -
so "Vendor-Version/120.0" is no version token either.
- Version search: continue behind the product token examined before,
so the time grows linearly with the length of the user agent
(1,000,000 characters of "Chrome/a": 1.7 s before, 2 ms now).
- Cache size: providers register themselves weakly when created; the
cache.size gauges and cache-size counters sum the live caches when
observed. Entries cached before telemetry was enabled are counted,
several core providers no longer overwrite each other, and nothing is
counted on the parse path anymore.
- Meters: meters the packages create (default, prefix variants) are
created once per name and disposed when replaced; caller meters are
never disposed. Repeated prefix registrations keep one meter.
- ConcurrentDictionary cache: ordinal keys like the MemoryCache.
Parser
- Browser and version tokens only count at the start of a token (at
the beginning or after a space, tab, '+', ';', '(', ')' or ','), for
every occurrence: "Knowledge/1.0" is no Edge, "MyChrome/2.0" no
Chrome. Headless Chrome and ELinks get rules of their own.
- '+' separates tokens like a space (URL-encoded logs such as IIS):
Safari, Opera and Internet Explorer versions are read again.
- Rules with a version token accept "Token 1.2" (Opera 9.50, MSIE 6.0,
several spaces, '+'); "MSIE MSIE 7.0" and "MSIE 6.0" work again.
- Platforms: "cros " instead of "cros" (Microsoft is no ChromeOS),
"windows phone" before "android". Robot key "YouBot/" (ShowyouBot).
- Fast path: the inlined IndexOf stays in front of the token-start
check, so rules that do not match cost what they did.
Telemetry
- Own meters are created once per name and reused, not disposed when
replaced: no measurement is lost during a switch.
- The core and the MemoryCache package reject a shared meter (same
instrument names, the values mixed silently).
- Meter prefixes: ASCII letters or digits followed by '.'.
Providers, DI, ASP.NET Core
- MemoryCache entries get all CacheEntryOptions (absolute expiration,
priority, tokens, eviction callbacks, size).
- HttpUserAgentParserMemoryCachedProvider implements IDisposable and
disposes its MemoryCache.
- Accessor registrations use TryAdd (idempotent in any order); an
empty or white-space User-Agent header returns null.
- Docs: readme snippets that did not compile, regex creation, token
rules, allocation statement, URL-encoded user agents.
…ters
Telemetry
- A meter that the core or the MemoryCache package has used stays
reserved for it while the meter lives: both create cache.hit,
cache.miss and cache.size, and a meter keeps its instruments, so a
handover after a switch mixed the series. The reservation is made
before the instruments are created, which also covers a registration
from a listener callback and a listener that throws.
- If a listener throws while instruments are published, the meter in
use stays active and a new own meter is disposed.
- A replaced own meter (default or prefix) is disposed again, so
changing prefixes keeps one meter; measurements racing with that
switch are best effort. Meters of the caller are never disposed.
Parser
- The version tokens of Opera ("Version/") and Internet Explorer
("rv:") only count after the browser token.
- ChromeOS: "cros+" for URL-encoded logs next to "cros ".
- Robot key " YouBot/" so "ShowyouBot/1.0" is no YouBot.
Telemetry (one registration implementation for all packages) - .NET calls MeterListener callbacks while instruments are created and while a meter is disposed. Both happen outside the registration lock now; the lock only switches the state. Mutual registrations of the core and MemoryCache packages from listener callbacks no longer deadlock, and a nested registration of another own meter leaves no meter behind. - Each meter gets one instrument container before any instrument is created. After a listener threw, a later registration only adds the missing instruments: cache.size exists at most once per meter and reports while its meter is in use. - Passing the own meter in use keeps it (no disposal). Robots - "YouBot/" matches again at any position; ShowyouBot has an entry of its own before it.
- HttpUserAgentStatics.Robots is a read-only list now; SetRobots replaces the robots the parser detects (atomically, for all following parses), DefaultRobots holds the defaults. Writing into the array is no longer possible. - The parser works on an immutable robot set (list, anchor prefilter, grouped matcher) and reads it once per parse. The check that the keys of the public array were unchanged (95 reference comparisons, 17 ns on .NET 11 for every user agent) and the slow paths for replaced keys are gone. - Benchmarks: BenchmarkDotNet 0.16.0-preview.2 runs every case in its own process on .NET 11 as well, so --inProcess is no longer needed; in one process Dynamic PGO adapted the code to the cases measured before (Googlebot 9 ns alone, 20 ns after the other user agents). The library comparison uses the ShortRun job out of process, too.
feat(tests): add EventCounterTestListener and MeterTestListener refactor(tests): update HttpUserAgentParserMemoryCachedProvider tests fix(tests): improve assertions in HttpUserAgentInformationExtensionsTests chore(tests): clean up UserAgentCatalogTests and related tests
gfoidl
reviewed
Nov 24, 2026
gfoidl
left a comment
Contributor
There was a problem hiding this comment.
Well...I review the product code but not at 100% detail, and just skimmed over the tests.
The points should be addressed for the whole PR, even when I didn't comment all places.
refactor(parser): simplify user agent parsing logic refactor(cache): improve cache handling and telemetry integration style(docs): update documentation for clarity and consistency chore(project): rename README.md for consistency
The packages contained the 512x512 logo (251 KB), while the DLLs are about 20 KB each. NuGet shows the icon at 128x128, so the packages now contain a 128x128 icon (30 KB). The readme keeps the 512x512 logo. The myCSharp.de NuGet logo is no longer used and is removed.
NuGet splits tags at spaces, so "User Agent" became the tags "User" and "Agent" on NuGet.org. The tags are now single words that describe what the packages detect, for example user-agent, browser-detection and bot-detection. useragent is kept. Console, ASP and Desktop are removed, because they do not describe the packages.
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.
Changes
HttpContextdirectly or useIHttpContextAccessorthrough dependency injection.4.0 migration.
HttpUserAgentStatics.Robotsis now a read-only property. Recompile consumers that used the array field and useSetRobots(...)to customize detection.How parsing works
Parsetakes a snapshot of the configured crawler rules, trims the header and checks the highest-priority rule first. With the defaults, a Googlebot match returns immediately, even when its contact URL contains a+.+. The detectors share a decoded view, soScreaming+Frog+SEO+Spidermatches the rule forScreaming Frog SEO Spider. The result retains the trimmed input as received.Chrome/158.0.0.0andEdg/158.0.0.0returns Edge 158.0.0.0 because Edge has higher priority. If no browser matches, the result is classified as unknown and includes any platform or device already identified.Verification
Performance on .NET 11
Change in mean time per uncached header. The shared 64 KiB rule table reduced full-catalog time by 39.5% versus the previous PR.
Full benchmark results
Earlier measurements across .NET 8–11 and individual headers
The earlier Googlebot optimization reduced its time from 22.526 ns to 7.280 ns (−67.7%, 0 B allocated). The table shows the earlier side-by-side Stopwatch comparison against main.
| Runtime | Browsers | Crawlers | Full catalog | Chrome on Windows | Unknown client |
| --- | ---: | ---: | ---: | ---: |
| .NET 8 | −23% | −56% | −37% | −16% | +3% |
| .NET 9 | −21% | −66% | −43% | −16% | −7% |
| .NET 10 | −20% | −61% | −39% | −9% | −8% |
| .NET 11 | −21% | −57% | −39% | −22% | −7% |
Earlier individual .NET 11 BenchmarkDotNet measurements: Chrome on Windows −24% · Firefox on Linux −6% · Chrome on Android −26% · Safari on iPhone −30% · Applebot −14% · Googlebot −14% · Unknown client −3%.
Closes #3, closes #5, closes #36.