wurk 1.16.0 → 1.17.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.
@@ -0,0 +1,657 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'serializers'
4
+ require_relative 'pagination'
5
+
6
+ module Wurk
7
+ class Web
8
+ module Dashboard
9
+ # The JSON API the SolidJS SPA reads, shared by the engine's
10
+ # ApiController and the standalone Rack mount (Dashboard::ApiEndpoint).
11
+ # Each includer supplies the controller interface: `params`, `render`,
12
+ # `head`, `request`, `response` (Dashboard::Controller, or
13
+ # ActionController in the engine) and its own `stream` action, which is
14
+ # the one place the two transports differ.
15
+ #
16
+ # Wire-compat: every payload field reads from the canonical Wurk inspector
17
+ # objects (Stats, Queue, RetrySet, ScheduledSet, DeadSet, ProcessSet,
18
+ # BatchSet, Cron::LoopSet) so dashboards stay aligned with the Redis schema
19
+ # in `docs/target/sidekiq-{free,pro,ent}.md`.
20
+ module ApiActions # rubocop:disable Metrics/ModuleLength
21
+ STREAM_TICK_SECONDS = 2.0
22
+ # Short so a capped slot rotates: a tab parked on the dashboard gives its
23
+ # thread back every half-minute and has to win a slot again to reopen.
24
+ STREAM_MAX_DURATION = 30.0
25
+ # Positive floor for `?tick=`: a zero/negative tick would `sleep 0` the SSE
26
+ # loop into a tight Redis-read/write spin (Live runs it in a spawned thread)
27
+ # for up to STREAM_MAX_DURATION. Clamp before it reaches drive_stream.
28
+ STREAM_MIN_TICK_SECONDS = 0.1
29
+
30
+ HISTORY_WINDOW_UNITS = { 's' => 1, 'm' => 60, 'h' => 3600, 'd' => 86_400 }.freeze
31
+ DEFAULT_HISTORY_WINDOW = 24 * 3600
32
+ # Sidekiq Web's dashboard `?days=N` range (free §25.4).
33
+ MAX_HISTORY_DAYS = 180
34
+ # Far past any real set; bounds a `?cursor=` before it reaches LRANGE.
35
+ MAX_CURSOR = 1 << 40
36
+
37
+ # Per-set action whitelists. Maps the SPA's action name to the
38
+ # SortedEntry/JobSet method. Anything not listed 400s — keeps the bulk/
39
+ # single dispatchers from reaching arbitrary methods off a request param.
40
+ RETRY_ACTIONS = { 'retry' => :retry, 'delete' => :delete, 'kill' => :kill }.freeze
41
+ SCHEDULED_ACTIONS = { 'delete' => :delete, 'add_to_queue' => :add_to_queue }.freeze
42
+ DEAD_ACTIONS = { 'retry' => :retry, 'delete' => :delete }.freeze
43
+
44
+ # Boot-time flags the SPA reads once to shape the UI (e.g. hide destructive
45
+ # actions and show the read-only banner). Always a GET, so it stays
46
+ # reachable while read-only mode blocks mutations.
47
+ def meta
48
+ config = ::Wurk::Web.config
49
+ render json: {
50
+ version: ::Wurk::VERSION,
51
+ read_only: config.read_only? || !mutations_authorized?(config),
52
+ read_only_message: config.read_only_message,
53
+ custom_tabs: config.custom_tabs
54
+ }
55
+ end
56
+
57
+ def stats
58
+ render json: ::Wurk::Api::Serializers.stats_payload(::Wurk::Stats::Snapshot.new)
59
+ end
60
+
61
+ def queues
62
+ snapshot = ::Wurk::Stats::Snapshot.new(consumers: true)
63
+ render json: snapshot.queue_summaries.map { |q|
64
+ ::Wurk::Api::Serializers.queue_summary(q).merge(consumers: snapshot.consumers.fetch(q.name, 0))
65
+ }
66
+ end
67
+
68
+ # `?direction=asc` lists oldest first, the job the next fetch takes at the
69
+ # top, as Sidekiq Web's queue page does (free §25.4).
70
+ def queue
71
+ q = ::Wurk::Queue.new(params[:name].to_s)
72
+ page = ::Wurk::Api::Pagination.window(params)
73
+ gauges, jobs = queue_page(q, page, params[:direction].to_s == 'asc')
74
+ render json: {
75
+ name: q.name, size: gauges.size, latency: gauges.latency, paused: gauges.paused?,
76
+ **::Wurk::Api::Pagination.meta(page), jobs: jobs
77
+ }
78
+ end
79
+
80
+ # Empties one queue (UNLINK list + drop from the `queues` set).
81
+ def clear_queue
82
+ ::Wurk::Queue.new(params[:name].to_s).clear
83
+ render json: { ok: true }
84
+ end
85
+
86
+ # Removes a single job from a queue by jid — one Lua round-trip
87
+ # (Fast::QueueExt#delete_job) instead of a paged find_job walk.
88
+ def delete_queue_job
89
+ jid = params[:jid].to_s
90
+ return render(json: { error: 'jid required' }, status: :bad_request) if jid.empty?
91
+
92
+ removed = ::Wurk::Queue.new(params[:name].to_s).delete_job(jid)
93
+ return render(json: { error: 'unknown job' }, status: :not_found) if removed.nil?
94
+
95
+ render json: { ok: true, deleted: true }
96
+ end
97
+
98
+ # Pause/unpause a queue (Pro §6, §10.1). Idempotent; returns the resulting
99
+ # state so the SPA can update its toggle without a refetch round-trip.
100
+ def pause_queue
101
+ ::Wurk::Queue.new(params[:name].to_s).pause!
102
+ render json: { ok: true, paused: true }
103
+ end
104
+
105
+ def unpause_queue
106
+ ::Wurk::Queue.new(params[:name].to_s).unpause!
107
+ render json: { ok: true, paused: false }
108
+ end
109
+
110
+ def retries = render_sorted_set(::Wurk::RetrySet.new)
111
+ def scheduled = render_sorted_set(::Wurk::ScheduledSet.new)
112
+ def dead = render_sorted_set(::Wurk::DeadSet.new)
113
+
114
+ # One entry with its backtrace, which listing rows leave out: inflating
115
+ # it costs a base64 decode, an inflate and a JSON parse per row, for a
116
+ # field only the detail view shows. `:key` is "<score>|<jid>".
117
+ def retry_entry = render_sorted_entry(::Wurk::RetrySet.new)
118
+ def scheduled_entry = render_sorted_entry(::Wurk::ScheduledSet.new)
119
+ def dead_entry = render_sorted_entry(::Wurk::DeadSet.new)
120
+
121
+ # --- Retry set mutations -------------------------------------------------
122
+ def retry_job = single_entry_action(::Wurk::RetrySet.new, RETRY_ACTIONS, params[:cmd])
123
+ def retries_bulk = bulk_entry_action(::Wurk::RetrySet.new, RETRY_ACTIONS)
124
+
125
+ def retries_all
126
+ set = ::Wurk::RetrySet.new
127
+ return sweep_matching(set, RETRY_ACTIONS) if filtered_sweep?
128
+
129
+ count = case params[:cmd].to_s
130
+ when 'retry' then set.retry_all
131
+ when 'kill' then set.kill_all
132
+ when 'delete' then clear_set(set)
133
+ else return render(json: { error: 'unknown action' }, status: :bad_request)
134
+ end
135
+ render json: { ok: true, count: count }
136
+ end
137
+
138
+ # --- Scheduled set mutations ---------------------------------------------
139
+ def scheduled_job = single_entry_action(::Wurk::ScheduledSet.new, SCHEDULED_ACTIONS, params[:cmd])
140
+ def scheduled_bulk = bulk_entry_action(::Wurk::ScheduledSet.new, SCHEDULED_ACTIONS)
141
+
142
+ def scheduled_all
143
+ set = ::Wurk::ScheduledSet.new
144
+ return sweep_matching(set, SCHEDULED_ACTIONS) if filtered_sweep?
145
+
146
+ case params[:cmd].to_s
147
+ when 'delete' then render json: { ok: true, count: clear_set(set) }
148
+ when 'add_to_queue' then drain_set(set, :add_to_queue)
149
+ else render(json: { error: 'unknown action' }, status: :bad_request)
150
+ end
151
+ end
152
+
153
+ # --- Dead set mutations --------------------------------------------------
154
+ def dead_job = single_entry_action(::Wurk::DeadSet.new, DEAD_ACTIONS, params[:cmd])
155
+ def dead_bulk = bulk_entry_action(::Wurk::DeadSet.new, DEAD_ACTIONS)
156
+
157
+ def dead_all
158
+ set = ::Wurk::DeadSet.new
159
+ return sweep_matching(set, DEAD_ACTIONS) if filtered_sweep?
160
+
161
+ count = case params[:cmd].to_s
162
+ when 'retry' then set.retry_all
163
+ when 'delete' then clear_set(set)
164
+ else return render(json: { error: 'unknown action' }, status: :bad_request)
165
+ end
166
+ render json: { ok: true, count: count }
167
+ end
168
+
169
+ def processes
170
+ set = ::Wurk::ProcessSet.new
171
+ live = set.to_a # before #leader: the walk reads `dear-leader` in its pipeline
172
+ leader_identity = set.leader
173
+ render json: live.map { |p| ::Wurk::Api::Serializers.process_row(p, leader_identity: leader_identity) }
174
+ end
175
+
176
+ # Currently-executing jobs across the cluster (WorkSet), oldest first.
177
+ # The Busy page's process-detail modal filters client-side by process_id.
178
+ def workers
179
+ render json: ::Wurk::WorkSet.new.map { |pid, tid, work| ::Wurk::Api::Serializers.work_row(pid, tid, work) }
180
+ end
181
+
182
+ # Busy-page controls: SIGTSTP (quiet — drop fetch, drain in-flight) and
183
+ # SIGTERM (stop — graceful shutdown). Both are async; the target notices on
184
+ # its next heartbeat (≤10s). `identity` absent or "all" signals every live
185
+ # process.
186
+ def quiet_process = signal_processes(:quiet!)
187
+ def stop_process = signal_processes(:stop!)
188
+
189
+ # Rows are Batch::Status#summary: #data with the failed and dead jid sets
190
+ # counted rather than listed. GET /api/batches/:bid carries the jids.
191
+ # `?dead=1` lists `dead-batches` instead (Pro's Dead batches tab);
192
+ # `?tag=` narrows either to the batches carrying that tag, and takes the
193
+ # place of `?substr=` (BatchSet#tagged_snapshot).
194
+ def batches
195
+ page = ::Wurk::Api::Pagination.window(params)
196
+ set = %w[1 true].include?(params[:dead].to_s) ? ::Wurk::Batch::DeadSet.new : ::Wurk::BatchSet.new
197
+ total, rows = batch_rows(set, page, params[:tag].to_s)
198
+ render json: { total: total, **::Wurk::Api::Pagination.meta(page), batches: rows }
199
+ end
200
+
201
+ def batch
202
+ status = ::Wurk::Batch::Status.new(params[:bid].to_s)
203
+ return render(json: { error: 'unknown batch' }, status: :not_found) unless status.exists?
204
+
205
+ render json: status.data.transform_keys(&:to_sym)
206
+ rescue ::ArgumentError
207
+ render json: { error: 'unknown batch' }, status: :not_found
208
+ end
209
+
210
+ def flows
211
+ page = ::Wurk::Api::Pagination.window(params)
212
+ total, rows = page_rows(::Wurk::FlowSet.new, page) { |status| ::Wurk::Api::Serializers.flow_row(status) }
213
+ render json: { total: total, **::Wurk::Api::Pagination.meta(page), flows: rows }
214
+ end
215
+
216
+ def flow
217
+ status = flow_status
218
+ return render(json: { error: 'unknown flow' }, status: :not_found) unless status&.exists?
219
+
220
+ render json: ::Wurk::Api::Serializers.flow_detail(status)
221
+ end
222
+
223
+ # The kill switch (slice 11 decision 4). Read-only mode 403s it via the
224
+ # Authorization middleware, like every other non-GET here. `abandoned`
225
+ # comes back false for a flow that had already finished or been abandoned —
226
+ # neither is stuck, and neither is touched.
227
+ def abandon_flow
228
+ status = flow_status
229
+ return render(json: { error: 'unknown flow' }, status: :not_found) unless status&.exists?
230
+
231
+ render json: { ok: true, abandoned: ::Wurk::Flow.abandon(status.fid) }
232
+ end
233
+
234
+ def limiters
235
+ page = ::Wurk::Api::Pagination.window(params)
236
+ total, rows = ::Wurk::Web::Enterprise::Limits.page(
237
+ filter: params[:substr], offset: ::Wurk::Api::Pagination.offset(page), count: page[:count]
238
+ )
239
+ render json: { total: total, **::Wurk::Api::Pagination.meta(page),
240
+ limiters: rows.map { |name, meta| ::Wurk::Api::Serializers.limiter_row(name, meta) } }
241
+ end
242
+
243
+ def reset_limiter
244
+ ::Wurk::Web::Enterprise::Limits.reset(params[:name].to_s)
245
+ render json: { ok: true }
246
+ end
247
+
248
+ def cron
249
+ now = ::Time.now.to_i
250
+ render json: ::Wurk::Cron::LoopSet.new.map { |lp| ::Wurk::Api::Serializers.cron_row(lp, now) }
251
+ end
252
+
253
+ def pause_cron = render_cron_action(::Wurk::Web::Enterprise::Periodic.pause(params[:lid].to_s))
254
+ def unpause_cron = render_cron_action(::Wurk::Web::Enterprise::Periodic.unpause(params[:lid].to_s))
255
+
256
+ def enqueue_cron
257
+ jid = ::Wurk::Web::Enterprise::Periodic.enqueue_now(params[:lid].to_s)
258
+ return render(json: { error: 'unknown loop' }, status: :not_found) if jid.nil?
259
+
260
+ render json: { ok: true, jid: jid }
261
+ end
262
+
263
+ def cron_history
264
+ render json: { lid: params[:lid].to_s, history: ::Wurk::Web::Enterprise::Periodic.history(params[:lid].to_s) }
265
+ end
266
+
267
+ # `?minutes=` (default 60) is served raw — the Query layer routes ≤480 to
268
+ # per-minute buckets and >480 onto the 10-minute buckets, raising
269
+ # WindowTooWide (400 below) past the 30-day ceiling; a non-positive window
270
+ # raises ArgumentError there and 400s the same way. `?hours=` is clamped
271
+ # to MAX_HOURS (default 24 when present) and always takes the 10-minute
272
+ # path. The response echoes the REQUESTED window so the SPA's label
273
+ # matches the served period.
274
+ def metrics
275
+ minutes, hours = metrics_window_raw(params)
276
+ rows = ::Wurk::Web::Enterprise::Historical.top(minutes: minutes, hours: hours, class_filter: params[:substr])
277
+ payload = { minutes: hours ? hours * 60 : minutes,
278
+ top_jobs: rows.map { |(klass, totals)| ::Wurk::Api::Serializers.metric_row(klass, totals) } }
279
+ # hours is echoed only when the request used it, so a minutes request
280
+ # keeps the two-key shape (minutes + top_jobs) it has always had.
281
+ payload[:hours] = hours if hours
282
+ render json: payload
283
+ rescue ::ArgumentError, ::Wurk::Metrics::Query::WindowTooWide => e
284
+ render json: { error: e.message }, status: :bad_request
285
+ end
286
+
287
+ def metrics_for_job
288
+ klass = params[:klass].to_s
289
+ minutes, hours = metrics_window(params)
290
+ rows = ::Wurk::Web::Enterprise::Historical.for_job(klass, minutes: minutes, hours: hours)
291
+ series = rows.map { |row| row.merge(at: row[:at].to_f) }
292
+ render json: { klass: klass, minutes: minutes, hours: hours, series: series }
293
+ rescue ::ArgumentError, ::Wurk::Metrics::Query::WindowTooWide => e
294
+ render json: { error: e.message }, status: :bad_request
295
+ end
296
+
297
+ # Cluster-total throughput/failures time-series for the dashboard charts.
298
+ # `:bucket` is 1m/5m/1h; `?window=24h` (s/m/h/d suffix) or `?days=N`
299
+ # (1..180, wins over window) is clamped to the bucket's retention.
300
+ # Chart-ready array under `series`.
301
+ def history
302
+ window = history_window(params)
303
+ series = ::Wurk::Web::Enterprise::Historical.history(params[:bucket].to_s, window: window)
304
+ render json: { bucket: params[:bucket].to_s, window: window, series: series.map { |row| ::Wurk::Api::Serializers.history_point(row) } }
305
+ rescue ::ArgumentError => e
306
+ render json: { error: e.message }, status: :bad_request
307
+ end
308
+
309
+ # Ent §5.3 Historical snapshots from the capped `history:metrics` stream.
310
+ # `?limit=N` (default 1000) most-recent points, oldest→newest, each
311
+ # `{at:, processed:, failures:, …}`. Fields are read generically so a
312
+ # migrated Sidekiq Ent stream renders as-is.
313
+ def history_snapshots
314
+ limit = ::Wurk::Api::Pagination.clamp_int(
315
+ params[:limit], 1, ::Wurk::History::STREAM_CAP, ::Wurk::History::STREAM_DEFAULT_LIMIT
316
+ )
317
+ render json: { snapshots: ::Wurk::Web::Enterprise::Historical.snapshots(limit: limit) }
318
+ end
319
+
320
+ # Per-queue size/latency gauge time-series for the Metrics/Historical tab.
321
+ # `:bucket` is 1m/5m/1h; `?window=24h` (s/m/h/d) is clamped to the bucket's
322
+ # retention (`?days=N` as on #history); optional `?queue=<name>` narrows
323
+ # to one queue. Each queue's `points` are chart-ready.
324
+ def queue_history # rubocop:disable Metrics/AbcSize
325
+ window = history_window(params)
326
+ queues = params[:queue].to_s.empty? ? nil : [params[:queue].to_s]
327
+ series = ::Wurk::Web::Enterprise::Historical.queue_history(params[:bucket].to_s, window: window,
328
+ queues: queues)
329
+ render json: {
330
+ bucket: params[:bucket].to_s,
331
+ window: window,
332
+ queues: series.map { |row| ::Wurk::Api::Serializers.queue_history_series(row) }
333
+ }
334
+ rescue ::ArgumentError => e
335
+ render json: { error: e.message }, status: :bad_request
336
+ end
337
+
338
+ def search
339
+ substr = params[:substr].to_s
340
+ return render(json: { substr: substr, total: 0, hits: [], truncated: false }) if substr.empty?
341
+
342
+ search = ::Wurk::Web::Search.new(substr, kinds: parse_search_kinds(params), limit: parse_search_limit(params))
343
+ hits = search.to_a
344
+ render json: { substr: substr, total: hits.size, hits: hits, truncated: search.truncated? }
345
+ end
346
+
347
+ # Profiles list (v8.0+). The SPA links each row to /profiles/:key (view)
348
+ # and /profiles/:key/data (raw blob). Newest first.
349
+ def profiles
350
+ records = ::Wurk::ProfileSet.new.map { |rec| ::Wurk::Api::Serializers.profile_record(rec) }
351
+ render json: records.sort_by { |r| -(r[:started_at] || 0) }
352
+ end
353
+
354
+ # Engine-relative path probed as a representative mutation. Must be a real
355
+ # mutating route (POST /api/retries — bulk retry/delete/kill) so that a
356
+ # path-sensitive hook resolves it the same way the Authorization middleware
357
+ # will resolve the actual mutation. Probing `request.path_info` (which here
358
+ # is the GET /api/meta path) would let such a hook allow the probe while
359
+ # still 403ing real mutations, reviving the "button shows, then 403s" gap.
360
+ MUTATION_PROBE_PATH = '/api/retries'
361
+ private_constant :MUTATION_PROBE_PATH
362
+
363
+ private
364
+
365
+ # [tick, max duration] in seconds for the `stream` action. `?tick=` and
366
+ # `?max_duration=` are test/debug knobs; the SPA never sets them.
367
+ # `?max_duration=0` emits one tick and closes.
368
+ def stream_window
369
+ clamp = ::Wurk::Api::Pagination.method(:clamp_float)
370
+ [clamp.call(params[:tick], STREAM_MIN_TICK_SECONDS, STREAM_TICK_SECONDS, STREAM_TICK_SECONDS),
371
+ clamp.call(params[:max_duration], 0.0, STREAM_MAX_DURATION, STREAM_MAX_DURATION)]
372
+ end
373
+
374
+ # Per-request read-only signal for the SPA. When a registered authorization
375
+ # hook would reject a *mutating* request for this user (e.g. a viewer role
376
+ # that may GET but not retry/kill), report `read_only` so the SPA hides the
377
+ # destructive actions — the Authorization middleware already 403s the
378
+ # mutation itself, this just stops the buttons from showing. With no hook
379
+ # registered, `authorized?` is always true, so this is a no-op and the flag
380
+ # keeps reflecting the global read-only mode. Probes POST on a canonical
381
+ # mutating path (SAFE_METHODS are GET/HEAD/OPTIONS) so a path-sensitive hook
382
+ # answers for a real mutation, not the GET /api/meta request carrying it.
383
+ def mutations_authorized?(config)
384
+ config.authorized?(request.env, 'POST', MUTATION_PROBE_PATH)
385
+ end
386
+
387
+ # nil for an empty fid, which Flow::Status refuses rather than reading
388
+ # `flow:` — the key prefix itself, which is not a flow. Both callers turn
389
+ # that into the same 404 a fid nothing was created under gets, because from
390
+ # outside there is no difference worth telling apart.
391
+ def flow_status
392
+ ::Wurk::Flow::Status.new(params[:fid].to_s)
393
+ rescue ::ArgumentError
394
+ nil
395
+ end
396
+
397
+ # Resolves a single entry by "<score>|<jid>" key and applies a whitelisted
398
+ # action. 400 on an unknown action, 404 when the key matches nothing (e.g.
399
+ # the entry was already retried/deleted from another tab).
400
+ def single_entry_action(set, actions, cmd)
401
+ method = actions[cmd.to_s]
402
+ return render(json: { error: 'unknown action' }, status: :bad_request) unless method
403
+
404
+ entries = entries_for(set, [params[:key]])
405
+ return render(json: { error: 'unknown job' }, status: :not_found) if entries.empty?
406
+
407
+ render_applied(entries.size, apply_each(entries, method))
408
+ end
409
+
410
+ # Bulk variant: `keys[]` + a single `cmd` applied to every resolved entry.
411
+ def bulk_entry_action(set, actions)
412
+ method = actions[params[:cmd].to_s]
413
+ return render(json: { error: 'unknown action' }, status: :bad_request) unless method
414
+
415
+ keys = Array(params[:keys]).map(&:to_s).uniq
416
+ # Each key costs a pipelined ZRANGEBYSCORE plus per-entry mutations; an uncapped
417
+ # list lets one POST issue tens of thousands of round-trips. The UI's
418
+ # per-row selections accumulate across pages (toggleAll works against
419
+ # the visible page's keys only) and the bulk POST sends the whole Set,
420
+ # so this cap — not the page size — is the bound.
421
+ return render(json: { error: 'too many keys (max 1000)' }, status: :bad_request) if keys.size > 1000
422
+
423
+ entries = entries_for(set, keys)
424
+ render_applied(entries.size, apply_each(entries, method))
425
+ end
426
+
427
+ # One entry the client rejects (a payload failing validation, a raising
428
+ # middleware) must not 500 the request with every later entry unapplied.
429
+ # SortedEntry has already put a failed entry back in its set, so the
430
+ # failure is reported per key and the loop moves on. A Redis error is not
431
+ # per-entry — it propagates to the 503 handler instead of failing every
432
+ # remaining key one by one.
433
+ def apply_each(entries, method)
434
+ entries.each_with_object([]) do |entry, failures|
435
+ entry.public_send(method)
436
+ rescue *::Wurk::Configuration::REDIS_ERROR_CLASSES
437
+ raise
438
+ rescue StandardError => e
439
+ ::Wurk.configuration.handle_exception(e, context: "Wurk::ApiController##{method}", jid: entry.jid)
440
+ failures << { key: entry.id, error: "#{e.class}: #{e.message}" }
441
+ end
442
+ end
443
+
444
+ # 422 when any entry failed, so the SPA's error toast fires; `count` is
445
+ # what was applied either way.
446
+ def render_applied(total, failures, extra = {})
447
+ body = { ok: failures.empty?, count: total - failures.size, **extra }
448
+ return render(json: body) if failures.empty?
449
+
450
+ render json: body.merge(failed: failures), status: 422
451
+ end
452
+
453
+ # Sends `method` (:quiet! / :stop!) to one process by identity, or to every
454
+ # live process when identity is blank/"all". Embedded processes are skipped
455
+ # (they raise on quiet!/stop! — there's no separate process to signal). 404s
456
+ # when a named identity isn't in the live set.
457
+ def signal_processes(method) # rubocop:disable Metrics/AbcSize
458
+ identity = params[:identity].to_s
459
+ if identity.empty? || identity == 'all'
460
+ count = ::Wurk::ProcessSet.new.reject(&:embedded?).each { |p| p.public_send(method) }.size
461
+ return render(json: { ok: true, count: count })
462
+ end
463
+
464
+ process = ::Wurk::ProcessSet[identity]
465
+ return render(json: { error: 'unknown process' }, status: :not_found) unless process
466
+
467
+ process.public_send(method) unless process.embedded?
468
+ render json: { ok: true, count: process.embedded? ? 0 : 1 }
469
+ end
470
+
471
+ # Maps "<score>|<jid>" keys to live SortedEntry objects via score-bracketed
472
+ # fetch (exact float match, narrowed by jid) — avoids depending on float→
473
+ # string round-tripping between JS and Ruby. Skips malformed/empty keys.
474
+ # One pipelined round trip for every key (JobSet#fetch_pairs).
475
+ def entries_for(set, keys)
476
+ pairs = keys.filter_map do |key|
477
+ score, jid = key.to_s.split('|', 2)
478
+ [score.to_f, jid] unless jid.nil? || jid.empty?
479
+ end
480
+ set.fetch_pairs(pairs)
481
+ end
482
+
483
+ def batch_rows(set, page, tag)
484
+ symbolize = ->(summary) { summary.transform_keys(&:to_sym) }
485
+ return page_rows(set, page, &symbolize) if tag.empty?
486
+
487
+ total, summaries = set.tagged_snapshot(tag, ::Wurk::Api::Pagination.offset(page), page[:count])
488
+ [total, summaries.map(&symbolize)]
489
+ end
490
+
491
+ def filtered_sweep? = !params[:substr].to_s.empty?
492
+
493
+ # `<set>/all/:cmd?substr=`: applies `cmd` to the entries the same filtered
494
+ # listing shows, newest first, at most SWEEP_LIMIT of them within the
495
+ # filter's scan budget per request. The answer carries `done` (the walk
496
+ # reached the end of the set) and `cursor`, the raw offset to send back as
497
+ # `?cursor=` to carry on: the rows examined minus those this request moved
498
+ # out of the set. Entries added or removed meanwhile above that offset
499
+ # shift it, so a resumed sweep can re-examine or skip a few rows.
500
+ def sweep_matching(set, actions)
501
+ method = actions[params[:cmd].to_s]
502
+ return render(json: { error: 'unknown action' }, status: :bad_request) unless method
503
+
504
+ entries, scanned_to, done = matching_entries(set)
505
+ failures = apply_each(entries, method)
506
+ cursor = scanned_to - (entries.size - failures.size)
507
+ render_applied(entries.size, failures, matched: entries.size, done: done, cursor: cursor)
508
+ end
509
+
510
+ # [the matches from `?cursor=`, the raw offset the walk stopped at, done].
511
+ def matching_entries(set)
512
+ from = ::Wurk::Api::Pagination.clamp_int(params[:cursor], 0, MAX_CURSOR, 0)
513
+ rows = ::Wurk::Api::Pagination.walk(from) { |offset, count| set.snapshot(offset, count).last }
514
+ entries, examined, done = ::Wurk::Api::Pagination.matching(rows, params[:substr].to_s) do |entry|
515
+ ::Wurk::Api::Serializers.sorted_entry(entry)
516
+ end
517
+ [entries, from + examined, done]
518
+ end
519
+
520
+ # UNLINKs the whole set, returning the count removed (read before clearing
521
+ # so the response reports what was deleted).
522
+ def clear_set(set)
523
+ total = set.size
524
+ set.clear
525
+ total
526
+ end
527
+
528
+ # Drains a set by applying `method` to every entry. Snapshot first, then
529
+ # apply: mutating while the paged iterator scans would shift ZRANGE
530
+ # offsets mid-scan, and the old "loop until empty" alternative never
531
+ # terminates on a busy app (concurrent perform_in keeps the set non-empty)
532
+ # while wrongly enqueueing jobs scheduled *after* the operator clicked.
533
+ # Entries removed concurrently no-op their apply.
534
+ def drain_set(set, method)
535
+ entries = set.to_a
536
+ render_applied(entries.size, apply_each(entries, method))
537
+ end
538
+
539
+ def render_sorted_set(set)
540
+ page = ::Wurk::Api::Pagination.window(params)
541
+ total, entries = page_rows(set, page) { |entry| ::Wurk::Api::Serializers.sorted_entry(entry) }
542
+ render json: { total: total, **::Wurk::Api::Pagination.meta(page), entries: entries }
543
+ end
544
+
545
+ # [total, rows] of one listing page. Unfiltered, the page is read straight
546
+ # off Redis at its offset (the set's #snapshot), so page 999 costs what
547
+ # page 0 does; a filter counts matching rows, so it walks the set through
548
+ # the same #snapshot, bounded by FILTER_SCAN_LIMIT.
549
+ def page_rows(set, page, &)
550
+ if page[:substr].empty?
551
+ total, members = set.snapshot(::Wurk::Api::Pagination.offset(page), page[:count])
552
+ return [total, members.map(&)]
553
+ end
554
+
555
+ rows = ::Wurk::Api::Pagination.walk { |offset, count| set.snapshot(offset, count).last }
556
+ [set.size, ::Wurk::Api::Pagination.slice(rows, page, &)]
557
+ end
558
+
559
+ # The gauges (anything answering size/latency/paused?) and the page's rows.
560
+ def queue_page(queue, page, oldest_first)
561
+ serialize = ->(rec) { ::Wurk::Api::Serializers.job_record(rec) }
562
+ unless page[:substr].empty?
563
+ rows = ::Wurk::Api::Pagination.walk { |offset, count| queue_records(queue, offset, count, oldest_first).last }
564
+ return [queue, ::Wurk::Api::Pagination.slice(rows, page, &serialize)]
565
+ end
566
+
567
+ snapshot, records = queue_records(queue, ::Wurk::Api::Pagination.offset(page), page[:count], oldest_first)
568
+ [snapshot, records.map(&serialize)]
569
+ end
570
+
571
+ # [snapshot, its records in listing order]. Oldest first reads the same
572
+ # LRANGE from the tail: negative indexes `-(offset + count)..-(offset + 1)`,
573
+ # which Redis clamps at the head, then reversed.
574
+ def queue_records(queue, offset, count, oldest_first)
575
+ snapshot = queue.snapshot(oldest_first ? -(offset + count) : offset, count)
576
+ [snapshot, oldest_first ? snapshot.records.reverse : snapshot.records]
577
+ end
578
+
579
+ def render_sorted_entry(set)
580
+ entry = entries_for(set, [params[:key]]).first
581
+ return render(json: { error: 'unknown job' }, status: :not_found) unless entry
582
+
583
+ render json: ::Wurk::Api::Serializers.sorted_entry_detail(entry)
584
+ end
585
+
586
+ def render_cron_action(success)
587
+ return render(json: { error: 'unknown loop' }, status: :not_found) unless success
588
+
589
+ render json: { ok: true }
590
+ end
591
+
592
+ def parse_search_kinds(params)
593
+ params[:kinds].is_a?(::Array) ? params[:kinds] : params[:kinds].to_s.split(',')
594
+ end
595
+
596
+ def parse_search_limit(params)
597
+ ::Wurk::Api::Pagination.clamp_int(
598
+ params[:limit], 1, ::Wurk::Web::Search::MAX_LIMIT, ::Wurk::Web::Search::DEFAULT_LIMIT
599
+ )
600
+ end
601
+
602
+ # `?days=N` (1..MAX_HISTORY_DAYS) in seconds when it parses, else
603
+ # `?window=`.
604
+ def history_window(params)
605
+ days = ::Wurk::Api::Pagination.clamp_int(params[:days], 1, MAX_HISTORY_DAYS, nil)
606
+ days ? days * HISTORY_WINDOW_UNITS.fetch('d') : parse_window(params[:window])
607
+ end
608
+
609
+ # Resolves the per-class metrics window. `minutes:` wins when present;
610
+ # `hours:` is used otherwise; default falls back to 60 minutes so callers
611
+ # that pass neither still get a useful series.
612
+ # `?window=24h` → seconds. Accepts an s/m/h/d suffix (bare number = seconds).
613
+ # Falls back to 24h on a missing or unparseable value; the Query layer
614
+ # clamps the result to the bucket's retention.
615
+ def parse_window(raw)
616
+ match = raw.to_s.strip.downcase.match(/\A(\d+)([smhd]?)\z/)
617
+ return DEFAULT_HISTORY_WINDOW unless match
618
+
619
+ Integer(match[1]) * HISTORY_WINDOW_UNITS.fetch(match[2].empty? ? 's' : match[2])
620
+ end
621
+
622
+ # `?hours=` wins over `?minutes=`; minutes > MAX_MINUTES (480) promote onto
623
+ # the 10-minute buckets in the Query layer, so the clamp ceiling is the
624
+ # 30-day equivalent (MAX_HOURS * 60 minutes), not 480. Absent both, the
625
+ # window defaults to 60 minutes.
626
+ def metrics_window(params)
627
+ pagination = ::Wurk::Api::Pagination
628
+ max_hours = ::Wurk::Metrics::Query::MAX_HOURS
629
+ if params[:hours]
630
+ [nil, pagination.clamp_int(params[:hours], 1, max_hours, 24)]
631
+ else
632
+ [pagination.clamp_int(params[:minutes], 1, max_hours * 60, 60), nil]
633
+ end
634
+ end
635
+
636
+ # #metrics variant: `?minutes=` goes through raw so a window past the
637
+ # 30-day ceiling (MAX_HOURS * 60) reaches the Query layer and raises
638
+ # WindowTooWide — the endpoint answers 400 rather than silently serving
639
+ # a shorter window than the SPA's label claims. Unparseable values fall
640
+ # back to the 60-minute default; `?hours=` is clamped as above.
641
+ def metrics_window_raw(params)
642
+ pagination = ::Wurk::Api::Pagination
643
+ max_hours = ::Wurk::Metrics::Query::MAX_HOURS
644
+ if params[:hours]
645
+ [nil, pagination.clamp_int(params[:hours], 1, max_hours, 24)]
646
+ elsif params[:minutes]
647
+ [Integer(params[:minutes], 10), nil]
648
+ else
649
+ [60, nil]
650
+ end
651
+ rescue ::ArgumentError, ::TypeError
652
+ [60, nil]
653
+ end
654
+ end
655
+ end
656
+ end
657
+ end