|
| 1 | +"""Liveness and readiness endpoints for orchestration. |
| 2 | +
|
| 3 | +``/healthz`` reports that the process is up. ``/readyz`` reports whether the |
| 4 | +service can actually serve S3 requests, by checking the object store and the |
| 5 | +Celery broker. When storage is disabled, those dependencies are not required |
| 6 | +and report ``disabled``. |
| 7 | +""" |
| 8 | + |
| 9 | +import logging |
| 10 | + |
| 11 | +from apiflask import APIBlueprint |
| 12 | +from flask import current_app, jsonify |
| 13 | + |
| 14 | +from app.storage.s3 import S3Backend |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | +health_bp = APIBlueprint("health", __name__) |
| 19 | + |
| 20 | +# Short connection timeout (seconds) so readiness checks fail quickly. |
| 21 | +_BROKER_TIMEOUT = 3 |
| 22 | + |
| 23 | + |
| 24 | +def check_storage(settings) -> tuple[bool, str]: |
| 25 | + """Return whether the object store is reachable, with a detail string.""" |
| 26 | + if not settings.storage_enabled: |
| 27 | + return True, "disabled" |
| 28 | + try: |
| 29 | + S3Backend.from_settings(settings).health_check() |
| 30 | + return True, "ok" |
| 31 | + except Exception as error: # noqa: BLE001 - any failure means not ready |
| 32 | + logger.warning("Storage readiness check failed: %s", error) |
| 33 | + return False, str(error) |
| 34 | + |
| 35 | + |
| 36 | +def check_broker(settings) -> tuple[bool, str]: |
| 37 | + """Return whether the Celery broker is reachable, with a detail string.""" |
| 38 | + if not settings.storage_enabled: |
| 39 | + return True, "disabled" |
| 40 | + try: |
| 41 | + from kombu import Connection |
| 42 | + |
| 43 | + with Connection(settings.celery_broker_url) as connection: |
| 44 | + connection.ensure_connection(max_retries=1, timeout=_BROKER_TIMEOUT) |
| 45 | + return True, "ok" |
| 46 | + except Exception as error: # noqa: BLE001 - any failure means not ready |
| 47 | + logger.warning("Broker readiness check failed: %s", error) |
| 48 | + return False, str(error) |
| 49 | + |
| 50 | + |
| 51 | +@health_bp.get("/healthz") |
| 52 | +def healthz(): |
| 53 | + """Liveness: the process is running.""" |
| 54 | + return jsonify({"status": "ok"}), 200 |
| 55 | + |
| 56 | + |
| 57 | +@health_bp.get("/readyz") |
| 58 | +def readyz(): |
| 59 | + """Readiness: dependencies needed to serve requests are reachable.""" |
| 60 | + settings = current_app.config["SETTINGS"] |
| 61 | + |
| 62 | + storage_ok, storage_detail = check_storage(settings) |
| 63 | + broker_ok, broker_detail = check_broker(settings) |
| 64 | + ready = storage_ok and broker_ok |
| 65 | + |
| 66 | + body = { |
| 67 | + "status": "ready" if ready else "not ready", |
| 68 | + "checks": {"storage": storage_detail, "broker": broker_detail}, |
| 69 | + } |
| 70 | + return jsonify(body), (200 if ready else 503) |
0 commit comments