module ApplicationHelper
View helpers shared across the application, covering theme selection, permission checks, badge classes, navigation, and formatting.
Constants
- ENGINE_LIFECYCLE_STAGES
-
Ordered lifecycle stages for the engine stepper.
- EngineSession
-
One engine session (generation): a single provisioning → ready → drain →stop cycle. Durations are derived from the lifecycle transition timestamps; a nil field means the transition fell outside the query window and is rendered as “—” rather than a fabricated number.
- OPERATION_METRICS
-
Metrics that each operation actually moves, used to scope the diff display.
- STEP_LABELS
Public Instance Methods
Source
# File app/helpers/application_helper.rb, line 119 def active_path?(path) current = request.path return current == path || current == "#{path}/" if path == "/" current == path || current.start_with?(path.end_with?("/") ? path : "#{path}/") end
Compares a nav target against the current path. “/” matches only the root (otherwise every page would look selected); other paths match by prefix so nested actions stay highlighted on their section. @param path [String] the nav target to compare against the request path. @return [Boolean] true when the current path matches the target.
Source
# File app/helpers/application_helper.rb, line 23 def can_cancel_query? respond_to?(:current_user) && current_user && (current_user.admin? || current_user.operator?) end
Whether the current user may cancel queries and queued executions. @return [Boolean] true for admins and operators.
Source
# File app/helpers/application_helper.rb, line 17 def can_run_maintenance? current_user&.admin? || current_user&.operator? end
Operators may trigger maintenance runs; everything else that mutates a plan stays admin-only. @return [Boolean] true when the current user is an admin or an operator.
Source
# File app/helpers/application_helper.rb, line 130 def compact_number(number) n = number.to_i case n when 0...1_000 then n.to_s when 1_000...10_000 then format("%.1fk", n / 1000.0).sub(".0k", "k") else format("%.0fk", n / 1000.0) end end
1234 -> “1k”, 1234_500 -> “1.2k”, 10_000 -> “10k”. Used for the sidebar counters so big lakes stay readable. @param number [Numeric] the number to compact. @return [String] the compacted, human-readable number.
Source
# File app/helpers/application_helper.rb, line 226 def duration_label(seconds) return nil if seconds.nil? seconds = seconds.to_i if seconds < 60 "#{seconds}s" elsif seconds < 3600 "#{(seconds / 60).round} min" else "#{(seconds / 3600.0).round(1)} h" end end
Formats a duration in seconds as a short human label (e.g. “45s”, “12 min”, “1.5 h”). Returns nil when given nil. @param seconds [Numeric, nil] the duration in seconds. @return [String, nil] the formatted duration, or nil when seconds is nil.
Source
# File app/helpers/application_helper.rb, line 453 def engine_coordinator_target TrinoProvisioner.target rescue Kubeclient::HttpError, Kubeclient::ResourceNotFoundError, KeyError, SocketError, Timeout::Error t("activity.engine.title") end
Coordinator Deployment target (namespace/name) for the engine strip subtitle and the engine history panel header.
Resolved through the provisioner, so the adapter in use decides - the strip and the history panel used to resolve the same value through two different paths (TrinoK8sClient directly vs. TrinoProvisioner), one of which raised.
The rescue is deliberately narrow: an unreachable API or a missing Deployment is expected and falls back to a label, but a NoMethodError is a programming error and must not be swallowed - a bare rescue StandardError here hid a missing target on every provisioner adapter.
@return [String] the deployment target or a fallback label.
Source
# File app/helpers/application_helper.rb, line 420 def engine_deadline(state) case state.status when "starting" (state.status_changed_at + TrinoEngineSupervisor::READY_TIMEOUT).iso8601 when "draining" (state.drain_started_at + TrinoEngineSupervisor::DRAIN_GRACE).iso8601 end end
Returns the deadline ISO8601 timestamp for the current engine phase, or nil when no deadline exists (steady states like up/down). @param state [TrinoEngineState] the current engine state. @return [String, nil] ISO8601 timestamp or nil.
# File app/helpers/application_helper.rb, line 265 def engine_event_generation(event) gen = event.context["generation"] return gen if gen.presence event.message.to_s[/generation (\d+)/, 1] end
The generation of a lifecycle event, from context or parsed from the legacy message. @param event [ErrorEvent] the lifecycle event. @return [String, nil] the generation, or nil when unknown.
Source
# File app/helpers/application_helper.rb, line 254 def engine_event_label(event) state = event.context["state"] return state if state.presence event.message.to_s.sub(/\Aengine /, "").split(" (", 2).first.presence || event.context["generation"] || "—" end
The engine state of a lifecycle event, from its structured context when present, otherwise parsed from the legacy “engine <state> (generation N)” message. @param event [ErrorEvent] the lifecycle event. @return [String] the state label.
Source
# File app/helpers/application_helper.rb, line 311 def engine_failed_stage(state) return nil unless state.status == "failed" || state.last_error.present? "starting" end
The stage that was in flight when a start failed, so the stepper can leave that segment red instead of reverting the whole line to inert grey.
A failed engine never reached up, so the segment that was running is the one leaving starting.
@param state [TrinoEngineState] the current engine state. @return [String, nil] the stage, or nil when nothing failed.
# File app/helpers/application_helper.rb, line 341 def engine_lifecycle_stepper(status, timer: false, failed_at: nil, idle: false) stages = ENGINE_LIFECYCLE_STAGES active_index = stages.index(status) || 0 countdown = %w[starting draining stopping].include?(status) capture do stages.each_with_index do |stage, i| step = [ "step", "step--#{stage}" ] step << "done" if i < active_index step << "active" if i == active_index step << "idle" if idle && i == active_index step << "failed" if failed_at == stage concat content_tag(:span, safe_join([ content_tag(:span, "", class: "step-dot"), content_tag(:span, t("activity.engine.stage_#{stage}")) ]), class: step.join(" ")) next if i == stages.length - 1 link = [ "step-link", "step-link--#{stage}" ] if i < active_index # A passed connector keeps its own stage's colour at full width. link << "done" elsif failed_at == stage # The segment that was in flight when the start failed stays red at # the width it reached. link << "failed" elsif i == active_index && countdown link << "progress" link << "bar-warn" if status == "draining" # Only stopping has no measurable duration to fill against. link << "indeterminate" if status == "stopping" elsif i == active_index && idle link << "resting" end options = { class: link.join(" ") } options[:data] = { engine_timer_target: "bar" } if link.include?("progress") && timer concat content_tag(:span, "", options) end end end
Renders the lifecycle stepper: stage nodes (dot + label) joined by full-width connectors.
Each passed connector holds the colour of the stage it represents at full width, so the line ACCUMULATES and “how far did it get” stays readable, including after the fact. Previously every completed connector was painted one neutral grey, so the line neither grew with the lifecycle nor said anything about it.
The in-flight connector fills against the median duration of that phase (see engine_phase_estimates), not against the timeout. The timeout still matters, but as an APPEARANCE change - the JS controller switches to a warning treatment past the estimate and to a failure treatment at the deadline - rather than as the denominator.
idle is not stage zero: with the engine scaled to zero and nothing waiting, the line renders as resting rather than as “stuck at the first stage”, which is the state an operator sees most often.
@param status [String] the current engine status. @param timer [Boolean] whether to wire the progress connector to the timer. @param failed_at [String, nil] the stage that was in flight when a start failed. @param idle [Boolean] whether the engine is at rest with no demand. @return [String] HTML-safe stepper markup.
# File app/helpers/application_helper.rb, line 398 def engine_phase_detail(state, queries: 0) case state.status when "up" t("activity.engine.up_detail", queries: queries) when "starting" attempt = [ state.start_attempts, 1 ].max t("activity.engine.starting_detail", attempt: attempt, max: TrinoEngineSupervisor::MAX_START_ATTEMPTS) when "draining" t("activity.engine.draining_detail") when "stopping" t("activity.engine.stopping_detail") when "failed" t("activity.engine.failed_detail", error: state.last_error.presence || "unknown") else t("activity.engine.down") end end
Phase detail line below the stepper. @param state [TrinoEngineState] the current engine state. @param queries [Integer] the number of active queries on the cluster. @return [String] the translated detail text.
# File app/helpers/application_helper.rb, line 536 def engine_phase_estimates(sessions) { starting: median(sessions.reject(&:running?).filter_map(&:ready_seconds)), draining: median(sessions.reject(&:running?).filter_map(&:drain_seconds)) } end
Median duration of each timed phase, from the sessions already reconstructed for the history panel.
This is the denominator the stepper fills against. Filling against the TIMEOUT instead made a healthy ~22s start render as ~5% of an 8-minute bar and then jump to up, so a normal start looked stalled and a bar near 100% meant “about to fail” - the opposite of the usual reading.
Only completed sessions contribute: a running one has no final duration. Returns nil per phase when nothing has completed yet, so the caller can fall back to an honest indeterminate rather than to a fabricated estimate.
@param sessions [Array<EngineSession>] the reconstructed sessions @return [Hash{Symbol => Float, nil}] median seconds per phase
Source
# File app/helpers/application_helper.rb, line 386 def engine_phase_time(state) case state.status when "up" then t("activity.engine.uptime", time: time_ago_in_words(state.status_changed_at)) when "starting" then t("activity.engine.time_before_timeout", time: distance_of_time_in_words_to_now(state.status_changed_at + TrinoEngineSupervisor::READY_TIMEOUT)) when "draining" then t("activity.engine.stops_in", time: distance_of_time_in_words_to_now(state.drain_started_at + TrinoEngineSupervisor::DRAIN_GRACE)) end end
The phase time for the engine detail row: remaining time for the timed states, uptime for the up state, nothing otherwise. @param state [TrinoEngineState] the current engine state. @return [String, nil] the translated time text.
Source
# File app/helpers/application_helper.rb, line 498 def engine_sessions(events) ordered = events.sort_by(&:last_seen_at) groups = [] current = nil ordered.each do |event| if event.context&.dig("state") == "starting" groups << current if current current = [ event ] elsif current current << event else # The window opened mid-session (no starting transition in the slice). current = [ event ] end end groups << current if current groups .map { |group| build_engine_session(session_generation(group), group) } .sort_by { |session| session.started_at || Time.at(0) } .reverse end
Groups engine lifecycle transitions into one session per engine run, newest first. A session is delimited by its “starting” transition — the generation counter is bumped on EVERY transition (it is the CAS guard’s predicate), so grouping by generation would split one start→ready→drain→stop cycle into four one-event sessions and show clean shutdowns as failed.
@param events [Array<ErrorEvent>] lifecycle events ordered by last_seen_at desc @return [Array<EngineSession>] the sessions, newest first
# File app/helpers/application_helper.rb, line 276 def engine_status_badge_class(status) case status when "up" then "badge-healthy" when "starting" then "badge-warning" when "draining" then "badge-running" when "stopping" then "badge-warn" when "failed" then "badge-critical" else "badge-neutral" end end
Badge class for a given engine status, so each lifecycle state gets its own colour in the engine strip and history table. @param status [String, nil] the engine status. @return [String] a badge-* CSS class.
Source
# File app/helpers/application_helper.rb, line 290 def engine_status_label(state) case state.status when "up" then t("activity.engine.up", time: time_ago_in_words(state.status_changed_at)) when "starting" then t("activity.engine.starting", attempt: [ state.start_attempts, 1 ].max, max: TrinoEngineSupervisor::MAX_START_ATTEMPTS) when "draining" then t("activity.engine.draining", time: distance_of_time_in_words_to_now(state.drain_started_at + TrinoEngineSupervisor::DRAIN_GRACE)) when "failed" then t("activity.engine.failed") else t("activity.engine.down") end end
Human label for the current engine status, with its time/re-attempt context. @param state [TrinoEngineState] the current engine state. @return [String] the translated label.
Source
# File app/helpers/application_helper.rb, line 475 def engine_target_label = engine_coordinator_target
Coordinator Deployment identifier for engine-sourced events. @return [String] e.g. “trino/production-coordinator”
Source
# File app/helpers/application_helper.rb, line 432 def engine_timer_mode(status) case status when "starting", "draining" then "countdown" when "up" then "uptime" else "none" end end
Timer mode for the Stimulus controller based on engine status. @param status [String] the current engine status. @return [String] “countdown”, “uptime”, or “none”.
# File app/helpers/application_helper.rb, line 67 def execution_status_badge_class(status) case status.to_s when "success" then "badge-ok" when "failed" then "badge-err" when "running" then "badge-running" when "skipped" then "badge-warning" else "badge-pending" end end
Maps an execution status to its badge CSS class. @param status [String, Symbol] the execution status. @return [String] the badge class for the status.
# File app/helpers/application_helper.rb, line 107 def execution_visual_state(execution) return :failed if execution.status == "failed" return :retrying if execution.retrying? :running end
Visual state of an execution. Returns :retrying, :failed or :running. A running execution with a positive retry count still has a dispatch retry in flight - its own demand keeps the engine up.
# File app/helpers/application_helper.rb, line 702 def format_metric_value(key, value) return "—" if value.nil? case key when "total_size_bytes" then number_to_human_size(value) when "oldest_snapshot_at" then value.is_a?(String) ? Time.parse(value).to_fs(:short) : value.to_fs(:short) else number_with_delimiter(value) end end
Formats a metric value for display.
Source
# File app/helpers/application_helper.rb, line 55 def health_badge_class(status) case status.to_s when "healthy" then "badge-ok" when "warning" then "badge-warn" when "critical" then "badge-err" else "badge-mute" end end
Maps a table health status to its badge CSS class. @param status [String, Symbol] the health status. @return [String] the badge class for the status.
Source
# File app/helpers/application_helper.rb, line 8 def html_theme return @theme if @theme.in?(%w[light dark]) %w[light dark].include?(cookies[:theme]) ? cookies[:theme] : "dark" end
Selected theme for the <html data-theme> attribute. Dark is the default; the theme toggle (CR-69) persists it on the account. The cookie is kept as a fallback for the anonymous/auth screens, where there is no signed-in user. @return [String] “light” or “dark”.
Source
# File app/helpers/application_helper.rb, line 547 def median(values) return nil if values.empty? sorted = values.sort middle = sorted.size / 2 sorted.size.odd? ? sorted[middle].to_f : ((sorted[middle - 1] + sorted[middle]) / 2.0) end
The median of a list of numbers, or nil when empty.
@param values [Array<Numeric>] the values @return [Float, nil] the median
Source
# File app/helpers/application_helper.rb, line 582 def metadata_diff(execution) before = execution.metadata_before after = execution.metadata_after return nil if before.nil? || after.nil? operations = execution.execution_steps.pluck(:operation).uniq rows = table_metric_rows(operations, before, after) rows += step_metric_rows(execution) return nil if rows.empty? content_tag(:div, class: "metadata-diff") do rows.map { |row| render_diff_row(row) }.reduce(:+) end end
Renders a before/after metadata diff for a maintenance execution.
Two complementary layers, rendered together (see #196): * the table-level metric diff, INCLUDING unchanged metrics — “4689 → 4689” after an optimize is itself the finding (the compaction achieved nothing); * what the steps themselves reported (row counts, batched statements). Only an operation with no tracked metric produces silence.
@param execution [ExecutionHistory] the execution with before/after snapshots @return [ActiveSupport::SafeBuffer, nil] the rendered diff, or nil when not available
# File app/helpers/application_helper.rb, line 176 def pager_arrow(path, glyph, enabled:) if enabled link_to(glyph.html_safe, path, class: "badge badge-mute pager-page", rel: "prev-next") else content_tag(:span, glyph.html_safe, class: "badge badge-mute pager-page pager-disabled") end end
Prev/next arrow; renders an inert dimmed span when disabled.
Source
# File app/helpers/application_helper.rb, line 170 def pagy_page_path(page) params = request.query_parameters.merge("page" => page) "#{request.path}?#{params.to_query}" end
Path to one pager page preserving every current query param.
# File app/helpers/application_helper.rb, line 30 def query_state_badge_class(state) case state.to_s when "RUNNING" then "badge-running" when "QUEUED" then "badge-warn" when "FINISHED", "FINISHING" then "badge-ok" when "FAILED" then "badge-err" else "badge-mute" end end
Maps a Trino query state to its badge CSS class. @param state [String, nil] the Trino query state. @return [String] the badge class for the state.
Source
# File app/helpers/application_helper.rb, line 637 def render_delta(delta) return content_tag(:span, "=", class: "metadata-diff-delta is-flat") if delta.nil? direction, magnitude = delta.values_at(:direction, :magnitude) glyph, css = case direction when :down then [ "↓", "is-down" ] when :up then [ "↑", "is-up" ] else [ nil, "is-new" ] end text = direction == :new ? magnitude.to_s : [ glyph, magnitude ].compact.join(" ") content_tag(:span, text, class: "metadata-diff-delta #{css}") end
Renders the delta cell with its direction.
ALWAYS emits a cell. The row is a five-column grid with display: contents, so there is no row box to absorb a missing cell - returning nil let the next row’s cells auto-place into the gap and shifted every column. An unchanged metric is also the common case, so dropping the cell meant the direction classes (is-down/is-up/is-new) were never rendered at all.
@param delta [Hash, nil] { direction:, magnitude: } or nil for unchanged @return [ActiveSupport::SafeBuffer] the delta cell
Source
# File app/helpers/application_helper.rb, line 604 def render_diff_row(row) label, old_val, new_val, delta = row if old_val.nil? && new_val.is_a?(String) content_tag(:div, class: "metadata-diff-row is-summary") do safe_join([ content_tag(:span, label, class: "metadata-diff-label"), content_tag(:span, new_val, class: "metadata-diff-new") ]) end else content_tag(:div, class: "metadata-diff-row") do safe_join([ content_tag(:span, label, class: "metadata-diff-label"), content_tag(:span, format_metric_value(key_for(label), old_val), class: "metadata-diff-old"), content_tag(:span, "→", class: "metadata-diff-arrow"), content_tag(:span, format_metric_value(key_for(label), new_val), class: "metadata-diff-new"), render_delta(delta) ]) end end end
Renders one diff row. A step-metric summary row (old == nil, summary in the new slot) spans the value columns; a table-metric row emits the five grid cells (label · old · → · new · delta) so columns align across rows.
@param row [Array] [label, old, new, delta] @return [ActiveSupport::SafeBuffer] the row
Source
# File app/helpers/application_helper.rb, line 560 def session_generation(events) events.map { |e| e.context&.dig("generation").to_i }.reject(&:zero?).min || 0 end
The generation label of a session: the generation of its starting transition, falling back to the oldest event when the slice lacks one.
@param events [Array<ErrorEvent>] the session’s events @return [Integer] the session generation
Source
# File app/helpers/application_helper.rb, line 100 def step_label(step) STEP_LABELS.fetch(step.to_s, step.to_s) end
Returns the human label for an execution step, falling back to the raw step name when it has no mapping. @param step [String, Symbol] the step identifier. @return [String] the human-readable step label.
Source
# File app/helpers/application_helper.rb, line 682 def step_metric_rows(execution) execution.execution_steps.order(:id).filter_map do |step| metrics = step.metrics || {} next if metrics.empty? rows = metrics["rows"].to_i statements = metrics["batched_statements"].to_i next if rows.zero? && statements.zero? op_label = t("maintenance.operations.#{step.operation}", default: step.operation.humanize) summary = [] summary << t("maintenance.step_metrics.processed", count: rows) if rows.positive? summary << t("maintenance.step_metrics.statements", count: statements) if statements.positive? next if summary.empty? [ op_label, nil, summary.join(" · "), nil ] end end
Fallback rows built from what the steps themselves reported. The step metrics carry the work done that no table-level metric reflects: row counts (orphans removed, snapshots expired), batched statements, elapsed time.
@param execution [ExecutionHistory] the execution with step metrics @return [Array<Array>] [label, old, new, delta] rows
Source
# File app/helpers/application_helper.rb, line 80 def strata_fill_class(status) case status.to_s when "healthy" then "strata-fill-ok" when "critical" then "strata-fill-critical" else "strata-fill-warning" end end
Maps a health status to the fill colour class used on the health strata bars. @param status [String, Symbol] the health status. @return [String] the strata fill class for the status.
Source
# File app/helpers/application_helper.rb, line 462 def table_health_tooltip(table) parts = [] if (avg = table.average_file_size) parts << "avg file #{number_to_human_size(avg)}" end parts << "#{table.snapshot_count} snapshots" if table.snapshot_count deletes = [ table.position_deletes, table.equality_deletes ].compact.sum parts << "#{number_to_human(deletes)} deletes / #{number_to_human(table.total_records)} records" if deletes.positive? parts.any? ? parts.join(" · ") : t("health.no_data") end
Concise composition summary for the health tooltip in the tables list. @param table [IcebergTable] the table whose composition is summarised. @return [String] the tooltip text, or a “no data” translation when empty.
# File app/helpers/application_helper.rb, line 661 def table_metric_rows(operations, before, after) relevant_keys = operations.flat_map { |op| OPERATION_METRICS[op] }.uniq return [] if relevant_keys.empty? relevant_keys.filter_map do |key| old_val = before[key] new_val = after[key] next if old_val.nil? && new_val.nil? label = t("maintenance.metrics.#{key}", default: key.humanize) delta = compute_delta(key, old_val, new_val) [ label, old_val, new_val, delta ] end end
The before/after rows for the operations’ table-level metrics.
Unchanged metrics are KEPT: “4689 → 4689” after an optimize is a meaningful finding (the compaction achieved nothing), so only a metric absent from both snapshots is skipped.
@param operations [Array<String>] the operations that ran @param before [Hash] the pre-maintenance metadata snapshot @param after [Hash] the post-maintenance metadata snapshot @return [Array<Array>] [label, old, new, delta] rows
Source
# File app/helpers/application_helper.rb, line 243 def timestamp(value) return content_tag(:span, "—", class: "cell-muted") if value.blank? content_tag(:span, value.to_fs(:db), class: "cell-num", title: value.iso8601) end
Renders a timestamp as a muted placeholder when blank, otherwise as a formatted cell with an ISO-8601 title tooltip. @param value [Time, DateTime, String, nil] the timestamp to display. @return [ActiveSupport::SafeBuffer] the rendered timestamp markup.
# File app/helpers/application_helper.rb, line 43 def user_status_badge_class(status) case status.to_s when "active" then "badge-ok" when "invited" then "badge-warn" when "suspended" then "badge-err" else "badge-mute" end end
Maps a user account status to its badge CSS class. @param status [String, Symbol] the user status. @return [String] the badge class for the status.