agentry 4.1.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1fd67b31c76d06af204fb10fca0a98adfc227fda38ffd9fea9c979e6a06ce2b7
4
- data.tar.gz: 50e882f61382f3dcc125a1796d523117132ec8a57f9226086e127b0a7c19a737
3
+ metadata.gz: 4955acbd400a3563fdc2c21136f0c2745c798de8aebd2f7aa8aaba8db566b45f
4
+ data.tar.gz: 3f1770deae11bd3aa63c36c4b05c0d9443118ae78c4cc5ace12537001e8459f0
5
5
  SHA512:
6
- metadata.gz: e06a9c44be8bd8185e545dc2a6420c248d9977ab33f3613d298f825884fbeaa6d01895c3b0c899c9a993cd6153dc44079265b292d256e8135e7ae53ea60a7869
7
- data.tar.gz: 292e1fa09c634b894fdb99869253900a43e69bb90746c38018d5cd05efe8076aab10ba7137284edc6339cda49349dcae545573dbe89d72b039f43a5cb505dd95
6
+ metadata.gz: bb0dc3f1b81a172637fe94a4e23eb3097244c5b8414126d52e2de708fe542c72b3d3b185fc1cc432f17eaca459cd98bfd3e641b28cf9d0fed83913ec75eb6700
7
+ data.tar.gz: 6506518072d5849303fbf24b1ee1982e73a2f70204618929e0a072d20f81a90c8477e6109b69783ac46738763bcc29205866fa5b34ac51ae0ac8928a81ff68b3
data/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [4.2.0] — 2026-12-01
6
+
7
+ Agentry now detects in Ractors, and scales with threads on JRuby.
8
+
9
+ **New**
10
+ - `Agentry.prepare_for_ractors!`, called at boot, lets any Ractor detect user agents: it builds everything like `Agentry.eager_load!`, then freezes the bot lists and matchers, which then raise `FrozenError` if changed. Each Ractor keeps its own cache, and setting `Agentry.cache_size` empties them all. Without the call, detecting in a Ractor raises `Agentry::Error` saying what to do. Nothing changes for apps that don't call it.
11
+
12
+ **Faster**
13
+ - On JRuby, reading Agentry's caches no longer takes a lock: a process answering user agents it has already seen goes from one thread's throughput to about 1.5 to 3 times it on 4 cores, instead of staying flat.
14
+
5
15
  ## [4.1.1] — 2026-11-29
6
16
 
7
17
  Agentry's caches are now safe to read from parallel threads on JRuby and TruffleRuby.
@@ -165,7 +175,8 @@ First release, forked from browser 6.2.0 (`dd88933`). Same API: `gem "agentry"`
165
175
  - A corpus of 20,328 user agents, with snapshot and diff scripts proving answers match upstream, and a
166
176
  request benchmark.
167
177
 
168
- [Unreleased]: https://github.com/levups/agentry/compare/v4.1.1...HEAD
178
+ [Unreleased]: https://github.com/levups/agentry/compare/v4.2.0...HEAD
179
+ [4.2.0]: https://github.com/levups/agentry/compare/v4.1.1...v4.2.0
169
180
  [4.1.1]: https://github.com/levups/agentry/compare/v4.1.0...v4.1.1
170
181
  [4.1.0]: https://github.com/levups/agentry/compare/v4.0.0...v4.1.0
171
182
  [4.0.0]: https://github.com/levups/agentry/compare/v3.1.2...v4.0.0
data/README.md CHANGED
@@ -22,11 +22,11 @@ since June 2025. It has the same methods under its own name, `Agentry` instead o
22
22
  answers to the old names, so code written for browser runs on it as it is (see
23
23
  [Switching from browser](#switching-from-browser)). Here is what is different:
24
24
 
25
- - It answers in 25 µs per request instead of 126 µs with browser 6.2.0, and in 2 µs for a user agent the process
26
- has seen before (Ruby 4.0.9 with YJIT, see [Performance](#performance)).
27
- - Its list of bots is updated every week. Of the 882 crawler user agents added to
25
+ - It answers in 17 µs per request instead of 110 µs with browser 6.2.0, and in 1.7 µs for a user agent the process
26
+ has seen before (Ruby 4.0.10 with YJIT, see [Performance](#performance)).
27
+ - Its list of bots is updated every week. Of the 883 crawler user agents added to
28
28
  [crawler-user-agents](https://github.com/monperrus/crawler-user-agents) since 2024 (test drivers and scanners
29
- left out), browser misses 353 and Agentry 11.
29
+ left out), browser misses 354 and Agentry 11.
30
30
  - It says what kind of bot sent the request: an AI crawler, a search engine, an assistant fetching a page for a
31
31
  person, a vulnerability scanner.
32
32
  - It can check that a request claiming to be Googlebot, Bingbot or GPTBot comes from the IP addresses Google,
@@ -130,6 +130,11 @@ Agentry::Bot.matchers << ->(ua, _browser) { ua.match?(/externalhit/i) }
130
130
  [Bots page](https://levups.github.io/agentry/bots.html#matchers) shows how to remove the built-in matchers or go
131
131
  back to the detection of browser 2.x.
132
132
 
133
+ Change these lists while the app boots, in an initializer, before any thread detects a user agent. Every
134
+ detection reads them without a lock, so a change made while requests run can raise or go unseen, above all on
135
+ JRuby and TruffleRuby, whose threads run in parallel. Agentry's own caches are safe to share between threads
136
+ on every Ruby.
137
+
133
138
  ### Verified crawlers
134
139
 
135
140
  Anyone can send `Googlebot` as their user agent. Google, Bing, OpenAI, Apple, Perplexity and DuckDuckGo publish the
@@ -259,6 +264,20 @@ following ones 0.2 ms. `Agentry.eager_load!` builds them at boot, so that a serv
259
264
  forking (Puma's `preload_app!`, Unicorn, Pitchfork) shares them with every worker. Rails calls it whenever it eager
260
265
  loads, which production does by default. Elsewhere, call `Agentry.eager_load!` before the fork.
261
266
 
267
+ To detect in Ractors, call `Agentry.prepare_for_ractors!` at boot, after the app has changed the lists and settings
268
+ and before the first Ractor starts. It builds everything like `Agentry.eager_load!`, then freezes the lists and
269
+ matchers, which no longer change: adding a bot or a matcher afterwards raises `FrozenError`
270
+ (`Agentry::Bot::IPRanges.refresh` still works). A matcher the app adds must be a class or a shareable lambda
271
+ (`Ractor.shareable_lambda` on Ruby 4), or `Agentry.prepare_for_ractors!` raises `Ractor::IsolationError`. Each
272
+ Ractor keeps its own cache, like each process of a preforking server, and setting `Agentry.cache_size` in the main
273
+ one empties them all. Detecting in a Ractor before `Agentry.prepare_for_ractors!` raises `Agentry::Error`.
274
+
275
+ ```ruby
276
+ Agentry::Bot.bots["acmebot"] = "Acme Bot"
277
+ Agentry.prepare_for_ractors!
278
+ Ractor.new { Agentry.new("acmebot/1.0").bot.name }.value # => "Acme Bot"
279
+ ```
280
+
262
281
  ## Switching from browser
263
282
 
264
283
  Replace `gem "browser"` with `gem "agentry", require: "browser"` in the Gemfile (keep `require: "browser/browser"`
@@ -299,12 +318,12 @@ the table above, then put `gem "browser"` back. The
299
318
 
300
319
  `bench/request.rb` asks what a web request typically asks (name, version, `bot?`, platform, device,
301
320
  accept-language) over 2,000 distinct user agents of the corpus and over 20 repeated ones, and keeps the median of 7
302
- runs. On Ruby 4.0.9 with YJIT:
321
+ runs. On Ruby 4.0.10 with YJIT:
303
322
 
304
323
  | Per request | browser 6.2.0 | Agentry |
305
324
  |---|---:|---:|
306
- | A new user agent | 126 µs, 245 objects | 25 µs, 52 objects |
307
- | A user agent seen before | 114 µs, 217 objects | 2 µs, 12 objects |
325
+ | A new user agent | 110 µs, 245 objects | 17 µs, 23 objects |
326
+ | A user agent seen before | 102 µs, 217 objects | 1.7 µs, 7 objects |
308
327
 
309
328
  The [benchmarks page](https://levups.github.io/agentry/benchmarks.html) has the runs without YJIT, the machine, and
310
329
  why Agentry is faster. To run them again:
@@ -96,6 +96,34 @@ module Agentry
96
96
  nil
97
97
  end
98
98
 
99
+ # For apps that detect in Ractors: builds everything at boot, then freezes the lists, which no app can change
100
+ # afterwards (FrozenError). Without Ractor (JRuby, TruffleRuby), it only eager-loads.
101
+ def self.prepare_for_ractors!
102
+ eager_load!
103
+ return unless defined?(Ractor)
104
+
105
+ shareable_lists.each { |list| Ractor.make_shareable(list) }
106
+ Bot.send(:make_keywords_shareable)
107
+ Cache.send(:make_remembered_lists_shareable)
108
+ @prepared_for_ractors = true
109
+ nil
110
+ end
111
+
112
+ def self.prepared_for_ractors?
113
+ @prepared_for_ractors || false
114
+ end
115
+
116
+ def self.shareable_lists
117
+ [
118
+ root, matchers, Platform.matchers, Device.matchers, Bot.matchers,
119
+ Bot.bots, Bot.bot_exceptions, Bot.search_engines, Bot.category_by_keyword,
120
+ Meta.rules, AcceptLanguage.languages, Device::Samsung.names,
121
+ Bot::IPRanges::SOURCES, Bot::IPRanges.prefixes_by_owner, Bot::IPRanges.ranges_by_owner,
122
+ Cloudflare.header_names, Cloudflare.env_key_by_signal
123
+ ]
124
+ end
125
+ private_class_method :shareable_lists
126
+
99
127
  class << self
100
128
  attr_accessor :user_agent_size_limit, :accept_language_size_limit
101
129
  attr_reader :cache_size
@@ -132,7 +132,7 @@ module Agentry
132
132
  address = parse(ip)
133
133
  domains = SOURCES.dig(owner, :domains)
134
134
  return false unless address && domains&.any?
135
- return resolves_to?(address, domains) if dns_cache_size.zero?
135
+ return resolves_to?(address, domains) if dns_cache_size.zero? || !Cache.main_ractor?
136
136
 
137
137
  key = "#{owner} #{address}"
138
138
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
@@ -178,6 +178,7 @@ module Agentry
178
178
 
179
179
  def self.load(prefixes_by_owner)
180
180
  ranges_by_owner = build_ranges(prefixes_by_owner)
181
+ Ractor.make_shareable([prefixes_by_owner, ranges_by_owner]) if Agentry.prepared_for_ractors?
181
182
  @prefixes_by_owner = prefixes_by_owner
182
183
  @ranges_by_owner = ranges_by_owner
183
184
  end
data/lib/agentry/bot.rb CHANGED
@@ -46,9 +46,9 @@ module Agentry
46
46
  end
47
47
 
48
48
  # Builds and Agentry.cache_size='s rebuild hold this lock, shared with the
49
- # subclasses, and check again under it; reads never take it (off CRuby a
50
- # pattern read takes its table's lock; a built trie never changes).
51
- # Each class keeps what it built, freed with the class.
49
+ # subclasses, and check again under it; reads never take it: a write
50
+ # replaces the frozen table of patterns whole, and a built trie never
51
+ # changes. Each class keeps what it built, freed with the class.
52
52
  KEYWORDS_LOCK = Mutex.new
53
53
  # Lists an app builds on each call would pile up.
54
54
  MAX_LISTS = 64
@@ -61,14 +61,18 @@ module Agentry
61
61
  def self.keywords_pattern(keywords)
62
62
  built_from, pattern = @pattern_by_list&.[](keywords)
63
63
  return pattern if built_from && unchanged?(keywords, built_from)
64
+ return build_keywords_pattern(keywords).last if Agentry.prepared_for_ractors?
64
65
 
65
66
  KEYWORDS_LOCK.synchronize do
66
- @pattern_by_list ||= Cache.send(:table).compare_by_identity
67
- built_from, pattern = @pattern_by_list[keywords]
67
+ built_from, pattern = @pattern_by_list&.[](keywords)
68
68
  next pattern if built_from && unchanged?(keywords, built_from)
69
69
 
70
- @pattern_by_list.clear if @pattern_by_list.size >= MAX_LISTS
71
- (@pattern_by_list[keywords] = build_keywords_pattern(keywords)).last
70
+ built = build_keywords_pattern(keywords)
71
+ pattern_by_list = (@pattern_by_list.nil? || @pattern_by_list.size >= MAX_LISTS) ?
72
+ {}.compare_by_identity : @pattern_by_list.dup
73
+ pattern_by_list[keywords] = built
74
+ @pattern_by_list = pattern_by_list.freeze
75
+ built.last
72
76
  end
73
77
  end
74
78
 
@@ -80,6 +84,7 @@ module Agentry
80
84
  list = bots
81
85
  built_list, built_from, trie = @known_bots_trie
82
86
  return trie if built_list.equal?(list) && unchanged?(list, built_from)
87
+ return build_known_bots_trie(list).last if Agentry.prepared_for_ractors?
83
88
 
84
89
  KEYWORDS_LOCK.synchronize do
85
90
  built_list, built_from, trie = @known_bots_trie
@@ -134,14 +139,31 @@ module Agentry
134
139
  end
135
140
 
136
141
  def self.rebuild_own_keywords
137
- @pattern_by_list&.to_a&.each do |list, (keywords, _pattern)|
138
- @pattern_by_list[list] = build_keywords_pattern(list) unless keywords_copy(list) == keywords
142
+ if @pattern_by_list
143
+ pattern_by_list = {}.compare_by_identity
144
+ @pattern_by_list.each do |list, built|
145
+ pattern_by_list[list] = (keywords_copy(list) == built.first) ? built : build_keywords_pattern(list)
146
+ end
147
+ @pattern_by_list = pattern_by_list.freeze
139
148
  end
140
149
  list, keywords, = @known_bots_trie
141
150
  @known_bots_trie = [list, *build_known_bots_trie(list)] if list && keywords_copy(list) != keywords
142
151
  end
143
- private_class_method :unchanged?, :keywords_copy, :build_keywords_pattern,
144
- :build_known_bots_trie, :rebuild_keywords, :self_and_subclasses, :rebuild_own_keywords
152
+
153
+ # Frozen by Agentry.prepare_for_ractors!, so that every Ractor reads what was built: a list built later, which
154
+ # Ractors can't share, is built on each call.
155
+ def self.make_keywords_shareable
156
+ self_and_subclasses.each { |bot_class| bot_class.send(:make_own_keywords_shareable) }
157
+ end
158
+
159
+ def self.make_own_keywords_shareable
160
+ Ractor.make_shareable(@pattern_by_list)
161
+ Ractor.make_shareable(@known_bots_trie)
162
+ end
163
+
164
+ private_class_method :unchanged?, :keywords_copy, :build_keywords_pattern, :build_known_bots_trie,
165
+ :rebuild_keywords, :self_and_subclasses, :rebuild_own_keywords, :make_keywords_shareable,
166
+ :make_own_keywords_shareable
145
167
 
146
168
  # The rank of a bots.yml keyword the user agent holds: the lowest, or the
147
169
  # first one found when `lowest: false`.
data/lib/agentry/cache.rb CHANGED
@@ -4,11 +4,13 @@ module Agentry
4
4
  # The detections of the last user agents, the parsed Accept-Language
5
5
  # headers, Client Hints and the versions compared, shared by the threads
6
6
  # of a process. Writes take the lock; on CRuby reads don't: under the GVL a
7
- # Hash read is atomic, and a thread that misses detects again.
7
+ # Hash read is atomic, and a thread that misses detects again. JRuby reads a
8
+ # concurrent map, TruffleRuby a table locked on reads too.
8
9
  module Cache
9
- # JRuby and TruffleRuby run threads in parallel: a Hash read racing an
10
- # insert or a clear may raise or miss, so their reads lock each table.
11
- # Only [] runs outside the writers' lock: size and to_a need no lock here.
10
+ # TruffleRuby and any other Ruby but CRuby and JRuby: threads run in
11
+ # parallel, and a Hash read racing an insert or a clear may raise or miss,
12
+ # so reads lock each table. Only [] runs outside the writers' lock: size
13
+ # needs no lock here.
12
14
  class LockedHash < Hash
13
15
  def initialize
14
16
  super
@@ -28,12 +30,54 @@ module Agentry
28
30
  end
29
31
  end
30
32
 
33
+ # JRuby runs threads in parallel too, and has a map whose reads take no
34
+ # lock: a lock on each read kept every thread at one thread's pace (#93).
35
+ # Keys reach it as Ruby Strings, compared like Hash keys: JRuby would
36
+ # otherwise convert each to a Java String, losing its encoding and bytes
37
+ # that aren't valid, or raise for an encoding Java lacks. Keys are Strings.
38
+ class ConcurrentTable
39
+ RUBY_STRING = Java::OrgJruby::RubyString if RUBY_ENGINE == "jruby"
40
+
41
+ def initialize
42
+ @map = java.util.concurrent.ConcurrentHashMap.new
43
+ end
44
+
45
+ def [](key)
46
+ @map.get(key.to_java(RUBY_STRING))
47
+ end
48
+
49
+ def []=(key, value)
50
+ @map.put(key.to_java(RUBY_STRING), value)
51
+ value
52
+ end
53
+
54
+ def size
55
+ @map.size
56
+ end
57
+
58
+ def empty?
59
+ @map.isEmpty
60
+ end
61
+
62
+ def keys
63
+ @map.keySet.to_a
64
+ end
65
+
66
+ def clear
67
+ @map.clear
68
+ end
69
+ end
70
+
31
71
  def self.table_class(engine)
32
- (engine == "ruby") ? Hash : LockedHash
72
+ case engine
73
+ when "ruby" then Hash
74
+ when "jruby" then ConcurrentTable
75
+ else LockedHash
76
+ end
33
77
  end
34
78
 
35
79
  TABLE = table_class(RUBY_ENGINE)
36
- private_constant :LockedHash, :TABLE
80
+ private_constant :LockedHash, :ConcurrentTable, :TABLE
37
81
 
38
82
  def self.table
39
83
  TABLE.new
@@ -47,13 +91,69 @@ module Agentry
47
91
  # A browser names 3 brands: a forged Sec-CH-UA naming dozens is parsed each time, so that an entry stays small.
48
92
  MAX_BRANDS_PER_CACHED_HINTS = 8
49
93
 
50
- @mutex = Mutex.new
51
- @detection_by_user_agent = table
52
- @languages_by_header = table
53
- @requirement_by_string = table
54
- @gem_version_by_version = table
55
- @client_hints_by_key = table
94
+ # What a cache holds can't cross Ractors: each Ractor keeps its own tables, like each process of a server.
95
+ class Tables
96
+ attr_reader :mutex, :detection_by_user_agent, :languages_by_header, :requirement_by_string,
97
+ :gem_version_by_version, :client_hints_by_key, :generation
98
+
99
+ def initialize(generation)
100
+ @mutex = Mutex.new
101
+ @detection_by_user_agent = Cache.send(:table)
102
+ @languages_by_header = Cache.send(:table)
103
+ @requirement_by_string = Cache.send(:table)
104
+ @gem_version_by_version = Cache.send(:table)
105
+ @client_hints_by_key = Cache.send(:table)
106
+ @generation = generation
107
+ end
108
+
109
+ # The block gives the generation the tables now hold, under their lock.
110
+ def clear
111
+ @mutex.synchronize do
112
+ @generation = yield
113
+ @detection_by_user_agent.clear
114
+ @languages_by_header.clear
115
+ @requirement_by_string.clear
116
+ @gem_version_by_version.clear
117
+ @client_hints_by_key.clear
118
+ end
119
+ end
120
+ end
121
+ private_constant :Tables
122
+
56
123
  @generation = 0
124
+ @tables = Tables.new(@generation)
125
+
126
+ if !defined?(Ractor)
127
+ def self.main_ractor?
128
+ true
129
+ end
130
+ elsif Ractor.respond_to?(:main?)
131
+ def self.main_ractor?
132
+ Ractor.main?
133
+ end
134
+ else
135
+ def self.main_ractor?
136
+ Ractor.current.equal?(Ractor.main)
137
+ end
138
+ end
139
+
140
+ def self.tables
141
+ main_ractor? ? @tables : ractor_tables
142
+ end
143
+
144
+ # Agentry.cache_size= clears the main Ractor's tables, and moves the generation the others compare theirs with.
145
+ def self.ractor_tables
146
+ tables = Ractor.current[:agentry_cache_tables] ||= new_ractor_tables
147
+ tables.clear { @generation } unless tables.generation == @generation
148
+ tables
149
+ end
150
+
151
+ def self.new_ractor_tables
152
+ raise Error, "call Agentry.prepare_for_ractors! at boot, before detecting in a Ractor" unless
153
+ Agentry.prepared_for_ractors?
154
+
155
+ Tables.new(@generation)
156
+ end
57
157
 
58
158
  def self.cached_detection(ua)
59
159
  current_detection_by_user_agent[ua]
@@ -62,35 +162,43 @@ module Agentry
62
162
  def self.detection(ua)
63
163
  return Detection.new(ua) if Agentry.cache_size.zero?
64
164
 
65
- cached_detection(ua) || @mutex.synchronize do
165
+ tables = self.tables
166
+ cached_detection(ua) || tables.mutex.synchronize do
66
167
  ua = -ua
67
- store(@detection_by_user_agent, ua, Detection.new(ua))
168
+ store(tables.detection_by_user_agent, ua, Detection.new(ua))
68
169
  end
69
170
  end
70
171
 
71
172
  # Built once: an app asks the same few requirements (">= 17") of every request, and browsers send the same few
72
173
  # versions. The block builds one; DetectVersion keeps versions out of RubyGems' own caches.
73
174
  def self.requirement(expected_version, &)
74
- versioned(@requirement_by_string, expected_version, &)
175
+ return yield unless cacheable_version?(expected_version)
176
+
177
+ tables = self.tables
178
+ versioned(tables, tables.requirement_by_string, expected_version, &)
75
179
  end
76
180
 
77
181
  # Frozen once kept: shared by every thread, a version computes its segments once, before anyone reads it.
78
182
  def self.version(version, &)
79
- versioned(@gem_version_by_version, version, freeze: true, &)
183
+ return yield unless cacheable_version?(version)
184
+
185
+ tables = self.tables
186
+ versioned(tables, tables.gem_version_by_version, version, freeze: true, &)
80
187
  end
81
188
 
82
189
  # Only a String of class String, keyed by its interned copy: a subclass may read itself its own way (to_str),
83
190
  # and would compare in Ruby, where another thread may grow the Hash halfway through a lookup (lock-free on CRuby).
84
- def self.versioned(value_by_version, version, freeze: false)
85
- return yield unless version.instance_of?(String) && version.bytesize <= MAX_CACHED_VERSION_BYTES &&
86
- Agentry.cache_size.positive?
191
+ def self.cacheable_version?(version)
192
+ version.instance_of?(String) && version.bytesize <= MAX_CACHED_VERSION_BYTES && Agentry.cache_size.positive?
193
+ end
87
194
 
195
+ def self.versioned(tables, value_by_version, version, freeze: false)
88
196
  version = -version
89
197
  # Built outside the lock: a malformed version raises, and other threads keep storing meanwhile.
90
198
  value_by_version[version] || begin
91
199
  value = yield
92
200
  value.freeze if freeze
93
- @mutex.synchronize { store(value_by_version, version, value) }
201
+ tables.mutex.synchronize { store(value_by_version, version, value) }
94
202
  end
95
203
  end
96
204
 
@@ -98,13 +206,14 @@ module Agentry
98
206
  def self.accept_language(header)
99
207
  return AcceptLanguage.parse(header) if Agentry.cache_size.zero?
100
208
 
101
- languages = @languages_by_header[header]
209
+ tables = self.tables
210
+ languages = tables.languages_by_header[header]
102
211
  return languages.dup if languages
103
212
 
104
213
  languages = AcceptLanguage.parse(header)
105
214
  return languages if languages.size > MAX_LANGUAGES_PER_CACHED_HEADER
106
215
 
107
- @mutex.synchronize { store(@languages_by_header, -header, languages.freeze) }.dup
216
+ tables.mutex.synchronize { store(tables.languages_by_header, -header, languages.freeze) }.dup
108
217
  end
109
218
 
110
219
  # Keyed by the hint headers, which a Chromium browser sends alike on
@@ -114,13 +223,14 @@ module Agentry
114
223
  return ClientHints::NONE if values.all?(&:nil?)
115
224
 
116
225
  key = client_hints_key(values) if Agentry.cache_size.positive?
117
- client_hints = key && @client_hints_by_key[key]
226
+ tables = self.tables if key
227
+ client_hints = key && tables.client_hints_by_key[key]
118
228
  return client_hints if client_hints
119
229
 
120
230
  client_hints = ClientHints.new(headers, values)
121
231
  return client_hints unless key && client_hints.brand_count <= MAX_BRANDS_PER_CACHED_HINTS
122
232
 
123
- @mutex.synchronize { store(@client_hints_by_key, key, client_hints) }
233
+ tables.mutex.synchronize { store(tables.client_hints_by_key, key, client_hints) }
124
234
  end
125
235
 
126
236
  # One String made here, never the caller's: CRuby's lock-free lookup compares it in C, uninterrupted, where an
@@ -134,13 +244,13 @@ module Agentry
134
244
  end
135
245
 
136
246
  # Bumped when a matcher list, the bot list or its exceptions change: the
137
- # matchers are public arrays that apps extend at runtime.
247
+ # matchers are public arrays that apps extend at runtime, until Agentry.prepare_for_ractors! freezes them.
138
248
  def self.generation
139
249
  return @generation if lists_unchanged?
140
250
 
141
- @mutex.synchronize do
251
+ @tables.mutex.synchronize do
142
252
  @generation += 1
143
- @detection_by_user_agent.clear
253
+ @tables.detection_by_user_agent.clear
144
254
  remember_lists
145
255
  end
146
256
  @generation
@@ -153,14 +263,7 @@ module Agentry
153
263
  Bot.send(:rebuild_keywords)
154
264
  nil
155
265
  ensure
156
- @mutex.synchronize do
157
- @generation += 1
158
- @detection_by_user_agent.clear
159
- @languages_by_header.clear
160
- @requirement_by_string.clear
161
- @gem_version_by_version.clear
162
- @client_hints_by_key.clear
163
- end
266
+ @tables.clear { @generation += 1 }
164
267
  end
165
268
 
166
269
  # The bot list holds hundreds of entries: compared by identity and size,
@@ -185,9 +288,17 @@ module Agentry
185
288
  @bots_size = Bot.bots.size
186
289
  end
187
290
 
291
+ # Every Ractor compares the lists on each request: what it compares them with must be shareable too.
292
+ def self.make_remembered_lists_shareable
293
+ generation
294
+ Ractor.make_shareable([@browser_matchers, @platform_matchers, @device_matchers, @bot_matchers, @bot_exceptions])
295
+ end
296
+
297
+ # The tables first: in a Ractor before Agentry.prepare_for_ractors!, the lists generation reads can't be.
188
298
  def self.current_detection_by_user_agent
299
+ detection_by_user_agent = tables.detection_by_user_agent
189
300
  generation
190
- @detection_by_user_agent
301
+ detection_by_user_agent
191
302
  end
192
303
 
193
304
  def self.store(value_by_key, key, value)
@@ -195,7 +306,8 @@ module Agentry
195
306
  value_by_key[key] = value
196
307
  end
197
308
 
198
- private_class_method :table, :table_class, :lists_unchanged?, :remember_lists,
199
- :current_detection_by_user_agent, :client_hints_key, :versioned, :store
309
+ private_class_method :table, :table_class, :lists_unchanged?, :remember_lists, :make_remembered_lists_shareable,
310
+ :tables, :ractor_tables, :new_ractor_tables, :current_detection_by_user_agent, :client_hints_key, :versioned,
311
+ :cacheable_version?, :store
200
312
  end
201
313
  end
@@ -11,9 +11,60 @@ module Agentry
11
11
 
12
12
  self.class.new(segments.take_while { |segment| segment.is_a?(Integer) }.join("."))
13
13
  end
14
+
15
+ # RubyGems' own, without its class variable.
16
+ def bump
17
+ segments = self.segments
18
+ segments.pop while segments.any?(String)
19
+ segments.pop if segments.size > 1
20
+ segments[-1] = segments[-1].succ
21
+ self.class.new(segments.join("."))
22
+ end
14
23
  end
15
24
 
16
- private_constant :UncachedVersion
25
+ # Gem::Requirement for the Ractors other than the main one, which can read neither RubyGems' class variables
26
+ # nor its OPS lambdas: the same operators, over UncachedVersion.
27
+ class RactorRequirement < Gem::Requirement
28
+ def self.parse(requirement)
29
+ return ["=", requirement] if requirement.is_a?(Gem::Version)
30
+ raise BadRequirementError, "Illformed requirement [#{requirement.inspect}]" unless PATTERN =~ requirement.to_s
31
+
32
+ [-($1 || "="), UncachedVersion.new($2)]
33
+ end
34
+
35
+ # "!", RubyGems' source set, compares nothing.
36
+ def self.source_set
37
+ nil
38
+ end
39
+
40
+ def initialize(*requirements)
41
+ requirements = requirements.flatten
42
+ requirements.compact!
43
+ requirements.uniq!
44
+ requirements = [">= 0"] if requirements.empty?
45
+ @requirements = requirements.map { |requirement| self.class.parse(requirement) }
46
+ end
47
+
48
+ def satisfied_by?(version)
49
+ raise ArgumentError, "Need a Gem::Version: #{version.inspect}" unless version.is_a?(Gem::Version)
50
+
51
+ requirements.all? { |operator, required| satisfies?(version, operator, required) }
52
+ end
53
+
54
+ private def satisfies?(version, operator, required)
55
+ case operator
56
+ when "=" then version == required
57
+ when "!=" then version != required
58
+ when ">" then version > required
59
+ when "<" then version < required
60
+ when ">=" then version >= required
61
+ when "<=" then version <= required
62
+ when "~>" then version >= required && version.release < required.bump
63
+ end
64
+ end
65
+ end
66
+
67
+ private_constant :UncachedVersion, :RactorRequirement
17
68
 
18
69
  private def detect_version?(actual_version, expected_version)
19
70
  return true unless expected_version
@@ -22,7 +73,7 @@ module Agentry
22
73
  expected_version = parse_version(expected_version)
23
74
  actual_version = parse_version(actual_version)
24
75
 
25
- requirement = Cache.requirement(expected_version) { Gem::Requirement.create(expected_version) }
76
+ requirement = Cache.requirement(expected_version) { requirement_class.create(expected_version) }
26
77
  # RubyGems reads "!" as its source set marker, which compares nothing, and a requirement that can't be read
27
78
  # as UTF-8 raises an EncodingError: neither is a requirement a version meets.
28
79
  requirement.is_a?(Gem::Requirement) && requirement.satisfied_by?(gem_version(actual_version))
@@ -30,6 +81,10 @@ module Agentry
30
81
  false
31
82
  end
32
83
 
84
+ private def requirement_class
85
+ Cache.main_ractor? ? Gem::Requirement : RactorRequirement
86
+ end
87
+
33
88
  # The last one used: a cached platform asks for the same version on each request, also when Cache keeps none.
34
89
  private def gem_version(version)
35
90
  string, gem_version = @gem_version
@@ -247,11 +247,11 @@ module Agentry
247
247
  # without /i gives the same answer several times faster. Every prefix is 4
248
248
  # characters long: anchored, it tests the first 4 without copying them, and
249
249
  # grouped by first byte (parentheses nest two deep), at most 14 are tried.
250
- MOBILE_LOWERCASE_REGEX = Regexp.new(MOBILE_REGEX.source)
250
+ MOBILE_LOWERCASE_REGEX = Regexp.new(MOBILE_REGEX.source).freeze
251
251
  MOBILE_PREFIX_LOWERCASE_REGEX_BY_FIRST_BYTE = MOBILE_PREFIX_REGEX.source
252
252
  .scan(/(?:[^|()]|\((?:[^()]|\([^()]*\))*\))+/)
253
253
  .group_by { |prefix| prefix.getbyte(0) }
254
- .transform_values { |prefixes| Regexp.new("\\A(?:#{prefixes.join("|")})") }
254
+ .transform_values { |prefixes| Regexp.new("\\A(?:#{prefixes.join("|")})").freeze }
255
255
  .freeze
256
256
  private_constant :REQUIRED_PATTERN_BY_MATCHER, :MOBILE_REGEX, :MOBILE_PREFIX_REGEX, :MOBILE_LOWERCASE_REGEX,
257
257
  :MOBILE_PREFIX_LOWERCASE_REGEX_BY_FIRST_BYTE
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Agentry
4
- VERSION = "4.1.1"
4
+ VERSION = "4.2.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: agentry
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.1.1
4
+ version: 4.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nando Vieira