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
//! Loopback connection to the language client.

use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use futures::channel::mpsc::Receiver;
use futures::sink::Sink;
use futures::stream::{FusedStream, Stream, StreamExt};

use super::{ExitedError, Pending, ServerState, State};
use crate::jsonrpc::{Request, Response};

/// A loopback channel for server-to-client communication.
#[derive(Debug)]
pub struct ClientSocket {
    pub(super) rx: Receiver<Request>,
    pub(super) pending: Arc<Pending>,
    pub(super) state: Arc<ServerState>,
}

impl ClientSocket {
    /// Splits this `ClientSocket` into two halves capable of operating independently.
    ///
    /// The two halves returned implement the [`Stream`] and [`Sink`] traits, respectively.
    ///
    /// [`Stream`]: futures::Stream
    /// [`Sink`]: futures::Sink
    pub fn split(self) -> (RequestStream, ResponseSink) {
        let ClientSocket { rx, pending, state } = self;
        let state_ = state.clone();

        (
            RequestStream { rx, state: state_ },
            ResponseSink { pending, state },
        )
    }
}

/// Yields a stream of pending server-to-client requests.
impl Stream for ClientSocket {
    type Item = Request;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if self.state.get() == State::Exited || self.rx.is_terminated() {
            Poll::Ready(None)
        } else {
            self.rx.poll_next_unpin(cx)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.rx.size_hint()
    }
}

impl FusedStream for ClientSocket {
    fn is_terminated(&self) -> bool {
        self.rx.is_terminated()
    }
}

/// Routes client-to-server responses back to the server.
impl Sink<Response> for ClientSocket {
    type Error = ExitedError;

    fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        if self.state.get() == State::Exited || self.rx.is_terminated() {
            Poll::Ready(Err(ExitedError(())))
        } else {
            Poll::Ready(Ok(()))
        }
    }

    fn start_send(self: Pin<&mut Self>, item: Response) -> Result<(), Self::Error> {
        self.pending.insert(item);
        Ok(())
    }

    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }
}

/// Yields a stream of pending server-to-client requests.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct RequestStream {
    rx: Receiver<Request>,
    state: Arc<ServerState>,
}

impl Stream for RequestStream {
    type Item = Request;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if self.state.get() == State::Exited || self.rx.is_terminated() {
            Poll::Ready(None)
        } else {
            self.rx.poll_next_unpin(cx)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.rx.size_hint()
    }
}

impl FusedStream for RequestStream {
    fn is_terminated(&self) -> bool {
        self.rx.is_terminated()
    }
}

/// Routes client-to-server responses back to the server.
#[derive(Debug)]
pub struct ResponseSink {
    pending: Arc<Pending>,
    state: Arc<ServerState>,
}

impl Sink<Response> for ResponseSink {
    type Error = ExitedError;

    fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        if self.state.get() == State::Exited {
            Poll::Ready(Err(ExitedError(())))
        } else {
            Poll::Ready(Ok(()))
        }
    }

    fn start_send(self: Pin<&mut Self>, item: Response) -> Result<(), Self::Error> {
        self.pending.insert(item);
        Ok(())
    }

    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }
}