"""Read-only application health assessment. All external operations are supplied through injected probes. """ import re import time from core.configuration import ( ConfigurationError, validate_config, ) class HealthError(RuntimeError): """Application health could not be established.""" def require(condition, message): if not condition: raise HealthError(message) class HealthVerifier: def __init__( self, config, *, http_probe, service_probe, database_probe, redis_probe, asset_probe, release_probe, attempts=1, retry_delay=2, sleep=time.sleep, ): try: validated = validate_config(config) except ConfigurationError: raise HealthError( "Invalid health configuration" ) from None require( type(attempts) is int and 1 <= attempts <= 10, "Invalid health verification attempt count", ) require( type(retry_delay) is int and 0 <= retry_delay <= 30, "Invalid health retry delay", ) for probe in ( http_probe, service_probe, database_probe, redis_probe, asset_probe, release_probe, sleep, ): require( callable(probe), "Invalid health probe", ) site = validated["site"] docker = validated["docker"] health = validated["health"] self._origin = ( "http://127.0.0.1:" + str(site["origin_port"]) ) self._domain = site["domain"] self._endpoints = tuple( health["endpoints"] ) self._timeout = health["timeout_seconds"] self._services = ( docker["php_service"], docker["web_service"], docker["queue_service"], docker["scheduler_service"], ) self._http = http_probe self._service = service_probe self._database = database_probe self._redis = redis_probe self._assets = asset_probe self._release = release_probe self._attempts = attempts self._retry_delay = retry_delay self._sleep = sleep def _invoke(self, label, probe, *args, **kwargs): try: return probe(*args, **kwargs) except Exception: raise HealthError( f"Health probe failed: {label}" ) from None def _check_release(self, expected): actual = self._invoke( "active release", self._release, ) require( isinstance(actual, str) and actual == expected, "Active release identity mismatch", ) def _verify_once(self, expected, attempt): self._check_release(expected) result = { "format_version": 1, "release": expected, "attempt": attempt, "http": {}, "services": {}, "database": False, "redis": False, "assets": False, "healthy": False, } for endpoint in self._endpoints: status = self._invoke( f"HTTP {endpoint}", self._http, self._origin + endpoint, host=self._domain, timeout=self._timeout, ) require( type(status) is int and status == 200, f"HTTP health check failed: {endpoint}", ) result["http"][endpoint] = status for service in self._services: ready = self._invoke( f"service {service}", self._service, service, timeout=self._timeout, ) require( ready is True, f"Service not ready: {service}", ) result["services"][service] = True for name, probe in ( ("database", self._database), ("redis", self._redis), ("assets", self._assets), ): ready = self._invoke( name, probe, timeout=self._timeout, ) require( ready is True, f"Health check failed: {name}", ) result[name] = True self._check_release(expected) result["healthy"] = True return result def verify(self, expected_release): require( isinstance(expected_release, str) and re.fullmatch( r"[1-9][0-9]{0,19}", expected_release, ) is not None, "Invalid expected release identifier", ) for attempt in range( 1, self._attempts + 1, ): try: return self._verify_once( expected_release, attempt, ) except HealthError: if attempt == self._attempts: raise self._sleep(self._retry_delay) raise HealthError( "Application health verification failed" )