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