Class: Sidekiq::TUI

Inherits:
Object
  • Object
show all
Includes:
Component
Defined in:
lib/sidekiq/tui.rb,
lib/sidekiq/tui/tabs.rb,
lib/sidekiq/tui/controls.rb,
lib/sidekiq/tui/filtering.rb,
lib/sidekiq/tui/tabs/busy.rb,
lib/sidekiq/tui/tabs/dead.rb,
lib/sidekiq/tui/tabs/home.rb,
lib/sidekiq/tui/tabs/queues.rb,
lib/sidekiq/tui/tabs/metrics.rb,
lib/sidekiq/tui/tabs/retries.rb,
lib/sidekiq/tui/tabs/set_tab.rb,
lib/sidekiq/tui/tabs/base_tab.rb,
lib/sidekiq/tui/tabs/scheduled.rb

Defined Under Namespace

Modules: Controls, Filtering, Tabs Classes: BaseTab, PageOptions

Constant Summary collapse

REFRESH_INTERVAL_SECONDS =
2
LOCALE_DIRECTORIES =
[File.expand_path("#{File.dirname(__FILE__)}/../../web/locales")]

Instance Attribute Summary collapse

Attributes included from Component

#config

Instance Method Summary collapse

Methods included from Component

#default_tag, #fire_event, #handle_exception, #hostname, #identity, #inspect, #logger, #mono_ms, #process_nonce, #real_ms, #redis, #safe_thread, #tid, #watchdog

Constructor Details

#initialize(cfg, language: ENV["LANG"] || "en") ⇒ TUI

language is meant to be a locale code, e.g. LANG=en_US.utf-8



28
29
30
31
32
33
34
35
36
# File 'lib/sidekiq/tui.rb', line 28

def initialize(cfg, language: ENV["LANG"] || "en")
  @lang = language
  @config = cfg
  @base_style = nil
  @last_refresh = Time.at(0)
  @fps = Array.new(2) { 0 }
  @previous_fps = 0
  @showing = :main
end

Instance Attribute Details

#langObject (readonly)

Returns the value of attribute lang.



24
25
26
# File 'lib/sidekiq/tui.rb', line 24

def lang
  @lang
end

Instance Method Details

#allObject



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

def all
  @all ||= Tabs::All.map { |kls| kls.new(self) }
end

#available_localesObject



343
344
345
# File 'lib/sidekiq/tui.rb', line 343

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

#controls_line(keys) ⇒ Object



227
228
229
230
231
232
233
234
# File 'lib/sidekiq/tui.rb', line 227

def controls_line(keys)
  @tui.text_line(spans: keys.map { |hash|
    [
      @tui.text_span(content: hash[:display] || hash[:code], style: @hotkey_style),
      @tui.text_span(content: ": #{t(hash[:description])}  ")
    ]
  }.flatten)
end

#current_tabObject



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

def current_tab
  @current ||= @all.first
end

#debugging?Boolean

Returns:

  • (Boolean)


386
387
388
# File 'lib/sidekiq/tui.rb', line 386

def debugging?
  !!ENV["DEBUG"]
end

#find_locale_files(lang) ⇒ Object



347
348
349
# File 'lib/sidekiq/tui.rb', line 347

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

#handle_inputObject



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/sidekiq/tui.rb', line 236

def handle_input
  # We shouldn't need more than 10 FPS for a data-oriented app.
  # This throttles down our CPU usage. Default is 60 FPS.
  case @tui.poll_event(timeout: 0.1)
  in {type: :key, code: "esc"} if @showing == :help
    @showing = :main
  in {type: :key, code: code} if current_tab.filtering? && code.length == 1
    current_tab.append_to_filter(code)
    current_tab.refresh_data
  in {type: :key, code:, modifiers:}
    control = current_tab.controls.find { |ctrl|
      ctrl[:code] == code &&
        (ctrl[:modifiers] || []) == (modifiers || [])
    }
    return unless control
    control[:action].call(self, current_tab).tap {
      refresh_data if control[:refresh]
    }
  else
    # Ignore other events
  end
rescue => ex
  logger.error { [ex.message, ex.backtrace] }
end

#hotkey_line(key, description) ⇒ Object



220
221
222
223
224
225
# File 'lib/sidekiq/tui.rb', line 220

def hotkey_line(key, description)
  @tui.text_line(spans: [
    @tui.text_span(content: key, style: @hotkey_style),
    @tui.text_span(content: ": #{description}")
  ])
end

#load_localeObject



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/sidekiq/tui.rb', line 351

def load_locale
  require "yaml"
  lang = @lang.split(".").first # "en_US"
  while lang.size > 0
    hash = load_strings(lang)
    if hash.size > 0
      # found a working language dataset
      @lang = lang
      @strings = hash
      Sidekiq.logger.debug { "using the #{lang} locale" }
      break
    end
    # Try "en_US", "en_U", "en_", "en"
    # It's ugly and bruteforce but it works
    lang = lang[..-2]
  end
end

#load_strings(lang) ⇒ Object



328
329
330
331
332
333
334
335
# File 'lib/sidekiq/tui.rb', line 328

def load_strings(lang)
  {}.tap do |all|
    find_locale_files(lang).each do |file|
      strs = YAML.safe_load_file(file)
      all.merge! strs[lang]
    end
  end
end

#locale_filesObject



337
338
339
340
341
# File 'lib/sidekiq/tui.rb', line 337

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

Navigate tabs to the left or right.

Parameters:

  • direction (Symbol)

    :left or :right



313
314
315
316
317
# File 'lib/sidekiq/tui.rb', line 313

def navigate(direction)
  index_change = (direction == :right) ? 1 : -1
  @current = @all[(@all.index(current_tab) + index_change) % @all.size]
  @current.reset_data
end

#prepare(tui) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/sidekiq/tui.rb', line 38

def prepare(tui)
  load_locale

  @tui = tui
  @highlight_style = @tui.style(fg: :light_red, modifiers: [:underlined])
  @hotkey_style = @tui.style(modifiers: [:bold, :underlined])
  # eager load tabs
  all
end

#previous_fpsObject



376
377
378
379
380
381
382
383
384
# File 'lib/sidekiq/tui.rb', line 376

def previous_fps
  curidx = Time.now.to_i % 2
  prev = (curidx == 1) ? 0 : 1
  if (val = @fps[prev]) != 0
    @previous_fps = val
    @fps[prev] = 0
  end
  @previous_fps
end

#redis_urlObject



261
262
263
264
265
266
267
# File 'lib/sidekiq/tui.rb', line 261

def redis_url
  Sidekiq.redis do |conn|
    conn.config.server_url
  end
rescue
  "N/A"
end

#refresh_dataObject



273
274
275
276
277
278
279
280
# File 'lib/sidekiq/tui.rb', line 273

def refresh_data
  # logger.info GC.stat
  current_tab.refresh_data
  @last_refresh = Time.now
rescue => e
  handle_exception(e)
  current_tab.error = e
end

#renderObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/sidekiq/tui.rb', line 59

def render
  track_fps do
    if @showing == :main
      @tui.draw do |frame|
        main_area, controls_area = @tui.layout_split(
          frame.area,
          direction: :vertical,
          constraints: [
            @tui.constraint_fill(1),
            @tui.constraint_length(5)
          ]
        )

        # Split main area into tabs and content
        tabs_area, content_area = @tui.layout_split(
          main_area,
          direction: :vertical,
          constraints: [
            @tui.constraint_length(3),
            @tui.constraint_fill(1)
          ]
        )

        all_tabs = all
        tabs = @tui.tabs(
          titles: all_tabs.map { |tab| t(tab.name) },
          selected_index: all_tabs.index(current_tab),
          block: @tui.block(title: " #{Sidekiq::NAME}", borders: [:all], title_style: @tui.style(fg: :light_red, modifiers: [:bold])),
          divider: " | ",
          highlight_style: @highlight_style,
          style: @base_style
        )
        frame.render_widget(tabs, tabs_area)

        render_content_area(frame, content_area)
        render_controls(frame, controls_area)
      end
    end

    if @showing == :help
      @tui.draw do |frame|
        main_area, controls_area = @tui.layout_split(
          frame.area,
          direction: :vertical,
          constraints: [
            @tui.constraint_fill(1),
            @tui.constraint_length(4)
          ]
        )

        help_data = [
          ["Esc", "Close this window"],
          ["←/→", "Move between tabs"],
          ["h/l", "Move to prev/next page of data"],
          ["j/k", "Move to prev/next row in current page"],
          ["x", "Select/deselect current row"],
          ["A", "Select/deselect All rows in current page"],
          ["q", "Quit"]
        ]

        # striped styling like other tables in the app
        help_rows = help_data.map.with_index { |cells, idx|
          @tui.table_row(
            cells: cells,
            style: idx.even? ? nil : @tui.style(bg: :dark_gray)
          )
        }

        table = @tui.table(
          block: @tui.block(
            title: " #{Sidekiq::NAME} - Welcome to the Sidekiq Terminal UI ",
            borders: [:all],
            title_style: @tui.style(fg: :light_red, modifiers: [:bold])
          ),
          header: ["Key", "Action"],
          rows: help_rows,
          widths: [
            @tui.constraint_length(15),
            @tui.constraint_fill(1)
          ],
          column_spacing: 1
        )
        frame.render_widget(table, main_area)
        controls = @tui.block(
          title: t("Controls"),
          borders: [:all],
          children: [
            @tui.paragraph(
              text: [hotkey_line("Esc", "Close  ")]
            )
          ]
        )
        frame.render_widget(controls, controls_area)
      end
    end
  end
end

#render_content_area(frame, content_area) ⇒ Object



157
158
159
160
161
# File 'lib/sidekiq/tui.rb', line 157

def render_content_area(frame, content_area)
  return render_error(frame, content_area, current_tab.error) if current_tab.error

  current_tab.render(@tui, frame, content_area)
end

#render_controls(frame, area) ⇒ Object



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/sidekiq/tui.rb', line 163

def render_controls(frame, area)
  active_keys = current_tab.controls.filter { |hash| hash[:description] }

  # Dynamically split controls based on terminal width
  # Estimate space needed: each control needs ~key_length + description_length + 4 chars for ": " and spacing
  available_width = area.width - 4 # Account for borders

  lines = []
  current_line = []
  current_width = 0

  active_keys.each do |hash|
    # Estimate control width: key + ": " + description + "  " (spacing)
    key_text = hash[:display] || hash[:code]
    control_width = key_text.length + 2 + t(hash[:description]).length + 2

    if current_width + control_width > available_width && !current_line.empty?
      # Start a new line
      lines << controls_line(current_line)
      current_line = [hash]
      current_width = control_width
    else
      current_line << hash
      current_width += control_width
    end
  end

  # Add the last line
  lines << controls_line(current_line) unless current_line.empty?

  # Ensure we have at least 2 lines for layout consistency
  while lines.length < 2
    lines << @tui.text_line(spans: [])
  end

  footer = [
    @tui.text_span(content: "Redis: #{redis_url}    "),
    @tui.text_span(content: "#{t("Now")}: #{Time.now.utc}    "),
    @tui.text_span(content: "#{t("Locale")}: #{@lang}")
  ]

  if current_tab.data[:filter]
    @filter_style = @tui.style(fg: :white, bg: :dark_gray)
    footer += [
      @tui.text_span(content: "   #{t("Filter")}: ", style: @filter_style),
      @tui.text_span(content: current_tab.data[:filter], style: @filter_style),
      @tui.text_span(content: "_", style: @tui.style(fg: :white, bg: :dark_gray, modifiers: [:slow_blink]))
    ]
  end
  footer << @tui.text_span(content: "  FPS: #{previous_fps}") if debugging?
  lines << @tui.text_line(spans: footer)

  controls = @tui.block(title: t("Controls"), borders: [:all],
    children: [@tui.paragraph(text: lines)])
  frame.render_widget(controls, area)
end

#render_error(frame, area, err) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/sidekiq/tui.rb', line 282

def render_error(frame, area, err)
  header = [@tui.text_line(
    spans: [@tui.text_span(content: err.message, style: @tui.style(modifiers: [:bold]))],
    alignment: :center
  )]
  lines = Array(err.backtrace).map { |line| @tui.text_line(spans: [@tui.text_span(content: line)]) }

  frame.render_widget(
    @tui.paragraph(
      text: header + lines,
      alignment: :left,
      block: @tui.block(title: t("Error"), borders: [:all], border_style: @tui.style(fg: :light_red))
    ),
    area
  )
end

#run_loopObject



48
49
50
51
52
53
54
55
56
57
# File 'lib/sidekiq/tui.rb', line 48

def run_loop
  # Must log to a file, terminal is now controlled by Ratatui
  config.logger = Logger.new("tui.log")

  loop do
    refresh_data if should_refresh?
    render
    break if handle_input == :quit
  end
end

#should_refresh?Boolean

Returns:

  • (Boolean)


269
270
271
# File 'lib/sidekiq/tui.rb', line 269

def should_refresh?
  Time.now - @last_refresh >= REFRESH_INTERVAL_SECONDS
end

#show_helpObject



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

def show_help
  @showing = :help
end

#t(msg, options = nil) ⇒ Object



319
320
321
322
323
324
325
326
# File 'lib/sidekiq/tui.rb', line 319

public def t(msg, options = nil)
  string = @strings[msg] || msg
  if options.nil?
    string
  else
    string % options
  end
end

#track_fpsObject



369
370
371
372
373
374
# File 'lib/sidekiq/tui.rb', line 369

def track_fps
  # We hold two fps buckets: one for current second, one for previous second
  idx = Time.now.to_i % 2
  @fps[idx] += 1
  yield
end