lib/anycable/health_server.rb in anycable-0.5.2 vs lib/anycable/health_server.rb in anycable-0.6.0.rc1

- old
+ new

@@ -1,45 +1,67 @@ # frozen_string_literal: true -require 'webrick' -require 'anycable/server' +require "webrick" +require "anycable/server" -module Anycable - # Server for HTTP healthchecks - module HealthServer - class << self - def start(port) - return if running? +module AnyCable + # Server for HTTP healthchecks. + # + # Basic usage: + # + # # create a new healthcheck server for a specified + # # gRPC server lisening on the port + # health_server = AnyCable::HealthServer.new(grpc_server, port) + # + # # start health server in background + # health_server.start + # + # # stop health server + # health_server.stop + class HealthServer + SUCCESS_RESPONSE = [200, "Ready"].freeze + FAILURE_RESPONSE = [503, "Not Ready"].freeze - @health_server ||= build_server(port) - Thread.new { @health_server.start } + attr_reader :grpc_server, :port, :path, :server - Anycable.logger.info "HTTP health server is listening on #{port}" - end + def initialize(grpc_server, port:, path: "/health", logger: AnyCable.logger) + @grpc_server = grpc_server + @port = port + @path = path + @logger = logger + @server = build_server + end - def stop - return unless running? - @health_server.shutdown - end + def start + return if running? - def running? - @health_server&.status == :Running - end + Thread.new { server.start } - private + logger.info "HTTP health server is listening on localhost:#{port} and mounted at \"#{path}\"" + end - SUCCESS_RESPONSE = [200, "Ready"].freeze - FAILURE_RESPONSE = [503, "Not Ready"].freeze + def stop + return unless running? - def build_server(port) - WEBrick::HTTPServer.new( - Port: port, - Logger: Anycable.logger, - AccessLog: [] - ).tap do |server| - server.mount_proc '/health' do |_, res| - res.status, res.body = Anycable::Server.running? ? SUCCESS_RESPONSE : FAILURE_RESPONSE - end + server.shutdown + end + + def running? + server.status == :Running + end + + private + + attr_reader :logger + + def build_server + WEBrick::HTTPServer.new( + Port: port, + Logger: logger, + AccessLog: [] + ).tap do |server| + server.mount_proc path do |_, res| + res.status, res.body = grpc_server.running? ? SUCCESS_RESPONSE : FAILURE_RESPONSE end end end end end