mmtickets_common/network/
mod.rspub async fn connect_with_retry(
host: &str,
port: &str,
retry_interval: std::time::Duration,
max_duration: std::time::Duration,
) -> Result<async_nats::Client, String> {
let start_time = tokio::time::Instant::now();
loop {
let elapsed = start_time.elapsed();
if elapsed >= max_duration {
break;
}
let result = tokio::time::timeout(retry_interval, async {
async_nats::ConnectOptions::new()
.connect(format!("{}:{}", host, port))
.await
})
.await;
match result {
Ok(Ok(connection)) => return Ok(connection),
Ok(Err(error)) => {
println!("Failed to connect to NATS: {}, retrying...", error);
tokio::time::sleep(retry_interval).await;
}
Err(_) => {
println!("Failed to connect to NATS: timeout");
tokio::time::sleep(retry_interval).await;
}
}
}
Err(format!(
"Failed to connect to NATS after {} retries",
max_duration.as_secs()
))
}