Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ECO-240/improved-healthcheck #632

Merged
merged 5 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion app/controllers/health_controller.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,44 @@
class HealthController < ApplicationController

def index
head :ok
database_check_results = check_db_connections
if all_database_healthy?(database_check_results)
render json: {status: "ok", databases: database_check_results}, status: :ok
else
render json: {status: "error", databases: database_check_results}, status: :internal_server_error
end
end

private
def all_database_healthy?(database_check_results)
database_check_results.values.all? { |status| status[:status] == "ok" }
end

def check_db_connections
db_status = {}
databases.each do |role, connection|
db_status[role] = perform_health_check(connection)
ensure
ActiveRecord::Base.clear_active_connections!
end
db_status
end

def databases
{
primary: ActiveRecord::Base.connected_to(role: :writing) { ApplicationRecord.connection },
datahub: ActiveRecord::Base.connected_to(role: :reading) { DatahubRecord.connection }
}
end

def perform_health_check(connection)
if connection
connection.execute('SELECT 1')
{status: 'ok'}
else
{status: 'error', message: 'Connection not established'}
end
rescue => e
{status: 'error', message: e.message}
end
end
6 changes: 6 additions & 0 deletions spec/features/health_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,11 @@
visit health_path

expect(page.status_code).to be(200)

returned_data = JSON.parse(page.body)

expect(returned_data["status"]).to eq("ok")
expect(returned_data["databases"]["primary"]).to include("status" => "ok")
expect(returned_data["databases"]["datahub"]).to include("status" => "ok")
end
end
Loading