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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;

use bytes::Bytes;
use futures_util::future::select;
use futures_util::future::Either;
use tokio::codec::{FramedRead, FramedWrite};
use tokio::prelude::*;
use tokio::sync::{mpsc, oneshot};

use crate::codecs::CodecError;
use crate::frame::Response;
use crate::{Codec, Error, Frame, RawFrame};

#[derive(Debug)]
pub struct Request(pub Bytes, pub RawFrame, pub Option<ReplyTicket>);

#[derive(Debug)]
enum WriteCmd {
    Frame(Frame),
    Request(Bytes, RawFrame, Option<oneshot::Sender<Response>>),
    Reply(Bytes, Response),
    Exit,
}

#[derive(Debug)]
pub struct ReplyTicket {
    tag: Bytes,
    write_handle: mpsc::Sender<WriteCmd>,
    sent: bool,
}

impl ReplyTicket {
    pub async fn ok(mut self, reply: RawFrame) -> Result<(), mpsc::error::SendError> {
        self.sent = true;
        self.write_handle
            .send(WriteCmd::Frame(Frame::Response {
                tag: self.tag.split_off(0),
                response: Ok(reply),
            }))
            .await?;

        Ok(())
    }

    pub async fn error(
        mut self,
        code: Option<Bytes>,
        description: Option<Bytes>,
    ) -> Result<(), mpsc::error::SendError> {
        self.sent = true;
        let frame = Frame::error(self.tag.split_off(0), code, description);
        self.write_handle.send(WriteCmd::Frame(frame)).await?;

        Ok(())
    }
}

impl Drop for ReplyTicket {
    fn drop(&mut self) {
        if !self.sent {
            let mut write_handle = self.write_handle.clone();
            let frame = Frame::error(
                self.tag.split_off(0),
                None,
                Some("Request dropped without reply".into()),
            );
            tokio::spawn(async move {
                write_handle
                    .send(WriteCmd::Frame(frame))
                    .await
                    .expect("error on drop")
            });
        }
    }
}

#[derive(Clone)]
pub struct RequestSender(mpsc::Sender<WriteCmd>);

impl RequestSender {
    pub async fn call_remote(
        &mut self,
        command: Bytes,
        fields: RawFrame,
    ) -> Result<RawFrame, Error> {
        let (tx, rx) = oneshot::channel();
        self.0
            .send(WriteCmd::Request(command, fields, Some(tx)))
            .await?;

        rx.await?.map_err(|err| Error::Remote {
            code: err.code,
            description: err.description,
        })
    }

    pub async fn call_remote_noreply(
        &mut self,
        command: Bytes,
        fields: RawFrame,
    ) -> Result<(), Error> {
        self.0
            .send(WriteCmd::Request(command, fields, None))
            .await?;

        Ok(())
    }
}

pub struct Handle {
    write_res: oneshot::Receiver<Result<(), Error>>,
    read_res: oneshot::Receiver<Result<(), Error>>,
    write_loop_handle: mpsc::Sender<WriteCmd>,
    shutdown: Option<oneshot::Sender<()>>,
}

impl Handle {
    pub fn shutdown(&mut self) -> Result<(), Error> {
        if let Some(s) = self.shutdown.take() {
            // Read loop might already be shutdown.
            s.send(()).map_err(|_| Error::SendError)?;
        }
        Ok(())
    }

    pub async fn join(mut self) -> Result<(), Error> {
        let _ = (&mut self.write_res).await?;
        let _ = (&mut self.read_res).await?;
        Ok(())
    }

    pub fn request_sender(&self) -> RequestSender {
        RequestSender(self.write_loop_handle.clone())
    }
}

pub fn serve<R, W>(input: R, output: W) -> (Handle, mpsc::Receiver<Request>)
where
    R: AsyncRead + Unpin + Send + 'static,
    W: AsyncWrite + Unpin + Send + 'static,
{
    let (write_tx, write_rx) = mpsc::channel::<WriteCmd>(32);
    let write_tx2 = write_tx.clone();
    let (dispatch_tx, dispatch_rx) = mpsc::channel::<Request>(32);
    let (read_res_tx, read_res_rx) = oneshot::channel();
    let (write_res_tx, write_res_rx) = oneshot::channel();
    let (shutdown_tx, shutdown_rx) = oneshot::channel();

    tokio::spawn(async move {
        let res = read_loop(input, shutdown_rx, write_tx2, dispatch_tx).await;
        // Handle may already be dropped.
        let _ = read_res_tx.send(res);
    });
    tokio::spawn(async move {
        let res = write_loop(output, write_rx).await;
        // Handle may already be dropped.
        let _ = write_res_tx.send(res);
    });

    (
        Handle {
            write_res: write_res_rx,
            read_res: read_res_rx,
            write_loop_handle: write_tx,
            shutdown: Some(shutdown_tx),
        },
        dispatch_rx,
    )
}

impl Drop for Handle {
    fn drop(&mut self) {
        let _ = self.shutdown();
    }
}

async fn read_or_shutdown<S>(
    stream: &mut S,
    shutdown: &mut oneshot::Receiver<()>,
) -> Option<Result<RawFrame, CodecError>>
where
    S: Unpin + Stream<Item = Result<RawFrame, CodecError>>,
{
    let select_res = select(stream.next(), shutdown).await;
    match select_res {
        Either::Left((None, _)) => None,
        Either::Left((Some(frame), _)) => Some(frame),
        Either::Right((_, _)) => None,
    }
}

async fn read_loop<R>(
    input: R,
    mut shutdown: oneshot::Receiver<()>,
    mut write_tx: mpsc::Sender<WriteCmd>,
    mut dispatch_tx: mpsc::Sender<Request>,
) -> Result<(), Error>
where
    R: AsyncRead + Unpin,
{
    let codec_in: Codec<RawFrame> = Codec::new();
    let mut input = FramedRead::new(input, codec_in);

    while let Some(frame) = read_or_shutdown(&mut input, &mut shutdown).await {
        match frame?.try_into()? {
            Frame::Request {
                tag,
                command,
                fields,
            } => {
                let ticket = tag.map(|tag| ReplyTicket {
                    tag,
                    write_handle: write_tx.clone(),
                    sent: false,
                });

                // The application may close its dispatch channel. All
                // incoming requests will generate a "Request dropped
                // without reply" error.
                let _ = dispatch_tx.send(Request(command, fields, ticket)).await;
            }

            Frame::Response { tag, response } => {
                write_tx.send(WriteCmd::Reply(tag, response)).await?;
            }
        }
    }

    write_tx.send(WriteCmd::Exit).await?;
    Ok(())
}

async fn write_loop<W>(output: W, mut input: mpsc::Receiver<WriteCmd>) -> Result<(), Error>
where
    W: AsyncWrite + Unpin,
{
    let codec_out: Codec<RawFrame> = Codec::new();
    let mut output = FramedWrite::new(output, codec_out);
    let mut seqno: u64 = 0;
    let mut seqno_str = String::with_capacity(10);
    let mut reply_map = HashMap::new();

    while let Some(msg) = input.next().await {
        match msg {
            WriteCmd::Frame(frame) => {
                let frame = frame.into();
                output.send(frame).await?;
            }
            WriteCmd::Request(command, fields, reply) => {
                let tag = reply.map(|reply| {
                    seqno += 1;
                    seqno_str.clear();
                    write!(seqno_str, "{:x}", seqno).unwrap();

                    let seq_str: Bytes = seqno_str.as_bytes().into();
                    reply_map.insert(seq_str.clone(), reply);
                    seq_str
                });

                let frame = Frame::Request {
                    command,
                    tag,
                    fields,
                };
                output.send(frame.into()).await?;
            }
            WriteCmd::Reply(tag, response) => {
                let reply_tx = reply_map.remove(&tag).ok_or(Error::UnmatchedReply)?;
                reply_tx.send(response).map_err(|_| Error::SendError)?;
            }
            WriteCmd::Exit => input.close(),
        }
    }

    Ok(())
}