from __future__ import annotations from datetime import UTC, datetime class MetricsMixin: def increment_metric(self, name: str, amount: float = 1.0) -> None: now = datetime.now(UTC).isoformat() with self.connect() as conn: conn.execute( """ INSERT INTO service_metrics(name, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(name) DO UPDATE SET value=value + excluded.value, updated_at=excluded.updated_at """, (name, amount, now), ) def set_metric(self, name: str, value: float) -> None: now = datetime.now(UTC).isoformat() with self.connect() as conn: conn.execute( """ INSERT INTO service_metrics(name, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(name) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at """, (name, value, now), ) def get_service_metrics(self) -> dict[str, float]: with self.connect() as conn: rows = conn.execute("SELECT name, value FROM service_metrics").fetchall() return {str(row["name"]): float(row["value"]) for row in rows} def record_update_metrics( self, latency_ms: float, *, is_success: bool = False, is_dns_failure: bool = False, is_reconcile_failure: bool = False, is_bad_ip: bool = False, ) -> None: increments = { "update_requests_total": 1, "update_latency_ms_total": latency_ms, "update_latency_samples_total": 1, } if is_success: increments["update_success_total"] = 1 if is_dns_failure: increments["dns_failures_total"] = 1 if is_reconcile_failure: increments["dns_reconcile_failures_total"] = 1 if is_bad_ip: increments["bad_ip_total"] = 1 now = datetime.now(UTC).isoformat() with self.connect() as conn: conn.executemany( """ INSERT INTO service_metrics(name, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(name) DO UPDATE SET value=value + excluded.value, updated_at=excluded.updated_at """, [(name, value, now) for name, value in increments.items()], ) conn.execute( """ INSERT INTO service_metrics(name, value, updated_at) VALUES ('last_update_latency_ms', ?, ?) ON CONFLICT(name) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at """, (latency_ms, now), )