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,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
- require 'sidekiq/scheduled'
3
- require 'sidekiq/api'
2
+
3
+ require "zlib"
4
+ require "sidekiq/component"
4
5
 
5
6
  module Sidekiq
6
7
  ##
@@ -21,18 +22,19 @@ module Sidekiq
21
22
  #
22
23
  # A job looks like:
23
24
  #
24
- # { 'class' => 'HardWorker', 'args' => [1, 2, 'foo'], 'retry' => true }
25
+ # { 'class' => 'HardJob', 'args' => [1, 2, 'foo'], 'retry' => true }
25
26
  #
26
27
  # The 'retry' option also accepts a number (in place of 'true'):
27
28
  #
28
- # { 'class' => 'HardWorker', 'args' => [1, 2, 'foo'], 'retry' => 5 }
29
+ # { 'class' => 'HardJob', 'args' => [1, 2, 'foo'], 'retry' => 5 }
29
30
  #
30
31
  # The job will be retried this number of times before giving up. (If simply
31
32
  # 'true', Sidekiq retries 25 times)
32
33
  #
33
- # We'll add a bit more data to the job to support retries:
34
+ # Relevant options for job retries:
34
35
  #
35
- # * 'queue' - the queue to use
36
+ # * 'queue' - the queue for the initial job
37
+ # * 'retry_queue' - if job retries should be pushed to a different (e.g. lower priority) queue
36
38
  # * 'retry_count' - number of times we've retried so far.
37
39
  # * 'error_message' - the message from the exception
38
40
  # * 'error_class' - the exception class
@@ -46,32 +48,42 @@ module Sidekiq
46
48
  # The default number of retries is 25 which works out to about 3 weeks
47
49
  # You can change the default maximum number of retries in your initializer:
48
50
  #
49
- # Sidekiq.options[:max_retries] = 7
51
+ # Sidekiq.default_configuration[:max_retries] = 7
50
52
  #
51
- # or limit the number of retries for a particular worker with:
53
+ # or limit the number of retries for a particular job and send retries to
54
+ # a low priority queue with:
52
55
  #
53
- # class MyWorker
54
- # include Sidekiq::Worker
55
- # sidekiq_options :retry => 10
56
+ # class MyJob
57
+ # include Sidekiq::Job
58
+ # sidekiq_options retry: 10, retry_queue: 'low'
56
59
  # end
57
60
  #
58
61
  class JobRetry
59
- class Skip < ::RuntimeError; end
62
+ # Handled means the job failed but has been dealt with
63
+ # (by creating a retry, rescheduling it, etc). It still
64
+ # needs to be logged and dispatched to error_handlers.
65
+ class Handled < ::RuntimeError; end
66
+
67
+ # Skip means the job failed but Sidekiq does not need to
68
+ # create a retry, log it or send to error_handlers.
69
+ class Skip < Handled; end
60
70
 
61
- include Sidekiq::Util
71
+ include Sidekiq::Component
62
72
 
63
73
  DEFAULT_MAX_RETRY_ATTEMPTS = 25
64
74
 
65
- def initialize(options = {})
66
- @max_retries = Sidekiq.options.merge(options).fetch(:max_retries, DEFAULT_MAX_RETRY_ATTEMPTS)
75
+ def initialize(capsule)
76
+ @config = @capsule = capsule
77
+ @max_retries = Sidekiq.default_configuration[:max_retries] || DEFAULT_MAX_RETRY_ATTEMPTS
78
+ @backtrace_cleaner = Sidekiq.default_configuration[:backtrace_cleaner]
67
79
  end
68
80
 
69
81
  # The global retry handler requires only the barest of data.
70
82
  # We want to be able to retry as much as possible so we don't
71
- # require the worker to be instantiated.
72
- def global(msg, queue)
83
+ # require the job to be instantiated.
84
+ def global(jobstr, queue)
73
85
  yield
74
- rescue Skip => ex
86
+ rescue Handled => ex
75
87
  raise ex
76
88
  rescue Sidekiq::Shutdown => ey
77
89
  # ignore, will be pushed back onto queue during hard_shutdown
@@ -80,23 +92,31 @@ module Sidekiq
80
92
  # ignore, will be pushed back onto queue during hard_shutdown
81
93
  raise Sidekiq::Shutdown if exception_caused_by_shutdown?(e)
82
94
 
83
- raise e unless msg['retry']
84
- attempt_retry(nil, msg, queue, e)
85
- raise e
86
- end
95
+ msg = Sidekiq.load_json(jobstr)
96
+ if msg["retry"]
97
+ process_retry(nil, msg, queue, e)
98
+ else
99
+ @capsule.config.death_handlers.each do |handler|
100
+ handler.call(msg, e)
101
+ rescue => handler_ex
102
+ handle_exception(handler_ex, {context: "Error calling death handler", job: msg})
103
+ end
104
+ end
87
105
 
106
+ raise Handled
107
+ end
88
108
 
89
109
  # The local retry support means that any errors that occur within
90
- # this block can be associated with the given worker instance.
110
+ # this block can be associated with the given job instance.
91
111
  # This is required to support the `sidekiq_retries_exhausted` block.
92
112
  #
93
113
  # Note that any exception from the block is wrapped in the Skip
94
114
  # exception so the global block does not reprocess the error. The
95
115
  # Skip exception is unwrapped within Sidekiq::Processor#process before
96
116
  # calling the handle_exception handlers.
97
- def local(worker, msg, queue)
117
+ def local(jobinst, jobstr, queue)
98
118
  yield
99
- rescue Skip => ex
119
+ rescue Handled => ex
100
120
  raise ex
101
121
  rescue Sidekiq::Shutdown => ey
102
122
  # ignore, will be pushed back onto queue during hard_shutdown
@@ -105,95 +125,146 @@ module Sidekiq
105
125
  # ignore, will be pushed back onto queue during hard_shutdown
106
126
  raise Sidekiq::Shutdown if exception_caused_by_shutdown?(e)
107
127
 
108
- if msg['retry'] == nil
109
- msg['retry'] = worker.class.get_sidekiq_options['retry']
128
+ msg = Sidekiq.load_json(jobstr)
129
+ if msg["retry"].nil?
130
+ msg["retry"] = jobinst.class.get_sidekiq_options["retry"]
110
131
  end
111
132
 
112
- raise e unless msg['retry']
113
- attempt_retry(worker, msg, queue, e)
133
+ raise e unless msg["retry"]
134
+ process_retry(jobinst, msg, queue, e)
114
135
  # We've handled this error associated with this job, don't
115
136
  # need to handle it at the global level
116
- raise Skip
137
+ raise Handled
117
138
  end
118
139
 
119
140
  private
120
141
 
121
- # Note that +worker+ can be nil here if an error is raised before we can
122
- # instantiate the worker instance. All access must be guarded and
142
+ # Note that +jobinst+ can be nil here if an error is raised before we can
143
+ # instantiate the job instance. All access must be guarded and
123
144
  # best effort.
124
- def attempt_retry(worker, msg, queue, exception)
125
- max_retry_attempts = retry_attempts_from(msg['retry'], @max_retries)
145
+ def process_retry(jobinst, msg, queue, exception)
146
+ max_retry_attempts = retry_attempts_from(msg["retry"], @max_retries)
126
147
 
127
- msg['queue'] = if msg['retry_queue']
128
- msg['retry_queue']
129
- else
130
- queue
131
- end
148
+ msg["queue"] = (msg["retry_queue"] || queue)
132
149
 
133
- # App code can stuff all sorts of crazy binary data into the error message
134
- # that won't convert to JSON.
135
- m = exception.message.to_s[0, 10_000]
150
+ m = exception_message(exception)
136
151
  if m.respond_to?(:scrub!)
137
152
  m.force_encoding("utf-8")
138
153
  m.scrub!
139
154
  end
140
155
 
141
- msg['error_message'] = m
142
- msg['error_class'] = exception.class.name
143
- count = if msg['retry_count']
144
- msg['retried_at'] = Time.now.to_f
145
- msg['retry_count'] += 1
156
+ msg["error_message"] = m
157
+ msg["error_class"] = exception.class.name
158
+ count = if msg["retry_count"]
159
+ msg["retried_at"] = Time.now.to_f
160
+ msg["retry_count"] += 1
146
161
  else
147
- msg['failed_at'] = Time.now.to_f
148
- msg['retry_count'] = 0
162
+ msg["failed_at"] = Time.now.to_f
163
+ msg["retry_count"] = 0
164
+ end
165
+
166
+ if msg["backtrace"]
167
+ backtrace = @backtrace_cleaner.call(exception.backtrace)
168
+ lines = if msg["backtrace"] == true
169
+ backtrace
170
+ else
171
+ backtrace[0...msg["backtrace"].to_i]
172
+ end
173
+
174
+ msg["error_backtrace"] = compress_backtrace(lines)
149
175
  end
150
176
 
151
- if msg['backtrace'] == true
152
- msg['error_backtrace'] = exception.backtrace
153
- elsif !msg['backtrace']
154
- # do nothing
155
- elsif msg['backtrace'].to_i != 0
156
- msg['error_backtrace'] = exception.backtrace[0...msg['backtrace'].to_i]
177
+ return retries_exhausted(jobinst, msg, exception) if count >= max_retry_attempts
178
+
179
+ rf = msg["retry_for"]
180
+ return retries_exhausted(jobinst, msg, exception) if rf && ((msg["failed_at"] + rf) < Time.now.to_f)
181
+
182
+ strategy, delay = delay_for(jobinst, count, exception, msg)
183
+ case strategy
184
+ when :discard
185
+ return # poof!
186
+ when :kill
187
+ return retries_exhausted(jobinst, msg, exception)
157
188
  end
158
189
 
159
- if count < max_retry_attempts
160
- delay = delay_for(worker, count, exception)
161
- logger.debug { "Failure! Retry #{count} in #{delay} seconds" }
162
- retry_at = Time.now.to_f + delay
163
- payload = Sidekiq.dump_json(msg)
164
- Sidekiq.redis do |conn|
165
- conn.zadd('retry', retry_at.to_s, payload)
166
- end
167
- else
168
- # Goodbye dear message, you (re)tried your best I'm sure.
169
- retries_exhausted(worker, msg, exception)
190
+ # Logging here can break retries if the logging device raises ENOSPC #3979
191
+ # logger.debug { "Failure! Retry #{count} in #{delay} seconds" }
192
+ jitter = rand(10) * (count + 1)
193
+ retry_at = Time.now.to_f + delay + jitter
194
+ payload = Sidekiq.dump_json(msg)
195
+ redis do |conn|
196
+ conn.zadd("retry", retry_at.to_s, payload)
170
197
  end
171
198
  end
172
199
 
173
- def retries_exhausted(worker, msg, exception)
174
- logger.debug { "Retries exhausted for job" }
175
- begin
176
- block = worker && worker.sidekiq_retries_exhausted_block
177
- block.call(msg, exception) if block
178
- rescue => e
179
- handle_exception(e, { context: "Error calling retries_exhausted", job: msg })
200
+ # returns (strategy, seconds)
201
+ def delay_for(jobinst, count, exception, msg)
202
+ rv = begin
203
+ # sidekiq_retry_in can return two different things:
204
+ # 1. When to retry next, as an integer of seconds
205
+ # 2. A symbol which re-routes the job elsewhere, e.g. :discard, :kill, :default
206
+ block = jobinst&.sidekiq_retry_in_block
207
+
208
+ # the sidekiq_retry_in_block can be defined in a wrapped class (ActiveJob for instance)
209
+ unless msg["wrapped"].nil?
210
+ wrapped = Object.const_get(msg["wrapped"])
211
+ block = wrapped.respond_to?(:sidekiq_retry_in_block) ? wrapped.sidekiq_retry_in_block : nil
212
+ end
213
+ block&.call(count, exception, msg)
214
+ rescue Exception => e
215
+ handle_exception(e, {context: "Failure scheduling retry using the defined `sidekiq_retry_in` in #{jobinst.class.name}, falling back to default"})
216
+ nil
217
+ end
218
+
219
+ rv = rv.to_i if rv.respond_to?(:to_i)
220
+ delay = (count**4) + 15
221
+ if Integer === rv && rv > 0
222
+ delay = rv
223
+ elsif rv == :discard
224
+ return [:discard, nil] # do nothing, job goes poof
225
+ elsif rv == :kill
226
+ return [:kill, nil]
180
227
  end
181
228
 
182
- Sidekiq.death_handlers.each do |handler|
183
- begin
184
- handler.call(msg, exception)
185
- rescue => e
186
- handle_exception(e, { context: "Error calling death handler", job: msg })
229
+ [:default, delay]
230
+ end
231
+
232
+ def retries_exhausted(jobinst, msg, exception)
233
+ rv = begin
234
+ block = jobinst&.sidekiq_retries_exhausted_block
235
+
236
+ # the sidekiq_retries_exhausted_block can be defined in a wrapped class (ActiveJob for instance)
237
+ unless msg["wrapped"].nil?
238
+ wrapped = Object.const_get(msg["wrapped"])
239
+ block = wrapped.respond_to?(:sidekiq_retries_exhausted_block) ? wrapped.sidekiq_retries_exhausted_block : nil
187
240
  end
241
+ block&.call(msg, exception)
242
+ rescue => e
243
+ handle_exception(e, {context: "Error calling retries_exhausted", job: msg})
188
244
  end
189
245
 
190
- send_to_morgue(msg) unless msg['dead'] == false
246
+ return if rv == :discard # poof!
247
+ send_to_morgue(msg) unless msg["dead"] == false
248
+
249
+ @capsule.config.death_handlers.each do |handler|
250
+ handler.call(msg, exception)
251
+ rescue => e
252
+ handle_exception(e, {context: "Error calling death handler", job: msg})
253
+ end
191
254
  end
192
255
 
193
256
  def send_to_morgue(msg)
194
- Sidekiq.logger.info { "Adding dead #{msg['class']} job #{msg['jid']}" }
257
+ logger.info { "Adding dead #{msg["class"]} job #{msg["jid"]}" }
195
258
  payload = Sidekiq.dump_json(msg)
196
- DeadSet.new.kill(payload, notify_failure: false)
259
+ now = Time.now.to_f
260
+
261
+ redis do |conn|
262
+ conn.multi do |xa|
263
+ xa.zadd("dead", now.to_s, payload)
264
+ xa.zremrangebyscore("dead", "-inf", now - @capsule.config[:dead_timeout_in_seconds])
265
+ xa.zremrangebyrank("dead", 0, - @capsule.config[:dead_max_jobs])
266
+ end
267
+ end
197
268
  end
198
269
 
199
270
  def retry_attempts_from(msg_retry, default)
@@ -204,28 +275,6 @@ module Sidekiq
204
275
  end
205
276
  end
206
277
 
207
- def delay_for(worker, count, exception)
208
- if worker && worker.sidekiq_retry_in_block
209
- custom_retry_in = retry_in(worker, count, exception).to_i
210
- return custom_retry_in if custom_retry_in > 0
211
- end
212
- seconds_to_delay(count)
213
- end
214
-
215
- # delayed_job uses the same basic formula
216
- def seconds_to_delay(count)
217
- (count ** 4) + 15 + (rand(30)*(count+1))
218
- end
219
-
220
- def retry_in(worker, count, exception)
221
- begin
222
- worker.sidekiq_retry_in_block.call(count, exception)
223
- rescue Exception => e
224
- handle_exception(e, { context: "Failure scheduling retry using the defined `sidekiq_retry_in` in #{worker.class.name}, falling back to default" })
225
- nil
226
- end
227
- end
228
-
229
278
  def exception_caused_by_shutdown?(e, checked_causes = [])
230
279
  return false unless e.cause
231
280
 
@@ -237,5 +286,20 @@ module Sidekiq
237
286
  exception_caused_by_shutdown?(e.cause, checked_causes)
238
287
  end
239
288
 
289
+ # Extract message from exception.
290
+ # Set a default if the message raises an error
291
+ def exception_message(exception)
292
+ # App code can stuff all sorts of crazy binary data into the error message
293
+ # that won't convert to JSON.
294
+ exception.message.to_s[0, 10_000]
295
+ rescue
296
+ +"!!! ERROR MESSAGE THREW AN ERROR !!!"
297
+ end
298
+
299
+ def compress_backtrace(backtrace)
300
+ serialized = Sidekiq.dump_json(backtrace)
301
+ compressed = Zlib::Deflate.deflate(serialized)
302
+ [compressed].pack("m0") # Base64.strict_encode64
303
+ end
240
304
  end
241
305
  end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "time"
5
+
6
+ module Sidekiq
7
+ module JobUtil
8
+ # These functions encapsulate various job utilities.
9
+
10
+ TRANSIENT_ATTRIBUTES = %w[]
11
+
12
+ def validate(item)
13
+ raise(ArgumentError, "Job must be a Hash with 'class' and 'args' keys: `#{item}`") unless item.is_a?(Hash) && item.key?("class") && item.key?("args")
14
+ raise(ArgumentError, "Job args must be an Array: `#{item}`") unless item["args"].is_a?(Array) || item["args"].is_a?(Enumerator::Lazy)
15
+ raise(ArgumentError, "Job class must be either a Class or String representation of the class name: `#{item}`") unless item["class"].is_a?(Class) || item["class"].is_a?(String)
16
+ raise(ArgumentError, "Job 'at' must be a Numeric timestamp: `#{item}`") if item.key?("at") && !item["at"].is_a?(Numeric)
17
+ raise(ArgumentError, "Job tags must be an Array: `#{item}`") if item["tags"] && !item["tags"].is_a?(Array)
18
+ raise(ArgumentError, "retry_for must be a relative amount of time, e.g. 48.hours `#{item}`") if item["retry_for"] && item["retry_for"] > 1_000_000_000
19
+ end
20
+
21
+ def verify_json(item)
22
+ job_class = item["wrapped"] || item["class"]
23
+ args = item["args"]
24
+ mode = Sidekiq::Config::DEFAULTS[:on_complex_arguments]
25
+
26
+ if mode == :raise || mode == :warn
27
+ if (unsafe_item = json_unsafe?(args))
28
+ msg = <<~EOM
29
+ Job arguments to #{job_class} must be native JSON types, but #{unsafe_item.inspect} is a #{unsafe_item.class}.
30
+ See https://github.com/sidekiq/sidekiq/wiki/Best-Practices
31
+ To disable this error, add `Sidekiq.strict_args!(false)` to your initializer.
32
+ EOM
33
+
34
+ if mode == :raise
35
+ raise(ArgumentError, msg)
36
+ else
37
+ warn(msg)
38
+ end
39
+ end
40
+ end
41
+ end
42
+
43
+ def normalize_item(item)
44
+ validate(item)
45
+
46
+ # merge in the default sidekiq_options for the item's class and/or wrapped element
47
+ # this allows ActiveJobs to control sidekiq_options too.
48
+ defaults = normalized_hash(item["class"])
49
+ defaults = defaults.merge(item["wrapped"].get_sidekiq_options) if item["wrapped"].respond_to?(:get_sidekiq_options)
50
+ item = defaults.merge(item)
51
+
52
+ raise(ArgumentError, "Job must include a valid queue name") if item["queue"].nil? || item["queue"] == ""
53
+
54
+ # remove job attributes which aren't necessary to persist into Redis
55
+ TRANSIENT_ATTRIBUTES.each { |key| item.delete(key) }
56
+
57
+ item["jid"] ||= SecureRandom.hex(12)
58
+ item["class"] = item["class"].to_s
59
+ item["queue"] = item["queue"].to_s
60
+ item["retry_for"] = item["retry_for"].to_i if item["retry_for"]
61
+ item["created_at"] ||= Time.now.to_f
62
+ item
63
+ end
64
+
65
+ def normalized_hash(item_class)
66
+ if item_class.is_a?(Class)
67
+ raise(ArgumentError, "Message must include a Sidekiq::Job class, not class name: #{item_class.ancestors.inspect}") unless item_class.respond_to?(:get_sidekiq_options)
68
+ item_class.get_sidekiq_options
69
+ else
70
+ Sidekiq.default_job_options
71
+ end
72
+ end
73
+
74
+ private
75
+
76
+ RECURSIVE_JSON_UNSAFE = {
77
+ Integer => ->(val) {},
78
+ Float => ->(val) {},
79
+ TrueClass => ->(val) {},
80
+ FalseClass => ->(val) {},
81
+ NilClass => ->(val) {},
82
+ String => ->(val) {},
83
+ Array => ->(val) {
84
+ val.each do |e|
85
+ unsafe_item = RECURSIVE_JSON_UNSAFE[e.class].call(e)
86
+ return unsafe_item unless unsafe_item.nil?
87
+ end
88
+ nil
89
+ },
90
+ Hash => ->(val) {
91
+ val.each do |k, v|
92
+ return k unless String === k
93
+
94
+ unsafe_item = RECURSIVE_JSON_UNSAFE[v.class].call(v)
95
+ return unsafe_item unless unsafe_item.nil?
96
+ end
97
+ nil
98
+ }
99
+ }
100
+
101
+ RECURSIVE_JSON_UNSAFE.default = ->(val) { val }
102
+ RECURSIVE_JSON_UNSAFE.compare_by_identity
103
+ private_constant :RECURSIVE_JSON_UNSAFE
104
+
105
+ def json_unsafe?(item)
106
+ RECURSIVE_JSON_UNSAFE[item.class].call(item)
107
+ end
108
+ end
109
+ end