summaryrefslogtreecommitdiffstats
path: root/src/service/tcp.rs
blob: 6556af0375c1e666857d7ceb262d85e4d62acc39 (plain)
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
38
39
40
41
42
43
44
45
use std::{fmt::Display, net::SocketAddr, time::Duration};

use async_stream::try_stream;
use futures::Stream;
use serde::Deserialize;
use tokio::{io::Interest, net::TcpSocket};

use super::IntoService;

pub(crate) type Error = std::io::Error;

#[derive(Debug, Clone, Deserialize)]
pub struct Tcp {
    pub address: SocketAddr,
    #[serde(default = "super::default_interval")]
    pub interval: Duration,
}

impl Display for Tcp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "tcp://{}", self.address)
    }
}

impl IntoService for Tcp {
    type Error = Error;

    fn into_service(self) -> impl Stream<Item = Result<(), Self::Error>> {
        let mut interval = tokio::time::interval(self.interval);

        try_stream! {
            loop {
                interval.tick().await;

                let sock = TcpSocket::new_v4()?;
                sock.set_keepalive(true)?;

                let conn =  sock.connect(self.address).await?;
                // TODO: figure out how to wait for connection to close
                conn.ready(Interest::READABLE).await?;
                yield ();
            }
        }
    }
}