sidekiq 5.1.3 → 7.3.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (157) hide show
  1. checksums.yaml +5 -5
  2. data/Changes.md +756 -8
  3. data/LICENSE.txt +9 -0
  4. data/README.md +48 -51
  5. data/bin/multi_queue_bench +271 -0
  6. data/bin/sidekiq +22 -3
  7. data/bin/sidekiqload +213 -115
  8. data/bin/sidekiqmon +11 -0
  9. data/lib/generators/sidekiq/job_generator.rb +59 -0
  10. data/lib/generators/sidekiq/templates/{worker.rb.erb → job.rb.erb} +2 -2
  11. data/lib/generators/sidekiq/templates/{worker_spec.rb.erb → job_spec.rb.erb} +1 -1
  12. data/lib/generators/sidekiq/templates/{worker_test.rb.erb → job_test.rb.erb} +1 -1
  13. data/lib/sidekiq/api.rb +640 -330
  14. data/lib/sidekiq/capsule.rb +132 -0
  15. data/lib/sidekiq/cli.rb +244 -257
  16. data/lib/sidekiq/client.rb +132 -103
  17. data/lib/sidekiq/component.rb +68 -0
  18. data/lib/sidekiq/config.rb +293 -0
  19. data/lib/sidekiq/deploy.rb +64 -0
  20. data/lib/sidekiq/embedded.rb +63 -0
  21. data/lib/sidekiq/fetch.rb +49 -42
  22. data/lib/sidekiq/iterable_job.rb +55 -0
  23. data/lib/sidekiq/job/interrupt_handler.rb +24 -0
  24. data/lib/sidekiq/job/iterable/active_record_enumerator.rb +53 -0
  25. data/lib/sidekiq/job/iterable/csv_enumerator.rb +47 -0
  26. data/lib/sidekiq/job/iterable/enumerators.rb +135 -0
  27. data/lib/sidekiq/job/iterable.rb +231 -0
  28. data/lib/sidekiq/job.rb +385 -0
  29. data/lib/sidekiq/job_logger.rb +49 -12
  30. data/lib/sidekiq/job_retry.rb +167 -103
  31. data/lib/sidekiq/job_util.rb +109 -0
  32. data/lib/sidekiq/launcher.rb +209 -102
  33. data/lib/sidekiq/logger.rb +131 -0
  34. data/lib/sidekiq/manager.rb +43 -46
  35. data/lib/sidekiq/metrics/query.rb +158 -0
  36. data/lib/sidekiq/metrics/shared.rb +97 -0
  37. data/lib/sidekiq/metrics/tracking.rb +148 -0
  38. data/lib/sidekiq/middleware/chain.rb +113 -56
  39. data/lib/sidekiq/middleware/current_attributes.rb +113 -0
  40. data/lib/sidekiq/middleware/i18n.rb +7 -7
  41. data/lib/sidekiq/middleware/modules.rb +23 -0
  42. data/lib/sidekiq/monitor.rb +147 -0
  43. data/lib/sidekiq/paginator.rb +28 -16
  44. data/lib/sidekiq/processor.rb +175 -112
  45. data/lib/sidekiq/rails.rb +54 -39
  46. data/lib/sidekiq/redis_client_adapter.rb +114 -0
  47. data/lib/sidekiq/redis_connection.rb +65 -86
  48. data/lib/sidekiq/ring_buffer.rb +31 -0
  49. data/lib/sidekiq/scheduled.rb +139 -48
  50. data/lib/sidekiq/sd_notify.rb +149 -0
  51. data/lib/sidekiq/systemd.rb +26 -0
  52. data/lib/sidekiq/testing/inline.rb +6 -5
  53. data/lib/sidekiq/testing.rb +95 -94
  54. data/lib/sidekiq/transaction_aware_client.rb +51 -0
  55. data/lib/sidekiq/version.rb +3 -1
  56. data/lib/sidekiq/web/action.rb +22 -12
  57. data/lib/sidekiq/web/application.rb +225 -76
  58. data/lib/sidekiq/web/csrf_protection.rb +183 -0
  59. data/lib/sidekiq/web/helpers.rb +215 -118
  60. data/lib/sidekiq/web/router.rb +23 -19
  61. data/lib/sidekiq/web.rb +114 -106
  62. data/lib/sidekiq/worker_compatibility_alias.rb +13 -0
  63. data/lib/sidekiq.rb +95 -182
  64. data/sidekiq.gemspec +26 -23
  65. data/web/assets/images/apple-touch-icon.png +0 -0
  66. data/web/assets/javascripts/application.js +157 -61
  67. data/web/assets/javascripts/base-charts.js +106 -0
  68. data/web/assets/javascripts/chart.min.js +13 -0
  69. data/web/assets/javascripts/chartjs-plugin-annotation.min.js +7 -0
  70. data/web/assets/javascripts/dashboard-charts.js +192 -0
  71. data/web/assets/javascripts/dashboard.js +35 -283
  72. data/web/assets/javascripts/metrics.js +298 -0
  73. data/web/assets/stylesheets/application-dark.css +147 -0
  74. data/web/assets/stylesheets/application-rtl.css +10 -93
  75. data/web/assets/stylesheets/application.css +169 -522
  76. data/web/assets/stylesheets/bootstrap.css +2 -2
  77. data/web/locales/ar.yml +71 -64
  78. data/web/locales/cs.yml +62 -62
  79. data/web/locales/da.yml +60 -53
  80. data/web/locales/de.yml +65 -53
  81. data/web/locales/el.yml +43 -24
  82. data/web/locales/en.yml +86 -65
  83. data/web/locales/es.yml +70 -54
  84. data/web/locales/fa.yml +65 -65
  85. data/web/locales/fr.yml +83 -62
  86. data/web/locales/gd.yml +99 -0
  87. data/web/locales/he.yml +65 -64
  88. data/web/locales/hi.yml +59 -59
  89. data/web/locales/it.yml +53 -53
  90. data/web/locales/ja.yml +75 -64
  91. data/web/locales/ko.yml +52 -52
  92. data/web/locales/lt.yml +83 -0
  93. data/web/locales/nb.yml +61 -61
  94. data/web/locales/nl.yml +52 -52
  95. data/web/locales/pl.yml +45 -45
  96. data/web/locales/pt-br.yml +83 -55
  97. data/web/locales/pt.yml +51 -51
  98. data/web/locales/ru.yml +68 -63
  99. data/web/locales/sv.yml +53 -53
  100. data/web/locales/ta.yml +60 -60
  101. data/web/locales/tr.yml +101 -0
  102. data/web/locales/uk.yml +62 -61
  103. data/web/locales/ur.yml +64 -64
  104. data/web/locales/vi.yml +83 -0
  105. data/web/locales/zh-cn.yml +43 -16
  106. data/web/locales/zh-tw.yml +42 -8
  107. data/web/views/_footer.erb +18 -3
  108. data/web/views/_job_info.erb +21 -4
  109. data/web/views/_metrics_period_select.erb +12 -0
  110. data/web/views/_nav.erb +4 -18
  111. data/web/views/_paging.erb +2 -0
  112. data/web/views/_poll_link.erb +3 -6
  113. data/web/views/_summary.erb +7 -7
  114. data/web/views/busy.erb +79 -29
  115. data/web/views/dashboard.erb +49 -19
  116. data/web/views/dead.erb +3 -3
  117. data/web/views/filtering.erb +7 -0
  118. data/web/views/layout.erb +9 -7
  119. data/web/views/metrics.erb +91 -0
  120. data/web/views/metrics_for_job.erb +59 -0
  121. data/web/views/morgue.erb +14 -15
  122. data/web/views/queue.erb +33 -23
  123. data/web/views/queues.erb +19 -5
  124. data/web/views/retries.erb +19 -16
  125. data/web/views/retry.erb +3 -3
  126. data/web/views/scheduled.erb +17 -15
  127. metadata +84 -129
  128. data/.github/contributing.md +0 -32
  129. data/.github/issue_template.md +0 -11
  130. data/.gitignore +0 -13
  131. data/.travis.yml +0 -14
  132. data/3.0-Upgrade.md +0 -70
  133. data/4.0-Upgrade.md +0 -53
  134. data/5.0-Upgrade.md +0 -56
  135. data/COMM-LICENSE +0 -95
  136. data/Ent-Changes.md +0 -216
  137. data/Gemfile +0 -8
  138. data/LICENSE +0 -9
  139. data/Pro-2.0-Upgrade.md +0 -138
  140. data/Pro-3.0-Upgrade.md +0 -44
  141. data/Pro-4.0-Upgrade.md +0 -35
  142. data/Pro-Changes.md +0 -729
  143. data/Rakefile +0 -8
  144. data/bin/sidekiqctl +0 -99
  145. data/code_of_conduct.md +0 -50
  146. data/lib/generators/sidekiq/worker_generator.rb +0 -49
  147. data/lib/sidekiq/core_ext.rb +0 -1
  148. data/lib/sidekiq/delay.rb +0 -42
  149. data/lib/sidekiq/exception_handler.rb +0 -29
  150. data/lib/sidekiq/extensions/action_mailer.rb +0 -57
  151. data/lib/sidekiq/extensions/active_record.rb +0 -40
  152. data/lib/sidekiq/extensions/class_methods.rb +0 -40
  153. data/lib/sidekiq/extensions/generic_proxy.rb +0 -31
  154. data/lib/sidekiq/logging.rb +0 -122
  155. data/lib/sidekiq/middleware/server/active_record.rb +0 -23
  156. data/lib/sidekiq/util.rb +0 -66
  157. data/lib/sidekiq/worker.rb +0 -204
@@ -1,11 +1,8 @@
1
1
  # frozen_string_literal: true
2
- require 'sidekiq/util'
3
- require 'sidekiq/fetch'
4
- require 'sidekiq/job_logger'
5
- require 'sidekiq/job_retry'
6
- require 'thread'
7
- require 'concurrent/map'
8
- require 'concurrent/atomic/atomic_fixnum'
2
+
3
+ require "sidekiq/fetch"
4
+ require "sidekiq/job_logger"
5
+ require "sidekiq/job_retry"
9
6
 
10
7
  module Sidekiq
11
8
  ##
@@ -13,45 +10,45 @@ module Sidekiq
13
10
  #
14
11
  # 1. fetches a job from Redis
15
12
  # 2. executes the job
16
- # a. instantiate the Worker
13
+ # a. instantiate the job class
17
14
  # b. run the middleware chain
18
15
  # c. call #perform
19
16
  #
20
- # A Processor can exit due to shutdown (processor_stopped)
21
- # or due to an error during job execution (processor_died)
17
+ # A Processor can exit due to shutdown or due to
18
+ # an error during job execution.
22
19
  #
23
20
  # If an error occurs in the job execution, the
24
21
  # Processor calls the Manager to create a new one
25
22
  # to replace itself and exits.
26
23
  #
27
24
  class Processor
28
-
29
- include Util
25
+ include Sidekiq::Component
30
26
 
31
27
  attr_reader :thread
32
28
  attr_reader :job
29
+ attr_reader :capsule
33
30
 
34
- def initialize(mgr)
35
- @mgr = mgr
31
+ def initialize(capsule, &block)
32
+ @config = @capsule = capsule
33
+ @callback = block
36
34
  @down = false
37
35
  @done = false
38
36
  @job = nil
39
37
  @thread = nil
40
- @strategy = (mgr.options[:fetch] || Sidekiq::BasicFetch).new(mgr.options)
41
- @reloader = Sidekiq.options[:reloader]
42
- @logging = (mgr.options[:job_logger] || Sidekiq::JobLogger).new
43
- @retrier = Sidekiq::JobRetry.new
38
+ @reloader = Sidekiq.default_configuration[:reloader]
39
+ @job_logger = (capsule.config[:job_logger] || Sidekiq::JobLogger).new(capsule.config)
40
+ @retrier = Sidekiq::JobRetry.new(capsule)
44
41
  end
45
42
 
46
- def terminate(wait=false)
43
+ def terminate(wait = false)
47
44
  @done = true
48
- return if !@thread
45
+ return unless @thread
49
46
  @thread.value if wait
50
47
  end
51
48
 
52
- def kill(wait=false)
49
+ def kill(wait = false)
53
50
  @done = true
54
- return if !@thread
51
+ return unless @thread
55
52
  # unlike the other actors, terminate does not wait
56
53
  # for the thread to finish because we don't know how
57
54
  # long the job will take to finish. Instead we
@@ -61,40 +58,45 @@ module Sidekiq
61
58
  @thread.value if wait
62
59
  end
63
60
 
61
+ def stopping?
62
+ @done
63
+ end
64
+
64
65
  def start
65
- @thread ||= safe_thread("processor", &method(:run))
66
+ @thread ||= safe_thread("#{config.name}/processor", &method(:run))
66
67
  end
67
68
 
68
69
  private unless $TESTING
69
70
 
70
71
  def run
71
- begin
72
- while !@done
73
- process_one
74
- end
75
- @mgr.processor_stopped(self)
76
- rescue Sidekiq::Shutdown
77
- @mgr.processor_stopped(self)
78
- rescue Exception => ex
79
- @mgr.processor_died(self, ex)
80
- end
72
+ # By setting this thread-local, Sidekiq.redis will access +Sidekiq::Capsule#redis_pool+
73
+ # instead of the global pool in +Sidekiq::Config#redis_pool+.
74
+ Thread.current[:sidekiq_capsule] = @capsule
75
+
76
+ process_one until @done
77
+ @callback.call(self)
78
+ rescue Sidekiq::Shutdown
79
+ @callback.call(self)
80
+ rescue Exception => ex
81
+ @callback.call(self, ex)
81
82
  end
82
83
 
83
- def process_one
84
+ def process_one(&block)
84
85
  @job = fetch
85
86
  process(@job) if @job
86
87
  @job = nil
87
88
  end
88
89
 
89
90
  def get_one
90
- begin
91
- work = @strategy.retrieve_work
92
- (logger.info { "Redis is online, #{Time.now - @down} sec downtime" }; @down = nil) if @down
93
- work
94
- rescue Sidekiq::Shutdown
95
- rescue => ex
96
- handle_fetch_exception(ex)
91
+ uow = capsule.fetcher.retrieve_work
92
+ if @down
93
+ logger.info { "Redis is online, #{::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - @down} sec downtime" }
94
+ @down = nil
97
95
  end
96
+ uow
97
+ rescue Sidekiq::Shutdown
98
+ rescue => ex
99
+ handle_fetch_exception(ex)
98
100
  end
99
101
 
100
102
  def fetch
@@ -108,8 +110,8 @@ module Sidekiq
108
110
  end
109
111
 
110
112
  def handle_fetch_exception(ex)
111
- if !@down
112
- @down = Time.now
113
+ unless @down
114
+ @down = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
113
115
  logger.error("Error fetching job: #{ex}")
114
116
  handle_exception(ex)
115
117
  end
@@ -117,26 +119,30 @@ module Sidekiq
117
119
  nil
118
120
  end
119
121
 
120
- def dispatch(job_hash, queue)
122
+ def dispatch(job_hash, queue, jobstr)
121
123
  # since middleware can mutate the job hash
122
- # we clone here so we report the original
124
+ # we need to clone it to report the original
123
125
  # job structure to the Web UI
124
- pristine = cloned(job_hash)
126
+ # or to push back to redis when retrying.
127
+ # To avoid costly and, most of the time, useless cloning here,
128
+ # we pass original String of JSON to respected methods
129
+ # to re-parse it there if we need access to the original, untouched job
125
130
 
126
- Sidekiq::Logging.with_job_hash_context(job_hash) do
127
- @retrier.global(pristine, queue) do
128
- @logging.call(job_hash, queue) do
129
- stats(pristine, queue) do
131
+ @job_logger.prepare(job_hash) do
132
+ @retrier.global(jobstr, queue) do
133
+ @job_logger.call(job_hash, queue) do
134
+ stats(jobstr, queue) do
130
135
  # Rails 5 requires a Reloader to wrap code execution. In order to
131
136
  # constantize the worker and instantiate an instance, we have to call
132
137
  # the Reloader. It handles code loading, db connection management, etc.
133
138
  # Effectively this block denotes a "unit of work" to Rails.
134
139
  @reloader.call do
135
- klass = constantize(job_hash['class'])
136
- worker = klass.new
137
- worker.jid = job_hash['jid']
138
- @retrier.local(worker, pristine, queue) do
139
- yield worker
140
+ klass = Object.const_get(job_hash["class"])
141
+ inst = klass.new
142
+ inst.jid = job_hash["jid"]
143
+ inst._context = self
144
+ @retrier.local(inst, jobstr, queue) do
145
+ yield inst
140
146
  end
141
147
  end
142
148
  end
@@ -145,84 +151,141 @@ module Sidekiq
145
151
  end
146
152
  end
147
153
 
148
- def process(work)
149
- jobstr = work.job
150
- queue = work.queue_name
154
+ IGNORE_SHUTDOWN_INTERRUPTS = {Sidekiq::Shutdown => :never}
155
+ private_constant :IGNORE_SHUTDOWN_INTERRUPTS
156
+ ALLOW_SHUTDOWN_INTERRUPTS = {Sidekiq::Shutdown => :immediate}
157
+ private_constant :ALLOW_SHUTDOWN_INTERRUPTS
151
158
 
152
- ack = false
159
+ def process(uow)
160
+ jobstr = uow.job
161
+ queue = uow.queue_name
162
+
163
+ # Treat malformed JSON as a special case: job goes straight to the morgue.
164
+ job_hash = nil
153
165
  begin
154
- # Treat malformed JSON as a special case: job goes straight to the morgue.
155
- job_hash = nil
156
- begin
157
- job_hash = Sidekiq.load_json(jobstr)
158
- rescue => ex
159
- handle_exception(ex, { :context => "Invalid JSON for job", :jobstr => jobstr })
160
- # we can't notify because the job isn't a valid hash payload.
161
- DeadSet.new.kill(jobstr, notify_failure: false)
162
- ack = true
163
- raise
166
+ job_hash = Sidekiq.load_json(jobstr)
167
+ rescue => ex
168
+ handle_exception(ex, {context: "Invalid JSON for job", jobstr: jobstr})
169
+ now = Time.now.to_f
170
+ redis do |conn|
171
+ conn.multi do |xa|
172
+ xa.zadd("dead", now.to_s, jobstr)
173
+ xa.zremrangebyscore("dead", "-inf", now - @capsule.config[:dead_timeout_in_seconds])
174
+ xa.zremrangebyrank("dead", 0, - @capsule.config[:dead_max_jobs])
175
+ end
164
176
  end
177
+ return uow.acknowledge
178
+ end
165
179
 
166
- ack = true
167
- dispatch(job_hash, queue) do |worker|
168
- Sidekiq.server_middleware.invoke(worker, job_hash, queue) do
169
- execute_job(worker, cloned(job_hash['args']))
180
+ ack = false
181
+ Thread.handle_interrupt(IGNORE_SHUTDOWN_INTERRUPTS) do
182
+ Thread.handle_interrupt(ALLOW_SHUTDOWN_INTERRUPTS) do
183
+ dispatch(job_hash, queue, jobstr) do |inst|
184
+ config.server_middleware.invoke(inst, job_hash, queue) do
185
+ execute_job(inst, job_hash["args"])
186
+ end
170
187
  end
188
+ ack = true
189
+ rescue Sidekiq::Shutdown
190
+ # Had to force kill this job because it didn't finish
191
+ # within the timeout. Don't acknowledge the work since
192
+ # we didn't properly finish it.
193
+ rescue Sidekiq::JobRetry::Skip => s
194
+ # Skip means we handled this error elsewhere. We don't
195
+ # need to log or report the error.
196
+ ack = true
197
+ raise s
198
+ rescue Sidekiq::JobRetry::Handled => h
199
+ # this is the common case: job raised error and Sidekiq::JobRetry::Handled
200
+ # signals that we created a retry successfully. We can acknowledge the job.
201
+ ack = true
202
+ e = h.cause || h
203
+ handle_exception(e, {context: "Job raised exception", job: job_hash})
204
+ raise e
205
+ rescue Exception => ex
206
+ # Unexpected error! This is very bad and indicates an exception that got past
207
+ # the retry subsystem (e.g. network partition). We won't acknowledge the job
208
+ # so it can be rescued when using Sidekiq Pro.
209
+ handle_exception(ex, {context: "Internal exception!", job: job_hash, jobstr: jobstr})
210
+ raise ex
171
211
  end
172
- rescue Sidekiq::Shutdown
173
- # Had to force kill this job because it didn't finish
174
- # within the timeout. Don't acknowledge the work since
175
- # we didn't properly finish it.
176
- ack = false
177
- rescue Exception => ex
178
- e = ex.is_a?(::Sidekiq::JobRetry::Skip) && ex.cause ? ex.cause : ex
179
- handle_exception(e, { :context => "Job raised exception", :job => job_hash, :jobstr => jobstr })
180
- raise e
181
212
  ensure
182
- work.acknowledge if ack
213
+ if ack
214
+ uow.acknowledge
215
+ end
183
216
  end
184
217
  end
185
218
 
186
- def execute_job(worker, cloned_args)
187
- worker.perform(*cloned_args)
219
+ def execute_job(inst, cloned_args)
220
+ inst.perform(*cloned_args)
188
221
  end
189
222
 
190
- WORKER_STATE = Concurrent::Map.new
191
- PROCESSED = Concurrent::AtomicFixnum.new
192
- FAILURE = Concurrent::AtomicFixnum.new
223
+ # Ruby doesn't provide atomic counters out of the box so we'll
224
+ # implement something simple ourselves.
225
+ # https://bugs.ruby-lang.org/issues/14706
226
+ class Counter
227
+ def initialize
228
+ @value = 0
229
+ @lock = Mutex.new
230
+ end
193
231
 
194
- def stats(job_hash, queue)
195
- tid = Sidekiq::Logging.tid
196
- WORKER_STATE[tid] = {:queue => queue, :payload => job_hash, :run_at => Time.now.to_i }
232
+ def incr(amount = 1)
233
+ @lock.synchronize { @value += amount }
234
+ end
197
235
 
198
- begin
199
- yield
200
- rescue Exception
201
- FAILURE.increment
202
- raise
203
- ensure
204
- WORKER_STATE.delete(tid)
205
- PROCESSED.increment
236
+ def reset
237
+ @lock.synchronize {
238
+ val = @value
239
+ @value = 0
240
+ val
241
+ }
206
242
  end
207
243
  end
208
244
 
209
- # Deep clone the arguments passed to the worker so that if
210
- # the job fails, what is pushed back onto Redis hasn't
211
- # been mutated by the worker.
212
- def cloned(thing)
213
- Marshal.load(Marshal.dump(thing))
214
- end
245
+ # jruby's Hash implementation is not threadsafe, so we wrap it in a mutex here
246
+ class SharedWorkState
247
+ def initialize
248
+ @work_state = {}
249
+ @lock = Mutex.new
250
+ end
251
+
252
+ def set(tid, hash)
253
+ @lock.synchronize { @work_state[tid] = hash }
254
+ end
215
255
 
216
- def constantize(str)
217
- names = str.split('::')
218
- names.shift if names.empty? || names.first.empty?
256
+ def delete(tid)
257
+ @lock.synchronize { @work_state.delete(tid) }
258
+ end
259
+
260
+ def dup
261
+ @lock.synchronize { @work_state.dup }
262
+ end
219
263
 
220
- names.inject(Object) do |constant, name|
221
- # the false flag limits search for name to under the constant namespace
222
- # which mimics Rails' behaviour
223
- constant.const_defined?(name, false) ? constant.const_get(name, false) : constant.const_missing(name)
264
+ def size
265
+ @lock.synchronize { @work_state.size }
266
+ end
267
+
268
+ def clear
269
+ @lock.synchronize { @work_state.clear }
224
270
  end
225
271
  end
226
272
 
273
+ PROCESSED = Counter.new
274
+ FAILURE = Counter.new
275
+ WORK_STATE = SharedWorkState.new
276
+
277
+ def stats(jobstr, queue)
278
+ WORK_STATE.set(tid, {queue: queue, payload: jobstr, run_at: Time.now.to_i})
279
+
280
+ begin
281
+ yield
282
+ rescue Exception
283
+ FAILURE.incr
284
+ raise
285
+ ensure
286
+ WORK_STATE.delete(tid)
287
+ PROCESSED.incr
288
+ end
289
+ end
227
290
  end
228
291
  end
data/lib/sidekiq/rails.rb CHANGED
@@ -1,44 +1,18 @@
1
1
  # frozen_string_literal: true
2
- module Sidekiq
3
- class Rails < ::Rails::Engine
4
- # We need to setup this up before any application configuration which might
5
- # change Sidekiq middleware.
6
- #
7
- # This hook happens after `Rails::Application` is inherited within
8
- # config/application.rb and before config is touched, usually within the
9
- # class block. Definitely before config/environments/*.rb and
10
- # config/initializers/*.rb.
11
- config.before_configuration do
12
- if ::Rails::VERSION::MAJOR < 5 && defined?(::ActiveRecord)
13
- Sidekiq.server_middleware do |chain|
14
- require 'sidekiq/middleware/server/active_record'
15
- chain.add Sidekiq::Middleware::Server::ActiveRecord
16
- end
17
- end
18
- end
19
2
 
20
- config.after_initialize do
21
- # This hook happens after all initializers are run, just before returning
22
- # from config/environment.rb back to sidekiq/cli.rb.
23
- # We have to add the reloader after initialize to see if cache_classes has
24
- # been turned on.
25
- #
26
- # None of this matters on the client-side, only within the Sidekiq process itself.
27
- #
28
- Sidekiq.configure_server do |_|
29
- if ::Rails::VERSION::MAJOR >= 5
30
- Sidekiq.options[:reloader] = Sidekiq::Rails::Reloader.new
31
- end
32
- end
33
- end
3
+ require "sidekiq/job"
4
+ require "rails"
34
5
 
6
+ module Sidekiq
7
+ class Rails < ::Rails::Engine
35
8
  class Reloader
36
9
  def initialize(app = ::Rails.application)
37
10
  @app = app
38
11
  end
39
12
 
40
13
  def call
41
- @app.reloader.wrap do
14
+ params = (::Rails::VERSION::STRING >= "7.1") ? {source: "job.sidekiq"} : {}
15
+ @app.reloader.wrap(**params) do
42
16
  yield
43
17
  end
44
18
  end
@@ -46,12 +20,53 @@ module Sidekiq
46
20
  def inspect
47
21
  "#<Sidekiq::Rails::Reloader @app=#{@app.class.name}>"
48
22
  end
23
+
24
+ def to_hash
25
+ {app: @app.class.name}
26
+ end
49
27
  end
50
- end if defined?(::Rails)
51
- end
52
28
 
53
- if defined?(::Rails) && ::Rails::VERSION::MAJOR < 4
54
- $stderr.puts("**************************************************")
55
- $stderr.puts("⛔️ WARNING: Sidekiq server is no longer supported by Rails 3.2 - please ensure your server/workers are updated")
56
- $stderr.puts("**************************************************")
57
- end
29
+ # By including the Options module, we allow AJs to directly control sidekiq features
30
+ # via the *sidekiq_options* class method and, for instance, not use AJ's retry system.
31
+ # AJ retries don't show up in the Sidekiq UI Retries tab, don't save any error data, can't be
32
+ # manually retried, don't automatically die, etc.
33
+ #
34
+ # class SomeJob < ActiveJob::Base
35
+ # queue_as :default
36
+ # sidekiq_options retry: 3, backtrace: 10
37
+ # def perform
38
+ # end
39
+ # end
40
+ initializer "sidekiq.active_job_integration" do
41
+ ActiveSupport.on_load(:active_job) do
42
+ include ::Sidekiq::Job::Options unless respond_to?(:sidekiq_options)
43
+ end
44
+ end
45
+
46
+ initializer "sidekiq.backtrace_cleaner" do
47
+ Sidekiq.configure_server do |config|
48
+ config[:backtrace_cleaner] = ->(backtrace) { ::Rails.backtrace_cleaner.clean(backtrace) }
49
+ end
50
+ end
51
+
52
+ # This hook happens after all initializers are run, just before returning
53
+ # from config/environment.rb back to sidekiq/cli.rb.
54
+ #
55
+ # None of this matters on the client-side, only within the Sidekiq process itself.
56
+ config.after_initialize do
57
+ Sidekiq.configure_server do |config|
58
+ config[:reloader] = Sidekiq::Rails::Reloader.new
59
+
60
+ # This is the integration code necessary so that if a job uses `Rails.logger.info "Hello"`,
61
+ # it will appear in the Sidekiq console with all of the job context.
62
+ unless ::Rails.logger == config.logger || ::ActiveSupport::Logger.logger_outputs_to?(::Rails.logger, $stdout)
63
+ if ::Rails.logger.respond_to?(:broadcast_to)
64
+ ::Rails.logger.broadcast_to(config.logger)
65
+ else
66
+ ::Rails.logger.extend(::ActiveSupport::Logger.broadcast(config.logger))
67
+ end
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+ require "redis_client"
5
+ require "redis_client/decorator"
6
+
7
+ module Sidekiq
8
+ class RedisClientAdapter
9
+ BaseError = RedisClient::Error
10
+ CommandError = RedisClient::CommandError
11
+
12
+ # You can add/remove items or clear the whole thing if you don't want deprecation warnings.
13
+ DEPRECATED_COMMANDS = %i[rpoplpush zrangebyscore zrevrange zrevrangebyscore getset hmset setex setnx].to_set
14
+
15
+ module CompatMethods
16
+ def info
17
+ @client.call("INFO") { |i| i.lines(chomp: true).map { |l| l.split(":", 2) }.select { |l| l.size == 2 }.to_h }
18
+ end
19
+
20
+ def evalsha(sha, keys, argv)
21
+ @client.call("EVALSHA", sha, keys.size, *keys, *argv)
22
+ end
23
+
24
+ # this is the set of Redis commands used by Sidekiq. Not guaranteed
25
+ # to be comprehensive, we use this as a performance enhancement to
26
+ # avoid calling method_missing on most commands
27
+ USED_COMMANDS = %w[bitfield bitfield_ro del exists expire flushdb
28
+ get hdel hget hgetall hincrby hlen hmget hset hsetnx incr incrby
29
+ lindex llen lmove lpop lpush lrange lrem mget mset ping pttl
30
+ publish rpop rpush sadd scard script set sismember smembers
31
+ srem ttl type unlink zadd zcard zincrby zrange zrem
32
+ zremrangebyrank zremrangebyscore]
33
+
34
+ USED_COMMANDS.each do |name|
35
+ define_method(name) do |*args, **kwargs|
36
+ @client.call(name, *args, **kwargs)
37
+ end
38
+ end
39
+
40
+ private
41
+
42
+ # this allows us to use methods like `conn.hmset(...)` instead of having to use
43
+ # redis-client's native `conn.call("hmset", ...)`
44
+ def method_missing(*args, &block)
45
+ warn("[sidekiq#5788] Redis has deprecated the `#{args.first}`command, called at #{caller(1..1)}") if DEPRECATED_COMMANDS.include?(args.first)
46
+ @client.call(*args, *block)
47
+ end
48
+ ruby2_keywords :method_missing if respond_to?(:ruby2_keywords, true)
49
+
50
+ def respond_to_missing?(name, include_private = false)
51
+ super # Appease the linter. We can't tell what is a valid command.
52
+ end
53
+ end
54
+
55
+ CompatClient = RedisClient::Decorator.create(CompatMethods)
56
+
57
+ class CompatClient
58
+ def config
59
+ @client.config
60
+ end
61
+ end
62
+
63
+ def initialize(options)
64
+ opts = client_opts(options)
65
+ @config = if opts.key?(:sentinels)
66
+ RedisClient.sentinel(**opts)
67
+ elsif opts.key?(:nodes)
68
+ # Sidekiq does not support Redis clustering but Sidekiq Enterprise's
69
+ # rate limiters are cluster-safe so we can scale to millions
70
+ # of rate limiters using a Redis cluster. This requires the
71
+ # `redis-cluster-client` gem.
72
+ # Sidekiq::Limiter.redis = { nodes: [...] }
73
+ RedisClient.cluster(**opts)
74
+ else
75
+ RedisClient.config(**opts)
76
+ end
77
+ end
78
+
79
+ def new_client
80
+ CompatClient.new(@config.new_client)
81
+ end
82
+
83
+ private
84
+
85
+ def client_opts(options)
86
+ opts = options.dup
87
+
88
+ if opts[:namespace]
89
+ raise ArgumentError, "Your Redis configuration uses the namespace '#{opts[:namespace]}' but this feature is no longer supported in Sidekiq 7+. See https://github.com/sidekiq/sidekiq/blob/main/docs/7.0-Upgrade.md#redis-namespace."
90
+ end
91
+
92
+ opts.delete(:size)
93
+ opts.delete(:pool_timeout)
94
+
95
+ if opts[:network_timeout]
96
+ opts[:timeout] = opts[:network_timeout]
97
+ opts.delete(:network_timeout)
98
+ end
99
+
100
+ opts[:name] = opts.delete(:master_name) if opts.key?(:master_name)
101
+ opts[:role] = opts[:role].to_sym if opts.key?(:role)
102
+ opts[:driver] = opts[:driver].to_sym if opts.key?(:driver)
103
+
104
+ # Issue #3303, redis-rb will silently retry an operation.
105
+ # This can lead to duplicate jobs if Sidekiq::Client's LPUSH
106
+ # is performed twice but I believe this is much, much rarer
107
+ # than the reconnect silently fixing a problem; we keep it
108
+ # on by default.
109
+ opts[:reconnect_attempts] ||= 1
110
+
111
+ opts
112
+ end
113
+ end
114
+ end