protosocket_rpc/server/
socket_server.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
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
use std::future::Future;
use std::io::Error;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;

use protosocket::Connection;
use tokio::sync::mpsc;

use super::connection_server::RpcConnectionServer;
use super::rpc_submitter::RpcSubmitter;
use super::server_traits::SocketService;

/// A `SocketRpcServer` is a server future. It listens on a socket and spawns new connections,
/// with a ConnectionService to handle each connection.
///
/// Protosockets use monomorphic messages: You can only have 1 kind of message per service.
/// The expected way to work with this is to use prost and protocol buffers to encode messages.
///
/// The socket server hosts your SocketService.
/// Your SocketService creates a ConnectionService for each new connection.
/// Your ConnectionService manages one connection. It is Dropped when the connection is closed.
pub struct SocketRpcServer<TSocketService>
where
    TSocketService: SocketService,
{
    socket_server: TSocketService,
    listener: tokio::net::TcpListener,
    max_buffer_length: usize,
    max_queued_outbound_messages: usize,
}

impl<TSocketService> SocketRpcServer<TSocketService>
where
    TSocketService: SocketService,
{
    /// Construct a new `SocketRpcServer` listening on the provided address.
    pub async fn new(
        address: std::net::SocketAddr,
        socket_server: TSocketService,
    ) -> crate::Result<Self> {
        let listener = tokio::net::TcpListener::bind(address).await?;
        Ok(Self {
            socket_server,
            listener,
            max_buffer_length: 16 * (2 << 20),
            max_queued_outbound_messages: 128,
        })
    }

    /// Set the maximum buffer length for connections created by this server after the setting is applied.
    pub fn set_max_buffer_length(&mut self, max_buffer_length: usize) {
        self.max_buffer_length = max_buffer_length;
    }

    /// Set the maximum queued outbound messages for connections created by this server after the setting is applied.
    pub fn set_max_queued_outbound_messages(&mut self, max_queued_outbound_messages: usize) {
        self.max_queued_outbound_messages = max_queued_outbound_messages;
    }
}

impl<TSocketService> Future for SocketRpcServer<TSocketService>
where
    TSocketService: SocketService,
{
    type Output = Result<(), Error>;

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        loop {
            break match self.listener.poll_accept(context) {
                Poll::Ready(result) => match result {
                    Ok((stream, address)) => {
                        stream.set_nodelay(true)?;
                        let (submitter, inbound_messages) = RpcSubmitter::new();
                        let (outbound_messages, outbound_messages_receiver) =
                            mpsc::channel(self.max_queued_outbound_messages);
                        let connection_service = self.socket_server.new_connection_service(address);
                        let connection_rpc_server = RpcConnectionServer::new(
                            connection_service,
                            inbound_messages,
                            outbound_messages,
                        );

                        let connection: Connection<RpcSubmitter<TSocketService>> = Connection::new(
                            stream,
                            address,
                            self.socket_server.deserializer(),
                            self.socket_server.serializer(),
                            self.max_buffer_length,
                            self.max_queued_outbound_messages,
                            outbound_messages_receiver,
                            submitter,
                        );

                        tokio::spawn(connection);
                        tokio::spawn(connection_rpc_server);

                        continue;
                    }
                    Err(e) => {
                        log::error!("failed to accept connection: {e:?}");
                        continue;
                    }
                },
                Poll::Pending => Poll::Pending,
            };
        }
    }
}