wait-on 0.0.14

Library and CLI Utility to wait on the availability of resources such as Files, HTTP Servers, Ports & Sockets
Documentation
use std::net::{IpAddr, SocketAddr};
use std::time::Duration;

use anyhow::Result;
use tokio::net::TcpStream;
use tokio::time::sleep;

use crate::{WaitOptions, Waitable};

/// Listens on a specific IP Address and Port using TCP protocol
#[derive(Clone)]
pub struct TcpWaiter {
    pub addr: IpAddr,
    pub port: u16,
}

impl TcpWaiter {
    pub fn new(addr: IpAddr, port: u16) -> Self {
        Self { addr, port }
    }

    pub fn socket(&self) -> SocketAddr {
        SocketAddr::new(self.addr, self.port)
    }
}

impl Waitable for TcpWaiter {
    async fn wait(&self, _: &WaitOptions) -> Result<()> {
        let connect = || async { TcpStream::connect(self.socket()).await };

        while (connect().await).is_err() {
            sleep(Duration::from_secs(1)).await;
        }

        Ok(())
    }
}