Module: Sidekiq::WebHelpers

Defined in:
lib/sidekiq/web/helpers.rb

Overview

These methods are available to pages within the Web UI and UI extensions. They are not public APIs for applications to use.

Constant Summary collapse

SAFE_QPARAMS =
%w[page direction]
RETRY_JOB_KEYS =
Set.new(%w[
  queue class args retry_count retried_at failed_at
  jid error_message error_class backtrace
  error_backtrace enqueued_at retry wrapped
  created_at tags display_class
])

Instance Method Summary collapse

Instance Method Details

#add_to_headObject

This view helper provide ability display you html code in to head of page. Example:

<% add_to_head do %>
  <link rel="stylesheet" .../>
  <meta .../>
<% end %>


181
182
183
184
# File 'lib/sidekiq/web/helpers.rb', line 181

def add_to_head
  @head_html ||= []
  @head_html << yield.dup if block_given?
end

#available_localesObject



136
137
138
# File 'lib/sidekiq/web/helpers.rb', line 136

def available_locales
  @@available_locales ||= Set.new(locale_files.map { |path| File.basename(path, ".yml") })
end

#clear_cachesObject



124
125
126
127
128
# File 'lib/sidekiq/web/helpers.rb', line 124

def clear_caches
  @@strings = nil
  @@locale_files = nil
  @@available_locales = nil
end

#csp_nonceObject



376
377
378
# File 'lib/sidekiq/web/helpers.rb', line 376

def csp_nonce
  env[:csp_nonce]
end

#csrf_tagObject



372
373
374
# File 'lib/sidekiq/web/helpers.rb', line 372

def csrf_tag
  ""
end

#current_pathObject



307
308
309
# File 'lib/sidekiq/web/helpers.rb', line 307

def current_path
  @current_path ||= request.path_info.gsub(/^\//, "")
end

#current_statusObject



311
312
313
# File 'lib/sidekiq/web/helpers.rb', line 311

def current_status
  (workset.size == 0) ? "idle" : "active"
end

#delete_or_add_queue(job, params) ⇒ Object



471
472
473
474
475
476
477
# File 'lib/sidekiq/web/helpers.rb', line 471

def delete_or_add_queue(job, params)
  if params["delete"]
    job.delete
  elsif params["add_to_queue"]
    job.add_to_queue
  end
end

#display_args(args, truncate_after_chars = 2000) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/sidekiq/web/helpers.rb', line 359

def display_args(args, truncate_after_chars = 2000)
  return "Invalid job payload, args is nil" if args.nil?
  return "Invalid job payload, args must be an Array, not #{args.class.name}" unless args.is_a?(Array)

  begin
    args.map { |arg|
      h(truncate(to_display(arg), truncate_after_chars))
    }.join(", ")
  rescue
    "Illegal job arguments: #{h args.inspect}"
  end
end

#display_custom_headObject



186
187
188
# File 'lib/sidekiq/web/helpers.rb', line 186

def display_custom_head
  @head_html.join if defined?(@head_html)
end

#display_tags(job, within = "retries") ⇒ Object



167
168
169
170
171
# File 'lib/sidekiq/web/helpers.rb', line 167

def display_tags(job, within = "retries")
  job.tags.map { |tag|
    "<span class='label label-info jobtag jobtag-#{Rack::Utils.escape_html(tag)}'>#{filter_link(tag, within)}</span>"
  }.join(" ")
end

#environment_title_prefixObject



442
443
444
445
446
# File 'lib/sidekiq/web/helpers.rb', line 442

def environment_title_prefix
  environment = Sidekiq.default_configuration[:environment] || ENV["APP_ENV"] || ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"

  "[#{environment.upcase}] " unless environment == "production"
end


159
160
161
162
163
164
165
# File 'lib/sidekiq/web/helpers.rb', line 159

def filter_link(jid, within = "retries")
  if within.nil?
    ::Rack::Utils.escape_html(jid)
  else
    "<a href='#{root_path}#{within}?substr=#{jid}'>#{::Rack::Utils.escape_html(jid)}</a>"
  end
end

#filtering(which, placeholder_key: "AnyJobContent", label_key: "Filter") ⇒ Object



155
156
157
# File 'lib/sidekiq/web/helpers.rb', line 155

def filtering(which, placeholder_key: "AnyJobContent", label_key: "Filter")
  erb(:filtering, locals: {which:, placeholder_key:, label_key:})
end

#find_locale_files(lang) ⇒ Object



140
141
142
# File 'lib/sidekiq/web/helpers.rb', line 140

def find_locale_files(lang)
  locale_files.select { |file| file =~ /\/#{lang}\.yml$/ }
end

#format_memory(rss_kb) ⇒ Object



405
406
407
408
409
410
411
412
413
414
415
# File 'lib/sidekiq/web/helpers.rb', line 405

def format_memory(rss_kb)
  return "0" if rss_kb.nil? || rss_kb == 0

  if rss_kb < 100_000
    "#{number_with_delimiter(rss_kb)} KB"
  elsif rss_kb < 10_000_000
    "#{number_with_delimiter((rss_kb / 1024.0).to_i)} MB"
  else
    "#{number_with_delimiter(rss_kb / (1024.0 * 1024.0), precision: 1)} GB"
  end
end

#get_localeObject



251
252
253
# File 'lib/sidekiq/web/helpers.rb', line 251

def get_locale
  strings(locale)
end

#h(text) ⇒ Object



422
423
424
425
426
427
428
# File 'lib/sidekiq/web/helpers.rb', line 422

def h(text)
  ::Rack::Utils.escape_html(text.to_s)
rescue ArgumentError => e
  raise unless e.message.eql?("invalid byte sequence in UTF-8")
  text.encode!("UTF-16", "UTF-8", invalid: :replace, replace: "").encode!("UTF-8", "UTF-16")
  retry
end

#job_params(job, score) ⇒ Object



331
332
333
# File 'lib/sidekiq/web/helpers.rb', line 331

def job_params(job, score)
  "#{score}-#{job["jid"]}"
end

#language_name(locale) ⇒ Object



144
145
146
# File 'lib/sidekiq/web/helpers.rb', line 144

def language_name(locale)
  strings(locale).fetch("LanguageName", locale)
end

#localeObject

Given an Accept-Language header like “fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2” this method will try to best match the available locales to the user’s preferred languages.



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/sidekiq/web/helpers.rb', line 216

def locale
  # session[:locale] is set via the locale selector from the footer
  @locale ||= if (l = session&.fetch(:locale, nil)) && available_locales.include?(l)
    l
  else
    matched_locale = nil
    # Attempt to find a case-insensitive exact match first
    user_preferred_languages.each do |preferred|
      # We only care about the language and primary subtag
      # "en-GB-oxendict" becomes "en-GB"
      language_tag = preferred.split("-")[0..1].join("-")
      matched_locale = available_locales.find { |available_locale| available_locale.casecmp?(language_tag) }
      break if matched_locale
    end

    return matched_locale if matched_locale

    # Find the first base language match
    # "en-US,es-MX;q=0.9" matches "en"
    user_preferred_languages.each do |preferred|
      base_language = preferred.split("-", 2).first
      matched_locale = available_locales.find { |available_locale| available_locale.casecmp?(base_language) }
      break if matched_locale
    end

    matched_locale || "en"
  end
end

#locale_filesObject



130
131
132
133
134
# File 'lib/sidekiq/web/helpers.rb', line 130

def locale_files
  @@locale_files ||= config.locales.flat_map { |path|
    Dir["#{path}/*.yml"]
  }
end

#number_with_delimiter(number, options = {}) ⇒ Object



417
418
419
420
# File 'lib/sidekiq/web/helpers.rb', line 417

def number_with_delimiter(number, options = {})
  precision = options[:precision] || 0
  %(<span data-nwp="#{precision}">#{number.round(precision)}</span>)
end

#parse_key(key) ⇒ Object



335
336
337
338
# File 'lib/sidekiq/web/helpers.rb', line 335

def parse_key(key)
  score, jid = key.split("-", 2)
  [score.to_f, jid]
end

#parse_yaml_new(path) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/sidekiq/web/helpers.rb', line 87

def parse_yaml_new(path)
  locale = nil
  map = {}
  IO.readlines(path, chomp: true).each do |line|
    case line
    when /\A\s*\#.*/
      # line comment
    when !locale && /\A([a-zA-Z\-_]+):/
      locale = $1
      map[locale] = {}
    when /\A\s+(\w+):\s+(.+)\z/
      # A few values have double quotes to include special characters in YAML.
      # Strip them off manually as our greedy match will include them.
      key = $1
      s = $2
      s = s[1..] if s[0] == "\""
      s = s[0..-2] if s[-1] == "\""
      map[locale][key] = s
    else
      raise ArgumentError, "unable to parse #{path}: #{line}"
    end
  end
  map
end

#parse_yaml_old(path) ⇒ Object

TODO Remove



82
83
84
85
# File 'lib/sidekiq/web/helpers.rb', line 82

def parse_yaml_old(path)
  require "yaml"
  YAML.safe_load_file(path)
end

#pollable?Boolean

Returns:

  • (Boolean)


456
457
458
459
# File 'lib/sidekiq/web/helpers.rb', line 456

def pollable?
  # there's no point to refreshing the metrics pages every N seconds
  !(current_path == "" || current_path.index("metrics"))
end

#processesObject



272
273
274
# File 'lib/sidekiq/web/helpers.rb', line 272

def processes
  @processes ||= Sidekiq::ProcessSet.new
end

#product_versionObject



448
449
450
# File 'lib/sidekiq/web/helpers.rb', line 448

def product_version
  "Sidekiq v#{Sidekiq::VERSION}"
end

#qparams(options) ⇒ Object

Merge options with current params, filter safe params, and stringify to query string



343
344
345
346
347
# File 'lib/sidekiq/web/helpers.rb', line 343

def qparams(options)
  stringified_options = options.transform_keys(&:to_s)

  to_query_string(request.params.merge(stringified_options))
end

#queue_names_by_capsule(pro) ⇒ Object



320
321
322
323
324
325
326
327
328
329
# File 'lib/sidekiq/web/helpers.rb', line 320

def queue_names_by_capsule(pro)
  cap = pro.capsules
  if cap
    cap.map { |k, v| v["weights"].keys.join(", ") }.join("; ")
  else
    # DEPRECATED Backwards compatibility with older processes.
    # 'capsules' element added in v8.0.9
    pro.queues.join(", ")
  end
end

#redirect_with_query(url) ⇒ Object

Any paginated list that performs an action needs to redirect back to the proper page after performing that action.



432
433
434
435
436
437
438
439
440
# File 'lib/sidekiq/web/helpers.rb', line 432

def redirect_with_query(url)
  r = request.referer
  if r && r =~ /\?/
    ref = URI(r)
    redirect("#{url}?#{ref.query}")
  else
    redirect url
  end
end

#redis_infoObject



299
300
301
# File 'lib/sidekiq/web/helpers.rb', line 299

def redis_info
  @info ||= Sidekiq.default_configuration.redis_info
end

#redis_urlObject



293
294
295
296
297
# File 'lib/sidekiq/web/helpers.rb', line 293

def redis_url
  Sidekiq.redis do |conn|
    conn.config.server_url
  end
end

#relative_time(time) ⇒ Object



315
316
317
318
# File 'lib/sidekiq/web/helpers.rb', line 315

def relative_time(time)
  stamp = time.getutc.iso8601
  %(<time class="ltr" dir="ltr" title="#{stamp}" datetime="#{stamp}">#{time}</time>)
end

#retry_extra_items(retry_job) ⇒ Object



397
398
399
400
401
402
403
# File 'lib/sidekiq/web/helpers.rb', line 397

def retry_extra_items(retry_job)
  @retry_extra_items ||= {}.tap do |extra|
    retry_job.item.each do |key, value|
      extra[key] = value unless RETRY_JOB_KEYS.include?(key)
    end
  end
end

#retry_or_delete_or_kill(job, params) ⇒ Object



461
462
463
464
465
466
467
468
469
# File 'lib/sidekiq/web/helpers.rb', line 461

def retry_or_delete_or_kill(job, params)
  if params["retry"]
    job.retry
  elsif params["delete"]
    job.delete
  elsif params["kill"]
    job.kill
  end
end

#root_pathObject



303
304
305
# File 'lib/sidekiq/web/helpers.rb', line 303

def root_path
  "#{env["SCRIPT_NAME"]}/"
end

#rtl?Boolean

Returns:

  • (Boolean)


194
195
196
# File 'lib/sidekiq/web/helpers.rb', line 194

def rtl?
  text_direction == "rtl"
end

#script_tag(location, **kwargs) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/sidekiq/web/helpers.rb', line 39

def script_tag(location, **kwargs)
  global = location.match?(/:\/\//)
  location = root_path + location if !global && !location.start_with?(root_path)
  attrs = {
    type: "text/javascript",
    nonce: csp_nonce,
    src: location
  }
  html_tag(:script, attrs.merge(kwargs)) {}
end

#search(jobset, substr) ⇒ Object



148
149
150
151
152
153
# File 'lib/sidekiq/web/helpers.rb', line 148

def search(jobset, substr)
  resultset = jobset.scan(substr).to_a
  @current_page = 1
  @count = @total_size = resultset.size
  resultset
end

#server_utc_timeObject



452
453
454
# File 'lib/sidekiq/web/helpers.rb', line 452

def server_utc_time
  Time.now.utc.strftime("%H:%M:%S UTC")
end

#singularize(str, count) ⇒ Object



116
117
118
119
120
121
122
# File 'lib/sidekiq/web/helpers.rb', line 116

def singularize(str, count)
  if count == 1 && str.respond_to?(:singularize) # rails
    str.singularize
  else
    str
  end
end

#sort_direction_labelObject



264
265
266
# File 'lib/sidekiq/web/helpers.rb', line 264

def sort_direction_label
  (url_params("direction") == "asc") ? "&uarr;" : "&darr;"
end

#sorted_processesObject

Sorts processes by hostname following the natural sort order



277
278
279
280
281
282
283
284
285
286
287
# File 'lib/sidekiq/web/helpers.rb', line 277

def sorted_processes
  @sorted_processes ||= begin
    return processes unless processes.all? { |p| p["hostname"] }

    processes.to_a.sort_by do |process|
      # Kudos to `shurikk` on StackOverflow
      # https://stackoverflow.com/a/15170063/575547
      process["hostname"].split(/(\d+)/).map { |a| /\d+/.match?(a) ? a.to_i : a }
    end
  end
end

#statsObject



289
290
291
# File 'lib/sidekiq/web/helpers.rb', line 289

def stats
  @stats ||= Sidekiq::Stats.new
end

#store_nameObject



10
11
12
13
14
15
# File 'lib/sidekiq/web/helpers.rb', line 10

def store_name
  hash = redis_info
  return "Dragonfly" if hash.has_key?("dragonfly_version")
  return "Valkey" if hash.has_key?("valkey_version")
  "Redis"
end

#store_versionObject



17
18
19
20
21
22
# File 'lib/sidekiq/web/helpers.rb', line 17

def store_version
  hash = redis_info
  return hash["dragonfly_version"] if hash.has_key?("dragonfly_version")
  return hash["valkey_version"] if hash.has_key?("valkey_version")
  hash["redis_version"]
end

#strings(lang) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/sidekiq/web/helpers.rb', line 68

def strings(lang)
  @@strings ||= {}

  # Allow sidekiq-web extensions to add locale paths
  # so extensions can be localized
  @@strings[lang] ||= config.locales.each_with_object({}) do |path, global|
    find_locale_files(lang).each do |file|
      strs = parse_yaml_new(file)
      global.merge!(strs[lang])
    end
  end
end

#style_tag(location, **kwargs) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/sidekiq/web/helpers.rb', line 24

def style_tag(location, **kwargs)
  global = location.match?(/:\/\//)
  location = root_path + location if !global && !location.start_with?(root_path)
  attrs = {
    type: "text/css",
    media: "screen",
    rel: "stylesheet",
    nonce: csp_nonce,
    href: location
  }
  add_to_head do
    html_tag(:link, attrs.merge(kwargs))
  end
end

#t(msg, options = {}) ⇒ Object



255
256
257
258
259
260
261
262
# File 'lib/sidekiq/web/helpers.rb', line 255

def t(msg, options = {})
  string = get_locale[msg] || strings("en")[msg] || msg
  if options.empty?
    string
  else
    string % options
  end
end

#text_directionObject



190
191
192
# File 'lib/sidekiq/web/helpers.rb', line 190

def text_direction
  get_locale["TextDirection"] || "ltr"
end

#to_display(arg) ⇒ Object



380
381
382
383
384
385
386
387
388
# File 'lib/sidekiq/web/helpers.rb', line 380

def to_display(arg)
  arg.inspect
rescue
  begin
    arg.to_s
  rescue => ex
    "Cannot display argument: [#{ex.class.name}] #{ex.message}"
  end
end

#to_json(x) ⇒ Object



112
113
114
# File 'lib/sidekiq/web/helpers.rb', line 112

def to_json(x)
  Sidekiq.dump_json(x)
end

#to_query_string(hash) ⇒ Object



349
350
351
352
353
# File 'lib/sidekiq/web/helpers.rb', line 349

def to_query_string(hash)
  hash.map { |key, value|
    SAFE_QPARAMS.include?(key) ? "#{key}=#{CGI.escape(value.to_s)}" : next
  }.compact.join("&")
end

#truncate(text, truncate_after_chars = 2000) ⇒ Object



355
356
357
# File 'lib/sidekiq/web/helpers.rb', line 355

def truncate(text, truncate_after_chars = 2000)
  (truncate_after_chars && text.size > truncate_after_chars) ? "#{text[0..truncate_after_chars]}..." : text
end

#unfiltered?Boolean

sidekiq/sidekiq#3243

Returns:

  • (Boolean)


246
247
248
249
# File 'lib/sidekiq/web/helpers.rb', line 246

def unfiltered?
  s = url_params("substr")
  yield unless s && s.size > 0
end

#user_preferred_languagesObject

See www.rfc-editor.org/rfc/rfc9110.html#section-12.5.4 Returns an array of language tags ordered by their quality value

Inspiration taken from github.com/iain/http_accept_language/blob/master/lib/http_accept_language/parser.rb



202
203
204
205
206
207
208
209
210
211
212
# File 'lib/sidekiq/web/helpers.rb', line 202

def user_preferred_languages
  languages = env["HTTP_ACCEPT_LANGUAGE"]
  languages.to_s.gsub(/\s+/, "").split(",").map { |language|
    locale, quality = language.split(";q=", 2)
    locale = nil if locale == "*" # Ignore wildcards
    quality = quality ? quality.to_f : 1.0
    [locale, quality]
  }.sort { |(_, left), (_, right)|
    right <=> left
  }.map(&:first).compact
end

#worksetObject



268
269
270
# File 'lib/sidekiq/web/helpers.rb', line 268

def workset
  @work ||= Sidekiq::WorkSet.new
end