|
| 1 | +use std::{net::SocketAddr, sync::Arc}; |
| 2 | + |
| 3 | +use axum::{extract::State, http::StatusCode, response::Json, routing::get, Router}; |
| 4 | +use serde::{Deserialize, Serialize}; |
| 5 | +use tokio::net::TcpListener; |
| 6 | +use tracing::{error, info}; |
| 7 | + |
| 8 | +use crate::{ |
| 9 | + database::postgres::client::PostgresClient, indexer::task_tracker::active_indexing_count, |
| 10 | + manifest::core::Manifest, system_state::is_running, |
| 11 | +}; |
| 12 | + |
| 13 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 14 | +pub struct HealthStatus { |
| 15 | + pub status: HealthStatusType, |
| 16 | + pub timestamp: String, |
| 17 | + pub services: HealthServices, |
| 18 | + pub indexing: IndexingStatus, |
| 19 | +} |
| 20 | + |
| 21 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 22 | +pub struct HealthServices { |
| 23 | + pub database: HealthStatusType, |
| 24 | + pub indexing: HealthStatusType, |
| 25 | + pub sync: HealthStatusType, |
| 26 | +} |
| 27 | + |
| 28 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 29 | +pub struct IndexingStatus { |
| 30 | + pub active_tasks: usize, |
| 31 | + pub is_running: bool, |
| 32 | +} |
| 33 | + |
| 34 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 35 | +#[serde(rename_all = "lowercase")] |
| 36 | +pub enum HealthStatusType { |
| 37 | + Healthy, |
| 38 | + Unhealthy, |
| 39 | + Unknown, |
| 40 | + NotConfigured, |
| 41 | + Disabled, |
| 42 | + NoData, |
| 43 | + Stopped, |
| 44 | +} |
| 45 | + |
| 46 | +#[derive(Clone)] |
| 47 | +pub struct HealthServerState { |
| 48 | + pub manifest: Arc<Manifest>, |
| 49 | + pub postgres_client: Option<Arc<PostgresClient>>, |
| 50 | +} |
| 51 | + |
| 52 | +pub struct HealthServer { |
| 53 | + port: u16, |
| 54 | + state: HealthServerState, |
| 55 | +} |
| 56 | + |
| 57 | +impl HealthServer { |
| 58 | + pub fn new( |
| 59 | + port: u16, |
| 60 | + manifest: Arc<Manifest>, |
| 61 | + postgres_client: Option<Arc<PostgresClient>>, |
| 62 | + ) -> Self { |
| 63 | + Self { port, state: HealthServerState { manifest, postgres_client } } |
| 64 | + } |
| 65 | + |
| 66 | + pub async fn start(self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { |
| 67 | + let app = Router::new().route("/health", get(health_handler)).with_state(self.state); |
| 68 | + |
| 69 | + let addr = SocketAddr::from(([0, 0, 0, 0], self.port)); |
| 70 | + let listener = TcpListener::bind(addr).await?; |
| 71 | + |
| 72 | + info!("🩺 Health server started on http://0.0.0.0:{}/health", self.port); |
| 73 | + |
| 74 | + axum::serve(listener, app).await?; |
| 75 | + Ok(()) |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +async fn health_handler( |
| 80 | + State(state): State<HealthServerState>, |
| 81 | +) -> Result<(StatusCode, Json<HealthStatus>), StatusCode> { |
| 82 | + let database_health = check_database_health(&state).await; |
| 83 | + let indexing_health = check_indexing_health(); |
| 84 | + let sync_health = check_sync_health(&state).await; |
| 85 | + |
| 86 | + let overall_status = determine_overall_status(&database_health, &indexing_health, &sync_health); |
| 87 | + |
| 88 | + let health_status = |
| 89 | + build_health_status(overall_status, database_health, indexing_health, sync_health); |
| 90 | + |
| 91 | + let status_code = if matches!(health_status.status, HealthStatusType::Healthy) { |
| 92 | + StatusCode::OK |
| 93 | + } else { |
| 94 | + StatusCode::SERVICE_UNAVAILABLE |
| 95 | + }; |
| 96 | + |
| 97 | + Ok((status_code, Json(health_status))) |
| 98 | +} |
| 99 | + |
| 100 | +fn build_health_status( |
| 101 | + overall_status: HealthStatusType, |
| 102 | + database_health: HealthStatusType, |
| 103 | + indexing_health: HealthStatusType, |
| 104 | + sync_health: HealthStatusType, |
| 105 | +) -> HealthStatus { |
| 106 | + HealthStatus { |
| 107 | + status: overall_status, |
| 108 | + timestamp: chrono::Utc::now().to_rfc3339(), |
| 109 | + services: HealthServices { |
| 110 | + database: database_health, |
| 111 | + indexing: indexing_health, |
| 112 | + sync: sync_health, |
| 113 | + }, |
| 114 | + indexing: IndexingStatus { |
| 115 | + active_tasks: active_indexing_count(), |
| 116 | + is_running: is_running(), |
| 117 | + }, |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +async fn check_database_health(state: &HealthServerState) -> HealthStatusType { |
| 122 | + if !state.manifest.storage.postgres_enabled() { |
| 123 | + return HealthStatusType::Disabled; |
| 124 | + } |
| 125 | + |
| 126 | + match &state.postgres_client { |
| 127 | + Some(client) => match client.query_one("SELECT 1", &[]).await { |
| 128 | + Ok(_) => HealthStatusType::Healthy, |
| 129 | + Err(e) => { |
| 130 | + error!("Database health check failed: {}", e); |
| 131 | + HealthStatusType::Unhealthy |
| 132 | + } |
| 133 | + }, |
| 134 | + None => HealthStatusType::NotConfigured, |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +fn check_indexing_health() -> HealthStatusType { |
| 139 | + if is_running() { |
| 140 | + HealthStatusType::Healthy |
| 141 | + } else { |
| 142 | + HealthStatusType::Stopped |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +async fn check_sync_health(state: &HealthServerState) -> HealthStatusType { |
| 147 | + if state.manifest.storage.postgres_enabled() { |
| 148 | + check_postgres_sync_health(state).await |
| 149 | + } else if state.manifest.storage.csv_enabled() { |
| 150 | + check_csv_sync_health(state) |
| 151 | + } else { |
| 152 | + HealthStatusType::Disabled |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +async fn check_postgres_sync_health(state: &HealthServerState) -> HealthStatusType { |
| 157 | + match &state.postgres_client { |
| 158 | + Some(client) => { |
| 159 | + match client.query_one_or_none( |
| 160 | + r#"SELECT 1 FROM information_schema.tables WHERE table_schema NOT IN ('information_schema', 'pg_catalog', 'rindexer_internal') AND table_name NOT LIKE 'latest_block' AND table_name NOT LIKE '%_last_known_%' AND table_name NOT LIKE '%_last_run_%' LIMIT 1"#, |
| 161 | + &[] |
| 162 | + ).await { |
| 163 | + Ok(Some(_)) => HealthStatusType::Healthy, |
| 164 | + Ok(None) => HealthStatusType::NoData, |
| 165 | + Err(e) => { |
| 166 | + error!("Sync health check failed: {}", e); |
| 167 | + HealthStatusType::Unhealthy |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | + None => HealthStatusType::NotConfigured, |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +fn check_csv_sync_health(state: &HealthServerState) -> HealthStatusType { |
| 176 | + match &state.manifest.storage.csv { |
| 177 | + Some(csv_details) => { |
| 178 | + let csv_path = std::path::Path::new(&csv_details.path); |
| 179 | + if !csv_path.exists() { |
| 180 | + return HealthStatusType::NoData; |
| 181 | + } |
| 182 | + |
| 183 | + match std::fs::read_dir(csv_path) { |
| 184 | + Ok(entries) => { |
| 185 | + let csv_files: Vec<_> = entries |
| 186 | + .filter_map(|entry| entry.ok()) |
| 187 | + .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "csv")) |
| 188 | + .collect(); |
| 189 | + |
| 190 | + if csv_files.is_empty() { |
| 191 | + HealthStatusType::NoData |
| 192 | + } else { |
| 193 | + HealthStatusType::Healthy |
| 194 | + } |
| 195 | + } |
| 196 | + Err(_) => HealthStatusType::Unhealthy, |
| 197 | + } |
| 198 | + } |
| 199 | + None => HealthStatusType::NotConfigured, |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +fn determine_overall_status( |
| 204 | + database: &HealthStatusType, |
| 205 | + indexing: &HealthStatusType, |
| 206 | + sync: &HealthStatusType, |
| 207 | +) -> HealthStatusType { |
| 208 | + if matches!(database, HealthStatusType::Unhealthy | HealthStatusType::NotConfigured) |
| 209 | + || matches!(indexing, HealthStatusType::Stopped) |
| 210 | + || matches!(sync, HealthStatusType::Unhealthy | HealthStatusType::NotConfigured) |
| 211 | + { |
| 212 | + HealthStatusType::Unhealthy |
| 213 | + } else if matches!(sync, HealthStatusType::NoData) { |
| 214 | + // Sync NoData is acceptable when no event tables exist yet |
| 215 | + HealthStatusType::Healthy |
| 216 | + } else { |
| 217 | + HealthStatusType::Healthy |
| 218 | + } |
| 219 | +} |
| 220 | + |
| 221 | +pub async fn start_health_server( |
| 222 | + port: u16, |
| 223 | + manifest: Arc<Manifest>, |
| 224 | + postgres_client: Option<Arc<PostgresClient>>, |
| 225 | +) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { |
| 226 | + let health_server = HealthServer::new(port, manifest, postgres_client); |
| 227 | + health_server.start().await |
| 228 | +} |
0 commit comments