sitegoose 0.3.3 → 0.3.4

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.
@@ -15,21 +15,51 @@
15
15
  # to the Dead set, sidekiq_retry_in returning :kill). Sidekiq stopping a job
16
16
  # mid-run (Sidekiq::Shutdown) is neither timed nor sent: it runs again. What's
17
17
  # waiting is sent when Sidekiq shuts down.
18
+ #
19
+ # The queues' backlog (sdk/protocols/queues.md, system "sidekiq"): the
20
+ # Sidekiq process reads every queue once a minute through Sidekiq's API
21
+ # (sidekiq/api): waiting is Sidekiq::Queue#size, oldest_s its latency,
22
+ # running the WorkSet's jobs per queue, delayed the ScheduledSet's and
23
+ # RetrySet's jobs per queue, failed the DeadSet's. One process reads a
24
+ # minute (a Redis key per minute decides which); the others count only.
25
+ # added and finished are each process's own: a client middleware counts the
26
+ # jobs pushed, once each (it marks the job it counted, so the scheduler or a
27
+ # retry moving it back isn't a second one), the server middleware the jobs
28
+ # that left for good (done, or failed on the last attempt, or given up).
18
29
 
19
30
  module SiteGoose
20
31
  module Sidekiq
21
32
  SKIP = :@__sitegoose_skip
22
33
  DEFAULT_RETRIES = 25
34
+ SYSTEM = "sidekiq"
35
+ # Set in the job's own hash (stored with it in Redis) once a push has
36
+ # been counted as added: the scheduler, a retry or the Web UI pushing the
37
+ # same job back carries it, so the job is never counted twice.
38
+ ADDED = "sitegoose_added"
39
+ # The jid the server middleware just counted as finished: the death
40
+ # handler, which runs after it in the same thread, leaves it.
41
+ COUNTED = :sitegoose_sidekiq_finished
23
42
 
24
43
  module_function
25
44
 
26
- # Adds the server middleware, the death handler and the shutdown flush.
45
+ # Adds the server and client middleware, the death handler, the queue
46
+ # readings and the shutdown flush; in a process that only pushes jobs (a
47
+ # Rails server), the client middleware.
27
48
  # platform: default the configured one (SiteGoose.platform).
28
49
  def install(platform = nil)
29
50
  ::Sidekiq.configure_server do |config|
30
51
  config.server_middleware { |chain| chain.add ServerMiddleware, platform }
52
+ config.client_middleware { |chain| chain.add ClientMiddleware, platform } if config.respond_to?(:client_middleware)
31
53
  config.death_handlers << ->(job, error) { Sidekiq.died(platform, job, error) } if config.respond_to?(:death_handlers)
32
- config.on(:shutdown) { SiteGoose.within { (platform || SiteGoose.platform)&.flush } } if config.respond_to?(:on)
54
+ if config.respond_to?(:on)
55
+ config.on(:startup) { Sidekiq.start_reading(platform, config) }
56
+ config.on(:shutdown) { SiteGoose.within { (platform || SiteGoose.platform)&.flush } }
57
+ end
58
+ end
59
+ return unless ::Sidekiq.respond_to?(:configure_client)
60
+
61
+ ::Sidekiq.configure_client do |config|
62
+ config.client_middleware { |chain| chain.add ClientMiddleware, platform } if config.respond_to?(:client_middleware)
33
63
  end
34
64
  end
35
65
 
@@ -37,8 +67,11 @@ module SiteGoose
37
67
  (job["wrapped"] || job["class"]).to_s
38
68
  end
39
69
 
70
+ # Sidekiq 7+'s configuration, 6.5's Sidekiq[] (its Sidekiq.options logs
71
+ # a deprecation warning on every call, here every job), or older 6's.
40
72
  def max_retries
41
73
  config = if ::Sidekiq.respond_to?(:default_configuration) then ::Sidekiq.default_configuration
74
+ elsif ::Sidekiq.respond_to?(:[]) then ::Sidekiq
42
75
  elsif ::Sidekiq.respond_to?(:options) then ::Sidekiq.options
43
76
  end
44
77
  value = config && config[:max_retries]
@@ -48,19 +81,31 @@ module SiteGoose
48
81
  end
49
82
 
50
83
  # Whether this run is the job's last: no retries, or the retries used up.
51
- # retry_count is nil on the first run and 0 on the first retry.
84
+ # retry_count is nil on the first run and 0 on the first retry. As
85
+ # Sidekiq's JobRetry reads it: a retry that isn't an Integer is the
86
+ # default count, and retry_for (7.1+) retries for a time rather than a
87
+ # count, so no run is known to be the last; Sidekiq's death handler
88
+ # counts and sends the one it gives up.
52
89
  def last_attempt?(job)
53
90
  retry_option = job["retry"]
54
91
  return true if retry_option == false || retry_option.nil?
92
+ return false if job["retry_for"]
55
93
 
56
- allowed = retry_option == true ? max_retries : retry_option.to_i
94
+ allowed = retry_option.is_a?(Integer) ? retry_option : max_retries
57
95
  attempts = job["retry_count"].nil? ? 0 : job["retry_count"].to_i + 1
58
96
  attempts >= allowed
59
97
  end
60
98
 
61
99
  def died(platform, job, error)
62
100
  made = platform || SiteGoose.platform
63
- return unless made && error.is_a?(Exception)
101
+ return unless made
102
+
103
+ # Given up before its last attempt (sidekiq_retry_in :kill): it left
104
+ # the queue for good, and the middleware didn't count it.
105
+ counted = Thread.current[COUNTED]
106
+ Thread.current[COUNTED] = nil
107
+ finished(made, job["queue"]) if job.is_a?(Hash) && (counted.nil? || counted != job["jid"])
108
+ return unless error.is_a?(Exception)
64
109
 
65
110
  error.remove_instance_variable(SKIP) if error.instance_variable_defined?(SKIP)
66
111
  route = "/(job) #{SiteGoose.text(name_of(job), 180)}"
@@ -70,6 +115,192 @@ module SiteGoose
70
115
  nil
71
116
  end
72
117
 
118
+ # ---- The queues ----
119
+
120
+ def finished(made, queue)
121
+ made.queues&.count(SYSTEM, broker, queue.to_s, :finished) unless queue.to_s.empty?
122
+ rescue StandardError
123
+ nil
124
+ end
125
+
126
+ # Whether a push is a new job rather than Sidekiq's scheduler, a retry
127
+ # or the Web UI moving one onto its queue (client middleware runs for
128
+ # all of them, with the job hash as it was stored). A job counted when
129
+ # it was first pushed carries ADDED; a retry carries retry_count. Sidekiq
130
+ # keeps nothing else that tells them apart: created_at is set once for a
131
+ # whole push_bulk, so its age says nothing about a push.
132
+ def new_job?(job)
133
+ job.is_a?(Hash) && !job.key?(ADDED) && !job.key?("retry_count")
134
+ end
135
+
136
+ # Where the queues live: host, port and Redis database, never a user
137
+ # name or password. Read once from Sidekiq's connection.
138
+ def broker
139
+ @broker ||= begin
140
+ found = ::Sidekiq.redis { |conn| broker_of(conn) }
141
+ found.is_a?(String) && !found.empty? ? found : broker_from_url(ENV["REDIS_URL"])
142
+ rescue StandardError
143
+ broker_from_url(ENV["REDIS_URL"])
144
+ end
145
+ end
146
+
147
+ # For tests, and after the configuration changed.
148
+ def broker=(value)
149
+ @broker = value
150
+ end
151
+
152
+ # A connection's host:port/db: redis-client's config (Sidekiq 7+), or
153
+ # the redis gem's connection hash (Sidekiq 6).
154
+ def broker_of(conn)
155
+ if conn.respond_to?(:config) && conn.config.respond_to?(:host)
156
+ config = conn.config
157
+ path = config.respond_to?(:path) ? config.path : nil
158
+ return broker_string(config.host, config.port, config.db, path)
159
+ end
160
+ if conn.respond_to?(:connection)
161
+ info = conn.connection
162
+ return broker_string(info[:host], info[:port], info[:db], info[:path]) if info.is_a?(Hash)
163
+ end
164
+ nil
165
+ end
166
+
167
+ def broker_from_url(url)
168
+ uri = URI.parse(url.to_s)
169
+ return "localhost:6379/0" if uri.host.nil?
170
+
171
+ broker_string(uri.host, uri.port, uri.path.to_s.delete("/").to_i, nil)
172
+ rescue URI::Error
173
+ "localhost:6379/0"
174
+ end
175
+
176
+ def broker_string(host, port, db, path)
177
+ db = db.to_i
178
+ return "#{path.to_s.split('/').last.to_s[0, 80]}/#{db}" if path.is_a?(String) && !path.empty?
179
+
180
+ # Only what follows a user name or password, were one ever there.
181
+ host = host.to_s.split("@").last.to_s.gsub(%r{[\s/]}, "")[0, 120]
182
+ host = "localhost" if host.empty?
183
+ "#{host}:#{port.to_i.positive? ? port.to_i : 6379}/#{db}"
184
+ end
185
+
186
+ # The queues this process runs jobs from (Sidekiq 7's capsules, or 6's
187
+ # options): their finished count is 0 in a quiet minute, not unknown.
188
+ def own_queues(config)
189
+ names = if config.respond_to?(:capsules) then config.capsules.values.flat_map(&:queues)
190
+ elsif config.respond_to?(:queues) then config.queues
191
+ elsif config.respond_to?(:options) then config.options[:queues]
192
+ elsif config.respond_to?(:[]) then config[:queues]
193
+ end
194
+ Array(names).map(&:to_s).reject(&:empty?).uniq
195
+ rescue StandardError
196
+ []
197
+ end
198
+
199
+ # At Sidekiq's startup: this process reads the queues once a minute.
200
+ def start_reading(platform, config = nil)
201
+ made = platform || SiteGoose.platform
202
+ queues = made&.queues
203
+ return unless queues
204
+
205
+ own_queues(config).each { |name| queues.counting(SYSTEM, broker, name, :finished) }
206
+ queues.watch(Reader.new(queues.sender, made.core.site_id))
207
+ rescue StandardError => e
208
+ made&.core&.log("queues", "could not start reading Sidekiq's queues:", e.message)
209
+ end
210
+
211
+ # Sidekiq's queues, read through its public API (sidekiq/api).
212
+ class Reader
213
+ # A sorted set bigger than this isn't counted per queue (Sidekiq reads
214
+ # it 50 jobs at a time, each parsed): its field is unknown rather than
215
+ # megabytes read from Redis every minute. With one queue no job has to
216
+ # be read: the set's size is that queue's.
217
+ SET_MAX = 1_000
218
+ LOCK_SECONDS = 90
219
+
220
+ # sender: this process (Queues#sender); site: the site the readings are
221
+ # for, so two sites sharing one Redis each get theirs.
222
+ def initialize(sender, site = "")
223
+ @sender = sender
224
+ @site = site.to_s
225
+ end
226
+
227
+ # -> one reading per queue ({system:, broker:, queue:, waiting: ...}),
228
+ # [] when another process reads this minute. Raises when Redis
229
+ # doesn't answer (a gap).
230
+ def read
231
+ require "sidekiq/api" unless defined?(::Sidekiq::Queue)
232
+ return [] unless reader_this_minute?
233
+
234
+ broker = Sidekiq.broker
235
+ queues = ::Sidekiq::Queue.all.first(Queues::MAX_QUEUES)
236
+ names = queues.map { |queue| queue.name.to_s }
237
+ running = safely { running_by_queue }
238
+ scheduled = safely { by_queue(::Sidekiq::ScheduledSet.new, names) }
239
+ retrying = safely { by_queue(::Sidekiq::RetrySet.new, names) }
240
+ dead = safely { by_queue(::Sidekiq::DeadSet.new, names) }
241
+ queues.map do |queue|
242
+ name = queue.name.to_s
243
+ waiting = queue.size.to_i
244
+ { system: SYSTEM, broker: broker, queue: name, waiting: waiting,
245
+ running: running && running[name].to_i,
246
+ delayed: scheduled && retrying ? scheduled[name].to_i + retrying[name].to_i : nil,
247
+ failed: dead && dead[name].to_i,
248
+ oldest_s: oldest(queue, waiting) }
249
+ end
250
+ end
251
+
252
+ # Seconds the oldest waiting job has waited: 0 with none, unknown when
253
+ # Sidekiq can't say (a job pushed without enqueued_at reads 0.0).
254
+ def oldest(queue, waiting)
255
+ return 0 if waiting.zero?
256
+
257
+ latency = queue.latency.to_f
258
+ latency.positive? ? latency.round : nil
259
+ rescue StandardError
260
+ nil
261
+ end
262
+
263
+ def safely
264
+ yield
265
+ rescue StandardError
266
+ nil
267
+ end
268
+
269
+ def running_by_queue
270
+ set = defined?(::Sidekiq::WorkSet) ? ::Sidekiq::WorkSet.new : ::Sidekiq::Workers.new
271
+ out = Hash.new(0)
272
+ set.each do |_process, _thread, work|
273
+ name = work.respond_to?(:queue) ? work.queue : work["queue"]
274
+ out[name.to_s] += 1
275
+ end
276
+ out
277
+ end
278
+
279
+ # queue name -> jobs of the set in it, or nil when that would mean
280
+ # reading more than SET_MAX jobs.
281
+ def by_queue(set, names = [])
282
+ size = set.size
283
+ out = Hash.new(0)
284
+ return out if size.zero?
285
+ return out.merge!(names[0] => size) if names.size == 1
286
+ return nil if size > SET_MAX
287
+
288
+ set.each { |entry| out[entry.queue.to_s] += 1 }
289
+ out
290
+ end
291
+
292
+ # One Sidekiq process reads a minute: the first to set this minute's
293
+ # key. Without the answer (an old client, a namespace) it reads anyway:
294
+ # gauges taken twice are harmless, the dashboard keeps the largest.
295
+ def reader_this_minute?
296
+ key = "sitegoose:queues:#{@site}:#{MinuteRows.minute}"
297
+ got = ::Sidekiq.redis { |conn| conn.call("SET", key, @sender, "NX", "EX", LOCK_SECONDS.to_s) }
298
+ got.nil? || got == false ? false : true
299
+ rescue StandardError
300
+ true
301
+ end
302
+ end
303
+
73
304
  class ServerMiddleware
74
305
  include ::Sidekiq::ServerMiddleware if defined?(::Sidekiq::ServerMiddleware)
75
306
 
@@ -77,18 +308,64 @@ module SiteGoose
77
308
  @platform = platform
78
309
  end
79
310
 
80
- def call(_worker, job, _queue, &block)
311
+ def call(_worker, job, queue, &block)
81
312
  made = @platform || SiteGoose.platform
82
313
  return yield if made.nil?
83
314
 
84
315
  Forking.check
85
316
  last = Sidekiq.last_attempt?(job)
86
- made.job(Sidekiq.name_of(job), report: lambda { |error|
87
- # Retried: Rails' own error report (its executor wraps the job) is
88
- # told to leave it too.
89
- error.instance_variable_set(SKIP, true) if !last && !error.frozen?
90
- last
91
- }, &block)
317
+ done = false
318
+ begin
319
+ result = made.job(Sidekiq.name_of(job), report: lambda { |error|
320
+ # Retried: Rails' own error report (its executor wraps the job) is
321
+ # told to leave it too.
322
+ error.instance_variable_set(SKIP, true) if !last && !error.frozen?
323
+ last
324
+ }, &block)
325
+ done = true
326
+ result
327
+ rescue SignalException, SystemExit
328
+ # Sidekiq::Shutdown: it runs again.
329
+ raise
330
+ rescue Exception # rubocop:disable Lint/RescueException -- raised on
331
+ done = last
332
+ raise
333
+ ensure
334
+ if done
335
+ Thread.current[COUNTED] = job["jid"]
336
+ Sidekiq.finished(made, queue)
337
+ end
338
+ end
339
+ end
340
+ end
341
+
342
+ # Counts the jobs this process pushes (Health -> Server speed -> Jobs:
343
+ # added), once each: the scheduler and a retry pushing one back aren't
344
+ # new jobs. A scheduled job counts when it is scheduled. One pushed by a
345
+ # process without this middleware counts when the scheduler moves it.
346
+ class ClientMiddleware
347
+ include ::Sidekiq::ClientMiddleware if defined?(::Sidekiq::ClientMiddleware)
348
+
349
+ def initialize(platform = nil)
350
+ @platform = platform
351
+ end
352
+
353
+ def call(_worker_class, job, queue, _redis_pool = nil)
354
+ result = yield
355
+ begin
356
+ if result && Sidekiq.new_job?(job)
357
+ counter = (@platform || SiteGoose.platform)&.queues
358
+ if counter&.on?
359
+ counter.count(SYSTEM, Sidekiq.broker, (queue || job["queue"]).to_s, :added)
360
+ # The hash Sidekiq pushes (the job itself, unless a middleware
361
+ # handed back another).
362
+ (result.is_a?(Hash) ? result : job)[ADDED] = true
363
+ end
364
+ end
365
+ rescue StandardError
366
+ nil
367
+ end
368
+ result
92
369
  end
93
370
  end
94
371
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SiteGoose
4
- VERSION = "0.3.3"
4
+ VERSION = "0.3.4"
5
5
  end
data/lib/sitegoose.rb CHANGED
@@ -25,6 +25,8 @@ require_relative "sitegoose/performance"
25
25
  require_relative "sitegoose/errors"
26
26
  require_relative "sitegoose/query_text"
27
27
  require_relative "sitegoose/queries"
28
+ require_relative "sitegoose/calls"
29
+ require_relative "sitegoose/queues"
28
30
  require_relative "sitegoose/crawlers"
29
31
  require_relative "sitegoose/analytics"
30
32
  require_relative "sitegoose/small_modules"
@@ -259,3 +261,6 @@ module SiteGoose
259
261
  end
260
262
 
261
263
  require_relative "sitegoose/railtie" if defined?(::Rails::Railtie)
264
+ # Faraday's middleware is registered when Faraday is already loaded; else
265
+ # require "sitegoose/faraday" after it.
266
+ require_relative "sitegoose/faraday" if defined?(::Faraday::Middleware)
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sitegoose
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.3
4
+ version: 0.3.4
5
5
  platform: ruby
6
6
  authors:
7
7
  - steviec87
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-04 00:00:00.000000000 Z
11
+ date: 2026-11-07 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rack
@@ -32,9 +32,10 @@ dependencies:
32
32
  version: '4'
33
33
  description: 'Rack middleware and a Railtie: a firewall with rate limits, shared blocks,
34
34
  attack patterns and a browser check; error monitoring (Rails.error, Sidekiq); server
35
- speed per route; crawler counts; server-side events, leads and audit log; feature
36
- flags and maintenance mode; and the gems, settings and machine figures the Security
37
- check needs. Standard library and rack only.'
35
+ speed per route, with its database queries, outgoing calls, job queues and how close
36
+ the server is to its limits; crawler counts; server-side events, leads and audit
37
+ log; feature flags and maintenance mode; and the gems, settings and machine figures
38
+ the Security check needs. Standard library and rack only.'
38
39
  email:
39
40
  executables: []
40
41
  extensions: []
@@ -44,10 +45,12 @@ files:
44
45
  - README.md
45
46
  - lib/sitegoose.rb
46
47
  - lib/sitegoose/analytics.rb
48
+ - lib/sitegoose/calls.rb
47
49
  - lib/sitegoose/challenge.rb
48
50
  - lib/sitegoose/core.rb
49
51
  - lib/sitegoose/crawlers.rb
50
52
  - lib/sitegoose/errors.rb
53
+ - lib/sitegoose/faraday.rb
51
54
  - lib/sitegoose/firewall.rb
52
55
  - lib/sitegoose/inventory.rb
53
56
  - lib/sitegoose/ip.rb
@@ -58,6 +61,7 @@ files:
58
61
  - lib/sitegoose/proxy.rb
59
62
  - lib/sitegoose/queries.rb
60
63
  - lib/sitegoose/query_text.rb
64
+ - lib/sitegoose/queues.rb
61
65
  - lib/sitegoose/railtie.rb
62
66
  - lib/sitegoose/request_rules.rb
63
67
  - lib/sitegoose/resources.rb