fingerly 0.4.1 → 0.5.1

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.
@@ -0,0 +1,421 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fingerly
4
+ # Reports the requests your server served, so AI crawlers and fetchers that
5
+ # never run a page's JavaScript are seen, and answers what sent a request
6
+ # from what the server said about it before.
7
+ #
8
+ # Build one per process at start-up and share it: it is safe to use from
9
+ # every thread and fiber. Mount {AgentSightings::Middleware} to report, and
10
+ # call {#lookup} where a decision needs the answer:
11
+ #
12
+ # SIGHTINGS = Fingerly::AgentSightings.new(
13
+ # secret_key: ENV.fetch("FINGERLY_SECRET_KEY"),
14
+ # client_ip: ->(request) { request.header("CF-Connecting-IP") }
15
+ # )
16
+ #
17
+ # answer = SIGHTINGS.lookup(request.env)
18
+ # if answer.visitor_kind == Fingerly::VisitorKind::AI_BOT
19
+ # # ...
20
+ # end
21
+ #
22
+ # The SDK forwards raw input and remembers answers; it never judges a user
23
+ # agent or an address itself. Reports go out from one background thread,
24
+ # never from a request, and every failure leaves requests served as usual:
25
+ # {#lookup} then answers {UNKNOWN}. Memory is bounded by {#capacity} answers
26
+ # and {MAX_PENDING} pending reports. The path, query string, cookies,
27
+ # +Authorization+, other headers and bodies are never sent or logged.
28
+ class AgentSightings
29
+ include Redacted
30
+
31
+ # The answer when nothing is known about a request: serve it as usual.
32
+ # Its +visitor_kind+ is +""+, which no server answer carries, so a check
33
+ # against a {VisitorKind} constant fails open.
34
+ UNKNOWN = AgentSighting.new("ttl" => 0, "visitor_kind" => "")
35
+
36
+ DEFAULT_CAPACITY = 4096
37
+ MAX_CAPACITY = 65_536
38
+ # Pending reports held at most; a new request past this stays {UNKNOWN}
39
+ # and is counted in {#dropped_count}.
40
+ MAX_PENDING = 1000
41
+ # A flush sends at most this many items...
42
+ FLUSH_ITEMS = Agents::MAX_SIGHTINGS
43
+ # ...and at most this many bytes of fields; reaching either starts one.
44
+ FLUSH_BYTES = 64 * 1024
45
+ # Seconds after its oldest item that a buffer is flushed.
46
+ FLUSH_AFTER = 2
47
+ # Seconds one flush may take, the response body included.
48
+ FLUSH_DEADLINE = 5
49
+ # Seconds {#flush} waits for a flush already in flight: its deadline and a
50
+ # second of margin.
51
+ IN_FLIGHT_WAIT = FLUSH_DEADLINE + 1
52
+ # The longest header value reported, in bytes.
53
+ MAX_HEADER_BYTES = 4096
54
+ # The most requests one item may stand for.
55
+ MAX_COUNT = 1_000_000
56
+
57
+ # Seconds between the background thread's checks.
58
+ TICK = 0.25
59
+ # Seconds reporting stops after the key was refused.
60
+ AUTH_PAUSE = 60
61
+ # Seconds reporting stops after a 429 that named no Retry-After.
62
+ RATE_LIMIT_PAUSE = 60
63
+ # The shortest stop after a 429, whatever its Retry-After said.
64
+ RETRY_AFTER_MIN = 1
65
+ # The longest stop after a 429, whatever its Retry-After said, so a huge
66
+ # value cannot end reporting for the life of the process.
67
+ RETRY_AFTER_MAX = 86_400
68
+ # Backoff bounds, in seconds, after a 503 or a transport error.
69
+ BACKOFF_MIN = 1
70
+ BACKOFF_MAX = 60
71
+ # Seconds between two log lines of one kind.
72
+ LOG_INTERVAL = 60
73
+
74
+ # Paths reported whatever their content type.
75
+ WELL_KNOWN_PATHS = %w[/robots.txt /llms.txt /llms-full.txt].freeze
76
+
77
+ # @return [Integer] the most answers remembered
78
+ attr_reader :capacity
79
+
80
+ # @param secret_key [String] a server-only key, +fly_sk_{environment}_…+
81
+ # @param client_ip [#call] resolves the visitor's address from a
82
+ # {ProxyRequest}, exactly as for {Proxy}: read it from a header your own
83
+ # infrastructure sets, or {ProxyRequest#peer_host}. Never use the
84
+ # left-most +X-Forwarded-For+ value: the visitor writes it. A request
85
+ # whose address cannot be resolved is not reported.
86
+ # @param capacity [Integer] the most answers remembered; a value above
87
+ # {MAX_CAPACITY} is read as {MAX_CAPACITY}
88
+ # @param endpoint [String, nil] overrides the Fingerly API origin
89
+ # @param allow_insecure_loopback [Boolean] lets +endpoint+ be plain +http+
90
+ # on a loopback host, for development and tests
91
+ # @param configure_http [Proc, nil] receives the +Net::HTTP+ before it
92
+ # connects
93
+ # @param logger [#warn, nil] receives the few lines this writes; standard
94
+ # error without one
95
+ # @raise [ConfigurationError] for an invalid key, callback or option
96
+ def initialize(secret_key:, client_ip:, capacity: DEFAULT_CAPACITY, endpoint: nil,
97
+ allow_insecure_loopback: false, configure_http: nil, logger: nil, clock: nil)
98
+ raise ConfigurationError, "client_ip is required" unless client_ip.respond_to?(:call)
99
+ unless capacity.is_a?(Integer) && capacity.positive?
100
+ raise ConfigurationError, "capacity must be a positive Integer"
101
+ end
102
+ if logger && !logger.respond_to?(:warn)
103
+ raise ConfigurationError, "logger must respond to warn"
104
+ end
105
+
106
+ @client = Client.new(secret_key: secret_key, endpoint: endpoint, timeout: FLUSH_DEADLINE,
107
+ configure_http: configure_http,
108
+ allow_insecure_loopback: allow_insecure_loopback)
109
+ @capacity = [capacity, MAX_CAPACITY].min
110
+ @logger = logger
111
+ @reader = Reader.new(client_ip, ->(line) { log_limited(:client_ip, line) })
112
+ # Only answers, pending reports and log limits age by this clock; waits
113
+ # use the real one.
114
+ @clock = clock || -> { AgentSightings.monotonic }
115
+ @lock = Mutex.new
116
+ @changed = ConditionVariable.new
117
+ @cache = AnswerCache.new(@capacity)
118
+ @buffer = PendingBuffer.new(MAX_PENDING, MAX_COUNT)
119
+ @dropped = 0
120
+ @in_flight = false
121
+ @paused_until = nil
122
+ @backoff = nil
123
+ @log_lock = Mutex.new
124
+ @logged_at = {}
125
+ @closed = false
126
+ @thread = nil
127
+ @pid = Process.pid
128
+ end
129
+
130
+ # The server's last answer for this request, from memory only.
131
+ #
132
+ # Never waits on the network and never raises.
133
+ #
134
+ # @param request [Hash, #env] the Rack environment, or a request object
135
+ # that holds one, such as +Rack::Request+ or a Rails +request+
136
+ # @return [AgentSighting] the answer, or {UNKNOWN}: serve the request as
137
+ # usual
138
+ def lookup(request)
139
+ sighting = @reader.sighting(request)
140
+ return UNKNOWN if sighting.nil?
141
+
142
+ @lock.synchronize do
143
+ forked!
144
+ @cache.get(sighting.key, now)
145
+ end || UNKNOWN
146
+ rescue StandardError
147
+ UNKNOWN
148
+ end
149
+
150
+ # Records one served request for the next report. {Middleware} calls it
151
+ # for the responses in its scope; call it yourself only from a framework
152
+ # Rack does not reach.
153
+ #
154
+ # In memory only: never waits on the network and never raises.
155
+ #
156
+ # @param request [Hash, #env] the Rack environment, or a request object
157
+ # that holds one
158
+ # @return [nil]
159
+ def report(request)
160
+ return nil if @closed
161
+
162
+ sighting = @reader.sighting(request)
163
+ return nil if sighting.nil?
164
+
165
+ @lock.synchronize do
166
+ forked!
167
+ start_flusher
168
+ @dropped += 1 if @buffer.add(sighting, now) == :dropped
169
+ @changed.broadcast if full?
170
+ end
171
+ nil
172
+ rescue StandardError
173
+ nil
174
+ end
175
+
176
+ # Sends what is pending now, on the calling thread, and waits for it.
177
+ #
178
+ # For serverless runtimes, before an invocation ends; long-running servers
179
+ # need not call it. Sends nothing while reporting is paused by a refusal.
180
+ # Never raises, and works from a signal handler too.
181
+ #
182
+ # @return [nil]
183
+ def flush
184
+ return AgentSightings.outside_trap(locks) { flush } if AgentSightings.trap_context?
185
+
186
+ loop do
187
+ outcome = await_idle(AgentSightings.monotonic + IN_FLIGHT_WAIT) ? flush_once : :failed
188
+ # The background thread took a batch after the wait: wait for it too.
189
+ next if outcome == :busy
190
+ break unless outcome == :sent
191
+ break if @lock.synchronize { @buffer.empty? }
192
+ end
193
+ nil
194
+ rescue StandardError
195
+ nil
196
+ end
197
+
198
+ # Stops the background thread, then flushes what is pending as {#flush}
199
+ # does, unless reporting is paused. Later reports are ignored; {#lookup}
200
+ # keeps answering from memory. Safe to call more than once, from several
201
+ # threads at once, and from a signal handler such as +trap("TERM")+,
202
+ # which it holds up {TRAP_WAIT} seconds at most.
203
+ #
204
+ # @return [nil]
205
+ def close
206
+ return AgentSightings.outside_trap(locks) { close } if AgentSightings.trap_context?
207
+
208
+ thread = @lock.synchronize do
209
+ forked!
210
+ @closed = true
211
+ @changed.broadcast
212
+ @thread
213
+ end
214
+ thread&.join(FLUSH_DEADLINE + 1)
215
+ flush
216
+ rescue StandardError
217
+ nil
218
+ end
219
+
220
+ # @return [Integer] requests not reported because the pending buffer was
221
+ # full, in this process
222
+ def dropped_count
223
+ @lock.synchronize do
224
+ forked!
225
+ @dropped
226
+ end
227
+ end
228
+
229
+ private
230
+
231
+ def redacted_fields
232
+ [["capacity", @capacity], ["secret_key", Redacted::MARK]]
233
+ end
234
+
235
+ def now = @clock.call
236
+
237
+ # A forked child starts over: its parent reports what was pending, and
238
+ # the parent's thread does not exist here. Remembered answers stay valid.
239
+ def forked!
240
+ return if @pid == Process.pid
241
+
242
+ @pid = Process.pid
243
+ @buffer.clear
244
+ @dropped = 0
245
+ @in_flight = false
246
+ @thread = nil
247
+ @log_lock = Mutex.new
248
+ @logged_at = {}
249
+ end
250
+
251
+ def start_flusher
252
+ return if @closed || @thread&.alive?
253
+
254
+ @thread = Thread.new { run_flusher }
255
+ @thread.name = "fingerly-agent-sightings"
256
+ @thread.report_on_exception = false
257
+ end
258
+
259
+ def run_flusher
260
+ loop do
261
+ @lock.synchronize do
262
+ @changed.wait(@lock, TICK) unless @closed || due?
263
+ end
264
+ return if @closed
265
+
266
+ loop { break unless @lock.synchronize { due? } && flush_once == :sent }
267
+ rescue StandardError
268
+ # A bug here must not end reporting for the life of the process.
269
+ sleep TICK
270
+ end
271
+ end
272
+
273
+ def full?
274
+ @buffer.size >= FLUSH_ITEMS || @buffer.bytes >= FLUSH_BYTES
275
+ end
276
+
277
+ def paused?
278
+ !@paused_until.nil? && now < @paused_until
279
+ end
280
+
281
+ def due?
282
+ return false if @buffer.empty? || paused?
283
+
284
+ full? || now - @buffer.oldest_at >= FLUSH_AFTER
285
+ end
286
+
287
+ # Waits until no flush is in flight.
288
+ #
289
+ # @return [Boolean] false when the deadline passed first
290
+ def await_idle(deadline)
291
+ @lock.synchronize do
292
+ forked!
293
+ while @in_flight
294
+ left = deadline - AgentSightings.monotonic
295
+ return false if left <= 0
296
+
297
+ @changed.wait(@lock, [left, TICK].min)
298
+ end
299
+ true
300
+ end
301
+ end
302
+
303
+ # Sends one batch, unless another flush is in flight, nothing is
304
+ # pending, or reporting is paused.
305
+ #
306
+ # @return [Symbol] +:sent+, +:failed+, +:busy+ or +:idle+
307
+ def flush_once
308
+ batch = @lock.synchronize do
309
+ forked!
310
+ return :busy if @in_flight
311
+ return :idle if @buffer.empty? || paused?
312
+
313
+ @in_flight = true
314
+ @buffer.take(FLUSH_ITEMS, FLUSH_BYTES)
315
+ end
316
+ begin
317
+ deliver(batch)
318
+ ensure
319
+ @lock.synchronize do
320
+ # A kept batch was restored already; this settles the others.
321
+ @buffer.settle(batch)
322
+ @in_flight = false
323
+ @changed.broadcast
324
+ end
325
+ end
326
+ end
327
+
328
+ # Sends a batch and applies the failure table of section 6.
329
+ def deliver(batch)
330
+ inputs = batch.map { |item| AgentSightingInput.new(**item.fields, count: item.hits) }
331
+ answer = @client.agents.report_sightings(inputs)
332
+ if answer.items.size != batch.size
333
+ return drop("the API answered a report with the wrong number of items")
334
+ end
335
+
336
+ accepted(batch, answer)
337
+ rescue APIError => e
338
+ refused(e, batch)
339
+ rescue TimeoutError => e
340
+ # Once connected, the server may have counted the batch, and a retry
341
+ # would count it twice. Before that, nothing was sent.
342
+ e.connected? ? drop("a report timed out after it was sent") : keep(batch)
343
+ rescue ConnectionError => e
344
+ # A connection lost once the whole request was written is a timeout
345
+ # after sending by another name: the server may have counted it.
346
+ e.sent? ? drop("a report's connection failed after it was sent") : keep(batch)
347
+ rescue StandardError
348
+ drop("the API answered a report with a body that could not be read")
349
+ end
350
+
351
+ def accepted(batch, answer)
352
+ @lock.synchronize do
353
+ @cache.store(answer.rules_version,
354
+ batch.zip(answer.items).map { |item, sighting| [item.key, sighting] }, now)
355
+ @backoff = nil
356
+ end
357
+ :sent
358
+ end
359
+
360
+ def refused(error, batch)
361
+ case error.status
362
+ when 429
363
+ pause(AgentSightings.rate_limit_pause(error))
364
+ restore(batch)
365
+ when 401, 403
366
+ pause(AUTH_PAUSE)
367
+ log_limited(:auth, "fingerly agent sightings: the API refused the secret key " \
368
+ "(#{error.status}); the batch was dropped and reporting stops for " \
369
+ "#{AUTH_PAUSE} seconds")
370
+ when 503 then keep(batch)
371
+ # 422: no item in the batch was usable, an SDK bug, so never retried.
372
+ else drop("the API refused a report (#{error.status})")
373
+ end
374
+ :failed
375
+ end
376
+
377
+ # Puts the batch back and backs off: nothing was counted.
378
+ def keep(batch)
379
+ @lock.synchronize do
380
+ @backoff = @backoff ? [@backoff * 2, BACKOFF_MAX].min : BACKOFF_MIN
381
+ @paused_until = now + @backoff
382
+ end
383
+ restore(batch)
384
+ :failed
385
+ end
386
+
387
+ # The buffer's bound counts the batch in flight, so it always fits back.
388
+ def restore(batch)
389
+ @lock.synchronize { @buffer.restore(batch) }
390
+ end
391
+
392
+ def pause(seconds)
393
+ @lock.synchronize { @paused_until = now + seconds }
394
+ end
395
+
396
+ # A batch that sending again cannot help, or that may already count.
397
+ def drop(reason)
398
+ log_limited(:drop, "fingerly agent sightings: #{reason}; the batch was dropped")
399
+ :failed
400
+ end
401
+
402
+ # Logs a line at most once a minute for each kind. No line carries a
403
+ # request's fields.
404
+ def log_limited(kind, line)
405
+ at = now
406
+ due = @log_lock.synchronize do
407
+ last = @logged_at[kind]
408
+ next false if last && at - last < LOG_INTERVAL
409
+
410
+ @logged_at[kind] = at
411
+ end
412
+ log("#{line} (logged at most once a minute)") if due
413
+ end
414
+
415
+ def log(line)
416
+ @logger ? @logger.warn(line) : warn(line)
417
+ rescue *Config::CALLBACK_ERRORS
418
+ nil
419
+ end
420
+ end
421
+ end
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fingerly
4
+ class AgentSightings
5
+ # Rack middleware that reports the responses worth reporting to an
6
+ # {AgentSightings}.
7
+ #
8
+ # # config/application.rb
9
+ # config.middleware.use Fingerly::AgentSightings::Middleware, SIGHTINGS
10
+ #
11
+ # By default it reports every response with a +Content-Type+ of
12
+ # +text/html+ or +application/xhtml+xml+, and every request for
13
+ # +/robots.txt+, +/llms.txt+ and +/llms-full.txt+, whatever the status.
14
+ # Static assets, API routes and health checks are left out unless you
15
+ # include them. What is reported is decided by your own response and path,
16
+ # never by the visitor's user agent, address or headers.
17
+ #
18
+ # The report is made in memory after the application answered, so it
19
+ # never delays the response, and nothing it does can fail one.
20
+ class Middleware
21
+ # The response media types reported by default.
22
+ DEFAULT_CONTENT_TYPES = %w[text/html application/xhtml+xml].freeze
23
+
24
+ # @param app [#call] the rest of the Rack stack
25
+ # @param sightings [AgentSightings] where the reports go
26
+ # @param content_types [Array<String>] the response media types
27
+ # reported, replacing {DEFAULT_CONTENT_TYPES}; matched without regard
28
+ # to case or parameters
29
+ # @param include_path_prefixes [Array<String>] paths reported whatever
30
+ # their content type, such as +/feed+
31
+ # @param exclude_path_prefixes [Array<String>] paths never reported;
32
+ # these win over everything else
33
+ # @raise [ConfigurationError] for an option of the wrong shape
34
+ def initialize(app, sightings, content_types: DEFAULT_CONTENT_TYPES,
35
+ include_path_prefixes: [], exclude_path_prefixes: [])
36
+ unless sightings.is_a?(AgentSightings)
37
+ raise ConfigurationError, "sightings must be a Fingerly::AgentSightings"
38
+ end
39
+
40
+ @app = app
41
+ @sightings = sightings
42
+ @content_types = media_types(content_types)
43
+ @include = prefixes(include_path_prefixes, "include_path_prefixes")
44
+ @exclude = prefixes(exclude_path_prefixes, "exclude_path_prefixes")
45
+ freeze
46
+ end
47
+
48
+ # @param env [Hash] the Rack environment
49
+ # @return [Array(Integer, Hash, #each)] the application's response,
50
+ # untouched
51
+ def call(env)
52
+ response = @app.call(env)
53
+ begin
54
+ @sightings.report(env) if reported?(env["PATH_INFO"].to_s, response[1])
55
+ rescue StandardError
56
+ # Reporting never fails a response.
57
+ nil
58
+ end
59
+ response
60
+ end
61
+
62
+ # Whether a response is in scope.
63
+ #
64
+ # @param path [String] the application-relative path, +PATH_INFO+
65
+ # @param headers [Hash] the response headers
66
+ # @return [Boolean]
67
+ def reported?(path, headers)
68
+ return false if @exclude.any? { |prefix| path.start_with?(prefix) }
69
+ return true if WELL_KNOWN_PATHS.include?(path)
70
+ return true if @include.any? { |prefix| path.start_with?(prefix) }
71
+
72
+ @content_types.include?(media_type(headers))
73
+ end
74
+
75
+ def inspect
76
+ "#<Fingerly::AgentSightings::Middleware content_types=#{@content_types.inspect}>"
77
+ end
78
+
79
+ # A Content-Type's media type, lowercase and without parameters, or nil
80
+ # when it names none.
81
+ #
82
+ # @api private
83
+ def self.media(value)
84
+ media = value.split(";", 2).first.to_s.strip.downcase
85
+ media.empty? ? nil : media
86
+ end
87
+
88
+ private
89
+
90
+ # Rack 3 names headers in lowercase; Rack 2 applications may not.
91
+ def media_type(headers)
92
+ value = headers["content-type"] || headers["Content-Type"]
93
+ if value.nil? && headers.respond_to?(:each)
94
+ headers.each { |name, found| value = found if name.to_s.casecmp?("content-type") }
95
+ end
96
+ value = value.first if value.is_a?(Array)
97
+ return nil unless value.is_a?(String)
98
+
99
+ Middleware.media(value)
100
+ end
101
+
102
+ # The configured types read as a response's are, so +"text/html;
103
+ # charset=utf-8"+ or +" Text/HTML"+ still match.
104
+ def media_types(value)
105
+ types = strings(value, "content_types").map { |type| Middleware.media(type) }
106
+ if types.include?(nil)
107
+ raise ConfigurationError, "content_types must be media types such as text/html"
108
+ end
109
+
110
+ types.uniq.freeze
111
+ end
112
+
113
+ def strings(value, name)
114
+ unless value.is_a?(Array) && value.all? { |item| item.is_a?(String) && !item.empty? }
115
+ raise ConfigurationError, "#{name} must be an Array of non-empty Strings"
116
+ end
117
+
118
+ value
119
+ end
120
+
121
+ def prefixes(value, name)
122
+ list = strings(value, name)
123
+ unless list.all? { |prefix| prefix.start_with?("/") }
124
+ raise ConfigurationError, "#{name} must be paths that start with /"
125
+ end
126
+
127
+ list.dup.freeze
128
+ end
129
+ end
130
+ end
131
+ end