"""Внутренний health-listener на loopback (порт 8081). Он изолирован: не публикуется, не проксируется LB и не даёт доступа к бизнес-API. Нужен docker healthcheck и сценарию `stop-one`, чтобы не открывать health-путь через mTLS-вход. """ import json import logging import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from . import broker, config, db, s3 log = logging.getLogger("health") def _readiness(): checks = {} try: db.ping() checks["database"] = True except Exception as exc: # noqa: BLE001 - health must not raise checks["database"] = False log.warning("readiness: database %s", type(exc).__name__) try: s3.ping() checks["s3"] = True except Exception as exc: # noqa: BLE001 checks["s3"] = False log.warning("readiness: s3 %s", type(exc).__name__) try: checks["broker"] = bool(broker.wait_ready(timeout=1)) except Exception as exc: # noqa: BLE001 checks["broker"] = False log.warning("readiness: broker %s", type(exc).__name__) return all(checks.values()), checks class Handler(BaseHTTPRequestHandler): server_version = "messenger-health" sys_version = "" def do_GET(self): # noqa: N802 - BaseHTTPRequestHandler API if self.path.startswith("/health/live"): self._send(200, {"status": "ok"}) elif self.path.startswith("/health/ready"): ready, checks = _readiness() self._send(200 if ready else 503, {"status": "ok" if ready else "unavailable", "checks": checks}) else: self._send(404, {"error": "not_found"}) def _send(self, status, payload): body = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body) def log_message(self, fmt, *args): # noqa: A003 - silence per-request noise return def start(): """Поднимает health-listener в фоновом потоке (не блокирует uvicorn).""" server = ThreadingHTTPServer(("127.0.0.1", config.HEALTH_PORT), Handler) server.daemon_threads = True log.info("health listener on 127.0.0.1:%d", config.HEALTH_PORT) thread = threading.Thread(target=server.serve_forever, name="health", daemon=True) thread.start() return thread