aboutsummaryrefslogtreecommitdiff
path: root/src/tcp.rs
blob: 5684c41c44b484f1021dc32f1919381f1ad83f59 (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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
//! TCP backed channel and listener implementations.
//!
//! ```no_run
//! #[urpc::service]
//! trait Hello {
//!     type Error = ();
//!
//!     async fn hello(name: String) -> String;
//! }
//!
//! struct HelloServer;
//!
//! impl Hello for HelloServer {
//!     async fn hello(&self, _ctx: urpc::Context, name: String) -> Result<String, ()> {
//!         Ok(format!("Hello, {name}!"))
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>>{
//!     let listener = urpc::tcp::bind("0.0.0.0:3000").await?;
//!
//!     // spawn the server
//!     tokio::spawn(async move {
//!         urpc::Server::default()
//!             .with_listener(listener)
//!             .with_service(HelloServer.into_service())
//!             .serve()
//!             .await
//!     });
//!
//!     // create a client
//!     let channel = urpc::ClientChannel::new(urpc::tcp::connect("127.0.0.1:3000").await?);
//!     let client = HelloClient::new(channel);
//!     let greeting = client.hello("World".into()).await.unwrap();
//!     assert_eq!(greeting, "Hello, World!");
//!     Ok(())
//! }
//! ```
use std::pin::Pin;

use futures::{Sink, Stream};
use tokio::{
    net::{TcpListener, TcpStream, ToSocketAddrs},
    sync::mpsc::Receiver,
    task::AbortHandle,
};
use tokio_util::codec::Framed;

use crate::{
    Channel, Listener,
    protocol::{RpcMessage, RpcMessageCodec},
};

pub struct TcpChannel(Framed<TcpStream, RpcMessageCodec>);

impl TcpChannel {
    fn new(stream: TcpStream) -> Self {
        Self(Framed::new(stream, RpcMessageCodec::default()))
    }

    pub async fn connect(addrs: impl ToSocketAddrs) -> std::io::Result<Self> {
        let stream = TcpStream::connect(addrs).await?;
        Ok(Self::new(stream))
    }
}

impl Sink<RpcMessage> for TcpChannel {
    type Error = std::io::Error;

    fn poll_ready(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::result::Result<(), Self::Error>> {
        Sink::poll_ready(Pin::new(&mut self.get_mut().0), cx)
    }

    fn start_send(self: Pin<&mut Self>, item: RpcMessage) -> std::result::Result<(), Self::Error> {
        Sink::start_send(Pin::new(&mut self.get_mut().0), item)
    }

    fn poll_flush(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::result::Result<(), Self::Error>> {
        Sink::poll_flush(Pin::new(&mut self.get_mut().0), cx)
    }

    fn poll_close(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::result::Result<(), Self::Error>> {
        Sink::poll_close(Pin::new(&mut self.get_mut().0), cx)
    }
}

impl Stream for TcpChannel {
    type Item = std::io::Result<RpcMessage>;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        Stream::poll_next(Pin::new(&mut self.get_mut().0), cx)
    }
}

impl Channel for TcpChannel {}

pub struct TcpChannelListener {
    receiver: Receiver<TcpChannel>,
    abort: AbortHandle,
}

impl Drop for TcpChannelListener {
    fn drop(&mut self) {
        self.abort.abort();
    }
}

impl TcpChannelListener {
    pub async fn bind(addrs: impl ToSocketAddrs) -> std::io::Result<Self> {
        let listener = TcpListener::bind(addrs).await?;
        let (sender, receiver) = tokio::sync::mpsc::channel(8);
        let abort = tokio::spawn(async move {
            while let Ok((stream, _addr)) = listener.accept().await {
                if sender.send(TcpChannel::new(stream)).await.is_err() {
                    break;
                }
            }
        })
        .abort_handle();
        Ok(Self { receiver, abort })
    }
}

impl Stream for TcpChannelListener {
    type Item = std::io::Result<TcpChannel>;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        self.get_mut().receiver.poll_recv(cx).map(|v| v.map(Ok))
    }
}

impl Listener<TcpChannel> for TcpChannelListener {}

pub async fn bind(addrs: impl ToSocketAddrs) -> std::io::Result<TcpChannelListener> {
    TcpChannelListener::bind(addrs).await
}

pub async fn connect(addrs: impl ToSocketAddrs) -> std::io::Result<TcpChannel> {
    TcpChannel::connect(addrs).await
}