wurk 1.18.0 → 1.20.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0e76dc31e4cdd0cb170fb6d3882e01ce20596a4092938d87401eef04f26f30a0
4
- data.tar.gz: 480f9e50d3a4360f23825b0cb6479e7ac4c3dda891a52c253731adf32ebe1ce6
3
+ metadata.gz: 68607081f66bca6632668d2f456e66dfe87906ec13fa0582fac43868c5c11793
4
+ data.tar.gz: cb235411d7e504bccfdc83766540a6d5b6e9df3b2e41447efbc8928565be35d4
5
5
  SHA512:
6
- metadata.gz: f281b9e976f9c75961588a310f8544eed21e47bb835b3f31fec6155cd6dc4a670d04a15acc8bfbbaeaa0e55428c46aaf9375475c02891137ac090b54b27a5577
7
- data.tar.gz: 200d2fa2e32212ba98e8f4c190f08791edda35a3308fe597830e8eea2c8863d3a60f29508799897d73e758891d1b6f20b5b096bd8dc9a8ac3b84c0ff71c72dc5
6
+ metadata.gz: 386b8055b1fcd9de03d0451a0393df9af87f4746f6846c869ffae59fa6307eab8d3120bca67e2b9e85b98d68202fe2e8bf50833d086c0eaade01ce0090edf3d1
7
+ data.tar.gz: 927b92fb1a5fbbc69a4eea1945aeb659adc10eb9b1755678f6d214d356ac8b8a9f40893d6163482bbe50f7912dbbe46b0fe805e9781e59ad978005ba90ce653a
data/README.md CHANGED
@@ -308,7 +308,7 @@ Wurk is MIT and stays that way. If what you need is a commercial support contrac
308
308
 
309
309
  `bundle install && restart`. The worker command stays as it was: Wurk ships `sidekiq` and `sidekiqswarm` executables, so `bundle exec sidekiq -C config/sidekiq.yml` in a Procfile or manifest keeps working. Wurk reads and writes the same Redis schema, so there is no data migration: Wurk picks up the queues, schedules, retries, batches and periodic loops Sidekiq left behind. Running Sidekiq and Wurk workers against one Redis *at the same time* is tested for stock Sidekiq 8 only, which may roll from one to the other under the conditions the guide lists; for a Sidekiq 7.x, Pro or Enterprise app a live production move is a **drain cutover** (stop Sidekiq's workers, confirm nothing is in flight, start Wurk), with a matching rollback. The [production cutover](https://github.com/developerz-ai/wurk/blob/main/docs/migrate-from-sidekiq.md#9-production-cutover) section has every step and command. The upstream suites of sidekiq-cron, sidekiq-unique-jobs, sidekiq-failures and sentry-sidekiq run against Wurk in the [`ecosystem` CI job](https://github.com/developerz-ai/wurk/blob/main/.github/workflows/ecosystem.yml) (see [`test/ecosystem/`](https://github.com/developerz-ai/wurk/tree/main/test/ecosystem)). sidekiq-scheduler, sidekiq-status and sidekiq-throttled are target additions tracked in [docs/idea/14-ecosystem-compat.md](https://github.com/developerz-ai/wurk/blob/main/docs/idea/14-ecosystem-compat.md).
310
310
 
311
- **Keeping a `sidekiq-*` add-on gem?** Those gems declare `add_dependency "sidekiq"`, which would reinstall real Sidekiq next to Wurk. Satisfy it with Wurk's git-only [`sidekiq` shim gem](https://github.com/developerz-ai/wurk/tree/main/ecosystem/sidekiq-shim) instead, pinned to the tag of the Wurk release you run: `gem "sidekiq", github: "developerz-ai/wurk", tag: "v1.18.0", glob: "ecosystem/sidekiq-shim/*.gemspec"`. Only sidekiq-cron, sidekiq-unique-jobs, sidekiq-failures and sentry-sidekiq are exercised that way, by the `ecosystem` workflow; treat the others as untested.
311
+ **Keeping a `sidekiq-*` add-on gem?** Those gems declare `add_dependency "sidekiq"`, which would reinstall real Sidekiq next to Wurk. Satisfy it with Wurk's git-only [`sidekiq` shim gem](https://github.com/developerz-ai/wurk/tree/main/ecosystem/sidekiq-shim) instead, pinned to the tag of the Wurk release you run: `gem "sidekiq", github: "developerz-ai/wurk", tag: "v1.20.0", glob: "ecosystem/sidekiq-shim/*.gemspec"`. Only sidekiq-cron, sidekiq-unique-jobs, sidekiq-failures and sentry-sidekiq are exercised that way, by the `ecosystem` workflow; treat the others as untested.
312
312
 
313
313
  Full walkthrough — config side-by-side, the Redis key/`sidekiq_options` mapping, known incompatibilities, moving sidekiq-cron schedules over (`rake wurk:import:cron`), and the production cutover and rollback playbook: **[docs/migrate-from-sidekiq.md](https://github.com/developerz-ai/wurk/blob/main/docs/migrate-from-sidekiq.md)**. On the night, keep the **[incident runbook](https://github.com/developerz-ai/wurk/blob/main/docs/runbook.md)** open.
314
314
 
data/lib/wurk/dead_set.rb CHANGED
@@ -1,11 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative 'job_set'
4
+ require_relative 'metrics/deaths'
4
5
 
5
6
  module Wurk
6
7
  # Capped ZSET of jobs that exhausted retries (the "morgue"). Bounded by
7
8
  # `dead_max_jobs` and `dead_timeout_in_seconds` config knobs — every
8
- # `kill` trims both axes. Death handlers fire by default — including on
9
+ # `kill` trims both axes, and counts the job into Metrics::Deaths, which
10
+ # the trim never touches. Death handlers fire by default — including on
9
11
  # API/UI kills, matching Sidekiq — unless `notify_failure: false`.
10
12
  #
11
13
  # Spec: docs/target/sidekiq-free.md §19.5, §17.2, §31.8.
@@ -52,8 +54,7 @@ module Wurk
52
54
  # malformed path has no parseable job to hand a handler. `max_jobs:` /
53
55
  # `timeout:` propagate to #trim (see there for the override rationale).
54
56
  def kill_raw(payload, max_jobs: nil, timeout: nil) # rubocop:disable Naming/PredicateMethod
55
- now = ::Process.clock_gettime(::Process::CLOCK_REALTIME)
56
- Wurk.redis { |conn| conn.call('ZADD', @name, now.to_s, payload) }
57
+ add(payload)
57
58
  trim(max_jobs: max_jobs, timeout: timeout)
58
59
  true
59
60
  end
@@ -65,8 +66,7 @@ module Wurk
65
66
  # receive `(job, ex)`. `max_jobs:` / `timeout:` propagate to the auto-trim;
66
67
  # see `#trim` for the rationale.
67
68
  def kill(message, opts = {})
68
- now = ::Process.clock_gettime(::Process::CLOCK_REALTIME)
69
- Wurk.redis { |conn| conn.call('ZADD', @name, now.to_s, message) }
69
+ add(message)
70
70
  trim(max_jobs: opts[:max_jobs], timeout: opts[:timeout]) if opts.fetch(:trim, true)
71
71
  fire_death_handlers(message, opts[:ex] || api_kill_error) if opts.fetch(:notify_failure, true)
72
72
  true
@@ -74,6 +74,14 @@ module Wurk
74
74
 
75
75
  private
76
76
 
77
+ def add(message)
78
+ now = ::Process.clock_gettime(::Process::CLOCK_REALTIME)
79
+ Wurk.redis do |conn|
80
+ conn.call('ZADD', @name, now.to_s, message)
81
+ Metrics::Deaths.record(conn, message)
82
+ end
83
+ end
84
+
77
85
  # Only the death handlers see it, so a kill that notifies none (a UI kill,
78
86
  # `kill_all` over a whole set) never pays for the caller's backtrace.
79
87
  def api_kill_error
data/lib/wurk/keys.rb CHANGED
@@ -47,6 +47,12 @@ module Wurk
47
47
  # elapsed. Per-day variants append `:YYYY-MM-DD`. Spec: sidekiq-pro.md §7.
48
48
  STAT_EXPIRED = 'stat:expired'
49
49
 
50
+ # Jobs moved to the dead set, per queue and class (Metrics::Deaths): HASH,
51
+ # field = JSON `[queue, class]`, value = count. A Wurk extra like
52
+ # `status:` — Sidekiq keeps no death counter — and, unlike the capped
53
+ # `dead` set it counts into, it only ever grows.
54
+ STAT_DEATHS = 'stat:deaths'
55
+
50
56
  # TTL applied to per-day `stat:processed:*` / `stat:failed:*` /
51
57
  # `stat:expired:*` strings. 5 years, in seconds. Matches
52
58
  # Sidekiq::Launcher::STATS_TTL.
@@ -0,0 +1,12 @@
1
+ -- Counts one job into the death counter (Metrics::Deaths). A field already in
2
+ -- the hash always counts; a new one counts only while the hash holds fewer than
3
+ -- the cap, and into the overflow field past it, so junk payloads cannot grow
4
+ -- the hash, or a scrape of it, without bound.
5
+ -- KEYS = [deaths hash]
6
+ -- ARGV = [field, max fields, overflow field]
7
+ -- Returns the field's new count.
8
+ local field = ARGV[1]
9
+ if redis.call("hexists", KEYS[1], field) == 0 and redis.call("hlen", KEYS[1]) >= tonumber(ARGV[2]) then
10
+ field = ARGV[3]
11
+ end
12
+ return redis.call("hincrby", KEYS[1], field, 1)
@@ -0,0 +1,25 @@
1
+ -- Wurk only: sidekiq-unique-jobs 8.x has no refresh. Pushes out the expiry of a
2
+ -- lock this jid still holds, re-applying from now what lock.lua and
3
+ -- queue_and_lock.lua set when the lock was taken. Takes nothing: a jid that is
4
+ -- not in LOCKED gets 0 and no key is written. Every key is in KEYS.
5
+ -- KEYS = [digest, queued, primed, locked, info, changelog, digests, expiring_digests]
6
+ -- ARGV = [jid, pttl, now]
7
+ -- Returns 1 when this jid holds the lock, 0 otherwise.
8
+ local digest, locked, info, expiring = KEYS[1], KEYS[4], KEYS[5], KEYS[8]
9
+ local job_id, pttl, now = ARGV[1], tonumber(ARGV[2]), tonumber(ARGV[3])
10
+
11
+ if redis.call("HEXISTS", locked, job_id) == 0 then
12
+ return 0
13
+ end
14
+
15
+ if pttl > 0 then
16
+ redis.call("PEXPIRE", digest, pttl)
17
+ redis.call("PEXPIRE", locked, pttl)
18
+ redis.call("PEXPIRE", info, pttl)
19
+ -- An until_expired lock is also indexed by expiry, and the reaper deletes it
20
+ -- once that score passes. Scored as lock.lua scores it (seconds plus
21
+ -- milliseconds, the gem's arithmetic); XX leaves every other digest out.
22
+ redis.call("ZADD", expiring, "XX", now + pttl, digest)
23
+ end
24
+
25
+ return 1
data/lib/wurk/lua.rb CHANGED
@@ -63,8 +63,10 @@ module Wurk
63
63
  # retry would starve the whole cluster's scheduled jobs. It is moved to the
64
64
  # dead set (scored `now`, like a kill) so it stays inspectable, and the
65
65
  # sweep continues. pcall keeps a failed decode from raising out of the script.
66
- # KEYS = [sorted_set, queues_set, dead_set]
67
- # ARGV = [now, queue_prefix, now_ms, batch]
66
+ # Each one moved is counted into the death counter the way
67
+ # `lua/count_death.lua` counts (Metrics::Deaths), under queue `unknown`.
68
+ # KEYS = [sorted_set, queues_set, dead_set, deaths_hash]
69
+ # ARGV = [now, queue_prefix, now_ms, batch, deaths_max_fields, deaths_overflow_field]
68
70
  # Returns the number of members handled (promoted or moved to dead).
69
71
  # Order matters: decode + push BEFORE zrem. Redis Lua has no rollback,
70
72
  # so a failed cjson.decode after a zrem would lose the job. Decode first;
@@ -126,6 +128,18 @@ module Wurk
126
128
  if not last then return job end
127
129
  return string.sub(job, 1, e) .. colon .. ARGV[3] .. string.sub(job, last + 1)
128
130
  end
131
+ local function label(v) if type(v) == "string" and v ~= "" then return v end end
132
+ -- Best effort, pcall only: a refused count (a wrong-typed key, maxmemory)
133
+ -- must not stop the ZREM below, or the member is re-buried every sweep.
134
+ local function count_death(decoded)
135
+ local job = type(decoded) == "table" and decoded or {}
136
+ local field = cjson.encode({"unknown", label(job["wrapped"]) or label(job["class"]) or "unknown"})
137
+ local size = redis.pcall("hlen", KEYS[4])
138
+ if redis.pcall("hexists", KEYS[4], field) == 0 and type(size) == "number" and size >= tonumber(ARGV[5]) then
139
+ field = ARGV[6]
140
+ end
141
+ redis.pcall("hincrby", KEYS[4], field, 1)
142
+ end
129
143
  local jobs = redis.call("zrangebyscore", KEYS[1], "-inf", ARGV[1], "LIMIT", 0, tonumber(ARGV[4]))
130
144
  for i = 1, #jobs do
131
145
  local job = jobs[i]
@@ -138,6 +152,7 @@ module Wurk
138
152
  redis.call("zadd", KEYS[3], ARGV[1], job)
139
153
  end
140
154
  redis.call("zrem", KEYS[1], job)
155
+ if type(q) ~= "string" then count_death(ok and decoded) end
141
156
  end
142
157
  return #jobs
143
158
  LUA
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require_relative '../keys'
5
+ require_relative '../lua'
6
+
7
+ module Wurk
8
+ module Metrics
9
+ # Cluster-wide, monotonic count of jobs moved to the dead set, per queue and
10
+ # class, in `stat:deaths` (Keys::STAT_DEATHS). The dead set is capped at
11
+ # `dead_max_jobs`: once full, every kill trims the oldest entry, so its size
12
+ # stops moving and cannot say how many jobs died. This count can.
13
+ #
14
+ # Labels come from the payload's `queue` and its `wrapped` class (an
15
+ # ActiveJob's own class) or `class`, never the jid or args. A field the
16
+ # payload cannot supply is `unknown`. Distinct pairs past MAX_SERIES fold
17
+ # into OVERFLOW (`lua/count_death.lua`).
18
+ #
19
+ # Best effort, and only Wurk writes it (a stock Sidekiq process in a mixed
20
+ # fleet does not). #record reports a failed count, which may or may not have
21
+ # landed (a lost reply); the schedule-promote script cannot report, and drops it.
22
+ #
23
+ # Fields are encoded `script_safe`, escaping `/` as Redis's cjson does, so a
24
+ # pair the schedule-promote script counts lands on the same field.
25
+ module Deaths
26
+ MAX_SERIES = 500
27
+ UNKNOWN = 'unknown'
28
+ OTHER = 'other'
29
+ OVERFLOW = ::JSON.generate([OTHER, OTHER]).freeze
30
+ # Name, help and type of the `/metrics` family (Metrics::Prometheus), whose
31
+ # samples are #samples. Read from shared Redis, so every scrape target
32
+ # reports the same value: aggregate with `max`.
33
+ FAMILY = ['wurk_jobs_dead_total', 'Jobs moved to the dead set, by queue and class (stat:deaths).',
34
+ 'counter'].freeze
35
+
36
+ class << self
37
+ # Counts one death. Runs once, never replayed (`eval_once`), so a dropped
38
+ # socket can lose a count but never add one. Reported, not raised: the
39
+ # job is already in the dead set, and a caller that saw a raise would
40
+ # treat the kill as failed and kill it again.
41
+ def record(conn, payload, config: Wurk.configuration)
42
+ Lua::Loader.eval_once(conn, :count_death, keys: [Keys::STAT_DEATHS],
43
+ argv: [field(payload), MAX_SERIES, OVERFLOW])
44
+ rescue RedisClient::Error => e
45
+ config.handle_exception(e, context: 'dead-set death counter')
46
+ end
47
+
48
+ # The hash field for one payload: JSON `[queue, class]`.
49
+ def field(payload)
50
+ job = payload.is_a?(::String) ? parse(payload) : payload
51
+ job = {} unless job.is_a?(::Hash)
52
+ ::JSON.generate([label(job['queue']) || UNKNOWN, label(job['wrapped']) || label(job['class']) || UNKNOWN],
53
+ script_safe: true)
54
+ end
55
+
56
+ # `[[{ 'queue' => q, 'class' => c }, count], …]` from an HGETALL reply
57
+ # (a Hash under RESP3, a flat Array under RESP2), sorted by labels. Two
58
+ # fields that decode to the same labels (escaped differently by another
59
+ # writer) are summed.
60
+ def samples(reply)
61
+ pairs = reply.is_a?(::Hash) ? reply : Array(reply).each_slice(2)
62
+ totals = ::Hash.new(0)
63
+ pairs.each { |raw, count| totals[labels(raw)] += count.to_i }
64
+ totals.sort_by { |labels, _| labels.values }
65
+ end
66
+
67
+ private
68
+
69
+ def parse(payload)
70
+ ::JSON.parse(payload)
71
+ rescue ::JSON::ParserError
72
+ nil
73
+ end
74
+
75
+ def label(value)
76
+ value if value.is_a?(::String) && !value.empty?
77
+ end
78
+
79
+ def labels(raw)
80
+ queue, klass = parse(raw)
81
+ { 'queue' => label(queue) || UNKNOWN, 'class' => label(klass) || UNKNOWN }
82
+ end
83
+ end
84
+ end
85
+ end
86
+ end
@@ -6,11 +6,13 @@ require_relative '../keys'
6
6
  require_relative '../version'
7
7
  require_relative '../queue_consumers'
8
8
  require_relative 'process_counters'
9
+ require_relative 'deaths'
9
10
 
10
11
  module Wurk
11
12
  module Metrics
12
13
  # Prometheus text exposition (format 0.0.4) served by the health listener at
13
- # `GET /metrics`. Reads only keys Sidekiq already writes — no new Redis keys.
14
+ # `GET /metrics`. Reads keys Sidekiq already writes, plus Wurk's own death
15
+ # counter (`stat:deaths`, Metrics::Deaths); it writes none.
14
16
  #
15
17
  # Two families, and the difference matters when aggregating:
16
18
  # * cluster gauges/counters (`wurk_queue_*`, `wurk_processed_total`, …)
@@ -57,7 +59,7 @@ module Wurk
57
59
  # scheduler is behind.
58
60
  SET_HEADS = Scheduled::SETS.map { |set| ['ZRANGE', set, 0, 0, 'WITHSCORES'] }.freeze
59
61
  # Names come last: the detail pass is built from them.
60
- FIRST_PASS = [*SCALARS.values, *SET_HEADS, ['GET', Wurk::Leader::DEFAULT_KEY],
62
+ FIRST_PASS = [*SCALARS.values, *SET_HEADS, ['GET', Wurk::Leader::DEFAULT_KEY], ['HGETALL', Keys::STAT_DEATHS],
61
63
  ['SMEMBERS', Keys::QUEUES_SET], ['SMEMBERS', Keys::PROCESSES]].freeze
62
64
 
63
65
  QUEUE_GAUGES = [
@@ -98,7 +100,7 @@ module Wurk
98
100
  ProcessRow = Struct.new(:identity, :pid, :busy, :concurrency, :beat, :rss_kb, :quiet, :queues, :rtt_us,
99
101
  :oldest_run_at)
100
102
  Snapshot = Struct.new(:ok, :taken_at, :processed, :failed, :scheduled, :retries, :dead, :queues, :processes,
101
- :leader, :set_heads, keyword_init: true)
103
+ :leader, :set_heads, :deaths, keyword_init: true)
102
104
 
103
105
  def initialize(config, ttl: TTL, nonce: Component::PROCESS_NONCE, hostname: Component.hostname,
104
106
  clock: -> { ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) })
@@ -139,6 +141,7 @@ module Wurk
139
141
  ProcessFamilies.render(out, swarm: swarm)
140
142
  if snap.ok
141
143
  cluster(out, snap)
144
+ family(out, *Deaths::FAMILY, snap.deaths)
142
145
  local(out, snap, expected_children, fresh_window)
143
146
  end
144
147
  out
@@ -155,7 +158,7 @@ module Wurk
155
158
  queues, processes = names(first)
156
159
  rows = process_rows(processes, detail.drop(queues.size * 2), local_identities(processes))
157
160
  Snapshot.new(ok: true, taken_at: now, **scalars(first), leader: first[SCALARS.size + SET_HEADS.size],
158
- set_heads: heads_of_sets(first),
161
+ set_heads: heads_of_sets(first), deaths: Deaths.samples(first[SCALARS.size + SET_HEADS.size + 1]),
159
162
  queues: queue_rows(queues, detail, rows), processes: rows)
160
163
  rescue StandardError => e
161
164
  @config.logger&.warn { "Wurk::Metrics::Prometheus refresh failed: #{e.class}: #{e.message}" }
@@ -4,6 +4,7 @@ require_relative 'component'
4
4
  require_relative 'keys'
5
5
  require_relative 'lua'
6
6
  require_relative 'lua/loader'
7
+ require_relative 'metrics/deaths'
7
8
  require_relative 'client'
8
9
  require_relative 'process_set'
9
10
  require_relative 'timer_loop'
@@ -150,10 +151,12 @@ module Wurk
150
151
  def bury(jobstr, sset)
151
152
  # Two commands, no MULTI: a server that refuses the ZADD mid-transaction
152
153
  # (Dragonfly at maxmemory) still applies the ZREM, and the member is gone.
153
- # A crash between them costs one more trip through here.
154
+ # A crash between them costs one more trip through here. The count runs
155
+ # last and never raises, so a replay of the block cannot count twice.
154
156
  @config.redis(idempotent: true) do |conn|
155
157
  conn.call('ZADD', Keys::DEAD, real_time.to_s, jobstr)
156
158
  conn.call('ZREM', sset, jobstr)
159
+ Metrics::Deaths.record(conn, jobstr, config: @config)
157
160
  end
158
161
  rescue *TRANSIENT_ERRORS => e
159
162
  handle_exception(e, { context: 'scheduler_restore', set: sset })
@@ -238,8 +241,9 @@ module Wurk
238
241
  promoted = Wurk::Lua::Loader.eval_cached(
239
242
  conn,
240
243
  :reliable_schedule_promote,
241
- keys: [sset, Keys::QUEUES_SET, Keys::DEAD],
242
- argv: [real_time.to_s, Keys::QUEUE_PREFIX, real_ms.to_s, PROMOTE_BATCH.to_s]
244
+ keys: [sset, Keys::QUEUES_SET, Keys::DEAD, Keys::STAT_DEATHS],
245
+ argv: [real_time.to_s, Keys::QUEUE_PREFIX, real_ms.to_s, PROMOTE_BATCH.to_s,
246
+ Metrics::Deaths::MAX_SERIES.to_s, Metrics::Deaths::OVERFLOW]
243
247
  ).to_i
244
248
  Scheduled.record_promotions(sset, promoted)
245
249
  break if promoted < PROMOTE_BATCH || @done
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Wurk
4
+ module UniqueJobs
5
+ # `UniqueJobs.refresh_lock!`: pushes out the TTL of the lock a running job
6
+ # still holds, so a `perform` that can outlast any sane `lock_ttl` keeps its
7
+ # lock by renewing it instead of by a TTL long enough to cover the slowest
8
+ # run (which a crashed run then holds for just as long). Wurk only: the gem
9
+ # sets a lock's TTL once, when the lock is taken.
10
+ #
11
+ # One script (`unique_jobs_refresh.lua`) checks that the jid is still in the
12
+ # lock's LOCKED hash and only then re-applies the expiry; it never takes a
13
+ # lock, so a refresh that comes too late returns false and the caller
14
+ # decides what a lost lock means for its run.
15
+ class LockRefresh
16
+ # The types whose lock during `perform` is the runtime one, `<digest>:RUN`.
17
+ # until_and_while_executing gave up its push lock when `perform` started.
18
+ RUNTIME_LOCKS = [Lock::WhileExecuting, Lock::UntilAndWhileExecuting].freeze
19
+
20
+ # The payload of every unique job running in this process, by jid, so the
21
+ # job (or a thread it started) can name its lock by jid alone. Filled by
22
+ # the server middleware around `perform`.
23
+ module Running
24
+ @items = {}
25
+ @mutex = ::Mutex.new
26
+
27
+ class << self
28
+ def track(item)
29
+ jid = item[JID]
30
+ @mutex.synchronize { @items[jid] = item }
31
+ yield
32
+ ensure
33
+ @mutex.synchronize { @items.delete(jid) }
34
+ end
35
+
36
+ def [](jid) = @mutex.synchronize { @items[jid] }
37
+ end
38
+ end
39
+
40
+ def initialize(job, ttl: nil)
41
+ @item = item_for(job)
42
+ @pttl = pttl_for(ttl)
43
+ end
44
+
45
+ def call
46
+ UniqueJobs.redis do |conn|
47
+ Script.call(:unique_jobs_refresh, conn, keys: key.to_a, argv: [@item[JID], @pttl, UniqueJobs.now_f])
48
+ end == 1
49
+ end
50
+
51
+ private
52
+
53
+ def item_for(job)
54
+ item = case job
55
+ when ::Hash then job
56
+ when ::String then running(job)
57
+ else
58
+ raise ::ArgumentError, "expected a job payload, a jid or a job instance, got #{job.inspect}" \
59
+ unless job.class.respond_to?(:get_sidekiq_options)
60
+
61
+ running(job.jid)
62
+ end
63
+ [JID, LOCK, LOCK_DIGEST].each do |field|
64
+ raise ::ArgumentError, "not a unique job payload: no `#{field}` in #{item.inspect}" unless item[field]
65
+ end
66
+ item
67
+ end
68
+
69
+ def running(jid)
70
+ Running[jid] || raise(::ArgumentError,
71
+ "no job #{jid.inspect} is running under a Wurk::UniqueJobs lock in this process; " \
72
+ 'refresh_lock! by jid works only inside its perform (or a thread it started)')
73
+ end
74
+
75
+ # Seconds, from the caller or else the TTL the lock was taken with: the
76
+ # `lock_ttl` the payload carries. 0 means the lock never expires, so a
77
+ # refresh only answers whether it is still held.
78
+ def pttl_for(ttl)
79
+ return LockConfig.new(@item).pttl if ttl.nil?
80
+ raise ::ArgumentError, "ttl must be a positive number of seconds, got #{ttl.inspect}" \
81
+ unless ttl.is_a?(::Numeric) && (ttl * 1_000).to_i.positive?
82
+
83
+ (ttl * 1_000).to_i
84
+ end
85
+
86
+ def key
87
+ digest = @item[LOCK_DIGEST]
88
+ runtime = RUNTIME_LOCKS.any? { |klass| lock_class <= klass }
89
+ Key.new(runtime && !digest.end_with?(RUN_SUFFIX) ? "#{digest}#{RUN_SUFFIX}" : digest)
90
+ end
91
+
92
+ def lock_class
93
+ type = @item[LOCK].to_sym
94
+ UniqueJobs.locks.fetch(type) { raise UnknownLock, "No implementation for `lock: :#{type}`" }
95
+ end
96
+ end
97
+ end
98
+ end
@@ -82,7 +82,7 @@ module Wurk
82
82
  def call(worker, item, _queue, &)
83
83
  return yield unless lockable?(worker, item)
84
84
 
85
- with_context(:server) { lock_instance.execute(&) }
85
+ with_context(:server) { LockRefresh::Running.track(item) { lock_instance.execute(&) } }
86
86
  end
87
87
  end
88
88
  end
@@ -8,6 +8,7 @@ require_relative 'unique_jobs/job'
8
8
  require_relative 'unique_jobs/locksmith'
9
9
  require_relative 'unique_jobs/on_conflict'
10
10
  require_relative 'unique_jobs/lock'
11
+ require_relative 'unique_jobs/lock_refresh'
11
12
  require_relative 'unique_jobs/digests'
12
13
  require_relative 'unique_jobs/middleware'
13
14
  require_relative 'unique_jobs/orphans'
@@ -26,6 +27,7 @@ module Wurk
26
27
  # - A waiting lock blocks on its own connection, not a concurrent-ruby future.
27
28
  # - The reaper reads each job once per run, not once per digest, and counts
28
29
  # jobs in wurk's private lists as live (see Orphans::Reaper).
30
+ # - `refresh_lock!` renews a running job's lock (LockRefresh); the gem has none.
29
31
  # - No changelog debug logging (`debug_lua`), CLI, upgrade from v6 locks or
30
32
  # version keys: there is nothing to upgrade from.
31
33
  module UniqueJobs
@@ -80,6 +82,13 @@ module Wurk
80
82
  config.enabled = was if block_given?
81
83
  end
82
84
 
85
+ # Pushes out the TTL of the lock `job` holds while it runs: `job` is the
86
+ # running job instance (`self` in `perform`), its jid, or its payload.
87
+ # True when this jid still held the lock (now good for `ttl` seconds, by
88
+ # default the `lock_ttl` it was taken with); false when it no longer did,
89
+ # and then nothing is written. See LockRefresh.
90
+ def refresh_lock!(job, ttl: nil) = LockRefresh.new(job, ttl: ttl).call
91
+
83
92
  def reflections = @reflections ||= Reflections.new
84
93
  def reflect = yield(reflections)
85
94
  def redis(&) = Wurk.redis(&)
data/lib/wurk/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Wurk
4
- VERSION = '1.18.0'
4
+ VERSION = '1.20.0'
5
5
  end
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.18.0",
3
- "timestamp": "2026-11-23T05:16:18.120Z"
2
+ "version": "1.20.0",
3
+ "timestamp": "2026-11-24T02:15:30.375Z"
4
4
  }
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: wurk
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.18.0
4
+ version: 1.20.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - developerz.ai
@@ -332,6 +332,7 @@ files:
332
332
  - lib/wurk/lua/batch_push.lua
333
333
  - lib/wurk/lua/batch_remove_jobs.lua
334
334
  - lib/wurk/lua/batch_schedule.lua
335
+ - lib/wurk/lua/count_death.lua
335
336
  - lib/wurk/lua/debounce.lua
336
337
  - lib/wurk/lua/fast_delete.rb
337
338
  - lib/wurk/lua/fast_delete_window.lua
@@ -364,11 +365,13 @@ files:
364
365
  - lib/wurk/lua/unique_jobs_lock.lua
365
366
  - lib/wurk/lua/unique_jobs_queue.lua
366
367
  - lib/wurk/lua/unique_jobs_queue_and_lock.lua
368
+ - lib/wurk/lua/unique_jobs_refresh.lua
367
369
  - lib/wurk/lua/unique_jobs_unlock.lua
368
370
  - lib/wurk/manager.rb
369
371
  - lib/wurk/metrics.rb
370
372
  - lib/wurk/metrics/accumulator.rb
371
373
  - lib/wurk/metrics/dashboard_series.rb
374
+ - lib/wurk/metrics/deaths.rb
372
375
  - lib/wurk/metrics/exposition.rb
373
376
  - lib/wurk/metrics/flusher.rb
374
377
  - lib/wurk/metrics/histogram.rb
@@ -475,6 +478,7 @@ files:
475
478
  - lib/wurk/unique_jobs/errors.rb
476
479
  - lib/wurk/unique_jobs/job.rb
477
480
  - lib/wurk/unique_jobs/lock.rb
481
+ - lib/wurk/unique_jobs/lock_refresh.rb
478
482
  - lib/wurk/unique_jobs/locksmith.rb
479
483
  - lib/wurk/unique_jobs/middleware.rb
480
484
  - lib/wurk/unique_jobs/on_conflict.rb