require "rack/ecg/version"
require "json"
require "open3"
require "rack/ecg/check_factory"
module Rack
class ECG
DEFAULT_MOUNT_AT = "/_ecg"
DEFAULT_CHECKS = [:http]
DEFAULT_FAILURE_STATUS = 500
def initialize(app = nil, checks: DEFAULT_CHECKS, at: DEFAULT_MOUNT_AT, hook: nil,
failure_status: DEFAULT_FAILURE_STATUS)
@app = app
check_configuration = checks || []
@check_factory = CheckFactory.new(check_configuration, DEFAULT_CHECKS)
@mount_at = at || DEFAULT_MOUNT_AT
@result_hook = hook
@failure_response_status = failure_status
end
def call(env)
if env["PATH_INFO"] == @mount_at
check_results = @check_factory.build_all.inject({}) do |results, check|
results.merge(check.result.as_json)
end
success = check_results.none? { |check| check[1][:status] == Check::Status::ERROR }
response_status = success ? 200 : @failure_response_status
@result_hook&.call(success, check_results)
= {
"x-rack-ecg-version" => Rack::ECG::VERSION,
"content-type" => "application/json",
}
response_body = JSON.pretty_generate(check_results)
[response_status, , [response_body]]
elsif @app
@app.call(env)
else
[404, {}, []]
end
end
end
end