diff --git a/README.md b/README.md index 6d1a4f4..46570ab 100644 --- a/README.md +++ b/README.md @@ -223,7 +223,7 @@ In another Rack app, `use Agentry::Middleware do … end` takes the same block. ## Cache, limits and boot Each process remembers what it found for the last 1,000 user agents (browser, platform, device and bot answers) -and the last 1,000 `Accept-Language` headers, about 1 KB per user agent. A user agent seen before costs about 2 µs. +the last 1,000 `Accept-Language` headers and the last 1,000 versions compared, about 1 KB per user agent. A user agent seen before costs about 2 µs. The cache empties itself when it is full, and when `Agentry.matchers`, `Agentry::Bot.matchers`, `Agentry::Platform.matchers`, `Agentry::Device.matchers`, the bot list or its exceptions change. Setting `Agentry.cache_size` empties it too, for example after renaming an entry of `Agentry::Bot.bots` in place: diff --git a/docs/guide.html b/docs/guide.html index 4fbe180..1e8ea45 100644 --- a/docs/guide.html +++ b/docs/guide.html @@ -219,7 +219,7 @@

Options

headers:nilThe Rack env of the request, passed to Agentry.new; read for the Client Hints and the Cloudflare headers. The Rails helper and the middleware pass it. Agentry.user_agent_size_limit2048Largest user agent accepted, in bytes. A larger one raises Agentry::Error. Agentry.accept_language_size_limit2048Largest Accept-Language header accepted, in bytes. A larger one raises Agentry::Error. A header listing more than 32 languages is parsed on each request, never cached. - Agentry.cache_size1000Distinct user agents (and Accept-Language headers) whose detection each process keeps, about 1 KB each; emptied when full or when a matcher list or the bot list changes. 0 turns it off. + Agentry.cache_size1000Distinct user agents (and Accept-Language headers, and versions compared) whose detection each process keeps, about 1 KB each; emptied when full or when a matcher list or the bot list changes. 0 turns it off. Agentry::Bot.matchersthree built-in matchersCallables deciding whether a user agent is a bot. See Bots. Agentry::Bot.botsbots.ymlKnown bots, keyed by a lowercase substring of their user agent. Agentry::Bot.search_enginessearch_engines.ymlBots answering bot.search_engine?. diff --git a/lib/agentry/cache.rb b/lib/agentry/cache.rb index 08b23c9..3e76563 100644 --- a/lib/agentry/cache.rb +++ b/lib/agentry/cache.rb @@ -1,18 +1,22 @@ # frozen_string_literal: true module Agentry - # The detections of the last user agents and the parsed Accept-Language - # headers, shared by the threads of a process. Reads take no lock: under the - # GVL a Hash read is atomic, and a thread that misses detects again. Writes - # do, for the Rubies without a GVL. + # The detections of the last user agents, the parsed Accept-Language + # headers and the versions compared, shared by the threads of a process. + # Reads take no lock: under the GVL a Hash read is atomic, and a thread + # that misses detects again. Writes do, for the Rubies without a GVL. module Cache # Far more than a browser sends. A longer list is parsed again each time: 2 KB of "a,a,a" makes a thousand # objects, and a thousand such headers would hold 100 MB. MAX_LANGUAGES_PER_CACHED_HEADER = 32 + # A browser sends a version of a few bytes: a longer one is built each time, so that the cache stays small. + MAX_CACHED_VERSION_BYTES = 32 @mutex = Mutex.new @detection_by_user_agent = {} @languages_by_header = {} + @requirement_by_version = {} + @gem_version_by_version = {} @generation = 0 def self.cached_detection(ua) @@ -28,6 +32,27 @@ def self.detection(ua) end end + # Built once: an app asks the same few requirements (">= 17") of every request, and browsers send the same few + # versions. The block builds one; DetectVersion keeps versions out of RubyGems' own caches. + def self.requirement(expected_version, &) + versioned(@requirement_by_version, expected_version, &) + end + + def self.version(version, &) + versioned(@gem_version_by_version, version, &) + end + + def self.versioned(value_by_version, version) + return yield unless version.is_a?(String) && version.bytesize <= MAX_CACHED_VERSION_BYTES && + Agentry.cache_size.positive? + + # Built outside the lock: a malformed version raises, and other threads keep storing meanwhile. + value_by_version[version] || begin + value = yield + @mutex.synchronize { store(value_by_version, -version, value) } + end + end + # A copy each time: callers may change the array they get. def self.accept_language(header) return AcceptLanguage.parse(header) if Agentry.cache_size.zero? @@ -58,6 +83,8 @@ def self.clear @mutex.synchronize do @detection_by_user_agent.clear @languages_by_header.clear + @requirement_by_version.clear + @gem_version_by_version.clear end end @@ -93,6 +120,6 @@ def self.store(value_by_key, key, value) end private_class_method :lists_unchanged?, :remember_lists, - :current_detection_by_user_agent, :store + :current_detection_by_user_agent, :versioned, :store end end diff --git a/lib/agentry/detect_version.rb b/lib/agentry/detect_version.rb index 5d25e2b..0553c93 100644 --- a/lib/agentry/detect_version.rb +++ b/lib/agentry/detect_version.rb @@ -13,9 +13,7 @@ def release end end - # A browser's version is a few bytes: a longer one is not kept, so that a cached platform stays small. - MAX_KEPT_VERSION_BYTES = 32 - private_constant :UncachedVersion, :MAX_KEPT_VERSION_BYTES + private_constant :UncachedVersion private def detect_version?(actual_version, expected_version) return true unless expected_version @@ -24,19 +22,19 @@ def release expected_version = parse_version(expected_version) actual_version = parse_version(actual_version) - Gem::Requirement.create(expected_version) + Cache.requirement(expected_version) { Gem::Requirement.create(expected_version) } .satisfied_by?(gem_version(actual_version)) rescue ArgumentError false end - # The last one built: a cached platform asks for the same version on each request. + # The last one used: a cached platform asks for the same version on each request, also when Cache keeps none. private def gem_version(version) string, gem_version = @gem_version return gem_version if string == version - gem_version = UncachedVersion.create(version) - @gem_version = [version, gem_version] if version.bytesize <= MAX_KEPT_VERSION_BYTES + gem_version = Cache.version(version) { UncachedVersion.create(version) } + @gem_version = [version, gem_version] if version.bytesize <= Cache::MAX_CACHED_VERSION_BYTES gem_version end diff --git a/test/unit/cache_test.rb b/test/unit/cache_test.rb index e8060d6..83e4e68 100644 --- a/test/unit/cache_test.rb +++ b/test/unit/cache_test.rb @@ -175,6 +175,26 @@ def cached_user_agents Agentry::Bot.bot_exceptions.delete("cachedbot") end + test "compares versions alike with the cache on and off" do + chrome_user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " \ + "Chrome/142.0.0.0 Safari/537.36" + long_version = "1#{".0" * 40}" + answers = lambda do + browser = Agentry.new(chrome_user_agent.sub("142.0.0.0", long_version)) + chrome = Agentry.new(chrome_user_agent) + [chrome.chrome?(">= 10"), chrome.chrome?("< 10"), chrome.chrome?([">= 1", "< 1000"]), chrome.chrome?(Integer(chrome.version)), + chrome.chrome?("not a version"), browser.chrome?("~> 1.0"), browser.chrome?(">= 2")] + end + cached = Array.new(2) { answers.call } + kept_versions = %i[@requirement_by_version @gem_version_by_version] + .flat_map { |name| Agentry::Cache.instance_variable_get(name).keys } + assert_includes kept_versions, "142.0.0.0" + refute_includes kept_versions, long_version + Agentry.cache_size = 0 + + assert_equal [[true, false, true, true, false, true, false]] * 3, cached + [answers.call] + end + test "parses an accept language once and hands out copies" do first = Agentry.new("", accept_language: "fr-FR,en;q=0.8").accept_language first.clear