mmtickets_common/network/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
pub 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()
    ))
}