Files
mtusi2026lab7/app/health.py
T
eqktrinandO3 Agent Claude 23ac69428e ЛР7: перенести минимум lab6 в приложение (API, worker, OTel)
- бизнес-API без изменений контракта; транспорт теперь HTTPS за mTLS-relay
- retry задачи переопубликовывается через outbox (в lab6 задача после
  ошибки оставалась в queued навсегда); trace context сохраняется в
  outbox.headers, поэтому API -> broker -> worker остаётся одной трассой
- структурные JSON-логи: trace_id/span_id в теле строки (SDK игнорирует
  formatter, поэтому добавлен JsonLoggingHandler)
- закрыты дефекты lab6: закреплён uid datasource в dashboard, убрана
  зависимость от Valkey (сессии и rate limit - в PostgreSQL)
- метрики/логи/трассы уходят в Collector по OTLP с клиентским сертификатом

Co-Authored-By: O3 Agent Claude <noreply@ozon.ru>
2026-11-27 19:58:21 +03:00

73 lines
2.6 KiB
Python

"""Внутренний 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