robin-compat 0.1.2
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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +28 -0
- data/COPYING +674 -0
- data/LICENSE +165 -0
- data/README.md +258 -0
- data/exe/sidekiq +5 -0
- data/exe/sidekiqswarm +6 -0
- data/lib/robin/compat/cron_line.rb +46 -0
- data/lib/robin/compat/version.rb +8 -0
- data/lib/robin-compat.rb +3 -0
- data/lib/sidekiq/active_job.rb +87 -0
- data/lib/sidekiq/api.rb +352 -0
- data/lib/sidekiq/batch.rb +175 -0
- data/lib/sidekiq/capsule.rb +38 -0
- data/lib/sidekiq/cli.rb +70 -0
- data/lib/sidekiq/client.rb +84 -0
- data/lib/sidekiq/config.rb +190 -0
- data/lib/sidekiq/cron/job.rb +555 -0
- data/lib/sidekiq/cron/poller.rb +47 -0
- data/lib/sidekiq/cron/schedule_loader.rb +41 -0
- data/lib/sidekiq/cron/web.rb +7 -0
- data/lib/sidekiq/cron.rb +146 -0
- data/lib/sidekiq/deploy.rb +62 -0
- data/lib/sidekiq/iterable_job.rb +55 -0
- data/lib/sidekiq/job.rb +207 -0
- data/lib/sidekiq/job_retry.rb +23 -0
- data/lib/sidekiq/limiter.rb +144 -0
- data/lib/sidekiq/logger.rb +25 -0
- data/lib/sidekiq/middleware/chain.rb +27 -0
- data/lib/sidekiq/middleware/current_attributes.rb +19 -0
- data/lib/sidekiq/middleware/modules.rb +15 -0
- data/lib/sidekiq/middleware/server/statsd.rb +3 -0
- data/lib/sidekiq/periodic.rb +94 -0
- data/lib/sidekiq/pro/metrics.rb +134 -0
- data/lib/sidekiq/pro/web.rb +5 -0
- data/lib/sidekiq/rails.rb +18 -0
- data/lib/sidekiq/redis_connection.rb +166 -0
- data/lib/sidekiq/scheduler.rb +4 -0
- data/lib/sidekiq/testing/inline.rb +5 -0
- data/lib/sidekiq/testing.rb +188 -0
- data/lib/sidekiq/web.rb +112 -0
- data/lib/sidekiq-cron.rb +4 -0
- data/lib/sidekiq-ent/periodic/testing.rb +4 -0
- data/lib/sidekiq-ent/web.rb +5 -0
- data/lib/sidekiq-ent.rb +90 -0
- data/lib/sidekiq-pro.rb +16 -0
- data/lib/sidekiq-scheduler/config.rb +65 -0
- data/lib/sidekiq-scheduler/manager.rb +34 -0
- data/lib/sidekiq-scheduler/poller.rb +46 -0
- data/lib/sidekiq-scheduler/redis_manager.rb +108 -0
- data/lib/sidekiq-scheduler/schedule.rb +65 -0
- data/lib/sidekiq-scheduler/scheduled_job.rb +80 -0
- data/lib/sidekiq-scheduler/scheduler.rb +218 -0
- data/lib/sidekiq-scheduler/utils.rb +120 -0
- data/lib/sidekiq-scheduler/version.rb +6 -0
- data/lib/sidekiq-scheduler/web.rb +7 -0
- data/lib/sidekiq-scheduler.rb +48 -0
- data/lib/sidekiq.rb +222 -0
- metadata +121 -0
data/lib/sidekiq/api.rb
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "forwardable"
|
|
4
|
+
require "sidekiq"
|
|
5
|
+
|
|
6
|
+
module Sidekiq
|
|
7
|
+
# Sidekiq's data API on Robin's (see Robin::Stats, Robin::Queue...):
|
|
8
|
+
# Sidekiq's names, orderings and return values.
|
|
9
|
+
class Stats < Robin::Stats
|
|
10
|
+
QueueSummary = Data.define(:name, :size, :latency, :paused) do
|
|
11
|
+
alias_method :paused?, :paused
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
alias_method :fetch_stats!, :fetch
|
|
15
|
+
alias_method :fetch_stats_fast!, :fetch
|
|
16
|
+
alias_method :fetch_stats_slow!, :fetch
|
|
17
|
+
|
|
18
|
+
# Each queue's name, size, latency and paused flag, largest first.
|
|
19
|
+
def queue_summaries
|
|
20
|
+
c = @config
|
|
21
|
+
names = c.redis { |r| r.call("SMEMBERS", c.key("queues")) }
|
|
22
|
+
rows = c.redis do |r|
|
|
23
|
+
r.pipelined do |p|
|
|
24
|
+
names.each do |name|
|
|
25
|
+
p.call("LLEN", c.key("queue", name))
|
|
26
|
+
p.call("LINDEX", c.key("queue", name), -1)
|
|
27
|
+
p.call("SISMEMBER", c.key("paused"), name)
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
names.zip(rows.each_slice(3)).map do |name, (size, oldest, paused)|
|
|
32
|
+
QueueSummary.new(name: name, size: size, latency: Queue.latency_of(oldest), paused: paused == 1)
|
|
33
|
+
end.sort_by { |s| [-s.size, s.name] }
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Only the processed and failed counts can be reset (both by default).
|
|
37
|
+
def reset(*stats)
|
|
38
|
+
names = %w[processed failed]
|
|
39
|
+
names &= stats.flatten.map(&:to_s) unless stats.empty?
|
|
40
|
+
super(*names) unless names.empty?
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Daily processed and failed counts, newest first, for the
|
|
44
|
+
# +days_previous+ days up to +start_date+ (a Date; today by default).
|
|
45
|
+
class History
|
|
46
|
+
def initialize(days_previous, start_date = nil, config: Robin.config)
|
|
47
|
+
# Sidekiq keeps five years of daily counts.
|
|
48
|
+
raise ArgumentError, "days_previous must be between 1 and 1825" unless days_previous.between?(1, 5 * 365)
|
|
49
|
+
|
|
50
|
+
now = start_date ? Time.utc(start_date.year, start_date.month, start_date.day) : Time.now
|
|
51
|
+
@history = Stats.new(config: config).history(days: days_previous, now: now)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def processed = @history.fetch("processed")
|
|
55
|
+
|
|
56
|
+
def failed = @history.fetch("failed")
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# What Sidekiq's job records add to Robin's.
|
|
61
|
+
module JobRecordMethods
|
|
62
|
+
# Iteration state saved by an iterable job (Sidekiq::IterableJob).
|
|
63
|
+
IterableState = Struct.new(:jid, :raw) do
|
|
64
|
+
def cursor = Robin.load_json(raw.fetch("cursor")).fetch("c")
|
|
65
|
+
|
|
66
|
+
def iterations = raw.fetch("iterations").to_i
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# The job's iteration state, or nil if it has none.
|
|
70
|
+
def iterable_state
|
|
71
|
+
raw = @config.redis { |c| c.call("HGETALL", @config.key("iter", jid)) }
|
|
72
|
+
IterableState.new(jid, raw.each_slice(2).to_h) unless raw.empty?
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# When the job was created (or else pushed); the epoch for neither.
|
|
76
|
+
def created_at = super || enqueued_at || Time.at(0)
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
class JobRecord < Robin::JobRecord
|
|
80
|
+
include JobRecordMethods
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
class Queue < Robin::Queue
|
|
84
|
+
alias_method :id, :name
|
|
85
|
+
|
|
86
|
+
# Sidekiq starts with the most recently pushed job.
|
|
87
|
+
def each(&block)
|
|
88
|
+
# (Robin's each without a block would enumerate with this one.)
|
|
89
|
+
jobs = []
|
|
90
|
+
super { |job| jobs << job }
|
|
91
|
+
jobs.reverse_each(&block)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
private
|
|
95
|
+
|
|
96
|
+
def record(raw) = JobRecord.new(raw, name, config: @config)
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# A job in a sorted set, with Sidekiq's method names.
|
|
100
|
+
class SortedEntry < Robin::SortedEntry
|
|
101
|
+
include JobRecordMethods
|
|
102
|
+
|
|
103
|
+
def at = super.utc
|
|
104
|
+
|
|
105
|
+
# Pushes the job back onto its queue; as in Sidekiq, a retry made
|
|
106
|
+
# here doesn't count as one of the job's retries.
|
|
107
|
+
def retry
|
|
108
|
+
remove_and { Client.new(config: @config).push(queued_item) }
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# As in Sidekiq, a retry made here doesn't count as one of the job's
|
|
112
|
+
# retries.
|
|
113
|
+
def queued_item
|
|
114
|
+
super.tap { |item| item["retry_count"] = Integer(item.fetch("retry_count")) - 1 if item.key?("retry_count") }
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# Moves the job to the dead set, running the death handlers unless
|
|
118
|
+
# +notify_failure+ is false.
|
|
119
|
+
def kill(notify_failure: true, ex: nil)
|
|
120
|
+
remove_and do |item|
|
|
121
|
+
DeadSet.new(config: @config).kill(Robin.dump_json(item), notify_failure: notify_failure, ex: ex)
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def error? = !!self["error_class"]
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
class JobSet < Robin::JobSet
|
|
129
|
+
# Entries each ZSCAN call looks at (by default).
|
|
130
|
+
SCAN_COUNT = 100
|
|
131
|
+
|
|
132
|
+
def initialize(name = nil, config: Robin.config)
|
|
133
|
+
super(name || self.class::NAME, config: config)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# Sidekiq starts with the latest score.
|
|
137
|
+
def each(&block)
|
|
138
|
+
return to_enum unless block
|
|
139
|
+
|
|
140
|
+
super(reverse: true)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# Entries whose JSON matches +match+ (a glob: "*" is added on both
|
|
144
|
+
# sides unless it has one), yielded or returned.
|
|
145
|
+
def scan(match, count = SCAN_COUNT, &block)
|
|
146
|
+
pattern = match.include?("*") ? match : "*#{match}*"
|
|
147
|
+
found = []
|
|
148
|
+
cursor = "0"
|
|
149
|
+
@config.redis do |c|
|
|
150
|
+
loop do
|
|
151
|
+
cursor, pairs = c.call("ZSCAN", key, cursor, "MATCH", pattern, "COUNT", count)
|
|
152
|
+
pairs.each_slice(2) { |value, score| found << entry(score, value) }
|
|
153
|
+
break if cursor == "0"
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
block ? found.each(&block) : found
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# Entries with exactly this score (a Time, epoch seconds or a Range of
|
|
160
|
+
# either, which may be open-ended), optionally only the one with +jid+.
|
|
161
|
+
def fetch(score, jid = nil)
|
|
162
|
+
low, high = score.instance_of?(Range) ? [score.begin || "-inf", score.end || "+inf"] : [score, score]
|
|
163
|
+
raw = @config.redis { |c| c.call("ZRANGE", key, seconds(low), seconds(high), "BYSCORE", "WITHSCORES") }
|
|
164
|
+
entries = raw.each_slice(2).map { |value, s| entry(s, value) }
|
|
165
|
+
jid ? entries.select { |e| e.jid == jid } : entries
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def delete_by_value(_name, value) = @config.redis { |c| c.call("ZREM", key, value) } == 1
|
|
169
|
+
|
|
170
|
+
alias_method :delete, :delete_by_jid
|
|
171
|
+
|
|
172
|
+
# Pushes every entry back onto its queue, a page at a time; returns how
|
|
173
|
+
# many.
|
|
174
|
+
def retry_all = drain_pages { |page| retry_entries(page) }
|
|
175
|
+
|
|
176
|
+
# Moves every entry to the dead set, a page at a time (running the
|
|
177
|
+
# death handlers for each, with +notify_failure+); returns how many.
|
|
178
|
+
def kill_all(notify_failure: false, ex: nil)
|
|
179
|
+
return drain_pages { |page| kill_entries(page) } unless notify_failure
|
|
180
|
+
|
|
181
|
+
drain { |e| e.kill(ex: ex) }
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
private
|
|
185
|
+
|
|
186
|
+
def entry(score, value) = SortedEntry.new(self, score, value)
|
|
187
|
+
|
|
188
|
+
def seconds(time) = time.is_a?(Time) ? time.to_f : time
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
SortedSet = JobSet
|
|
192
|
+
|
|
193
|
+
class ScheduledSet < JobSet
|
|
194
|
+
NAME = "schedule"
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
class RetrySet < JobSet
|
|
198
|
+
NAME = "retry"
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
class DeadSet < JobSet
|
|
202
|
+
NAME = "dead"
|
|
203
|
+
|
|
204
|
+
# Adds a job (its JSON) to the dead set. Unless +notify_failure+ is
|
|
205
|
+
# false, runs the death handlers with +ex+ (by default an error saying
|
|
206
|
+
# the API killed it).
|
|
207
|
+
def kill(message, opts = {})
|
|
208
|
+
Robin::DeadSet.new(config: @config).kill(message)
|
|
209
|
+
unless opts[:notify_failure] == false
|
|
210
|
+
ex = opts[:ex] || RuntimeError.new("Job killed by API").tap { |e| e.set_backtrace(caller) }
|
|
211
|
+
job = Robin.load_json(message)
|
|
212
|
+
@config.death_handlers.each { |h| h.call(job, ex) }
|
|
213
|
+
end
|
|
214
|
+
true
|
|
215
|
+
end
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
# A running process, with Sidekiq's readers.
|
|
219
|
+
class Process < Robin::ProcessRecord
|
|
220
|
+
def [](key)
|
|
221
|
+
case key
|
|
222
|
+
when "busy" then busy
|
|
223
|
+
when "beat" then Robin.epoch_seconds(beat)
|
|
224
|
+
when "quiet" then quiet?.to_s
|
|
225
|
+
when "rss" then rss
|
|
226
|
+
when "rtt_us" then rtt_us
|
|
227
|
+
else info[key]
|
|
228
|
+
end
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
alias_method :id, :identity
|
|
232
|
+
|
|
233
|
+
def tag = self["tag"]
|
|
234
|
+
|
|
235
|
+
def labels = self["labels"].to_a
|
|
236
|
+
|
|
237
|
+
# The queues the process's capsules take jobs from.
|
|
238
|
+
def queues = capsules.empty? ? self["queues"].to_a : capsules.values.flat_map { |c| c.fetch("weights").keys }.uniq
|
|
239
|
+
|
|
240
|
+
# Each queue's weight (merged across capsules).
|
|
241
|
+
def weights = capsules.empty? ? self["weights"].to_a : capsules.values.map { |c| c.fetch("weights") }.reduce(:merge)
|
|
242
|
+
|
|
243
|
+
def capsules = self["capsules"].to_h
|
|
244
|
+
|
|
245
|
+
def version = self["version"]
|
|
246
|
+
|
|
247
|
+
def embedded? = !!self["embedded"]
|
|
248
|
+
|
|
249
|
+
def stopping? = quiet?
|
|
250
|
+
|
|
251
|
+
# An embedded process belongs to its host app, which stops it.
|
|
252
|
+
def quiet!
|
|
253
|
+
raise "Can't quiet an embedded process" if embedded?
|
|
254
|
+
|
|
255
|
+
super
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def stop!
|
|
259
|
+
raise "Can't stop an embedded process" if embedded?
|
|
260
|
+
|
|
261
|
+
super
|
|
262
|
+
end
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
class ProcessSet < Robin::ProcessSet
|
|
266
|
+
def self.[](identity, config: Robin.config) = new(false, config: config).find { |p| p.identity == identity }
|
|
267
|
+
|
|
268
|
+
# Like Sidekiq, removes departed processes from the set first unless
|
|
269
|
+
# +clean_plz+ is false.
|
|
270
|
+
def initialize(clean_plz = true, config: Robin.config)
|
|
271
|
+
super(config: config)
|
|
272
|
+
cleanup if clean_plz
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
# Removes processes whose records have expired from the set (at most
|
|
276
|
+
# once a minute across the cluster; Robin's leader does it anyway).
|
|
277
|
+
# Returns how many.
|
|
278
|
+
def cleanup
|
|
279
|
+
c = @config
|
|
280
|
+
return 0 unless c.redis { |r| r.call("SET", c.key("process_cleanup"), "1", "NX", "EX", 60) }
|
|
281
|
+
|
|
282
|
+
identities = c.redis { |r| r.call("SMEMBERS", c.key("processes")) }
|
|
283
|
+
alive = c.redis { |r| r.pipelined { |p| identities.each { |i| p.call("EXISTS", c.process_key(i)) } } }
|
|
284
|
+
gone = identities.zip(alive).filter_map { |identity, exists| identity if exists.zero? }
|
|
285
|
+
c.redis { |r| r.call("SREM", c.key("processes"), *gone) } unless gone.empty?
|
|
286
|
+
gone.size
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
def total_rss_in_kb = total_rss_kb
|
|
290
|
+
alias_method :total_rss, :total_rss_in_kb
|
|
291
|
+
|
|
292
|
+
# The leader's identity ("" when there is none).
|
|
293
|
+
def leader = super.to_s
|
|
294
|
+
|
|
295
|
+
private
|
|
296
|
+
|
|
297
|
+
def record(identity, data) = Process.new(identity, data, config: @config)
|
|
298
|
+
end
|
|
299
|
+
|
|
300
|
+
# A job running right now. Also Sidekiq 7's form of it, a Hash
|
|
301
|
+
# ({"queue", "payload", "run_at" (epoch seconds)}), read with #[] or any
|
|
302
|
+
# of Hash's methods.
|
|
303
|
+
class Work
|
|
304
|
+
extend Forwardable
|
|
305
|
+
|
|
306
|
+
def_delegators :to_h, *(::Hash.public_instance_methods - ::Object.public_instance_methods)
|
|
307
|
+
|
|
308
|
+
attr_reader :process_id, :thread_id
|
|
309
|
+
|
|
310
|
+
def initialize(process_id, thread_id, hash)
|
|
311
|
+
@process_id = process_id
|
|
312
|
+
@thread_id = thread_id
|
|
313
|
+
@hash = hash
|
|
314
|
+
end
|
|
315
|
+
|
|
316
|
+
def queue = @hash.fetch("queue")
|
|
317
|
+
|
|
318
|
+
def run_at = Time.at(Rational(@hash.fetch("run_at"), 1000))
|
|
319
|
+
|
|
320
|
+
# The job's JSON.
|
|
321
|
+
def payload = @payload ||= Robin.dump_json(@hash.fetch("payload"))
|
|
322
|
+
|
|
323
|
+
def job = JobRecord.new(payload, queue)
|
|
324
|
+
|
|
325
|
+
def to_h = @to_h ||= {"queue" => queue, "payload" => payload, "run_at" => Integer(run_at)}
|
|
326
|
+
|
|
327
|
+
alias_method :raw, :[]
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
class WorkSet < Robin::WorkSet
|
|
331
|
+
# Yields (process identity, thread id, Work), longest-running first.
|
|
332
|
+
def each(&block)
|
|
333
|
+
return to_enum unless block
|
|
334
|
+
|
|
335
|
+
works = []
|
|
336
|
+
super { |identity, tid, hash| works << [identity, tid, Work.new(identity, tid, hash)] }
|
|
337
|
+
works.sort_by { |*, work| work.run_at }.each { |args| block.call(*args) }
|
|
338
|
+
end
|
|
339
|
+
|
|
340
|
+
# How many jobs are running, as the processes last reported.
|
|
341
|
+
def size
|
|
342
|
+
c = @config
|
|
343
|
+
identities = c.redis { |r| r.call("SMEMBERS", c.key("processes")) }
|
|
344
|
+
c.redis { |r| r.pipelined { |p| identities.each { |i| p.call("HGET", c.process_key(i), "busy") } } }.sum(&:to_i)
|
|
345
|
+
end
|
|
346
|
+
|
|
347
|
+
def find_work(jid) = find { |*, work| work.job.jid == jid }&.last
|
|
348
|
+
alias_method :find_work_by_jid, :find_work
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
Workers = WorkSet
|
|
352
|
+
end
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "sidekiq"
|
|
4
|
+
|
|
5
|
+
module Sidekiq
|
|
6
|
+
# Sidekiq Pro's batches, as Robin::Batch:
|
|
7
|
+
#
|
|
8
|
+
# batch = Sidekiq::Batch.new
|
|
9
|
+
# batch.description = "Import #{import.id}"
|
|
10
|
+
# batch.on(:success, ImportCallbacks, "import_id" => import.id)
|
|
11
|
+
# batch.jobs { rows.each { |row| ImportRowJob.perform_async(row) } }
|
|
12
|
+
#
|
|
13
|
+
# Callbacks get (status, options), as with Sidekiq.
|
|
14
|
+
class Batch < Robin::Batch
|
|
15
|
+
NoSuchBatch = Robin::Batch::NoSuchBatch
|
|
16
|
+
|
|
17
|
+
# The server middleware that tracks batch jobs. Robin's servers always
|
|
18
|
+
# run it; tests add it to Sidekiq::Testing.server_middleware.
|
|
19
|
+
Server = Robin::Batch::ServerMiddleware
|
|
20
|
+
|
|
21
|
+
# As with Sidekiq Pro, the block's jobs are pushed together when it
|
|
22
|
+
# finishes, and none if it raises.
|
|
23
|
+
def jobs = super(atomic: true)
|
|
24
|
+
|
|
25
|
+
# Callback options are meant to be a Hash, but Sidekiq Pro takes any
|
|
26
|
+
# other value with a warning (from Pro 8.0.3) and hands it to the
|
|
27
|
+
# callback as given.
|
|
28
|
+
def on(event, target, options = {})
|
|
29
|
+
return super if Hash === options
|
|
30
|
+
|
|
31
|
+
config.logger.warn { "Sidekiq::Batch#on: callback options should be a Hash, not #{options.inspect}" }
|
|
32
|
+
super(event, target, Verbatim.new(options))
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# A value Robin::Batch#on stores as is (it stringifies a Hash's keys).
|
|
36
|
+
Verbatim = Struct.new(:value) do
|
|
37
|
+
def transform_keys = value
|
|
38
|
+
end
|
|
39
|
+
private_constant :Verbatim
|
|
40
|
+
|
|
41
|
+
# Stops the batch's jobs that haven't run yet (Robin skips them, and
|
|
42
|
+
# running ones see valid_within_batch? turn false).
|
|
43
|
+
def invalidate_all = cancel!
|
|
44
|
+
|
|
45
|
+
# Stops these jobs of the batch the same way (in one round trip,
|
|
46
|
+
# however many). Returns the jids.
|
|
47
|
+
def invalidate_jids(*jids)
|
|
48
|
+
jids = jids.flatten
|
|
49
|
+
Robin::Cancellation.cancel!(jids, ttl: TTL, config: config)
|
|
50
|
+
jids
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def invalidated? = cancelled?
|
|
54
|
+
|
|
55
|
+
def status = Status.new(bid, config: config)
|
|
56
|
+
|
|
57
|
+
def parent = parent_bid && self.class.new(parent_bid, config: config)
|
|
58
|
+
|
|
59
|
+
# A batch's state, as Sidekiq Pro's Batch::Status reports it.
|
|
60
|
+
class Status < Robin::Batch::Status
|
|
61
|
+
# Why a batch's job failed.
|
|
62
|
+
FailureInfo = Struct.new(:jid, :error_class, :error_message, :backtrace)
|
|
63
|
+
|
|
64
|
+
def initialize(bid, config: Robin.config)
|
|
65
|
+
super
|
|
66
|
+
raise NoSuchBatch, "no batch #{bid} (expired or deleted?)" unless exists?
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def created_at
|
|
70
|
+
ms = super
|
|
71
|
+
ms && Time.at(Rational(ms, 1000))
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def invalidated? = cancelled?
|
|
75
|
+
|
|
76
|
+
def failed_jids = failed_jobs.map { |job| job.fetch("jid") }
|
|
77
|
+
|
|
78
|
+
# Robin keeps each failure's error class and message, not its
|
|
79
|
+
# backtrace.
|
|
80
|
+
def failure_info
|
|
81
|
+
failed_jobs.map { |job| FailureInfo.new(job.fetch("jid"), job["error_class"], job["error_message"]) }
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# The failed jobs that are now in the dead set.
|
|
85
|
+
def dead_jids
|
|
86
|
+
dead = Robin::DeadSet.new(config: @config)
|
|
87
|
+
failed_jids.select { |jid| dead.find_job(jid) }
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def delete = delete!
|
|
91
|
+
|
|
92
|
+
# Waits until the batch is complete, checking every +interval+
|
|
93
|
+
# seconds.
|
|
94
|
+
def join(interval = 0.5)
|
|
95
|
+
until complete?
|
|
96
|
+
sleep interval
|
|
97
|
+
reload
|
|
98
|
+
end
|
|
99
|
+
self
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# The batch as a JSON-friendly Hash.
|
|
103
|
+
def data
|
|
104
|
+
{"bid" => bid, "total" => total, "pending" => pending, "failures" => failures,
|
|
105
|
+
"description" => description, "parent_bid" => parent_bid, "complete" => complete?,
|
|
106
|
+
"created_at" => created_at&.to_f, "fail_info" => failed_jobs, "tags" => tags}
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
private
|
|
110
|
+
|
|
111
|
+
def reload = initialize(bid, config: @config)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Batch summaries (Robin::Batch.list), every one of them (a limit of
|
|
115
|
+
# 0 is no limit): those tagged +tag+, if given.
|
|
116
|
+
def self.summaries(tag = nil) = list(limit: 0, tag: tag)
|
|
117
|
+
|
|
118
|
+
# The batches that haven't succeeded yet, newest first.
|
|
119
|
+
class BatchSet
|
|
120
|
+
include Enumerable
|
|
121
|
+
|
|
122
|
+
def each
|
|
123
|
+
return to_enum unless block_given?
|
|
124
|
+
|
|
125
|
+
Batch.summaries.each { |summary| yield Status.new(summary.fetch("bid")) unless summary.fetch("success_at") }
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def size = count
|
|
129
|
+
|
|
130
|
+
# The bids of the batches tagged +tag+ (Sidekiq Pro 8.1's tags),
|
|
131
|
+
# yielded or returned.
|
|
132
|
+
def scan_tags(tag, &block)
|
|
133
|
+
bids = Batch.summaries(tag).map { |summary| summary.fetch("bid") }
|
|
134
|
+
block ? bids.each(&block) : bids
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# The batches that had a job die.
|
|
139
|
+
class DeadSet
|
|
140
|
+
include Enumerable
|
|
141
|
+
|
|
142
|
+
def each
|
|
143
|
+
return to_enum unless block_given?
|
|
144
|
+
|
|
145
|
+
Batch.summaries.each { |summary| yield Status.new(summary.fetch("bid")) if summary.fetch("death_at") }
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def size = count
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
private
|
|
152
|
+
|
|
153
|
+
# A batch is a child only when created inside another's +jobs+ block
|
|
154
|
+
# (not merely inside a job that belongs to a batch).
|
|
155
|
+
def parent_for_new = Batch.current&.bid
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
BatchSet = Batch::BatchSet
|
|
159
|
+
|
|
160
|
+
module Job
|
|
161
|
+
# Batch helpers on running jobs.
|
|
162
|
+
module InstanceMethods
|
|
163
|
+
# The job's batch (adding jobs to it is atomic, as with any
|
|
164
|
+
# Sidekiq::Batch), or nil.
|
|
165
|
+
def batch = bid && Batch.new(bid)
|
|
166
|
+
|
|
167
|
+
# False once the job's batch was invalidated (cancelled): the job
|
|
168
|
+
# should stop.
|
|
169
|
+
def valid_within_batch? = !cancelled?
|
|
170
|
+
end
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# Batch callbacks get Sidekiq's status object.
|
|
175
|
+
Sidekiq.defaults!(Robin.config)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Sidekiq
|
|
4
|
+
# Sidekiq's capsules are Robin's (what config.capsule yields), with
|
|
5
|
+
# Sidekiq's other readers. In a worker thread,
|
|
6
|
+
# Thread.current[:sidekiq_capsule] is the capsule it works for.
|
|
7
|
+
Capsule = Robin::Capsule
|
|
8
|
+
|
|
9
|
+
module CapsuleMethods
|
|
10
|
+
# How its queues are checked: :strict (in order, no weights), :random
|
|
11
|
+
# (every weight 1) or :weighted.
|
|
12
|
+
def mode
|
|
13
|
+
if strict?
|
|
14
|
+
:strict
|
|
15
|
+
elsif weights.values.all? { |weight| weight == 1 }
|
|
16
|
+
:random
|
|
17
|
+
else
|
|
18
|
+
:weighted
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def to_h = {concurrency: concurrency, mode: mode, weights: weights}
|
|
23
|
+
|
|
24
|
+
# Robin's capsules share their config's Redis pool.
|
|
25
|
+
def redis_pool = RedisConnection::Pool.new(config.redis_pool)
|
|
26
|
+
|
|
27
|
+
def redis(&) = redis_pool.with(&)
|
|
28
|
+
|
|
29
|
+
def logger = config.logger
|
|
30
|
+
end
|
|
31
|
+
Robin::Capsule.include(CapsuleMethods)
|
|
32
|
+
|
|
33
|
+
# Sets Thread.current[:sidekiq_capsule] in each worker thread as it
|
|
34
|
+
# starts (see Sidekiq.defaults!).
|
|
35
|
+
CAPSULE_TRACKER = lambda do |event, _payload|
|
|
36
|
+
Thread.current[:sidekiq_capsule] = Robin::Capsule.current if event == "worker.started"
|
|
37
|
+
end
|
|
38
|
+
end
|
data/lib/sidekiq/cli.rb
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "sidekiq"
|
|
4
|
+
require "robin/cli"
|
|
5
|
+
|
|
6
|
+
module Sidekiq
|
|
7
|
+
# The `sidekiq` command: Robin's server, reading config/sidekiq.yml
|
|
8
|
+
# (with Sidekiq's settings) and taking Sidekiq's options.
|
|
9
|
+
#
|
|
10
|
+
# bundle exec sidekiq -C config/sidekiq.yml -e production
|
|
11
|
+
class CLI
|
|
12
|
+
# Settings in config/sidekiq.yml the server itself reads (or that
|
|
13
|
+
# Sidekiq no longer uses); the rest go into the configuration
|
|
14
|
+
# (config[:max_retries] and so on).
|
|
15
|
+
SERVER_SETTINGS = %i[concurrency queues require timeout tag environment processes health_port capsules
|
|
16
|
+
verbose pidfile logfile strict].freeze
|
|
17
|
+
|
|
18
|
+
# Sidekiq's application environment comes from the first of these,
|
|
19
|
+
# else it's development.
|
|
20
|
+
ENVIRONMENT_VARIABLES = %w[APP_ENV RAILS_ENV RACK_ENV].freeze
|
|
21
|
+
|
|
22
|
+
def self.instance = @instance ||= new
|
|
23
|
+
|
|
24
|
+
# Keeps the command line for #run, as Sidekiq's CLI#parse does.
|
|
25
|
+
def parse(argv = ARGV)
|
|
26
|
+
@argv = argv.dup
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Runs a server, as `sidekiq` does. Sidekiq's default concurrency is
|
|
30
|
+
# RAILS_MAX_THREADS when that's set, and its default environment
|
|
31
|
+
# development (so the config file's development section applies).
|
|
32
|
+
# Sidekiq's own keyword options (boot_app:...) don't apply.
|
|
33
|
+
def run(argv = @argv || ARGV, env: ENV, **)
|
|
34
|
+
threads = env["RAILS_MAX_THREADS"]
|
|
35
|
+
Robin.config.concurrency = Integer(threads) if threads
|
|
36
|
+
env["RACK_ENV"] = "development" unless env.values_at(*ENVIRONMENT_VARIABLES).any?
|
|
37
|
+
Robin::CLI.new(argv).run
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Runs a swarm, as Sidekiq Enterprise's `sidekiqswarm` does:
|
|
41
|
+
# SIDEKIQ_COUNT processes (default: one per CPU core), each restarted
|
|
42
|
+
# above SIDEKIQ_MAXMEM_MB megabytes of memory. The app is loaded once,
|
|
43
|
+
# before forking.
|
|
44
|
+
def swarm(argv = ARGV, env: ENV)
|
|
45
|
+
limit = env["SIDEKIQ_MAXMEM_MB"]
|
|
46
|
+
Robin.config.memory_limit_mb = Integer(limit) if limit
|
|
47
|
+
count = env["SIDEKIQ_COUNT"]
|
|
48
|
+
run(["swarm", *(["-n", count] if count), *argv], env:)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Applies the config file's other settings (see SERVER_SETTINGS), and
|
|
52
|
+
# its verbose setting. Null values leave defaults alone. Hashes are
|
|
53
|
+
# environment sections or capsules, except :scheduler:
|
|
54
|
+
# (sidekiq-scheduler's settings). Settings Robin has no name for are
|
|
55
|
+
# kept in Sidekiq.default_configuration when it's +config+'s.
|
|
56
|
+
def self.apply_settings(options, config)
|
|
57
|
+
sidekiq = Sidekiq.default_configuration
|
|
58
|
+
sidekiq = Config.new(config) unless sidekiq.robin.equal?(config)
|
|
59
|
+
options.each do |key, value|
|
|
60
|
+
next if SERVER_SETTINGS.include?(key) || value.nil? || (value.instance_of?(Hash) && !key.equal?(:scheduler))
|
|
61
|
+
|
|
62
|
+
sidekiq[key] = value
|
|
63
|
+
end
|
|
64
|
+
config.logger.level = ::Logger::DEBUG if options[:verbose]
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
Robin::CLI.config_paths.unshift("config/sidekiq.yml", "config/sidekiq.yml.erb")
|
|
70
|
+
Robin::CLI.config_file_hooks << ->(options, config) { Sidekiq::CLI.apply_settings(options, config) }
|