use std::time::{Duration, Instant};
pub async fn wait_for_http_ready(port: u16, timeout: Duration) -> Result<(), String> {
let deadline = Instant::now() + timeout;
let url = format!("http://127.0.0.1:{}/health", port);
let client = reqwest::Client::builder()
.timeout(Duration::from_millis(100))
.build()
.map_err(|e| format!("Failed to create HTTP client: {}", e))?;
while Instant::now() < deadline {
match client.get(&url).send().await {
Ok(resp) if resp.status().is_success() => {
return Ok(());
}
_ => {
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
}
Err(format!(
"HTTP server health check timed out after {:?} on port {}",
timeout, port
))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_wait_for_http_ready_timeout() {
let result = wait_for_http_ready(19999, Duration::from_millis(100)).await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("timed out"));
}
}