33class HealthController < ApplicationController
44 skip_before_action :verify_authenticity_token
55
6- def index
6+ def liveness
7+ checks = {
8+ database : check_database
9+ }
10+ render_health_response ( checks )
11+ end
12+
13+ def readiness
14+ checks = {
15+ database : check_database ,
16+ redis : check_redis ,
17+ sidekiq : check_sidekiq
18+ }
19+ render_health_response ( checks )
20+ end
21+
22+ private
23+
24+ def render_health_response ( checks )
725 health_status = {
826 status : 'ok' ,
927 timestamp : Time . current . iso8601 ,
10- checks : {
11- database : check_database ,
12- redis : check_redis
13- }
28+ checks : checks
1429 }
1530
16- status_code = health_status [ : checks] . values . all? { |check | check [ :status ] == 'ok' || check [ :status ] == 'warning ' } ? :ok : :service_unavailable
31+ status_code = checks . values . all? { |check | check [ :status ] == 'ok' } ? :ok : :service_unavailable
1732
1833 render json : health_status , status : status_code
1934 end
2035
21- private
22-
2336 def check_database
2437 start_time = Time . current
2538 ActiveRecord ::Base . connection . active?
@@ -44,7 +57,22 @@ def check_redis
4457 redis = Redis . new ( url : redis_url , timeout : 1 )
4558 redis . ping
4659
47- # Check if Sidekiq processes are actually running
60+ response_time = ( ( Time . current - start_time ) * 1000 ) . round ( 2 )
61+
62+ {
63+ status : 'ok' ,
64+ message : 'Redis connection is active' ,
65+ response_time_ms : response_time
66+ }
67+ rescue Redis ::CannotConnectError , Redis ::TimeoutError , SocketError => e
68+ {
69+ status : 'error' ,
70+ message : "Redis unavailable: #{ e . message } "
71+ }
72+ end
73+
74+ def check_sidekiq
75+ start_time = Time . current
4876 processes = Sidekiq ::ProcessSet . new
4977 workers_count = processes . size
5078
@@ -59,16 +87,16 @@ def check_redis
5987 }
6088 else
6189 {
62- status : 'warning ' ,
63- message : 'Redis is up but no Sidekiq workers are running' ,
90+ status : 'error ' ,
91+ message : 'No Sidekiq workers are running' ,
6492 response_time_ms : response_time ,
6593 workers : 0
6694 }
6795 end
68- rescue Redis :: CannotConnectError , Redis :: TimeoutError , SocketError => e
96+ rescue StandardError => e
6997 {
7098 status : 'error' ,
71- message : "Redis unavailable : #{ e . message } "
99+ message : "Sidekiq check failed : #{ e . message } "
72100 }
73101 end
74102end
0 commit comments