use crate::connection::{create_connection_object, Connection, ConnectionConfig};
use crate::error::{OgmiosError, Result};
use crate::schema::ServerHealth;
use tracing::debug;
pub const DEFAULT_MIN_SYNCHRONIZATION: f64 = 0.999;
pub async fn get_server_health(connection: Option<ConnectionConfig>) -> Result<ServerHealth> {
let conn = create_connection_object(connection);
get_server_health_from_connection(&conn).await
}
pub async fn get_server_health_from_connection(connection: &Connection) -> Result<ServerHealth> {
let url = format!("{}/health", connection.address.http);
debug!("Fetching server health from {}", url);
let response = reqwest::get(&url).await?;
let health: ServerHealth = response.json().await?;
Ok(health)
}
#[derive(Debug, Clone)]
pub struct EnsureServerHealthOptions {
pub connection: Option<ConnectionConfig>,
pub min_synchronization: f64,
}
impl Default for EnsureServerHealthOptions {
fn default() -> Self {
Self {
connection: None,
min_synchronization: DEFAULT_MIN_SYNCHRONIZATION,
}
}
}
pub async fn ensure_server_health(options: EnsureServerHealthOptions) -> Result<ServerHealth> {
let health = get_server_health(options.connection).await?;
if health.network_synchronization < options.min_synchronization {
return Err(OgmiosError::ServerNotReady {
synchronization: health.network_synchronization * 100.0,
minimum: options.min_synchronization * 100.0,
});
}
Ok(health)
}
#[derive(Debug, Clone)]
pub struct ServerNotReady {
pub synchronization: f64,
pub minimum: f64,
pub health: ServerHealth,
}
impl std::fmt::Display for ServerNotReady {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Server not ready: network synchronization is {:.2}%, minimum required is {:.2}%",
self.synchronization * 100.0,
self.minimum * 100.0
)
}
}
impl std::error::Error for ServerNotReady {}
pub async fn wait_for_server_ready(
connection: Option<ConnectionConfig>,
min_synchronization: f64,
poll_interval: std::time::Duration,
timeout: std::time::Duration,
) -> Result<ServerHealth> {
let deadline = tokio::time::Instant::now() + timeout;
loop {
match get_server_health(connection.clone()).await {
Ok(health) => {
if health.network_synchronization >= min_synchronization {
return Ok(health);
}
debug!(
"Server sync at {:.2}%, waiting for {:.2}%",
health.network_synchronization * 100.0,
min_synchronization * 100.0
);
}
Err(e) => {
debug!("Health check failed: {}, retrying...", e);
}
}
if tokio::time::Instant::now() >= deadline {
return Err(OgmiosError::Timeout {
timeout_ms: timeout.as_millis() as u64,
});
}
tokio::time::sleep(poll_interval).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_options() {
let options = EnsureServerHealthOptions::default();
assert!(options.connection.is_none());
assert_eq!(options.min_synchronization, DEFAULT_MIN_SYNCHRONIZATION);
}
}