Skip to content
Open
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion docs/guide.html
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ <h2 id="options-title">Options</h2>
<tr><td><code>headers:</code></td><td><code>nil</code></td><td>The Rack env of the request, passed to <code>Agentry.new</code>; read for the <a href="#client-hints">Client Hints</a> and the <a href="#cloudflare">Cloudflare</a> headers. The Rails helper and the middleware pass it.</td></tr>
<tr><td><code>Agentry.user_agent_size_limit</code></td><td>2048</td><td>Largest user agent accepted, in bytes. A larger one raises <code>Agentry::Error</code>.</td></tr>
<tr><td><code>Agentry.accept_language_size_limit</code></td><td>2048</td><td>Largest Accept-Language header accepted, in bytes. A larger one raises <code>Agentry::Error</code>. A header listing more than 32 languages is parsed on each request, never cached.</td></tr>
<tr><td><code>Agentry.cache_size</code></td><td>1000</td><td>Distinct 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. <code>0</code> turns it off.</td></tr>
<tr><td><code>Agentry.cache_size</code></td><td>1000</td><td>Distinct 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. <code>0</code> turns it off.</td></tr>
<tr><td><code>Agentry::Bot.matchers</code></td><td>three built-in matchers</td><td>Callables deciding whether a user agent is a bot. See <a href="bots.html#matchers">Bots</a>.</td></tr>
<tr><td><code>Agentry::Bot.bots</code></td><td><code>bots.yml</code></td><td>Known bots, keyed by a lowercase substring of their user agent.</td></tr>
<tr><td><code>Agentry::Bot.search_engines</code></td><td><code>search_engines.yml</code></td><td>Bots answering <code>bot.search_engine?</code>.</td></tr>
Expand Down
37 changes: 32 additions & 5 deletions lib/agentry/cache.rb
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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?
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
12 changes: 5 additions & 7 deletions lib/agentry/detect_version.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
20 changes: 20 additions & 0 deletions test/unit/cache_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down