Created
August 19, 2022 15:17
-
-
Save souzagab/751ee1da46e63607d73d10eabb16dc7d to your computer and use it in GitHub Desktop.
Health Endpoint using only Rack in Rails apps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This file is used by Rack-based servers to start the application. | |
require ::File.expand_path('config/environment', __dir__) | |
map "/health" do | |
run Rack::HealthCheck.new | |
end | |
run Rails.application |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/rack/health_check.rb | |
module Rack | |
class HealthCheck | |
def call(_env) | |
status = { | |
redis: { | |
connected: redis_connected? | |
}, | |
postgres: { | |
connected: postgres_connected?, | |
migrations_updated: postgres_migrations_updated? | |
} | |
} | |
[200, {}, [status.to_json]] | |
end | |
protected | |
def redis_connected? | |
$redis.ping == 'PONG' | |
rescue | |
false | |
end | |
def postgres_connected? | |
ApplicationRecord.establish_connection | |
ApplicationRecord.connection | |
ApplicationRecord.connected? | |
rescue | |
false | |
end | |
def postgres_migrations_updated? | |
return false unless postgres_connected? | |
!ApplicationRecord.connection.migration_context.needs_migration? | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment