"""Prometheus metrics for the optional HTTP service."""
from __future__ import annotations
from typing import Any
[docs]
class ApiMetrics:
"""Application-scoped Prometheus metrics with bounded label cardinality."""
[docs]
def __init__(self) -> None:
try:
from prometheus_client import CollectorRegistry, Counter, Gauge, Histogram
except ImportError as exc:
raise ImportError(
"Prometheus metrics require the optional API dependencies. "
"Install automated-document-parser[api]."
) from exc
self.registry = CollectorRegistry(auto_describe=True)
self.requests = Counter(
"adp_http_requests_total",
"Completed HTTP requests handled by the ADP API.",
("method", "route", "status"),
registry=self.registry,
)
self.request_duration = Histogram(
"adp_http_request_duration_seconds",
"HTTP request duration in seconds.",
("method", "route"),
registry=self.registry,
buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10),
)
self.jobs_enqueued = Counter(
"adp_ingestion_jobs_enqueued_total",
"Ingestion jobs accepted by the API.",
registry=self.registry,
)
self.job_states = Gauge(
"adp_ingestion_jobs",
"Current ingestion jobs by lifecycle state.",
("state",),
registry=self.registry,
)
self.worker_running = Gauge(
"adp_ingestion_worker_running",
"Whether the ingestion worker thread is running (1) or stopped (0).",
registry=self.registry,
)
self.worker_paused = Gauge(
"adp_ingestion_worker_paused",
"Whether the ingestion worker is paused (1) or active (0).",
registry=self.registry,
)
[docs]
def observe_request(
self, method: str, route: str, status_code: int, duration_seconds: float
) -> None:
"""Record a completed request using its route template, not raw URL."""
self.requests.labels(method, route, str(status_code)).inc()
self.request_duration.labels(method, route).observe(duration_seconds)
[docs]
def observe_job_enqueued(self) -> None:
"""Record a job accepted by the HTTP API."""
self.jobs_enqueued.inc()
[docs]
def update_runtime(
self, job_counts: dict[str, int], worker: dict[str, Any]
) -> None:
"""Refresh gauges from durable state rather than process-local counters."""
for state, count in job_counts.items():
self.job_states.labels(state).set(count)
self.worker_running.set(1 if worker.get("running") else 0)
self.worker_paused.set(1 if worker.get("paused") else 0)