Files

52 lines
1.5 KiB
Python

import threading
class APIMetrics:
"""
In-memory metrics tracker for the Ingestion API.
Thread-safe and async-safe counter for Prometheus scraping.
"""
def __init__(self):
self._lock = threading.Lock()
self._received_total: int = 0
self._acknowledged_total: int = 0
def increment_received(self, count: int = 1) -> None:
with self._lock:
self._received_total += count
def increment_acknowledged(self, count: int = 1) -> None:
with self._lock:
self._acknowledged_total += count
@property
def total_received(self) -> int:
with self._lock:
return self._received_total
@property
def total_acknowledged(self) -> int:
with self._lock:
return self._acknowledged_total
def get_prometheus_metrics(self) -> str:
"""
Formats metrics into standard Prometheus text format.
"""
with self._lock:
val_received = self._received_total
val_ack = self._acknowledged_total
return (
"# HELP cdr_api_received_total Total CDRs received by the API\n"
"# TYPE cdr_api_received_total counter\n"
f"cdr_api_received_total {val_received}\n"
"# HELP cdr_api_acknowledged_total Total CDRs successfully acknowledged by Kafka\n"
"# TYPE cdr_api_acknowledged_total counter\n"
f"cdr_api_acknowledged_total {val_ack}\n"
)
api_metrics = APIMetrics()