The personal finance app for everyone (by everyone)
Ruby
feat(self-hosting): surface Sidekiq-unhealthy nudge + admin system health page (#1906)
Khaostica6439a731ab32
diff --git a/app/controllers/admin/system_health_controller.rb b/app/controllers/admin/system_health_controller.rbnew file mode 100644index 0000000000..cd62ca7cc3--- /dev/null+++ b/app/controllers/admin/system_health_controller.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++module Admin+ class SystemHealthController < Admin::BaseController+ # Bypass the per-request memo / cross-request cache that the layout+ # banner uses. An operator landing on this page (often right after+ # restarting the worker) wants to confirm the current state, not a+ # snapshot up to `SidekiqHealth::CACHE_TTL` old. Also makes the page+ # work in managed mode, where `current_sidekiq_health` is nil.+ def show+ SidekiqHealth.expire_cache!+ @health = SidekiqHealth.new+ end+ end+enddiff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rbindex 7306d504f3..f1462f3b77 100644--- a/app/controllers/application_controller.rb+++ b/app/controllers/application_controller.rb@@ -16,7 +16,7 @@ class ApplicationController < ActionController::Basebefore_action :set_default_chatbefore_action :set_active_storage_url_options- helper_method :demo_config, :demo_host_match?, :show_demo_warning?+ helper_method :demo_config, :demo_host_match?, :show_demo_warning?, :current_sidekiq_healthprivatedef accept_pending_invitation_for(user)@@ -94,6 +94,18 @@ class ApplicationController < ActionController::Basedemo_host_match?end+ # Returns the current Sidekiq health snapshot in self-hosted mode and+ # `nil` in managed mode. Memoized per request and additionally cached+ # across requests by `SidekiqHealth.current`, so an authenticated page+ # render adds at most one Redis round-trip per cache window — not three+ # per request. Returns `nil` (not a healthy stand-in) in managed mode+ # so callers must explicitly handle the "check disabled" case; the+ # banner already gates on `Current.user&.super_admin?` and `present?`.+ def current_sidekiq_health+ return @current_sidekiq_health if defined?(@current_sidekiq_health)+ @current_sidekiq_health = Rails.application.config.app_mode.self_hosted? ? SidekiqHealth.current : nil+ end+def accessible_accountsCurrent.accessible_accountsenddiff --git a/app/models/sidekiq_health.rb b/app/models/sidekiq_health.rbnew file mode 100644index 0000000000..b0a5eab7c9--- /dev/null+++ b/app/models/sidekiq_health.rb@@ -0,0 +1,137 @@+# Snapshot of Sidekiq's current operational state, used to surface a+# user-facing "data unavailable" nudge when background jobs aren't being+# processed. This is the symptom side of the most common Docker Compose+# misconfiguration: the worker container isn't running, so sync jobs,+# balance recalculations, and net-worth updates silently never execute+# and the UI shows zeros without explaining why (#1481).+#+# Healthy = Redis reachable AND at least one worker heartbeat is fresh+# AND the oldest enqueued job hasn't been waiting longer than the+# configured latency budget. Anything else flips `healthy?` to false and+# `reason` gives the most-specific failure for display / logging.+#+# Reuse via `SidekiqHealth.current` (or `ApplicationController#current_sidekiq_health`)+# rather than `.new` so the result is shared across a request and cached+# for `CACHE_TTL` across requests — `.new` always hits Redis. All Sidekiq+# calls are eager-loaded in `initialize` and wrapped in a defensive+# rescue — a degraded Redis must never crash a page render.+class SidekiqHealth+ # A worker is considered alive if it published a heartbeat within this+ # window. Sidekiq's default heartbeat interval is 5s, so 2 minutes is+ # conservative — covers a temporarily-paused worker, deploy restart, or+ # transient Redis blip without flapping the banner. Operators on+ # under-resourced self-hosted boxes can raise it via+ # `SIDEKIQ_HEALTH_HEARTBEAT_TIMEOUT` (seconds) if heartbeats legitimately+ # arrive slower than this on their hardware.+ PROCESS_HEARTBEAT_TIMEOUT = (ENV["SIDEKIQ_HEALTH_HEARTBEAT_TIMEOUT"].presence&.to_i&.then { |s| s.seconds } || 2.minutes)++ # Oldest-enqueued-job age that we treat as "backed up". Tuned to the+ # default queue config in `config/sidekiq.yml` (concurrency: 3): a+ # healthy queue empties well inside this window even under bursty+ # sync load. Self-hosted deployments running a single-threaded worker+ # or large sync backlogs can raise it via `SIDEKIQ_HEALTH_LATENCY_THRESHOLD`+ # (seconds) to avoid a constant false-positive banner.+ LATENCY_THRESHOLD = (ENV["SIDEKIQ_HEALTH_LATENCY_THRESHOLD"].presence&.to_i&.then { |s| s.seconds } || 5.minutes)++ # How long a cached health snapshot is reused before re-querying Redis.+ # A bad worker is visible within `CACHE_TTL` of the failure — short+ # enough to feel live, long enough that authenticated page loads don't+ # round-trip Redis on every render. Override with `SIDEKIQ_HEALTH_CACHE_TTL`+ # (seconds) if needed.+ CACHE_TTL = (ENV["SIDEKIQ_HEALTH_CACHE_TTL"].presence&.to_i&.then { |s| s.seconds } || 60.seconds)++ CACHE_KEY = "sidekiq_health/v1"++ REASONS = %i[redis_unreachable no_worker_processes stale_heartbeat queue_backed_up].freeze++ attr_reader :processes_count, :last_heartbeat_at, :max_queue_latency, :queue_breakdown,+ :enqueued_count, :failed_count, :processed_count, :retry_count++ class << self+ # Convenience for view helpers / banners that just need the boolean.+ def healthy?+ current.healthy?+ end++ # Cached entry point. Re-uses a snapshot for up to `CACHE_TTL` so+ # the global banner check doesn't add a Redis round-trip per page+ # load. Cache misses still pay the full Sidekiq query, but only once+ # per TTL window across the whole process.+ def current+ Rails.cache.fetch(CACHE_KEY, expires_in: CACHE_TTL) { new }+ end++ # Forces the next `current` call to re-query Redis. Useful from the+ # admin page so an operator who just restarted the worker sees the+ # new state immediately.+ def expire_cache!+ Rails.cache.delete(CACHE_KEY)+ end+ end++ def initialize+ @processes_count = 0+ @last_heartbeat_at = nil+ @max_queue_latency = 0.0+ @queue_breakdown = []+ @enqueued_count = 0+ @failed_count = 0+ @processed_count = 0+ @retry_count = 0+ @load_failure = nil++ load_state!+ end++ def healthy?+ reason.nil?+ end++ # Most-specific failure first; nil when healthy. Stable symbol so the+ # banner i18n keys can switch on it.+ def reason+ return :redis_unreachable if @load_failure+ return :no_worker_processes if processes_count.zero?+ # A registered process with no published heartbeat is just as+ # suspect as one whose last heartbeat is stale — either way Sidekiq+ # isn't telling us a worker is alive.+ return :stale_heartbeat if last_heartbeat_at.nil? || last_heartbeat_at < PROCESS_HEARTBEAT_TIMEOUT.ago+ return :queue_backed_up if max_queue_latency > LATENCY_THRESHOLD+ nil+ end++ private+ # Eagerly fetches every Sidekiq stat we need in one pass so we can+ # catch Redis failures at the boundary instead of relying on lazy+ # Sidekiq client calls inside view code. Any failure is recorded as+ # `:redis_unreachable` — we never let a degraded broker crash a page.+ def load_state!+ process_set = Sidekiq::ProcessSet.new+ @processes_count = process_set.size++ beats = process_set.map { |p| p["beat"] }.compact+ @last_heartbeat_at = beats.present? ? Time.at(beats.max) : nil++ queues = Sidekiq::Queue.all+ latencies = queues.map { |q| q.latency.to_f }+ @max_queue_latency = latencies.max.to_f+ @queue_breakdown = queues.sort_by(&:name).map { |q| [ q.name, q.size, q.latency.to_f ] }++ stats = Sidekiq::Stats.new+ @enqueued_count = stats.enqueued.to_i+ @failed_count = stats.failed.to_i+ @processed_count = stats.processed.to_i+ @retry_count = stats.retry_size.to_i+ rescue Redis::BaseError, RedisClient::Error => e+ @load_failure = e+ Rails.logger.warn("[SidekiqHealth] Redis unreachable: #{e.class}: #{e.message}")+ rescue StandardError => e+ # Defensive fallback — Sidekiq internals can raise unexpected+ # errors (e.g., misconfigured client, version mismatch) and the+ # layout still has to render. Treat any non-Redis error as a+ # `:redis_unreachable` signal so the banner shows and the admin+ # gets pointed at the system-health page to investigate.+ @load_failure = e+ Rails.logger.warn("[SidekiqHealth] Unexpected error: #{e.class}: #{e.message}")+ end+enddiff --git a/app/views/admin/system_health/show.html.erb b/app/views/admin/system_health/show.html.erbnew file mode 100644index 0000000000..44d9a69dfd--- /dev/null+++ b/app/views/admin/system_health/show.html.erb@@ -0,0 +1,105 @@+<%= content_for :page_title, t(".title") %>++<div class="space-y-4">+ <% unless @health.healthy? %>+ <%= render DS::Alert.new(+ title: t(".alert.title"),+ message: t("shared.sidekiq_health_banner.reasons.#{@health.reason}"),+ variant: :warning,+ live: :polite+ ) %>+ <% end %>++ <div class="bg-container rounded-xl shadow-border-xs p-4">+ <h2 class="text-lg font-semibold mb-1"><%= t(".status_section_title") %></h2>+ <p class="text-sm text-secondary mb-4"><%= t(".status_section_description") %></p>++ <dl class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">+ <div>+ <dt class="text-secondary"><%= t(".labels.status") %></dt>+ <dd class="text-primary font-medium">+ <% if @health.healthy? %>+ <span class="text-success"><%= t(".values.healthy") %></span>+ <% else %>+ <span class="text-warning"><%= t(".values.unhealthy") %></span>+ <% end %>+ </dd>+ </div>+ <div>+ <dt class="text-secondary"><%= t(".labels.processes") %></dt>+ <dd class="text-primary font-medium"><%= @health.processes_count %></dd>+ </div>+ <div>+ <dt class="text-secondary"><%= t(".labels.last_heartbeat") %></dt>+ <dd class="text-primary font-medium">+ <% if @health.last_heartbeat_at %>+ <%= t(".values.time_ago", time_ago: time_ago_in_words(@health.last_heartbeat_at)) %>+ <% else %>+ <%= t(".values.never") %>+ <% end %>+ </dd>+ </div>+ <div>+ <dt class="text-secondary"><%= t(".labels.max_queue_latency") %></dt>+ <dd class="text-primary font-medium">+ <%= t(".values.seconds", seconds: number_with_precision(@health.max_queue_latency, precision: 1)) %>+ </dd>+ </div>+ </dl>+ </div>++ <div class="bg-container rounded-xl shadow-border-xs p-4">+ <h2 class="text-lg font-semibold mb-1"><%= t(".counters_section_title") %></h2>+ <p class="text-sm text-secondary mb-4"><%= t(".counters_section_description") %></p>++ <dl class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">+ <div>+ <dt class="text-secondary"><%= t(".labels.enqueued") %></dt>+ <dd class="text-primary font-medium"><%= number_with_delimiter(@health.enqueued_count) %></dd>+ </div>+ <div>+ <dt class="text-secondary"><%= t(".labels.retries") %></dt>+ <dd class="text-primary font-medium"><%= number_with_delimiter(@health.retry_count) %></dd>+ </div>+ <div>+ <dt class="text-secondary"><%= t(".labels.failed") %></dt>+ <dd class="text-primary font-medium"><%= number_with_delimiter(@health.failed_count) %></dd>+ </div>+ <div>+ <dt class="text-secondary"><%= t(".labels.processed_total") %></dt>+ <dd class="text-primary font-medium"><%= number_with_delimiter(@health.processed_count) %></dd>+ </div>+ </dl>+ </div>++ <div class="bg-container rounded-xl shadow-border-xs p-4">+ <h2 class="text-lg font-semibold mb-1"><%= t(".queues_section_title") %></h2>+ <p class="text-sm text-secondary mb-4"><%= t(".queues_section_description") %></p>++ <% breakdown = @health.queue_breakdown %>+ <% if breakdown.empty? %>+ <p class="text-sm text-secondary"><%= t(".values.no_queues") %></p>+ <% else %>+ <table class="w-full text-sm">+ <thead>+ <tr class="text-left text-secondary border-b border-primary">+ <th class="py-2 font-medium"><%= t(".labels.queue") %></th>+ <th class="py-2 font-medium"><%= t(".labels.size") %></th>+ <th class="py-2 font-medium"><%= t(".labels.latency") %></th>+ </tr>+ </thead>+ <tbody class="divide-y divide-primary">+ <% breakdown.each do |name, size, latency| %>+ <tr>+ <td class="py-2 text-primary"><%= name %></td>+ <td class="py-2 text-primary"><%= number_with_delimiter(size) %></td>+ <td class="py-2 text-primary">+ <%= t(".values.seconds", seconds: number_with_precision(latency, precision: 1)) %>+ </td>+ </tr>+ <% end %>+ </tbody>+ </table>+ <% end %>+ </div>+</div>diff --git a/app/views/layouts/shared/_htmldoc.html.erb b/app/views/layouts/shared/_htmldoc.html.erbindex 18ca6e799f..444e053f1f 100644--- a/app/views/layouts/shared/_htmldoc.html.erb+++ b/app/views/layouts/shared/_htmldoc.html.erb@@ -29,8 +29,31 @@<%# Custom overrides for browser's confirm API %><%= render "layouts/shared/confirm_dialog" %>- <%= render "impersonation_sessions/super_admin_bar" if Current.true_user&.super_admin? && show_super_admin_bar? %>- <%= render "impersonation_sessions/approval_bar" if Current.true_user&.impersonated_support_sessions&.initiated&.any? %>+ <% super_admin_bar_visible = Current.true_user&.super_admin? && show_super_admin_bar? %>+ <% approval_bar_visible = Current.true_user&.impersonated_support_sessions&.initiated&.any? %>++ <%= render "impersonation_sessions/super_admin_bar" if super_admin_bar_visible %>+ <%= render "impersonation_sessions/approval_bar" if approval_bar_visible %>++ <%# Only surface the Sidekiq nudge to operators who can act on it. The+ Redis round-trip and banner render are both skipped for non-super-admins+ and for managed-mode deployments — `current_sidekiq_health` returns+ nil in those cases. %>+ <% if Current.user&.super_admin? && current_sidekiq_health && !current_sidekiq_health.healthy? %>+ <%# Stack below any sticky impersonation bars instead of hard-coding+ 80px (`top-20`). Each bar is ~60px tall (`py-4` + content), so+ adjust the fixed offset based on how many are visible. %>+ <% banner_top_class = if super_admin_bar_visible && approval_bar_visible+ "top-36"+ elsif super_admin_bar_visible || approval_bar_visible+ "top-20"+ else+ "top-4"+ end %>+ <div class="fixed z-40 <%= banner_top_class %> left-1/2 -translate-x-1/2 w-full max-w-2xl px-4">+ <%= render "shared/sidekiq_health_banner", health: current_sidekiq_health %>+ </div>+ <% end %><%= yield %>diff --git a/app/views/settings/_settings_nav.html.erb b/app/views/settings/_settings_nav.html.erbindex 50fd37e58a..83fff7e804 100644--- a/app/views/settings/_settings_nav.html.erb+++ b/app/views/settings/_settings_nav.html.erb@@ -37,7 +37,8 @@ nav_sections = [{ label: t(".imports_label"), path: imports_path, icon: "download" },{ label: t(".exports_label"), path: family_exports_path, icon: "upload" },{ label: t(".sso_providers_label"), path: admin_sso_providers_path, icon: "key-round", if: Current.user&.super_admin? },- { label: t(".users_label"), path: admin_users_path, icon: "users", if: Current.user&.super_admin? }+ { label: t(".users_label"), path: admin_users_path, icon: "users", if: Current.user&.super_admin? },+ { label: t(".system_health_label"), path: admin_system_health_path, icon: "heart-pulse", if: Current.user&.super_admin? }]} : nil),diff --git a/app/views/shared/_sidekiq_health_banner.html.erb b/app/views/shared/_sidekiq_health_banner.html.erbnew file mode 100644index 0000000000..0c3756f12b--- /dev/null+++ b/app/views/shared/_sidekiq_health_banner.html.erb@@ -0,0 +1,33 @@+<%# locals: (health:) %>+<%#+ Rendered only to super admins from the global layout (`_htmldoc.html.erb`).+ Regular family members can't act on a Sidekiq outage and would just see a+ vague warning, so we don't show them anything — the system-health page is+ the one place this nudge points to and it's super-admin gated.+%>++<% return if health.healthy? %>+<% reason_key = health.reason %>++<div role="alert"+ aria-live="assertive"+ class="bg-warning/10 border border-warning/20 rounded-lg p-4 mb-4 text-sm text-primary">+ <div class="flex items-start gap-3">+ <div class="shrink-0">+ <%= icon "alert-triangle", size: "sm", color: "warning" %>+ </div>+ <div class="flex-1 space-y-1">+ <p class="font-semibold"><%= t("shared.sidekiq_health_banner.title") %></p>+ <p class="text-secondary"><%= t("shared.sidekiq_health_banner.body") %></p>+ <p class="text-secondary">+ <%= t("shared.sidekiq_health_banner.reasons.#{reason_key}") if reason_key %>+ </p>+ <%= render DS::Link.new(+ text: t("shared.sidekiq_health_banner.cta"),+ variant: "ghost",+ href: admin_system_health_path,+ icon: "arrow-right"+ ) %>+ </div>+ </div>+</div>diff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.ymlnew file mode 100644index 0000000000..b185de5692--- /dev/null+++ b/config/locales/views/admin/system_health/en.yml@@ -0,0 +1,33 @@+---+en:+ admin:+ system_health:+ show:+ title: System health+ alert:+ title: Background jobs aren't running+ status_section_title: Sidekiq status+ status_section_description: Current state of the background worker that powers syncs, balances, and net-worth calculations.+ counters_section_title: Job counters+ counters_section_description: Aggregate Sidekiq counters across all queues.+ queues_section_title: Queues+ queues_section_description: Per-queue depth and oldest-job age. Latency is the seconds the oldest job has been waiting.+ labels:+ status: Status+ processes: Worker processes+ last_heartbeat: Last heartbeat+ max_queue_latency: Oldest job age+ enqueued: Enqueued+ retries: Retries+ failed: Failed+ processed_total: Processed total+ queue: Queue+ size: Size+ latency: Latency+ values:+ healthy: Healthy+ unhealthy: Degraded+ time_ago: "%{time_ago} ago"+ never: Never+ seconds: "%{seconds}s"+ no_queues: "No queues are registered. The worker may not be running."diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 66bc4bed25..e67f32bba1 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -349,6 +349,7 @@ en:self_hosting_label: Self-Hostingsso_providers_label: SSO Providersstatement_vault_label: Statement Vault+ system_health_label: System healthtags_label: Tagstransactions_section_title: Transactionsusers_label: Usersdiff --git a/config/locales/views/shared/en.yml b/config/locales/views/shared/en.ymlindex 9d7606cf24..661bb4c8fb 100644--- a/config/locales/views/shared/en.yml+++ b/config/locales/views/shared/en.yml@@ -44,3 +44,12 @@ en:expense: Expenseincome: Incometransfer: Transfer+ sidekiq_health_banner:+ title: Some data may be out of date+ body: "Background jobs aren't being processed, so balances, net worth, and account syncs may be stale or missing."+ cta: View system health+ reasons:+ redis_unreachable: "The app can't reach Redis. Check your REDIS_URL and that Redis is running."+ no_worker_processes: "No Sidekiq worker process is connected. Start the worker container or systemd unit."+ stale_heartbeat: "The Sidekiq worker hasn't reported a heartbeat recently. It may be stuck or crashed."+ queue_backed_up: "The oldest enqueued job has been waiting beyond the latency budget. The worker is alive but falling behind."diff --git a/config/routes.rb b/config/routes.rbindex b104fc3652..1a44144904 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -842,6 +842,12 @@ Rails.application.routes.draw dodelete :invitations, to: "invitations#destroy_all"endend+ # Singular `resource :system_health` would otherwise route to+ # `Admin::SystemHealthsController` (Rails pluralizes the controller+ # name even for singular resources, unlike its plural siblings above+ # that happen to round-trip cleanly). The controller file is singular,+ # so name it explicitly.+ resource :system_health, only: :show, controller: "system_health"end# Defines the root path route ("/")diff --git a/test/controllers/admin/system_health_controller_test.rb b/test/controllers/admin/system_health_controller_test.rbnew file mode 100644index 0000000000..7081ebcdbb--- /dev/null+++ b/test/controllers/admin/system_health_controller_test.rb@@ -0,0 +1,56 @@+require "test_helper"++class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest+ test "super admin can view the system health page" do+ sign_in users(:sure_support_staff)+ SidekiqHealth.any_instance.stubs(:healthy?).returns(true)+ SidekiqHealth.any_instance.stubs(:processes_count).returns(1)+ SidekiqHealth.any_instance.stubs(:last_heartbeat_at).returns(Time.current)+ SidekiqHealth.any_instance.stubs(:max_queue_latency).returns(0.0)+ SidekiqHealth.any_instance.stubs(:enqueued_count).returns(0)+ SidekiqHealth.any_instance.stubs(:retry_count).returns(0)+ SidekiqHealth.any_instance.stubs(:failed_count).returns(0)+ SidekiqHealth.any_instance.stubs(:processed_count).returns(42)+ SidekiqHealth.any_instance.stubs(:queue_breakdown).returns([ [ "default", 0, 0.0 ] ])++ get admin_system_health_url++ assert_response :success+ assert_match(/Sidekiq status/, response.body)+ assert_match(/Healthy/, response.body)+ end++ test "renders degraded state with reason when Sidekiq is unhealthy" do+ sign_in users(:sure_support_staff)+ SidekiqHealth.any_instance.stubs(:healthy?).returns(false)+ SidekiqHealth.any_instance.stubs(:reason).returns(:no_worker_processes)+ SidekiqHealth.any_instance.stubs(:processes_count).returns(0)+ SidekiqHealth.any_instance.stubs(:last_heartbeat_at).returns(nil)+ SidekiqHealth.any_instance.stubs(:max_queue_latency).returns(0.0)+ SidekiqHealth.any_instance.stubs(:enqueued_count).returns(7)+ SidekiqHealth.any_instance.stubs(:retry_count).returns(0)+ SidekiqHealth.any_instance.stubs(:failed_count).returns(0)+ SidekiqHealth.any_instance.stubs(:processed_count).returns(0)+ SidekiqHealth.any_instance.stubs(:queue_breakdown).returns([])++ get admin_system_health_url++ assert_response :success+ assert_match(/Degraded/, response.body)+ assert_match(/No Sidekiq worker process is connected/, response.body)+ end++ test "non super admin is redirected away" do+ sign_in users(:family_admin)++ get admin_system_health_url++ assert_redirected_to root_path+ end++ test "unauthenticated user is redirected to sign in" do+ get admin_system_health_url++ assert_redirected_to new_session_path+ end+enddiff --git a/test/models/sidekiq_health_test.rb b/test/models/sidekiq_health_test.rbnew file mode 100644index 0000000000..9754ce982e--- /dev/null+++ b/test/models/sidekiq_health_test.rb@@ -0,0 +1,170 @@+require "test_helper"++class SidekiqHealthTest < ActiveSupport::TestCase+ def stub_sidekiq(processes: [], queues: [], stats: default_stats)+ Sidekiq::ProcessSet.stubs(:new).returns(processes)+ Sidekiq::Queue.stubs(:all).returns(queues)+ Sidekiq::Stats.stubs(:new).returns(stats)+ end++ def default_stats+ OpenStruct.new(enqueued: 0, failed: 0, processed: 0, retry_size: 0)+ end++ def fresh_process(beat_seconds_ago: 5)+ { "beat" => (Time.current - beat_seconds_ago.seconds).to_f }+ end++ def fake_queue(name: "default", size: 0, latency: 0.0)+ OpenStruct.new(name: name, size: size, latency: latency)+ end++ test "reports healthy when a worker is beating and no queue is backed up" do+ stub_sidekiq(+ processes: [ fresh_process ],+ queues: [ fake_queue ],+ stats: OpenStruct.new(enqueued: 0, failed: 0, processed: 100, retry_size: 0)+ )++ health = SidekiqHealth.new++ assert health.healthy?+ assert_nil health.reason+ assert_equal 1, health.processes_count+ assert_equal 100, health.processed_count+ end++ test "reports no_worker_processes when ProcessSet is empty" do+ stub_sidekiq(processes: [], queues: [])++ health = SidekiqHealth.new++ assert_not health.healthy?+ assert_equal :no_worker_processes, health.reason+ assert_equal 0, health.processes_count+ assert_nil health.last_heartbeat_at+ end++ test "reports stale_heartbeat when last beat is older than the timeout" do+ stub_sidekiq(+ processes: [ fresh_process(beat_seconds_ago: 10.minutes) ],+ queues: [ fake_queue ]+ )++ health = SidekiqHealth.new++ assert_not health.healthy?+ assert_equal :stale_heartbeat, health.reason+ end++ test "reports stale_heartbeat when a registered process has no heartbeat at all" do+ # Sidekiq's ProcessSet can return entries with a nil `beat` key during+ # startup or after a forced kill — treat it the same as a stale beat,+ # not as healthy.+ stub_sidekiq(+ processes: [ { "beat" => nil } ],+ queues: [ fake_queue ]+ )++ health = SidekiqHealth.new++ assert_not health.healthy?+ assert_equal :stale_heartbeat, health.reason+ assert_nil health.last_heartbeat_at+ end++ test "reports queue_backed_up when oldest job exceeds latency threshold" do+ stub_sidekiq(+ processes: [ fresh_process ],+ queues: [ fake_queue(size: 100, latency: 1.hour.to_f) ],+ stats: OpenStruct.new(enqueued: 100, failed: 0, processed: 50, retry_size: 0)+ )++ health = SidekiqHealth.new++ assert_not health.healthy?+ assert_equal :queue_backed_up, health.reason+ end++ test "reports redis_unreachable when Sidekiq raises a Redis connection error" do+ Sidekiq::ProcessSet.stubs(:new).raises(RedisClient::ConnectionError.new("Connection refused"))++ health = SidekiqHealth.new++ assert_not health.healthy?+ assert_equal :redis_unreachable, health.reason+ assert_equal 0, health.processes_count+ assert_equal 0.0, health.max_queue_latency+ assert_empty health.queue_breakdown+ end++ test "queue_breakdown returns sorted [name, size, latency] triples" do+ stub_sidekiq(+ processes: [ fresh_process ],+ queues: [ fake_queue(name: "b", size: 5, latency: 1.0), fake_queue(name: "a", size: 2, latency: 0.5) ],+ stats: OpenStruct.new(enqueued: 7, failed: 0, processed: 0, retry_size: 0)+ )++ health = SidekiqHealth.new++ assert_equal [ [ "a", 2, 0.5 ], [ "b", 5, 1.0 ] ], health.queue_breakdown+ end++ test "treats unexpected non-Redis exceptions as redis_unreachable rather than crashing" do+ Sidekiq::ProcessSet.stubs(:new).raises(StandardError.new("unexpected"))++ health = SidekiqHealth.new++ assert_not health.healthy?+ assert_equal :redis_unreachable, health.reason+ end++ test "current memoizes across calls inside the cache TTL" do+ with_memory_cache do+ stub_sidekiq(processes: [ fresh_process ], queues: [ fake_queue ])++ first = SidekiqHealth.current+ assert first.healthy?++ # If `current` re-queried Redis on the second call, raising from+ # ProcessSet would propagate through `load_state!`'s rescue and+ # flip `reason` to `:redis_unreachable`. The cached snapshot+ # should be returned instead — still healthy. We don't compare+ # object identity here: ActiveSupport::Cache::MemoryStore+ # Marshals values by default, so the second `fetch` returns an+ # `==`-equal but not `equal?`-identical instance.+ Sidekiq::ProcessSet.stubs(:new).raises(StandardError.new("would explode if re-queried"))+ second = SidekiqHealth.current++ assert second.healthy?+ assert_nil second.reason+ end+ end++ test "expire_cache! forces the next current call to re-query Redis" do+ with_memory_cache do+ stub_sidekiq(processes: [ fresh_process ], queues: [ fake_queue ])+ first = SidekiqHealth.current+ assert first.healthy?++ stub_sidekiq(processes: [], queues: [])+ SidekiqHealth.expire_cache!+ second = SidekiqHealth.current++ assert_not second.healthy?+ assert_equal :no_worker_processes, second.reason+ end+ end++ private+ # Stubs Rails.cache with an in-process MemoryStore for the duration+ # of the block so cache hit/miss behavior is actually exercised —+ # test env defaults to :null_store, which would skip every `fetch`+ # body and make caching invisible to assertions.+ def with_memory_cache+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ yield+ ensure+ Rails.unstub(:cache)+ end+end