wurk 1.16.0 → 1.17.1
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 +4 -4
- data/README.md +3 -1
- data/app/controllers/concerns/wurk/same_origin_guard.rb +8 -39
- data/app/controllers/concerns/wurk/sse_streaming.rb +3 -38
- data/app/controllers/wurk/api_controller.rb +8 -642
- data/app/controllers/wurk/dashboard_controller.rb +5 -156
- data/app/controllers/wurk/extensions_controller.rb +5 -43
- data/app/controllers/wurk/profiles_controller.rb +4 -117
- data/lib/wurk/api/serializers.rb +2 -2
- data/lib/wurk/batch/server_middleware.rb +3 -3
- data/lib/wurk/component.rb +1 -0
- data/lib/wurk/engine.rb +3 -111
- data/lib/wurk/fetcher/private_list_key.rb +40 -8
- data/lib/wurk/fetcher/reaper.rb +12 -4
- data/lib/wurk/fetcher/unparseable_keys.rb +8 -9
- data/lib/wurk/finished_job_cleanup.rb +155 -0
- data/lib/wurk/job_retry.rb +2 -10
- data/lib/wurk/processor.rb +26 -47
- data/lib/wurk/redis_pool.rb +16 -1
- data/lib/wurk/unique_jobs_compat/private_list_digests.rb +121 -0
- data/lib/wurk/unique_jobs_compat.rb +87 -0
- data/lib/wurk/version.rb +1 -1
- data/lib/wurk/web/asset_mount.rb +119 -0
- data/lib/wurk/web/dashboard/api_actions.rb +657 -0
- data/lib/wurk/web/dashboard/controller.rb +146 -0
- data/lib/wurk/web/dashboard/endpoints.rb +92 -0
- data/lib/wurk/web/dashboard/extension_actions.rb +53 -0
- data/lib/wurk/web/dashboard/profile_actions.rb +130 -0
- data/lib/wurk/web/dashboard/routes.rb +134 -0
- data/lib/wurk/web/dashboard/shell.rb +181 -0
- data/lib/wurk/web/dashboard/stats_tick.rb +49 -0
- data/lib/wurk/web/dashboard/stream_concurrency_guard.rb +97 -0
- data/lib/wurk/web/rack_app.rb +27 -29
- data/lib/wurk/web/same_origin.rb +43 -0
- data/lib/wurk.rb +1 -0
- data/vendor/assets/dashboard/wurk-manifest.json +2 -2
- metadata +17 -4
- data/app/controllers/concerns/wurk/stream_concurrency_guard.rb +0 -94
- /data/{app/controllers/wurk/api → lib/wurk/web/dashboard}/pagination.rb +0 -0
- /data/{app/controllers/wurk/api → lib/wurk/web/dashboard}/serializers.rb +0 -0
|
@@ -7,12 +7,10 @@ module Wurk
|
|
|
7
7
|
# The Reaper's report on a `queue:*|*` key that is not a private list it
|
|
8
8
|
# can read the owner of — a list whose owner tail does not parse, say
|
|
9
9
|
# `queue:<queue>|<host>|not-a-pid|<index>`, left behind by a producer that
|
|
10
|
-
# is not Wurk
|
|
11
|
-
# (
|
|
12
|
-
#
|
|
13
|
-
#
|
|
14
|
-
# (WARN, with the list's length) rather than skipped in silence on every
|
|
15
|
-
# sweep.
|
|
10
|
+
# is not Wurk, or a key that reads as both a Wurk and a Sidekiq Pro list
|
|
11
|
+
# (PrivateListKey.parse_full). Nothing will ever reclaim the jobs of an
|
|
12
|
+
# unparseable list, so it is said once per key per process (WARN, with the
|
|
13
|
+
# list's length) rather than skipped in silence on every sweep.
|
|
16
14
|
#
|
|
17
15
|
# The dedup memory is an in-memory ::Set in THIS process only: one
|
|
18
16
|
# UnparseableKeys per Reaper, one Reaper per Launcher, one Launcher per
|
|
@@ -43,9 +41,10 @@ module Wurk
|
|
|
43
41
|
@reported.clear if @reported.size >= MEMORY
|
|
44
42
|
@reported << key
|
|
45
43
|
@config.logger.warn do
|
|
46
|
-
"reaper: #{key.inspect} looks like a reliable-fetch private list but
|
|
47
|
-
'queue:<queue>|<host>|<pid>|<nonce>|<index
|
|
48
|
-
|
|
44
|
+
"reaper: #{key.inspect} looks like a reliable-fetch private list but does not read as " \
|
|
45
|
+
'exactly one of queue:<queue>|<host>|<pid>|<nonce>|<index>, the pre-nonce ' \
|
|
46
|
+
'queue:<queue>|<host>|<pid>|<index> or Sidekiq Pro\'s queue:sq|<identity>|<queue>; ' \
|
|
47
|
+
"its #{size} job(s) will not be recovered " \
|
|
49
48
|
'automatically. Inspect it and LMOVE them back onto their queue by hand ' \
|
|
50
49
|
'if they belong to a dead process. ' \
|
|
51
50
|
'Reported once per process: every worker that sees the key logs it for itself, ' \
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Wurk
|
|
4
|
+
# What a job still owes Redis after its `perform` returned and the bookkeeping
|
|
5
|
+
# behind it failed: a sidekiq-unique-jobs lock and a batch's success ack.
|
|
6
|
+
#
|
|
7
|
+
# The job is finished and is never run again for this, since a second run of a
|
|
8
|
+
# bank login or an email is the harm. So the owed writes wait here, in this
|
|
9
|
+
# process, and every Processor retries them before its next fetch. That costs
|
|
10
|
+
# no thread and no sleep during the outage, and they land as soon as Redis
|
|
11
|
+
# answers. A process that exits first says which locks it left (#give_up): the
|
|
12
|
+
# gem's reaper or the lock's TTL clears them.
|
|
13
|
+
class FinishedJobCleanup
|
|
14
|
+
# Names the job, with the Redis error as its `cause`.
|
|
15
|
+
class BookkeepingFailed < ::StandardError; end
|
|
16
|
+
|
|
17
|
+
STORE_ERRORS = [RedisClient::Error, ConnectionPool::Error, ConnectionPool::TimeoutError].freeze
|
|
18
|
+
# Past this many owed jobs the oldest is reported and dropped.
|
|
19
|
+
MEMORY = 10_000
|
|
20
|
+
RETRY_EVERY = 1.0
|
|
21
|
+
RUN_SUFFIX = ':RUN'
|
|
22
|
+
# This lock type is meant to outlive the job, until its TTL.
|
|
23
|
+
KEEPS_LOCK = 'until_expired'
|
|
24
|
+
|
|
25
|
+
Entry = Struct.new(:job, :pool, :config)
|
|
26
|
+
|
|
27
|
+
@entries = []
|
|
28
|
+
@lock = ::Mutex.new
|
|
29
|
+
@draining = ::Mutex.new
|
|
30
|
+
@next_try = 0.0
|
|
31
|
+
|
|
32
|
+
class << self
|
|
33
|
+
def store_error?(error) = STORE_ERRORS.any? { |klass| error.is_a?(klass) }
|
|
34
|
+
|
|
35
|
+
# Reports the failure, tries the owed writes once, keeps what did not land.
|
|
36
|
+
def settle(job, error, pool:, config:)
|
|
37
|
+
report(job, error, config)
|
|
38
|
+
entry = Entry.new(job, pool, config)
|
|
39
|
+
return unless owes_anything?(job)
|
|
40
|
+
return if attempt?(entry)
|
|
41
|
+
|
|
42
|
+
remember(entry)
|
|
43
|
+
config.logger.error { "#{describe(job)}: waiting for Redis to finish its cleanup" }
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Hot path: one empty check per fetch while nothing is owed.
|
|
47
|
+
def drain
|
|
48
|
+
return if @entries.empty? || monotonic < @next_try
|
|
49
|
+
return unless @draining.try_lock
|
|
50
|
+
|
|
51
|
+
begin
|
|
52
|
+
drain_entries
|
|
53
|
+
ensure
|
|
54
|
+
@draining.unlock
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# The process is stopping: one last try, then say what is left.
|
|
59
|
+
def give_up
|
|
60
|
+
return if @entries.empty?
|
|
61
|
+
|
|
62
|
+
@next_try = 0.0
|
|
63
|
+
drain
|
|
64
|
+
@lock.synchronize { @entries.slice!(0..) }.each { |entry| warn_left(entry) }
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def pending = @lock.synchronize { @entries.size }
|
|
68
|
+
|
|
69
|
+
def reset!
|
|
70
|
+
@lock.synchronize { @entries.clear }
|
|
71
|
+
@next_try = 0.0
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
private
|
|
75
|
+
|
|
76
|
+
def drain_entries
|
|
77
|
+
while (entry = @lock.synchronize { @entries.first })
|
|
78
|
+
unless attempt?(entry)
|
|
79
|
+
@next_try = monotonic + RETRY_EVERY
|
|
80
|
+
return
|
|
81
|
+
end
|
|
82
|
+
@lock.synchronize { @entries.delete_at(@entries.index { |held| held.equal?(entry) } || @entries.size) }
|
|
83
|
+
entry.config.logger.info { "#{describe(entry.job)}: cleanup finished after the Redis failure" }
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# true when nothing more can be done for this entry. Idempotent, so an
|
|
88
|
+
# entry half done by an earlier try is safe to run again.
|
|
89
|
+
def attempt?(entry)
|
|
90
|
+
release_unique_locks(entry.job)
|
|
91
|
+
ack_batch(entry.job, entry.pool)
|
|
92
|
+
true
|
|
93
|
+
rescue StandardError => e
|
|
94
|
+
return false if store_error?(e)
|
|
95
|
+
|
|
96
|
+
entry.config.handle_exception(e, { context: "#{describe(entry.job)}: cleanup failed", job: entry.job })
|
|
97
|
+
true
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Locksmith#unlock only drops a lock this jid holds. Both digests: an
|
|
101
|
+
# until_and_while_executing job takes its base lock back when an error
|
|
102
|
+
# crosses it, on top of the `:RUN` lock it may still hold.
|
|
103
|
+
def release_unique_locks(job)
|
|
104
|
+
digests(job).each { |digest| ::SidekiqUniqueJobs::Locksmith.new(job.merge('lock_digest' => digest)).unlock }
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def digests(job)
|
|
108
|
+
digest = job['lock_digest']
|
|
109
|
+
return [] unless digest && job['lock'].to_s != KEEPS_LOCK && defined?(::SidekiqUniqueJobs::Locksmith)
|
|
110
|
+
|
|
111
|
+
base = digest.delete_suffix(RUN_SUFFIX)
|
|
112
|
+
[base, "#{base}#{RUN_SUFFIX}"]
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# A replayed ack removes nothing, and the callback markers absorb a second
|
|
116
|
+
# fire (Batch::ServerMiddleware#ack_success).
|
|
117
|
+
def ack_batch(job, pool)
|
|
118
|
+
bid = job['bid']
|
|
119
|
+
return unless bid
|
|
120
|
+
|
|
121
|
+
_removed, pending, live, kids = pool.with { |conn| Batch.ack_success(conn, bid, job['jid']) }
|
|
122
|
+
Batch::Callbacks.maybe_fire(bid, pending: pending, live: live, kids: kids)
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def owes_anything?(job) = job['bid'] || digests(job).any?
|
|
126
|
+
|
|
127
|
+
def remember(entry)
|
|
128
|
+
dropped = @lock.synchronize do
|
|
129
|
+
@entries << entry
|
|
130
|
+
@entries.shift if @entries.size > MEMORY
|
|
131
|
+
end
|
|
132
|
+
warn_left(dropped) if dropped
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def warn_left(entry)
|
|
136
|
+
entry.config.logger.error do
|
|
137
|
+
"#{describe(entry.job)}: cleanup never reached Redis. Locks left: #{digests(entry.job).join(', ')}; " \
|
|
138
|
+
'the sidekiq-unique-jobs reaper or the lock TTL clears them. Batch: ' \
|
|
139
|
+
"#{entry.job['bid'] || 'none'}"
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def report(job, error, config)
|
|
144
|
+
raise BookkeepingFailed, "#{describe(job)}: Redis failed after perform returned, not running it again " \
|
|
145
|
+
"(#{error.class}: #{error.message}). Locks: #{digests(job).join(', ')}", cause: error
|
|
146
|
+
rescue BookkeepingFailed => e
|
|
147
|
+
config.handle_exception(e, { context: 'Bookkeeping failed after perform', job: job })
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
def describe(job) = "#{job['class']} JID-#{job['jid']}"
|
|
151
|
+
|
|
152
|
+
def monotonic = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
end
|
data/lib/wurk/job_retry.rb
CHANGED
|
@@ -38,14 +38,6 @@ module Wurk
|
|
|
38
38
|
# short-circuits processing (e.g. interrupt-handler re-pushed the job).
|
|
39
39
|
class Skip < Handled; end
|
|
40
40
|
|
|
41
|
-
# Raised by Processor when Redis stopped answering after `perform` had
|
|
42
|
-
# returned: the job did its work and only the bookkeeping behind it (a
|
|
43
|
-
# batch ack, a status row) failed. Counted as a failure it would be retried
|
|
44
|
-
# with a stale count or, on a last attempt, killed, and a batch would mark
|
|
45
|
-
# itself dead over a job that succeeded. Both guards let it through to the
|
|
46
|
-
# Processor, which puts the job back to run again. `cause` is the Redis error.
|
|
47
|
-
class StoreUnavailableAfterPerform < ::StandardError; end
|
|
48
|
-
|
|
49
41
|
def initialize(capsule)
|
|
50
42
|
@capsule = capsule
|
|
51
43
|
@config = capsule
|
|
@@ -58,7 +50,7 @@ module Wurk
|
|
|
58
50
|
# bubbles up so the swarm can drain.
|
|
59
51
|
def global(jobstr, queue)
|
|
60
52
|
yield
|
|
61
|
-
rescue Handled, Wurk::Shutdown
|
|
53
|
+
rescue Handled, Wurk::Shutdown
|
|
62
54
|
raise
|
|
63
55
|
rescue Exception => e # rubocop:disable Lint/RescueException
|
|
64
56
|
raise Wurk::Shutdown if exception_caused_by_shutdown?(e)
|
|
@@ -79,7 +71,7 @@ module Wurk
|
|
|
79
71
|
# circuit `global`'s rescue.
|
|
80
72
|
def local(jobinst, jobstr, queue)
|
|
81
73
|
yield
|
|
82
|
-
rescue Handled, Wurk::Shutdown
|
|
74
|
+
rescue Handled, Wurk::Shutdown
|
|
83
75
|
raise
|
|
84
76
|
rescue Exception => e # rubocop:disable Lint/RescueException
|
|
85
77
|
raise Wurk::Shutdown if exception_caused_by_shutdown?(e)
|
data/lib/wurk/processor.rb
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
require_relative 'component'
|
|
4
4
|
require_relative 'context'
|
|
5
5
|
require_relative 'dead_set'
|
|
6
|
+
require_relative 'finished_job_cleanup'
|
|
6
7
|
require_relative 'job_logger'
|
|
7
8
|
require_relative 'job_retry'
|
|
8
9
|
require_relative 'profiler'
|
|
@@ -41,40 +42,9 @@ module Wurk
|
|
|
41
42
|
# escaping the retry layer comes from the payload itself (a `retry_count`
|
|
42
43
|
# that is not a number, args that cannot be re-serialized into a retry) and
|
|
43
44
|
# will fail the same way every time.
|
|
44
|
-
TRANSIENT_FAILURES = [RedisClient::Error, ConnectionPool::Error, ConnectionPool::TimeoutError
|
|
45
|
-
JobRetry::StoreUnavailableAfterPerform].freeze
|
|
45
|
+
TRANSIENT_FAILURES = [RedisClient::Error, ConnectionPool::Error, ConnectionPool::TimeoutError].freeze
|
|
46
46
|
private_constant :TRANSIENT_FAILURES
|
|
47
47
|
|
|
48
|
-
# Redis not answering, or answering that it is not serving yet. Narrower than
|
|
49
|
-
# TRANSIENT_FAILURES on purpose: a refusal on the merits (WRONGTYPE, OOM)
|
|
50
|
-
# after `perform` would refuse the re-run's bookkeeping too, so requeueing it
|
|
51
|
-
# would re-run `perform` every REQUEUE_PAUSE for good.
|
|
52
|
-
STORE_UNAVAILABLE = [RedisClient::ConnectionError, ConnectionPool::TimeoutError].freeze
|
|
53
|
-
private_constant :STORE_UNAVAILABLE
|
|
54
|
-
STORE_NOT_SERVING = /\A(?:LOADING|BUSY|TRYAGAIN|CLUSTERDOWN)\b/
|
|
55
|
-
private_constant :STORE_NOT_SERVING
|
|
56
|
-
|
|
57
|
-
# How many times one process puts a job back for an outage after `perform`
|
|
58
|
-
# before the error goes to the retry policy after all. Unbounded, a write
|
|
59
|
-
# that keeps failing while the requeue lands (a second Redis a middleware
|
|
60
|
-
# talks to, a pool that stays exhausted) re-runs `perform` every
|
|
61
|
-
# REQUEUE_PAUSE for good. Process-local: the payload carries no counter.
|
|
62
|
-
STORE_REQUEUE_LIMIT = 3
|
|
63
|
-
STORE_REQUEUE_JIDS = 10_000
|
|
64
|
-
private_constant :STORE_REQUEUE_LIMIT, :STORE_REQUEUE_JIDS
|
|
65
|
-
@store_requeues = {}
|
|
66
|
-
@store_requeues_lock = ::Mutex.new
|
|
67
|
-
|
|
68
|
-
# True while `jid` has requeues left; counts this one.
|
|
69
|
-
def self.store_requeue?(jid)
|
|
70
|
-
@store_requeues_lock.synchronize do
|
|
71
|
-
count = @store_requeues.delete(jid).to_i + 1
|
|
72
|
-
@store_requeues.shift while @store_requeues.size >= STORE_REQUEUE_JIDS
|
|
73
|
-
@store_requeues[jid] = count
|
|
74
|
-
count <= STORE_REQUEUE_LIMIT
|
|
75
|
-
end
|
|
76
|
-
end
|
|
77
|
-
|
|
78
48
|
# Pause after putting a job back on an internal failure. The job goes to the
|
|
79
49
|
# tail, which is the next fetch, so without one a failure that persists
|
|
80
50
|
# re-runs `perform` as fast as the thread can loop.
|
|
@@ -143,6 +113,7 @@ module Wurk
|
|
|
143
113
|
# Single iteration: fetch one UoW, process it. Public so tests can drive
|
|
144
114
|
# the loop step-by-step without spawning a thread.
|
|
145
115
|
def process_one
|
|
116
|
+
FinishedJobCleanup.drain
|
|
146
117
|
@job = fetch
|
|
147
118
|
process(@job) if @job
|
|
148
119
|
@job = nil
|
|
@@ -276,6 +247,7 @@ module Wurk
|
|
|
276
247
|
# `respond_to?` because a config[:fetch_class] fetcher need not defer, and
|
|
277
248
|
# the capsule has no fetcher at all if the launcher died before prepare!.
|
|
278
249
|
def flush_acks
|
|
250
|
+
FinishedJobCleanup.give_up
|
|
279
251
|
fetcher = @capsule.fetcher
|
|
280
252
|
fetcher.flush_pending_acks if fetcher.respond_to?(:flush_pending_acks)
|
|
281
253
|
rescue StandardError => e
|
|
@@ -414,11 +386,7 @@ module Wurk
|
|
|
414
386
|
# slot and simply ACKs — the counter then ages out on its 72h TTL.
|
|
415
387
|
uow.jid = job_hash['jid'] if uow.respond_to?(:jid=)
|
|
416
388
|
|
|
417
|
-
dispatch(job_hash, queue, jobstr)
|
|
418
|
-
Thread.handle_interrupt(ALLOW_SHUTDOWN_INTERRUPTS) do
|
|
419
|
-
execute_job(instance, job_hash, queue)
|
|
420
|
-
end
|
|
421
|
-
end
|
|
389
|
+
dispatch(job_hash, queue, jobstr) { |instance| execute_job(instance, job_hash, queue) }
|
|
422
390
|
end
|
|
423
391
|
|
|
424
392
|
# Reported, never raised: this runs inside #process's ensure on the shutdown
|
|
@@ -483,23 +451,34 @@ module Wurk
|
|
|
483
451
|
instance
|
|
484
452
|
end
|
|
485
453
|
|
|
454
|
+
# Once `perform` has returned the job is done, whatever its unwind runs
|
|
455
|
+
# into. A Redis failure or a hard shutdown there must not run it again, at
|
|
456
|
+
# any retry setting: the job returns normally, so it is ACKed, and what it
|
|
457
|
+
# still owes Redis goes to FinishedJobCleanup. The rescues sit outside the
|
|
458
|
+
# interruptible scope, so a Shutdown cannot land between them and the ACK.
|
|
486
459
|
def execute_job(instance, job_hash, queue)
|
|
487
460
|
performed = false
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
461
|
+
Thread.handle_interrupt(ALLOW_SHUTDOWN_INTERRUPTS) do
|
|
462
|
+
@capsule.server_middleware.invoke(instance, job_hash, queue) do
|
|
463
|
+
RedisPool.job_performing!
|
|
464
|
+
result = instance.perform(*job_hash['args'])
|
|
465
|
+
performed = true
|
|
466
|
+
result
|
|
467
|
+
end
|
|
492
468
|
end
|
|
469
|
+
rescue Wurk::Shutdown => e
|
|
470
|
+
raise unless performed
|
|
471
|
+
|
|
472
|
+
settle_finished_job(job_hash, e)
|
|
493
473
|
rescue StandardError => e
|
|
494
|
-
raise unless performed &&
|
|
474
|
+
raise unless performed && FinishedJobCleanup.store_error?(e)
|
|
495
475
|
|
|
496
|
-
|
|
476
|
+
settle_finished_job(job_hash, e)
|
|
497
477
|
end
|
|
498
478
|
|
|
499
|
-
def
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
error.is_a?(RedisClient::CommandError) && STORE_NOT_SERVING.match?(error.message.to_s)
|
|
479
|
+
def settle_finished_job(job_hash, error)
|
|
480
|
+
FinishedJobCleanup.settle(job_hash, error, pool: @capsule.redis_pool, config: @capsule.config)
|
|
481
|
+
nil
|
|
503
482
|
end
|
|
504
483
|
|
|
505
484
|
# Bookkeeping wrapper. Publishes the in-flight job to WORK_STATE so the
|
data/lib/wurk/redis_pool.rb
CHANGED
|
@@ -114,9 +114,19 @@ module Wurk
|
|
|
114
114
|
# this — Sidekiq reaps on its 10s heartbeat.
|
|
115
115
|
REAP_MAX_INTERVAL = 10.0
|
|
116
116
|
|
|
117
|
+
# Thread variable the Processor bumps as it enters `perform`. A middleware
|
|
118
|
+
# can run `perform` inside a checkout (sidekiq-unique-jobs does), and a
|
|
119
|
+
# replay of that block would run the job again, so it is never replayed.
|
|
120
|
+
PERFORM_COUNT = :wurk_perform_count
|
|
121
|
+
|
|
117
122
|
attr_reader :size, :url, :name, :pool_timeout, :client_config, :redis_idle_timeout
|
|
118
123
|
|
|
119
124
|
class << self
|
|
125
|
+
def job_performing!
|
|
126
|
+
thread = ::Thread.current
|
|
127
|
+
thread.thread_variable_set(PERFORM_COUNT, thread.thread_variable_get(PERFORM_COUNT).to_i + 1)
|
|
128
|
+
end
|
|
129
|
+
|
|
120
130
|
# A redis-client middleware every pool built from now on carries, after
|
|
121
131
|
# any the host configured. Set only by the boot of a command that must not
|
|
122
132
|
# write Redis (Preflight::RedisGuard); nil everywhere else.
|
|
@@ -342,13 +352,16 @@ module Wurk
|
|
|
342
352
|
# Runs the block on the checked-out `conn`, retrying transient RedisClient
|
|
343
353
|
# errors in place: the same slot is reused across retries (redis-client
|
|
344
354
|
# redials a closed socket lazily), so a busy fetcher can't leak checkouts.
|
|
345
|
-
def run(conn, idempotent)
|
|
355
|
+
def run(conn, idempotent) # rubocop:disable Metrics/AbcSize
|
|
346
356
|
attempts = 0
|
|
347
357
|
odometer = conn.round_trips
|
|
358
|
+
performs = performs_on_this_thread
|
|
348
359
|
begin
|
|
349
360
|
attempts += 1
|
|
350
361
|
yield conn
|
|
351
362
|
rescue RedisClient::Error => e
|
|
363
|
+
raise if performs_on_this_thread != performs
|
|
364
|
+
|
|
352
365
|
plan = retry_plan(e, attempts, idempotent, conn.round_trips != odometer)
|
|
353
366
|
raise if plan == :propagate
|
|
354
367
|
|
|
@@ -363,6 +376,8 @@ module Wurk
|
|
|
363
376
|
end
|
|
364
377
|
end
|
|
365
378
|
|
|
379
|
+
def performs_on_this_thread = ::Thread.current.thread_variable_get(PERFORM_COUNT)
|
|
380
|
+
|
|
366
381
|
# Pure classification of a RedisClient error against the attempt count, the
|
|
367
382
|
# caller's apply-safety claim, and whether this attempt already completed a
|
|
368
383
|
# round trip (`dirty`):
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
require_relative '../keys'
|
|
5
|
+
|
|
6
|
+
module Wurk
|
|
7
|
+
module UniqueJobsCompat
|
|
8
|
+
# One read of every private list: the lock digests of the jobs in them.
|
|
9
|
+
#
|
|
10
|
+
# Any Redis error propagates, so a caller deciding what to delete deletes
|
|
11
|
+
# nothing. A list longer than a page is read in overlapping pages, because
|
|
12
|
+
# an ACK removing an entry shifts the rest toward the head: the overlap
|
|
13
|
+
# proves no entry slid past the read position, and ListMoved says it did.
|
|
14
|
+
class PrivateListDigests
|
|
15
|
+
class ListMoved < ::StandardError; end
|
|
16
|
+
|
|
17
|
+
Result = Struct.new(:digests, :unreadable)
|
|
18
|
+
|
|
19
|
+
MATCH = "#{Keys::QUEUE_PREFIX}*|*".freeze
|
|
20
|
+
SCAN_COUNT = 1000
|
|
21
|
+
PAGE = 1000
|
|
22
|
+
OVERLAP = 100
|
|
23
|
+
PIPELINE = 100
|
|
24
|
+
RUN_SUFFIX = ':RUN'
|
|
25
|
+
DIGEST_FIELDS = %w[lock_digest unique_digest].freeze
|
|
26
|
+
|
|
27
|
+
def initialize(page: PAGE, overlap: OVERLAP)
|
|
28
|
+
@page = page
|
|
29
|
+
@overlap = overlap
|
|
30
|
+
@result = Result.new(::Set.new, 0)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def call
|
|
34
|
+
private_lists.each_slice(PIPELINE) do |lists|
|
|
35
|
+
first_pages = Wurk.redis do |conn|
|
|
36
|
+
conn.pipelined { |pipe| lists.each { |list| pipe.call('LRANGE', list, 0, @page - 1) } }
|
|
37
|
+
end
|
|
38
|
+
lists.zip(first_pages) { |list, page| read_list(list, page) }
|
|
39
|
+
end
|
|
40
|
+
@result
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
|
|
45
|
+
def read_list(list, first_page)
|
|
46
|
+
collect(first_page)
|
|
47
|
+
previous = first_page
|
|
48
|
+
start = @page - @overlap
|
|
49
|
+
while previous.size == @page
|
|
50
|
+
page = read_page(list, start)
|
|
51
|
+
unless page.first(@overlap).intersect?(previous.last(@overlap))
|
|
52
|
+
raise ListMoved,
|
|
53
|
+
"#{list} moved past the read position"
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
collect(page)
|
|
57
|
+
previous = page
|
|
58
|
+
start += @page - @overlap
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def read_page(list, start)
|
|
63
|
+
Wurk.redis { |conn| conn.call('LRANGE', list, start, start + @page - 1) }
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def collect(payloads)
|
|
67
|
+
payloads.each { |payload| collect_payload(payload) }
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def collect_payload(payload)
|
|
71
|
+
job = parse(payload)
|
|
72
|
+
return collect_unreadable(payload) unless job.is_a?(::Hash)
|
|
73
|
+
|
|
74
|
+
DIGEST_FIELDS.each { |field| add(job[field]) if job[field].is_a?(::String) }
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# No way to tell which lock it holds, so every quoted string in it counts.
|
|
78
|
+
def collect_unreadable(payload)
|
|
79
|
+
@result.unreadable += 1
|
|
80
|
+
payload.b.split('"').each { |token| add(token) }
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def add(digest)
|
|
84
|
+
@result.digests << digest.delete_suffix(RUN_SUFFIX)
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def parse(payload)
|
|
88
|
+
Wurk.load_json(payload)
|
|
89
|
+
rescue ::JSON::ParserError, ::EncodingError
|
|
90
|
+
nil
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def private_lists
|
|
94
|
+
public_queues = Wurk.redis { |conn| conn.call('SMEMBERS', Keys::QUEUES_SET) }.to_set
|
|
95
|
+
scan_lists.select { |key| private_list?(key, public_queues) }
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Parsed by each reading on its own: a key that reads as both is one the
|
|
99
|
+
# fetcher refuses to reclaim, and the job in it is real.
|
|
100
|
+
def private_list?(key, public_queues)
|
|
101
|
+
return false unless key.valid_encoding?
|
|
102
|
+
return false if public_queues.include?(key.delete_prefix(Keys::QUEUE_PREFIX))
|
|
103
|
+
|
|
104
|
+
!(Fetcher::PrivateListKey.parse_pro(key) || Fetcher::PrivateListKey.parse_wurk(key)).nil?
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def scan_lists
|
|
108
|
+
cursor = '0'
|
|
109
|
+
keys = []
|
|
110
|
+
loop do
|
|
111
|
+
cursor, batch = Wurk.redis do |conn|
|
|
112
|
+
conn.call('SCAN', cursor, 'MATCH', MATCH, 'COUNT', SCAN_COUNT, 'TYPE', 'list')
|
|
113
|
+
end
|
|
114
|
+
keys.concat(batch)
|
|
115
|
+
break if cursor == '0'
|
|
116
|
+
end
|
|
117
|
+
keys.uniq
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
end
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative 'keys'
|
|
4
|
+
require_relative 'unique_jobs_compat/private_list_digests'
|
|
5
|
+
|
|
6
|
+
module Wurk
|
|
7
|
+
# Two corrections to sidekiq-unique-jobs, applied when a server boots with the
|
|
8
|
+
# gem loaded. The gem cannot see what only the reliable fetcher knows.
|
|
9
|
+
module UniqueJobsCompat
|
|
10
|
+
RUN_SUFFIX = ':RUN'
|
|
11
|
+
OOM = /\AOOM\b|\bout of memory\b/i
|
|
12
|
+
VERSION_KEY = 'uniquejobs:live'
|
|
13
|
+
|
|
14
|
+
# RubyReaper reads public queues, the retry and schedule sets and live
|
|
15
|
+
# workers. A job in a dead worker's private list is in none of them until it
|
|
16
|
+
# is reclaimed, so its lock read as orphaned and was deleted, and a duplicate
|
|
17
|
+
# ran beside the recovery.
|
|
18
|
+
#
|
|
19
|
+
# The lists are read once before the gem classifies its digests and once
|
|
20
|
+
# after, so a run costs O(digests + jobs). Both reads are needed: a job
|
|
21
|
+
# fetched after the gem looked at its public queue is only in the second, and
|
|
22
|
+
# one reclaimed back to its queue after that look is only in the first. A
|
|
23
|
+
# failed read raises here, ahead of the gem's delete.
|
|
24
|
+
module PrivateListsAreLive
|
|
25
|
+
def orphans
|
|
26
|
+
before = PrivateListDigests.new.call
|
|
27
|
+
candidates = super
|
|
28
|
+
after = PrivateListDigests.new.call
|
|
29
|
+
UniqueJobsCompat.report_unreadable([before.unreadable, after.unreadable].max)
|
|
30
|
+
candidates.reject do |digest|
|
|
31
|
+
base = digest.delete_suffix(RUN_SUFFIX)
|
|
32
|
+
before.digests.include?(base) || after.digests.include?(base)
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# The gem writes its version at boot, for upgrades it has not built yet, and
|
|
38
|
+
# a refusal there stops the worker. At `maxmemory` that is a crash loop with
|
|
39
|
+
# nothing draining the queues. Only this write is forgiven: a lock write
|
|
40
|
+
# refused by OOM still raises.
|
|
41
|
+
module VersionWriteIsOptional
|
|
42
|
+
def call
|
|
43
|
+
super
|
|
44
|
+
rescue StandardError => e # the gem wraps a script's error in its own class
|
|
45
|
+
raise unless OOM.match?(e.message.to_s)
|
|
46
|
+
|
|
47
|
+
Wurk.logger.error do
|
|
48
|
+
"sidekiq-unique-jobs: Redis is at maxmemory, so #{VERSION_KEY} was not set to " \
|
|
49
|
+
"#{UniqueJobsCompat.gem_version}. Booting anyway; locks are unaffected. (#{e.message})"
|
|
50
|
+
end
|
|
51
|
+
false
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
class << self
|
|
56
|
+
def install
|
|
57
|
+
return unless defined?(::SidekiqUniqueJobs::Orphans::RubyReaper) && defined?(::SidekiqUniqueJobs::UpdateVersion)
|
|
58
|
+
|
|
59
|
+
guard_reaper(::SidekiqUniqueJobs::Orphans::RubyReaper)
|
|
60
|
+
::SidekiqUniqueJobs::UpdateVersion.singleton_class.prepend(VersionWriteIsOptional)
|
|
61
|
+
true
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def guard_reaper(reaper)
|
|
65
|
+
return reaper.prepend(PrivateListsAreLive) if reaper.method_defined?(:orphans)
|
|
66
|
+
|
|
67
|
+
Wurk.logger.error do
|
|
68
|
+
"sidekiq-unique-jobs #{gem_version} has no RubyReaper#orphans, so its reaper can delete the lock of a " \
|
|
69
|
+
'job in a private list. Set `config.reaper = :none` or use a supported version.'
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def report_unreadable(count)
|
|
74
|
+
return unless count.positive?
|
|
75
|
+
|
|
76
|
+
Wurk.logger.warn do
|
|
77
|
+
"sidekiq-unique-jobs reaper: #{count} unreadable payload(s) in private lists; " \
|
|
78
|
+
'every lock they name was kept.'
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def gem_version
|
|
83
|
+
defined?(::SidekiqUniqueJobs::VERSION) ? ::SidekiqUniqueJobs::VERSION : 'unknown'
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
data/lib/wurk/version.rb
CHANGED