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
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
use anyhow::{bail, Context, Result};
use async_net::{TcpListener, TcpStream};
use futures::AsyncWriteExt;

use crate::runtime::AsyncKernel;
use crate::runtime::Block;
use crate::runtime::BlockMeta;
use crate::runtime::BlockMetaBuilder;
use crate::runtime::MessageIo;
use crate::runtime::MessageIoBuilder;
use crate::runtime::StreamIo;
use crate::runtime::StreamIoBuilder;
use crate::runtime::WorkIo;

pub struct TcpSink {
    port: u32,
    listener: Option<TcpListener>,
    socket: Option<TcpStream>,
}

impl TcpSink {
    pub fn new(port: u32) -> Block {
        Block::new_async(
            BlockMetaBuilder::new("TcpSink").build(),
            StreamIoBuilder::new().add_input("in", 1).build(),
            MessageIoBuilder::new().build(),
            TcpSink {
                port,
                listener: None,
                socket: None,
            },
        )
    }
}

#[async_trait]
impl AsyncKernel for TcpSink {
    async fn work(
        &mut self,
        io: &mut WorkIo,
        sio: &mut StreamIo,
        _mio: &mut MessageIo<Self>,
        _meta: &mut BlockMeta,
    ) -> Result<()> {
        if self.socket.is_none() {
            let (socket, _) = self
                .listener
                .as_mut()
                .context("no listener")?
                .accept()
                .await?;
            self.socket = Some(socket);
            debug!("tcp sink accepted connection");
        }

        let i = sio.input(0).slice::<u8>();

        match self
            .socket
            .as_mut()
            .context("no socket")?
            .write_all(i)
            .await
        {
            Ok(()) => {}
            Err(_) => bail!("tcp sink socket error"),
        }

        if sio.input(0).finished() {
            io.finished = true;
        }

        debug!("tcp sink wrote bytes {}", i.len());
        sio.input(0).consume(i.len());

        Ok(())
    }

    async fn init(
        &mut self,
        _sio: &mut StreamIo,
        _mio: &mut MessageIo<Self>,
        _meta: &mut BlockMeta,
    ) -> Result<()> {
        self.listener = Some(TcpListener::bind(format!("127.0.0.1:{}", self.port)).await?);
        Ok(())
    }
}

pub struct TcpSinkBuilder {
    port: u32,
}

impl TcpSinkBuilder {
    pub fn new(port: u32) -> TcpSinkBuilder {
        TcpSinkBuilder { port }
    }

    pub fn build(self) -> Block {
        TcpSink::new(self.port)
    }
}