sidekiq 6.2.1 → 6.3.1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of sidekiq might be problematic. Click here for more details.

Files changed (53) hide show
  1. checksums.yaml +4 -4
  2. data/Changes.md +52 -1
  3. data/LICENSE +1 -1
  4. data/README.md +2 -2
  5. data/lib/sidekiq/api.rb +80 -56
  6. data/lib/sidekiq/cli.rb +10 -2
  7. data/lib/sidekiq/client.rb +2 -2
  8. data/lib/sidekiq/extensions/generic_proxy.rb +3 -1
  9. data/lib/sidekiq/fetch.rb +5 -4
  10. data/lib/sidekiq/job.rb +13 -0
  11. data/lib/sidekiq/job_logger.rb +1 -1
  12. data/lib/sidekiq/job_retry.rb +3 -7
  13. data/lib/sidekiq/launcher.rb +18 -18
  14. data/lib/sidekiq/middleware/chain.rb +5 -3
  15. data/lib/sidekiq/middleware/current_attributes.rb +52 -0
  16. data/lib/sidekiq/rails.rb +11 -0
  17. data/lib/sidekiq/redis_connection.rb +4 -6
  18. data/lib/sidekiq/scheduled.rb +40 -15
  19. data/lib/sidekiq/testing.rb +1 -3
  20. data/lib/sidekiq/version.rb +1 -1
  21. data/lib/sidekiq/web/action.rb +1 -1
  22. data/lib/sidekiq/web/application.rb +4 -4
  23. data/lib/sidekiq/web/helpers.rb +9 -21
  24. data/lib/sidekiq/web.rb +4 -3
  25. data/lib/sidekiq/worker.rb +72 -5
  26. data/lib/sidekiq.rb +3 -1
  27. data/sidekiq.gemspec +1 -1
  28. data/web/assets/javascripts/application.js +82 -61
  29. data/web/assets/javascripts/dashboard.js +51 -51
  30. data/web/assets/stylesheets/application-dark.css +18 -31
  31. data/web/assets/stylesheets/application-rtl.css +0 -4
  32. data/web/assets/stylesheets/application.css +21 -233
  33. data/web/locales/ar.yml +8 -2
  34. data/web/locales/en.yml +4 -1
  35. data/web/locales/es.yml +18 -2
  36. data/web/locales/fr.yml +7 -0
  37. data/web/locales/ja.yml +3 -0
  38. data/web/locales/lt.yml +1 -1
  39. data/web/views/_footer.erb +1 -1
  40. data/web/views/_job_info.erb +1 -1
  41. data/web/views/_poll_link.erb +2 -5
  42. data/web/views/_summary.erb +7 -7
  43. data/web/views/busy.erb +5 -5
  44. data/web/views/dashboard.erb +22 -14
  45. data/web/views/dead.erb +1 -1
  46. data/web/views/layout.erb +1 -1
  47. data/web/views/morgue.erb +6 -6
  48. data/web/views/queue.erb +10 -10
  49. data/web/views/queues.erb +3 -3
  50. data/web/views/retries.erb +7 -7
  51. data/web/views/retry.erb +1 -1
  52. data/web/views/scheduled.erb +1 -1
  53. metadata +5 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 298711914bcb8534a9599c47b00b7410467ce324619ee70e7050d15c42f4c329
4
- data.tar.gz: '007900de7a1558633520c61870a58eff341e9c11009441dbabe0fbc177e4ed99'
3
+ metadata.gz: 33cb573c76378ff933909bdc009358cc94b81e9e50c17b6dd8160170fe744f25
4
+ data.tar.gz: f13c16da01f5cc0ef9514396aed899c8e1f69049d2d425892d3f5e774d68c6a7
5
5
  SHA512:
6
- metadata.gz: 592ecc114de13f0e43bba9193e1ffd3a973c89a43fac3ed1b750b6a70e29b5bf128a05657baf3fc2ccb77134f092efac055651907f01c0ed6d3c00d45a5ebdc9
7
- data.tar.gz: a7baed1f1df451e8bd5183fec4631e49c0761e700c4c95fc070389894894a5fb90103d0adce29da797bc1cae72f8a1f21e71da0279e8c18cb62e3b3b5ae05f0a
6
+ metadata.gz: 9829304cbe0810266d2a320b14386561a4f22965aa3f9fab311253c1edd9f3075298dadba28afc0f69f898ed69d858833e744e52db1012a0d23037ecbdf33ce3
7
+ data.tar.gz: b38f253759ab7e3479829faad0e60e42ad2a6281b4dc022c66b0af652c53e85e5d7362bc07ecf02ae3ae3c530e3619572ad070267d2690aa5b4fafc08762d73e
data/Changes.md CHANGED
@@ -1,6 +1,57 @@
1
1
  # Sidekiq Changes
2
2
 
3
- [Sidekiq Changes](https://github.com/mperham/sidekiq/blob/master/Changes.md) | [Sidekiq Pro Changes](https://github.com/mperham/sidekiq/blob/master/Pro-Changes.md) | [Sidekiq Enterprise Changes](https://github.com/mperham/sidekiq/blob/master/Ent-Changes.md)
3
+ [Sidekiq Changes](https://github.com/mperham/sidekiq/blob/main/Changes.md) | [Sidekiq Pro Changes](https://github.com/mperham/sidekiq/blob/main/Pro-Changes.md) | [Sidekiq Enterprise Changes](https://github.com/mperham/sidekiq/blob/main/Ent-Changes.md)
4
+
5
+ 6.3.1
6
+ ---------
7
+
8
+ - Fix keyword arguments error with CurrentAttributes on Ruby 3.0 [#5048]
9
+
10
+ 6.3.0
11
+ ---------
12
+
13
+ - **BREAK**: The Web UI has been refactored to remove jQuery. Any UI extensions
14
+ which use jQuery will break.
15
+ - **FEATURE**: Sidekiq.logger has been enhanced so any `Rails.logger`
16
+ output in jobs now shows up in the Sidekiq console. Remove any logger
17
+ hacks in your initializer and see if it Just Works™ now. [#5021]
18
+ - **FEATURE**: Add `Sidekiq::Job` alias for `Sidekiq::Worker`, to better
19
+ reflect industry standard terminology. You can now do this:
20
+ ```ruby
21
+ class MyJob
22
+ include Sidekiq::Job
23
+ sidekiq_options ...
24
+ def perform(args)
25
+ end
26
+ end
27
+ ```
28
+ - **FEATURE**: Support for serializing ActiveSupport::CurrentAttributes into each job. [#4982]
29
+ ```ruby
30
+ # config/initializers/sidekiq.rb
31
+ require "sidekiq/middleware/current_attributes"
32
+ Sidekiq::CurrentAttributes.persist(Myapp::Current) # Your AS::CurrentAttributes singleton
33
+ ```
34
+ - **FEATURE**: Add `Sidekiq::Worker.perform_bulk` for enqueuing jobs in bulk,
35
+ similar to `Sidekiq::Client.push_bulk` [#5042]
36
+ ```ruby
37
+ MyJob.perform_bulk([[1], [2], [3]])
38
+ ```
39
+ - Implement `queue_as`, `wait` and `wait_until` for ActiveJob compatibility [#5003]
40
+ - Scheduler now uses Lua to reduce Redis load and network roundtrips [#5044]
41
+ - Retry Redis operation if we get an `UNBLOCKED` Redis error [#4985]
42
+ - Run existing signal traps, if any, before running Sidekiq's trap [#4991]
43
+ - Fix fetch bug when using weighted queues which caused Sidekiq to stop
44
+ processing queues randomly [#5031]
45
+
46
+ 6.2.2
47
+ ---------
48
+
49
+ - Reduce retry jitter, add jitter to `sidekiq_retry_in` values [#4957]
50
+ - Minimize scheduler load on Redis at scale [#4882]
51
+ - Improve logging of delay jobs [#4904, BuonOno]
52
+ - Minor CSS improvements for buttons and tables, design PRs always welcome!
53
+ - Tweak Web UI `Cache-Control` header [#4966]
54
+ - Rename internal API class `Sidekiq::Job` to `Sidekiq::JobRecord` [#4955]
4
55
 
5
56
  6.2.1
6
57
  ---------
data/LICENSE CHANGED
@@ -6,4 +6,4 @@ for license text.
6
6
 
7
7
  Sidekiq Pro has a commercial-friendly license allowing private forks
8
8
  and modifications of Sidekiq. Please see https://sidekiq.org/products/pro.html for
9
- more detail. You can find the commercial license terms in COMM-LICENSE.
9
+ more detail. You can find the commercial license terms in COMM-LICENSE.txt.
data/README.md CHANGED
@@ -46,7 +46,7 @@ See the [Getting Started wiki page](https://github.com/mperham/sidekiq/wiki/Gett
46
46
  You can watch [this Youtube playlist](https://www.youtube.com/playlist?list=PLjeHh2LSCFrWGT5uVjUuFKAcrcj5kSai1) to learn all about
47
47
  Sidekiq and see its features in action. Here's the Web UI:
48
48
 
49
- ![Web UI](https://github.com/mperham/sidekiq/raw/master/examples/web-ui.png)
49
+ ![Web UI](https://github.com/mperham/sidekiq/raw/main/examples/web-ui.png)
50
50
 
51
51
 
52
52
  Want to Upgrade?
@@ -84,7 +84,7 @@ See the [Sidekiq support page](https://sidekiq.org/support.html) for details.
84
84
  License
85
85
  -----------------
86
86
 
87
- Please see [LICENSE](https://github.com/mperham/sidekiq/blob/master/LICENSE) for licensing details.
87
+ Please see [LICENSE](https://github.com/mperham/sidekiq/blob/main/LICENSE) for licensing details.
88
88
 
89
89
 
90
90
  Author
data/lib/sidekiq/api.rb CHANGED
@@ -8,7 +8,7 @@ require "base64"
8
8
  module Sidekiq
9
9
  class Stats
10
10
  def initialize
11
- fetch_stats!
11
+ fetch_stats_fast!
12
12
  end
13
13
 
14
14
  def processed
@@ -51,7 +51,8 @@ module Sidekiq
51
51
  Sidekiq::Stats::Queues.new.lengths
52
52
  end
53
53
 
54
- def fetch_stats!
54
+ # O(1) redis calls
55
+ def fetch_stats_fast!
55
56
  pipe1_res = Sidekiq.redis { |conn|
56
57
  conn.pipelined do
57
58
  conn.get("stat:processed")
@@ -64,25 +65,6 @@ module Sidekiq
64
65
  end
65
66
  }
66
67
 
67
- processes = Sidekiq.redis { |conn|
68
- conn.sscan_each("processes").to_a
69
- }
70
-
71
- queues = Sidekiq.redis { |conn|
72
- conn.sscan_each("queues").to_a
73
- }
74
-
75
- pipe2_res = Sidekiq.redis { |conn|
76
- conn.pipelined do
77
- processes.each { |key| conn.hget(key, "busy") }
78
- queues.each { |queue| conn.llen("queue:#{queue}") }
79
- end
80
- }
81
-
82
- s = processes.size
83
- workers_size = pipe2_res[0...s].sum(&:to_i)
84
- enqueued = pipe2_res[s..-1].sum(&:to_i)
85
-
86
68
  default_queue_latency = if (entry = pipe1_res[6].first)
87
69
  job = begin
88
70
  Sidekiq.load_json(entry)
@@ -95,6 +77,7 @@ module Sidekiq
95
77
  else
96
78
  0
97
79
  end
80
+
98
81
  @stats = {
99
82
  processed: pipe1_res[0].to_i,
100
83
  failed: pipe1_res[1].to_i,
@@ -103,10 +86,39 @@ module Sidekiq
103
86
  dead_size: pipe1_res[4],
104
87
  processes_size: pipe1_res[5],
105
88
 
106
- default_queue_latency: default_queue_latency,
107
- workers_size: workers_size,
108
- enqueued: enqueued
89
+ default_queue_latency: default_queue_latency
90
+ }
91
+ end
92
+
93
+ # O(number of processes + number of queues) redis calls
94
+ def fetch_stats_slow!
95
+ processes = Sidekiq.redis { |conn|
96
+ conn.sscan_each("processes").to_a
97
+ }
98
+
99
+ queues = Sidekiq.redis { |conn|
100
+ conn.sscan_each("queues").to_a
109
101
  }
102
+
103
+ pipe2_res = Sidekiq.redis { |conn|
104
+ conn.pipelined do
105
+ processes.each { |key| conn.hget(key, "busy") }
106
+ queues.each { |queue| conn.llen("queue:#{queue}") }
107
+ end
108
+ }
109
+
110
+ s = processes.size
111
+ workers_size = pipe2_res[0...s].sum(&:to_i)
112
+ enqueued = pipe2_res[s..-1].sum(&:to_i)
113
+
114
+ @stats[:workers_size] = workers_size
115
+ @stats[:enqueued] = enqueued
116
+ @stats
117
+ end
118
+
119
+ def fetch_stats!
120
+ fetch_stats_fast!
121
+ fetch_stats_slow!
110
122
  end
111
123
 
112
124
  def reset(*stats)
@@ -126,7 +138,8 @@ module Sidekiq
126
138
  private
127
139
 
128
140
  def stat(s)
129
- @stats[s]
141
+ fetch_stats_slow! if @stats[s].nil?
142
+ @stats[s] || raise(ArgumentError, "Unknown stat #{s}")
130
143
  end
131
144
 
132
145
  class Queues
@@ -141,7 +154,7 @@ module Sidekiq
141
154
  }
142
155
 
143
156
  array_of_arrays = queues.zip(lengths).sort_by { |_, size| -size }
144
- Hash[array_of_arrays]
157
+ array_of_arrays.to_h
145
158
  end
146
159
  end
147
160
  end
@@ -255,7 +268,7 @@ module Sidekiq
255
268
  break if entries.empty?
256
269
  page += 1
257
270
  entries.each do |entry|
258
- yield Job.new(entry, @name)
271
+ yield JobRecord.new(entry, @name)
259
272
  end
260
273
  deleted_size = initial_size - size
261
274
  end
@@ -265,7 +278,7 @@ module Sidekiq
265
278
  # Find the job with the given JID within this queue.
266
279
  #
267
280
  # This is a slow, inefficient operation. Do not use under
268
- # normal conditions. Sidekiq Pro contains a faster version.
281
+ # normal conditions.
269
282
  def find_job(jid)
270
283
  detect { |j| j.jid == jid }
271
284
  end
@@ -286,9 +299,9 @@ module Sidekiq
286
299
  # sorted set.
287
300
  #
288
301
  # The job should be considered immutable but may be
289
- # removed from the queue via Job#delete.
302
+ # removed from the queue via JobRecord#delete.
290
303
  #
291
- class Job
304
+ class JobRecord
292
305
  attr_reader :item
293
306
  attr_reader :value
294
307
 
@@ -316,21 +329,23 @@ module Sidekiq
316
329
 
317
330
  def display_class
318
331
  # Unwrap known wrappers so they show up in a human-friendly manner in the Web UI
319
- @klass ||= case klass
320
- when /\ASidekiq::Extensions::Delayed/
321
- safe_load(args[0], klass) do |target, method, _|
322
- "#{target}.#{method}"
323
- end
324
- when "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper"
325
- job_class = @item["wrapped"] || args[0]
326
- if job_class == "ActionMailer::DeliveryJob" || job_class == "ActionMailer::MailDeliveryJob"
327
- # MailerClass#mailer_method
328
- args[0]["arguments"][0..1].join("#")
329
- else
330
- job_class
331
- end
332
- else
333
- klass
332
+ @klass ||= self["display_class"] || begin
333
+ case klass
334
+ when /\ASidekiq::Extensions::Delayed/
335
+ safe_load(args[0], klass) do |target, method, _|
336
+ "#{target}.#{method}"
337
+ end
338
+ when "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper"
339
+ job_class = @item["wrapped"] || args[0]
340
+ if job_class == "ActionMailer::DeliveryJob" || job_class == "ActionMailer::MailDeliveryJob"
341
+ # MailerClass#mailer_method
342
+ args[0]["arguments"][0..1].join("#")
343
+ else
344
+ job_class
345
+ end
346
+ else
347
+ klass
348
+ end
334
349
  end
335
350
  end
336
351
 
@@ -443,7 +458,7 @@ module Sidekiq
443
458
  end
444
459
  end
445
460
 
446
- class SortedEntry < Job
461
+ class SortedEntry < JobRecord
447
462
  attr_reader :score
448
463
  attr_reader :parent
449
464
 
@@ -823,12 +838,13 @@ module Sidekiq
823
838
  # For Sidekiq Enterprise customers this number (in production) must be
824
839
  # less than or equal to your licensed concurrency.
825
840
  def total_concurrency
826
- sum { |x| x["concurrency"] }
841
+ sum { |x| x["concurrency"].to_i }
827
842
  end
828
843
 
829
- def total_rss
830
- sum { |x| x["rss"] || 0 }
844
+ def total_rss_in_kb
845
+ sum { |x| x["rss"].to_i }
831
846
  end
847
+ alias_method :total_rss, :total_rss_in_kb
832
848
 
833
849
  # Returns the identity of the current cluster leader or "" if no leader.
834
850
  # This is a Sidekiq Enterprise feature, will always return "" in Sidekiq
@@ -879,6 +895,10 @@ module Sidekiq
879
895
  self["identity"]
880
896
  end
881
897
 
898
+ def queues
899
+ self["queues"]
900
+ end
901
+
882
902
  def quiet!
883
903
  signal("TSTP")
884
904
  end
@@ -909,8 +929,8 @@ module Sidekiq
909
929
  end
910
930
 
911
931
  ##
912
- # A worker is a thread that is currently processing a job.
913
- # Programmatic access to the current active worker set.
932
+ # The WorkSet stores the work being done by this Sidekiq cluster.
933
+ # It tracks the process and thread working on each job.
914
934
  #
915
935
  # WARNING WARNING WARNING
916
936
  #
@@ -918,17 +938,17 @@ module Sidekiq
918
938
  # If you call #size => 5 and then expect #each to be
919
939
  # called 5 times, you're going to have a bad time.
920
940
  #
921
- # workers = Sidekiq::Workers.new
922
- # workers.size => 2
923
- # workers.each do |process_id, thread_id, work|
941
+ # works = Sidekiq::WorkSet.new
942
+ # works.size => 2
943
+ # works.each do |process_id, thread_id, work|
924
944
  # # process_id is a unique identifier per Sidekiq process
925
945
  # # thread_id is a unique identifier per thread
926
946
  # # work is a Hash which looks like:
927
- # # { 'queue' => name, 'run_at' => timestamp, 'payload' => msg }
947
+ # # { 'queue' => name, 'run_at' => timestamp, 'payload' => job_hash }
928
948
  # # run_at is an epoch Integer.
929
949
  # end
930
950
  #
931
- class Workers
951
+ class WorkSet
932
952
  include Enumerable
933
953
 
934
954
  def each(&block)
@@ -975,4 +995,8 @@ module Sidekiq
975
995
  end
976
996
  end
977
997
  end
998
+ # Since "worker" is a nebulous term, we've deprecated the use of this class name.
999
+ # Is "worker" a process, a type of job, a thread? Undefined!
1000
+ # WorkSet better describes the data.
1001
+ Workers = WorkSet
978
1002
  end
data/lib/sidekiq/cli.rb CHANGED
@@ -46,7 +46,15 @@ module Sidekiq
46
46
  # USR1 and USR2 don't work on the JVM
47
47
  sigs << "USR2" if Sidekiq.pro? && !jruby?
48
48
  sigs.each do |sig|
49
- trap sig do
49
+ old_handler = Signal.trap(sig) do
50
+ if old_handler.respond_to?(:call)
51
+ begin
52
+ old_handler.call
53
+ rescue Exception => exc
54
+ # signal handlers can't use Logger so puts only
55
+ puts ["Error in #{sig} handler", exc].inspect
56
+ end
57
+ end
50
58
  self_write.puts(sig)
51
59
  end
52
60
  rescue ArgumentError
@@ -396,7 +404,7 @@ module Sidekiq
396
404
  opts[:queues] ||= []
397
405
  opts[:strict] = true if opts[:strict].nil?
398
406
  raise ArgumentError, "queues: #{queue} cannot be defined twice" if opts[:queues].include?(queue)
399
- [weight.to_i, 1].max.times { opts[:queues] << queue }
407
+ [weight.to_i, 1].max.times { opts[:queues] << queue.to_s }
400
408
  opts[:strict] = false if weight.to_i > 0
401
409
  end
402
410
 
@@ -95,7 +95,7 @@ module Sidekiq
95
95
  return [] if args.empty? # no jobs to push
96
96
 
97
97
  at = items.delete("at")
98
- raise ArgumentError, "Job 'at' must be a Numeric or an Array of Numeric timestamps" if at && (Array(at).empty? || !Array(at).all?(Numeric))
98
+ raise ArgumentError, "Job 'at' must be a Numeric or an Array of Numeric timestamps" if at && (Array(at).empty? || !Array(at).all? { |entry| entry.is_a?(Numeric) })
99
99
  raise ArgumentError, "Job 'at' Array must have same size as 'args' Array" if at.is_a?(Array) && at.size != args.size
100
100
 
101
101
  normed = normalize_item(items)
@@ -186,7 +186,7 @@ module Sidekiq
186
186
 
187
187
  def raw_push(payloads)
188
188
  @redis_pool.with do |conn|
189
- conn.multi do
189
+ conn.pipelined do
190
190
  atomic_push(conn, payloads)
191
191
  end
192
192
  end
@@ -24,7 +24,9 @@ module Sidekiq
24
24
  if marshalled.size > SIZE_LIMIT
25
25
  ::Sidekiq.logger.warn { "#{@target}.#{name} job argument is #{marshalled.bytesize} bytes, you should refactor it to reduce the size" }
26
26
  end
27
- @performable.client_push({"class" => @performable, "args" => [marshalled]}.merge(@opts))
27
+ @performable.client_push({"class" => @performable,
28
+ "args" => [marshalled],
29
+ "display_class" => "#{@target}.#{name}"}.merge(@opts))
28
30
  end
29
31
  end
30
32
  end
data/lib/sidekiq/fetch.rb CHANGED
@@ -40,7 +40,7 @@ module Sidekiq
40
40
  # 4825 Sidekiq Pro with all queues paused will return an
41
41
  # empty set of queues with a trailing TIMEOUT value.
42
42
  if qs.size <= 1
43
- sleep(2)
43
+ sleep(TIMEOUT)
44
44
  return nil
45
45
  end
46
46
 
@@ -79,9 +79,10 @@ module Sidekiq
79
79
  if @strictly_ordered_queues
80
80
  @queues
81
81
  else
82
- queues = @queues.shuffle!.uniq
83
- queues << TIMEOUT
84
- queues
82
+ permute = @queues.shuffle
83
+ permute.uniq!
84
+ permute << TIMEOUT
85
+ permute
85
86
  end
86
87
  end
87
88
  end
@@ -0,0 +1,13 @@
1
+ require "sidekiq/worker"
2
+
3
+ module Sidekiq
4
+ # Sidekiq::Job is a new alias for Sidekiq::Worker as of Sidekiq 6.3.0.
5
+ # Use `include Sidekiq::Job` rather than `include Sidekiq::Worker`.
6
+ #
7
+ # The term "worker" is too generic and overly confusing, used in several
8
+ # different contexts meaning different things. Many people call a Sidekiq
9
+ # process a "worker". Some people call the thread that executes jobs a
10
+ # "worker". This change brings Sidekiq closer to ActiveJob where your job
11
+ # classes extend ApplicationJob.
12
+ Job = Worker
13
+ end
@@ -38,7 +38,7 @@ module Sidekiq
38
38
  # If we're using a wrapper class, like ActiveJob, use the "wrapped"
39
39
  # attribute to expose the underlying thing.
40
40
  h = {
41
- class: job_hash["wrapped"] || job_hash["class"],
41
+ class: job_hash["display_class"] || job_hash["wrapped"] || job_hash["class"],
42
42
  jid: job_hash["jid"]
43
43
  }
44
44
  h[:bid] = job_hash["bid"] if job_hash["bid"]
@@ -214,16 +214,12 @@ module Sidekiq
214
214
  end
215
215
 
216
216
  def delay_for(worker, count, exception)
217
+ jitter = rand(10) * (count + 1)
217
218
  if worker&.sidekiq_retry_in_block
218
219
  custom_retry_in = retry_in(worker, count, exception).to_i
219
- return custom_retry_in if custom_retry_in > 0
220
+ return custom_retry_in + jitter if custom_retry_in > 0
220
221
  end
221
- seconds_to_delay(count)
222
- end
223
-
224
- # delayed_job uses the same basic formula
225
- def seconds_to_delay(count)
226
- (count**4) + 15 + (rand(30) * (count + 1))
222
+ (count**4) + 15 + jitter
227
223
  end
228
224
 
229
225
  def retry_in(worker, count, exception)
@@ -69,10 +69,12 @@ module Sidekiq
69
69
 
70
70
  private unless $TESTING
71
71
 
72
+ BEAT_PAUSE = 5
73
+
72
74
  def start_heartbeat
73
75
  loop do
74
76
  heartbeat
75
- sleep 5
77
+ sleep BEAT_PAUSE
76
78
  end
77
79
  Sidekiq.logger.info("Heartbeat stopping...")
78
80
  end
@@ -211,6 +213,8 @@ module Sidekiq
211
213
  Your Redis network connection is performing extremely poorly.
212
214
  Last RTT readings were #{RTT_READINGS.buffer.inspect}, ideally these should be < 1000.
213
215
  Ensure Redis is running in the same AZ or datacenter as Sidekiq.
216
+ If these values are close to 100,000, that means your Sidekiq process may be
217
+ CPU overloaded; see https://github.com/mperham/sidekiq/discussions/5039
214
218
  EOM
215
219
  RTT_READINGS.reset
216
220
  end
@@ -238,26 +242,22 @@ module Sidekiq
238
242
  end
239
243
 
240
244
  def to_data
241
- @data ||= begin
242
- {
243
- "hostname" => hostname,
244
- "started_at" => Time.now.to_f,
245
- "pid" => ::Process.pid,
246
- "tag" => @options[:tag] || "",
247
- "concurrency" => @options[:concurrency],
248
- "queues" => @options[:queues].uniq,
249
- "labels" => @options[:labels],
250
- "identity" => identity
251
- }
252
- end
245
+ @data ||= {
246
+ "hostname" => hostname,
247
+ "started_at" => Time.now.to_f,
248
+ "pid" => ::Process.pid,
249
+ "tag" => @options[:tag] || "",
250
+ "concurrency" => @options[:concurrency],
251
+ "queues" => @options[:queues].uniq,
252
+ "labels" => @options[:labels],
253
+ "identity" => identity
254
+ }
253
255
  end
254
256
 
255
257
  def to_json
256
- @json ||= begin
257
- # this data changes infrequently so dump it to a string
258
- # now so we don't need to dump it every heartbeat.
259
- Sidekiq.dump_json(to_data)
260
- end
258
+ # this data changes infrequently so dump it to a string
259
+ # now so we don't need to dump it every heartbeat.
260
+ @json ||= Sidekiq.dump_json(to_data)
261
261
  end
262
262
  end
263
263
  end
@@ -90,12 +90,12 @@ module Sidekiq
90
90
  end
91
91
 
92
92
  def add(klass, *args)
93
- remove(klass) if exists?(klass)
93
+ remove(klass)
94
94
  entries << Entry.new(klass, *args)
95
95
  end
96
96
 
97
97
  def prepend(klass, *args)
98
- remove(klass) if exists?(klass)
98
+ remove(klass)
99
99
  entries.insert(0, Entry.new(klass, *args))
100
100
  end
101
101
 
@@ -132,7 +132,7 @@ module Sidekiq
132
132
  def invoke(*args)
133
133
  return yield if empty?
134
134
 
135
- chain = retrieve.dup
135
+ chain = retrieve
136
136
  traverse_chain = proc do
137
137
  if chain.empty?
138
138
  yield
@@ -144,6 +144,8 @@ module Sidekiq
144
144
  end
145
145
  end
146
146
 
147
+ private
148
+
147
149
  class Entry
148
150
  attr_reader :klass
149
151
 
@@ -0,0 +1,52 @@
1
+ require "active_support/current_attributes"
2
+
3
+ module Sidekiq
4
+ ##
5
+ # Automatically save and load any current attributes in the execution context
6
+ # so context attributes "flow" from Rails actions into any associated jobs.
7
+ # This can be useful for multi-tenancy, i18n locale, timezone, any implicit
8
+ # per-request attribute. See +ActiveSupport::CurrentAttributes+.
9
+ #
10
+ # @example
11
+ #
12
+ # # in your initializer
13
+ # require "sidekiq/middleware/current_attributes"
14
+ # Sidekiq::CurrentAttributes.persist(Myapp::Current)
15
+ #
16
+ module CurrentAttributes
17
+ class Save
18
+ def initialize(cattr)
19
+ @klass = cattr
20
+ end
21
+
22
+ def call(_, job, _, _)
23
+ job["cattr"] = @klass.attributes
24
+ yield
25
+ end
26
+ end
27
+
28
+ class Load
29
+ def initialize(cattr)
30
+ @klass = cattr
31
+ end
32
+
33
+ def call(_, job, _, &block)
34
+ if job.has_key?("cattr")
35
+ @klass.set(job["cattr"], &block)
36
+ else
37
+ yield
38
+ end
39
+ end
40
+ end
41
+
42
+ def self.persist(klass)
43
+ Sidekiq.configure_client do |config|
44
+ config.client_middleware.add Save, klass
45
+ end
46
+ Sidekiq.configure_server do |config|
47
+ config.client_middleware.add Save, klass
48
+ config.server_middleware.add Load, klass
49
+ end
50
+ end
51
+ end
52
+ end
data/lib/sidekiq/rails.rb CHANGED
@@ -37,6 +37,17 @@ module Sidekiq
37
37
  end
38
38
  end
39
39
 
40
+ initializer "sidekiq.rails_logger" do
41
+ Sidekiq.configure_server do |_|
42
+ # This is the integration code necessary so that if code uses `Rails.logger.info "Hello"`,
43
+ # it will appear in the Sidekiq console with all of the job context. See #5021 and
44
+ # https://github.com/rails/rails/blob/b5f2b550f69a99336482739000c58e4e04e033aa/railties/lib/rails/commands/server/server_command.rb#L82-L84
45
+ unless ::ActiveSupport::Logger.logger_outputs_to?(::Rails.logger, $stdout)
46
+ ::Rails.logger.extend(::ActiveSupport::Logger.broadcast(::Sidekiq.logger))
47
+ end
48
+ end
49
+ end
50
+
40
51
  # This hook happens after all initializers are run, just before returning
41
52
  # from config/environment.rb back to sidekiq/cli.rb.
42
53
  #
@@ -94,12 +94,10 @@ module Sidekiq
94
94
  def log_info(options)
95
95
  redacted = "REDACTED"
96
96
 
97
- # deep clone so we can muck with these options all we want
98
- #
99
- # exclude SSL params from dump-and-load because some information isn't
100
- # safely dumpable in current Rubies
101
- keys = options.keys
102
- keys.delete(:ssl_params)
97
+ # Deep clone so we can muck with these options all we want and exclude
98
+ # params from dump-and-load that may contain objects that Marshal is
99
+ # unable to safely dump.
100
+ keys = options.keys - [:logger, :ssl_params]
103
101
  scrubbed_options = Marshal.load(Marshal.dump(options.slice(*keys)))
104
102
  if scrubbed_options[:url] && (uri = URI.parse(scrubbed_options[:url])) && uri.password
105
103
  uri.password = redacted