use actix_web::rt::time::{Instant as RtInstant, interval_at};
use actix_web::web::Data;
use std::env::var;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Interval;
use tracing::{debug, info, warn};
use uuid::Uuid;
const B: &str = "\x1b[1m"; const Y: &str = "\x1b[33m"; const R: &str = "\x1b[31m"; const _G: &str = "\x1b[32m"; const Z: &str = "\x1b[0m";
use crate::AppState;
use crate::data::client_connections::{insert_connection_snapshot, prune_connection_snapshots};
use crate::drivers::postgresql::pool_manager::ConnectionPoolSnapshot;
use crate::drivers::postgresql::sqlx_driver::PostgresClientRegistry;
const DEFAULT_MONITOR_INTERVAL_SECS: u64 = 30;
const DEFAULT_MONITOR_RETENTION_HOURS: i64 = 24;
pub fn spawn_connection_monitor(app_state: Data<AppState>) {
let Some(logging_client_name) = app_state.logging_client_name.clone() else {
debug!("No logging client configured; skipping connection monitor");
return;
};
let Some(logging_pool) = app_state.pg_registry.get_pool(&logging_client_name) else {
warn!(
client = %logging_client_name,
"Logging client pool unavailable; skipping connection monitor"
);
return;
};
let registry: Arc<PostgresClientRegistry> = app_state.pg_registry.clone();
let host: String = var("HOSTNAME").unwrap_or_else(|_| "unknown".to_string());
let instance_id: Uuid = Uuid::new_v4();
let interval_secs: u64 = var("ATHENA_POOL_MONITOR_INTERVAL_SECS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(DEFAULT_MONITOR_INTERVAL_SECS);
let retention_hours: i64 = var("ATHENA_POOL_MONITOR_RETENTION_HOURS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(DEFAULT_MONITOR_RETENTION_HOURS);
info!(
client = %logging_client_name,
interval_secs,
retention_hours,
host,
instance_id = %instance_id,
"Starting connection pool monitor"
);
actix_web::rt::spawn(async move {
let start: RtInstant = RtInstant::now();
let mut ticker: Interval = interval_at(start, Duration::from_secs(interval_secs));
loop {
ticker.tick().await;
let snapshots: Vec<ConnectionPoolSnapshot> = registry.pool_snapshots();
let total: usize = snapshots.len();
let mut failed: i32 = 0;
let mut last_err: Option<sqlx::Error> = None;
for snapshot in &snapshots {
if let Err(err) =
insert_connection_snapshot(&logging_pool, snapshot, &host, instance_id).await
{
failed += 1;
if last_err.is_none() {
last_err = Some(err);
}
}
}
if failed > 0 {
warn!(
failed,
total,
error = %last_err.unwrap(),
"{}⚠{} {}Failed to write client_connections snapshot(s){} ({}failed{}={}, total={}); {}logging DB may be unreachable{}",
Y, Z, B, Z, B, Z, failed, total, R, Z
);
}
if let Err(err) = prune_connection_snapshots(&logging_pool, retention_hours).await {
debug!(error = %err, "Failed to prune old client_connections rows");
}
}
});
}