    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

    #![forbid(unsafe_code)]
    #![deny(rust_2018_idioms, nonstandard_style)]
    #![warn(future_incompatible)]

    use std::{
        fmt,
        future::Future,
        ops::{Deref, DerefMut},
        pin::Pin,
        task::{self, Poll},
    };

    use actix_web::{
        body::BoxBody,
        dev::Payload,
        error::PayloadError,
        http::header::{CONTENT_LENGTH, CONTENT_TYPE},
        web::BytesMut,
        Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, HttpResponseBuilder, Responder,
        ResponseError,
    };
    use derive_more::Display;
    use futures_util::{
        future::{FutureExt as _, LocalBoxFuture},
        stream::StreamExt as _,
    };
    use prost::{DecodeError as ProtoBufDecodeError, EncodeError as ProtoBufEncodeError, Message};

    #[derive(Debug, Display)]
    pub enum ProtoBufPayloadError {
        /// Payload size is bigger than 256k
        #[display(fmt = "Payload size is bigger than 256k")]
        Overflow,

        /// Content type error
        #[display(fmt = "Content type error")]
        ContentType,

        /// Serialize error
        #[display(fmt = "ProtoBuf serialize error: {}", _0)]
        Serialize(ProtoBufEncodeError),

        /// Deserialize error
        #[display(fmt = "ProtoBuf deserialize error: {}", _0)]
        Deserialize(ProtoBufDecodeError),

        /// Payload error
        #[display(fmt = "Error that occur during reading payload: {}", _0)]
        Payload(PayloadError),
    }

    impl ResponseError for ProtoBufPayloadError {
        fn error_response(&self) -> HttpResponse {
            match *self {
                ProtoBufPayloadError::Overflow => HttpResponse::PayloadTooLarge().into(),
                _ => HttpResponse::BadRequest().into(),
            }
        }
    }

    impl From<PayloadError> for ProtoBufPayloadError {
        fn from(err: PayloadError) -> ProtoBufPayloadError {
            ProtoBufPayloadError::Payload(err)
        }
    }

    impl From<ProtoBufDecodeError> for ProtoBufPayloadError {
        fn from(err: ProtoBufDecodeError) -> ProtoBufPayloadError {
            ProtoBufPayloadError::Deserialize(err)
        }
    }

    pub struct ProtoBuf<T: Message>(pub T);

    impl<T: Message> Deref for ProtoBuf<T> {
        type Target = T;

        fn deref(&self) -> &T {
            &self.0
        }
    }

    impl<T: Message> DerefMut for ProtoBuf<T> {
        fn deref_mut(&mut self) -> &mut T {
            &mut self.0
        }
    }

    impl<T: Message> fmt::Debug for ProtoBuf<T>
    where
        T: fmt::Debug,
    {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "ProtoBuf: {:?}", self.0)
        }
    }

    impl<T: Message> fmt::Display for ProtoBuf<T>
    where
        T: fmt::Display,
    {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            fmt::Display::fmt(&self.0, f)
        }
    }

    pub struct ProtoBufConfig {
        limit: usize,
    }

    impl ProtoBufConfig {
        /// Change max size of payload. By default max size is 256Kb
        pub fn limit(&mut self, limit: usize) -> &mut Self {
            self.limit = limit;
            self
        }
    }

    impl Default for ProtoBufConfig {
        fn default() -> Self {
            ProtoBufConfig { limit: 262_144 }
        }
    }

    impl<T> FromRequest for ProtoBuf<T>
    where
        T: Message + Default + 'static,
    {
        type Error = Error;
        type Future = LocalBoxFuture<'static, Result<Self, Error>>;

        #[inline]
        fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
            let limit = req
                .app_data::<ProtoBufConfig>()
                .map(|c| c.limit)
                .unwrap_or(262_144);
            ProtoBufMessage::new(req, payload)
                .limit(limit)
                .map(move |res| match res {
                    Err(e) => Err(e.into()),
                    Ok(item) => Ok(ProtoBuf(item)),
                })
                .boxed_local()
        }
    }

    impl<T: Message + Default> Responder for ProtoBuf<T> {
        type Body = BoxBody;

        fn respond_to(self, _: &HttpRequest) -> HttpResponse {
            let mut buf = Vec::new();
            match self.0.encode(&mut buf) {
                Ok(()) => HttpResponse::Ok()
                    .content_type("application/protobuf")
                    .body(buf),
                Err(err) => HttpResponse::from_error(Error::from(ProtoBufPayloadError::Serialize(err))),
            }
        }
    }

    pub struct ProtoBufMessage<T: Message + Default> {
        limit: usize,
        length: Option<usize>,
        stream: Option<Payload>,
        err: Option<ProtoBufPayloadError>,
        fut: Option<LocalBoxFuture<'static, Result<T, ProtoBufPayloadError>>>,
    }

    impl<T: Message + Default> ProtoBufMessage<T> {
        /// Create `ProtoBufMessage` for request.
        pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
            if req.content_type() != "application/protobuf" {
                return ProtoBufMessage {
                    limit: 262_144,
                    length: None,
                    stream: None,
                    fut: None,
                    err: Some(ProtoBufPayloadError::ContentType),
                };
            }

            let mut len = None;
            if let Some(l) = req.headers().get(CONTENT_LENGTH) {
                if let Ok(s) = l.to_str() {
                    if let Ok(l) = s.parse::<usize>() {
                        len = Some(l)
                    }
                }
            }

            ProtoBufMessage {
                limit: 262_144,
                length: len,
                stream: Some(payload.take()),
                fut: None,
                err: None,
            }
        }

        /// Change max size of payload. By default max size is 256Kb
        pub fn limit(mut self, limit: usize) -> Self {
            self.limit = limit;
            self
        }
    }

    impl<T: Message + Default + 'static> Future for ProtoBufMessage<T> {
        type Output = Result<T, ProtoBufPayloadError>;

        fn poll(mut self: Pin<&mut Self>, task: &mut task::Context<'_>) -> Poll<Self::Output> {
            if let Some(ref mut fut) = self.fut {
                return Pin::new(fut).poll(task);
            }

            if let Some(err) = self.err.take() {
                return Poll::Ready(Err(err));
            }

            let limit = self.limit;
            if let Some(len) = self.length.take() {
                if len > limit {
                    return Poll::Ready(Err(ProtoBufPayloadError::Overflow));
                }
            }

            let mut stream = self
                .stream
                .take()
                .expect("ProtoBufMessage could not be used second time");

            self.fut = Some(
                async move {
                    let mut body = BytesMut::with_capacity(8192);

                    while let Some(item) = stream.next().await {
                        let chunk = item?;
                        if (body.len() + chunk.len()) > limit {
                            return Err(ProtoBufPayloadError::Overflow);
                        } else {
                            body.extend_from_slice(&chunk);
                        }
                    }

                    Ok(<T>::decode(&mut body)?)
                }
                .boxed_local(),
            );
            self.poll(task)
        }
    }

    pub trait ProtoBufResponseBuilder {
        fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error>;
    }

    impl ProtoBufResponseBuilder for HttpResponseBuilder {
        fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error> {
            self.insert_header((CONTENT_TYPE, "application/protobuf"));

            let mut body = Vec::new();
            value
                .encode(&mut body)
                .map_err(ProtoBufPayloadError::Serialize)?;
            Ok(self.body(body))
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use actix_web::http::header;
        use actix_web::test::TestRequest;

        impl PartialEq for ProtoBufPayloadError {
            fn eq(&self, other: &ProtoBufPayloadError) -> bool {
                match *self {
                    ProtoBufPayloadError::Overflow => {
                        matches!(*other, ProtoBufPayloadError::Overflow)
                    }
                    ProtoBufPayloadError::ContentType => {
                        matches!(*other, ProtoBufPayloadError::ContentType)
                    }
                    _ => false,
                }
            }
        }

        #[derive(Clone, PartialEq, Message)]
        pub struct MyObject {
            #[prost(int32, tag = "1")]
            pub number: i32,
            #[prost(string, tag = "2")]
            pub name: String,
        }

        #[actix_web::test]
        async fn test_protobuf() {
            let protobuf = ProtoBuf(MyObject {
                number: 9,
                name: "test".to_owned(),
            });
            let req = TestRequest::default().to_http_request();
            let resp = protobuf.respond_to(&req);
            let ct = resp.headers().get(header::CONTENT_TYPE).unwrap();
            assert_eq!(ct, "application/protobuf");
        }

        #[actix_web::test]
        async fn test_protobuf_message() {
            let (req, mut pl) = TestRequest::default().to_http_parts();
            let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
            assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);

            let (req, mut pl) = TestRequest::get()
                .insert_header((header::CONTENT_TYPE, "application/text"))
                .to_http_parts();
            let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
            assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);

            let (req, mut pl) = TestRequest::get()
                .insert_header((header::CONTENT_TYPE, "application/protobuf"))
                .insert_header((header::CONTENT_LENGTH, "10000"))
                .to_http_parts();
            let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl)
                .limit(100)
                .await;
            assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::Overflow);
        }
    }