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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
use std::convert::TryFrom;
use std::pin::Pin;
use std::task::{Context, Poll};

use futures::io::Error as IoError;
use futures::io::ErrorKind;
use futures::io::Result as IoResult;
use futures::prelude::*;
use num_traits::FromPrimitive;

use super::*;
use crate::decode::{ArrayFuture, MsgPackFuture, StringFuture, ValueFuture};

pub enum RpcMessage<R> {
    Request(RpcRequestFuture<R>),
    Response(RpcResponseFuture<R>),
    Notify(RpcNotifyFuture<R>),
}

impl<R> RpcMessage<R> {
    fn request(id: MsgId, array: ArrayFuture<R>) -> Self {
        RpcMessage::Request(RpcRequestFuture { array, id })
    }

    fn response(id: MsgId, array: ArrayFuture<R>) -> Self {
        RpcMessage::Response(RpcResponseFuture { array, id })
    }

    fn notify(array: ArrayFuture<R>) -> Self {
        RpcMessage::Notify(RpcNotifyFuture { array })
    }
}

pub struct RpcRequestFuture<R> {
    array: ArrayFuture<R>,
    id: MsgId,
}

impl<R: AsyncRead + Unpin> RpcRequestFuture<R> {
    pub fn id(&self) -> MsgId {
        self.id
    }

    pub async fn method(self) -> IoResult<StringFuture<RpcParamsFuture<R>>> {
        self.array
            .next()
            .into_option()
            // Wrap with RpcParamsFuture before potentially returning the ValueFuture
            .map(|m| MsgPackFuture::new(RpcParamsFuture(m.into_inner())))
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "array missing method field"))?
            .decode()
            .await?
            .into_string()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "expected method string"))
    }

    pub async fn skip(self) -> IoResult<R>
    where
        R: Send + 'static,
    {
        self.method()
            .await?
            .skip()
            .await?
            .params()
            .await?
            .skip()
            .await
    }
}

pub struct RpcParamsFuture<R>(ArrayFuture<R>);

impl<R: AsyncRead + Unpin> RpcParamsFuture<R> {
    pub async fn params(self) -> IoResult<ArrayFuture<R>> {
        self.0
            .last()
            .into_option()
            .ok_or_else(|| {
                IoError::new(
                    ErrorKind::InvalidData,
                    "array missing params or too many fields",
                )
            })?
            .decode()
            .await?
            .into_array()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "expected params array"))
    }
}

impl<R: AsyncRead + Unpin> AsyncRead for RpcParamsFuture<R> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context,
        buf: &mut [u8],
    ) -> Poll<IoResult<usize>> {
        ArrayFuture::poll_read(Pin::new(&mut self.as_mut().0), cx, buf)
    }
}

pub struct RpcResponseFuture<R> {
    array: ArrayFuture<R>,
    id: MsgId,
}

impl<R: AsyncRead + Unpin> RpcResponseFuture<R> {
    pub fn id(&self) -> MsgId {
        self.id
    }

    pub async fn result(
        self,
    ) -> IoResult<Result<ValueFuture<RpcResultFuture<R>>, ValueFuture<RpcResultFuture<R>>>> {
        let err = self
            .array
            .next()
            .into_option()
            // Wrap with RpcResultFuture before potentially returning the ValueFuture
            .map(|m| MsgPackFuture::new(RpcResultFuture(m.into_inner())))
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "array missing error field"))?
            .decode()
            .await?;
        if let ValueFuture::Nil(m) = err {
            m.0.next()
                .into_option()
                // Wrap with RpcResultFuture before potentially returning the ValueFuture
                .map(|m| MsgPackFuture::new(RpcResultFuture(m.into_inner())))
                .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "array missing result field"))?
                .decode()
                .await
                .map(Ok)
        } else {
            Ok(Err(err))
        }
    }

    /// Consume this message and return the underlying reader
    pub fn skip(self) -> impl Future<Output = IoResult<R>>
    where
        R: Send + 'static,
    {
        self.array.skip()
    }
}

/// Container that ensures the response message array is consumed before
/// returning the underlying reader
pub struct RpcResultFuture<R>(ArrayFuture<R>);

impl<R: AsyncRead + Unpin + Send + 'static> RpcResultFuture<R> {
    pub async fn finish(self) -> IoResult<R> {
        self.0.skip().await
    }
}

impl<R: AsyncRead + Unpin> AsyncRead for RpcResultFuture<R> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context,
        buf: &mut [u8],
    ) -> Poll<IoResult<usize>> {
        ArrayFuture::poll_read(Pin::new(&mut self.as_mut().0), cx, buf)
    }
}

pub struct RpcNotifyFuture<R> {
    array: ArrayFuture<R>,
}

impl<R: AsyncRead + Unpin + Send> RpcNotifyFuture<R> {
    pub async fn method(self) -> IoResult<StringFuture<RpcParamsFuture<R>>> {
        self.array
            .next()
            .into_option()
            // Wrap with RpcParamsFuture before potentially returning the ValueFuture
            .map(|m| MsgPackFuture::new(RpcParamsFuture(m.into_inner())))
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "array missing method field"))?
            .decode()
            .await?
            .into_string()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "expected method string"))
    }

    pub async fn skip(self) -> IoResult<R>
    where
        R: 'static,
    {
        self.method()
            .await?
            .skip()
            .await?
            .params()
            .await?
            .skip()
            .await
    }
}

pub struct RpcStream<R> {
    reader: R,
}

impl<R: AsyncRead + Unpin> RpcStream<R> {
    pub fn new(reader: R) -> Self {
        RpcStream { reader }
    }

    pub fn as_mut(&mut self) -> RpcStream<&mut R> {
        RpcStream {
            reader: &mut self.reader,
        }
    }

    /// Helper used for request and response to read the msgid field
    async fn decode_msgid<R2: AsyncRead + Unpin>(
        array: ArrayFuture<R2>,
    ) -> IoResult<(MsgId, ArrayFuture<R2>)> {
        let msgid = array
            .next()
            .into_option()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "msgpack array 0-length"))?;
        let (msgid, array) = msgid
            .decode()
            .await?
            .into_u64()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "msgid not int"))?;
        let msgid = u32::try_from(msgid)
            .map_err(|_| IoError::new(ErrorKind::InvalidData, "msgid out of range"))?;
        Ok((MsgId(msgid), array))
    }

    pub async fn next(self) -> IoResult<RpcMessage<RpcStream<R>>> {
        // First, wrap our RpcStream in a MsgPackFuture rather than using the
        // underlying reader. When this message is fully consumed and its reader
        // is returned, the client will be left with this RpcStream pointing at
        // the next message.
        let msg = MsgPackFuture::new(self);
        let a = msg
            .decode()
            .await?
            .into_array()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "expected array"))?;
        let ty = a
            .next()
            .into_option()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "msgpack array 0-length"))?;
        let (ty, array) = ty
            .decode()
            .await?
            .into_u64()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidData, "msgtype not int"))?;

        match MsgType::from_u64(ty) {
            Some(MsgType::Request) => Self::decode_msgid(array)
                .await
                .map(|(msgid, array)| RpcMessage::request(msgid, array)),
            Some(MsgType::Response) => Self::decode_msgid(array)
                .await
                .map(|(msgid, array)| RpcMessage::response(msgid, array)),
            Some(MsgType::Notification) => Ok(RpcMessage::notify(array)),
            None => Err(IoError::new(
                ErrorKind::InvalidData,
                format!("invalid msgtype {}", ty),
            )),
        }
    }
}

impl<R: AsyncRead + Unpin> AsyncRead for RpcStream<R> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context,
        buf: &mut [u8],
    ) -> Poll<IoResult<usize>> {
        R::poll_read(Pin::new(&mut self.as_mut().reader), cx, buf)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use futures::io::Cursor;
    use rmpv::Value;

    #[test]
    fn decode_request() {
        // Serialize a method call message
        let call1 = Value::Array(vec![
            0.into(),
            1.into(),
            "summon".into(),
            Value::Array(vec!["husker".into(), "knights".into()]),
        ]);
        let call2 = Value::Array(vec![
            0.into(),
            2.into(),
            "floop".into(),
            Value::Array(vec!["pig".into()]),
        ]);
        let mut buf = Vec::new();
        rmpv::encode::write_value(&mut buf, &call1).unwrap();
        rmpv::encode::write_value(&mut buf, &call2).unwrap();
        let stream = RpcStream::new(Cursor::new(buf));

        async fn read_message<R: AsyncRead + Unpin>(stream: RpcStream<R>) -> IoResult<()> {
            let stream = match stream.next().await? {
                RpcMessage::Request(req) => {
                    assert_eq!(req.id(), 1.into());
                    let method: StringFuture<_> = req.method().await?;
                    let (method, params) = method.into_string().await?;
                    assert_eq!(method, "summon");
                    let params: ArrayFuture<_> = params.params().await?;
                    // Read first param into heap-allocated String
                    let (param1, params) = params
                        .next()
                        .into_option()
                        .unwrap()
                        .decode()
                        .await?
                        .into_string()
                        .unwrap()
                        .into_string()
                        .await?;
                    assert_eq!(param1, "husker");
                    // Read second (last) param into fixed-length buffer
                    let mut param2 = [0u8; 7];
                    let stream = params
                        .last()
                        .into_option()
                        .unwrap()
                        .decode()
                        .await?
                        .into_string()
                        .unwrap()
                        .read_all(&mut param2)
                        .await?;
                    assert_eq!(std::str::from_utf8(&param2).unwrap(), "knights");
                    stream
                }
                _ => panic!("Wrong message type"),
            };
            let _stream = match stream.next().await? {
                RpcMessage::Request(req) => {
                    assert_eq!(req.id(), 2.into());
                    let method: StringFuture<_> = req.method().await?;
                    let (method, params) = method.into_string().await?;
                    assert_eq!(method, "floop");
                    let params: ArrayFuture<_> = params.params().await?;
                    // Read first (last) param into fixed-length buffer
                    let mut param2 = [0u8; 3];
                    let stream = params
                        .last()
                        .into_option()
                        .unwrap()
                        .decode()
                        .await?
                        .into_string()
                        .unwrap()
                        .read_all(&mut param2)
                        .await?;
                    assert_eq!(std::str::from_utf8(&param2).unwrap(), "pig");
                    stream
                }
                _ => panic!("Wrong message type"),
            };
            Ok(())
        }

        futures::executor::LocalPool::new()
            .run_until(read_message(stream))
            .unwrap();
    }
}