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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
use prelude::*;
use std::{
    convert::Infallible,
    error::Error as StdError,
    fmt::{self, Debug, Display, Formatter},
};
use warp::{reply::Response as WarpResponse, Rejection};

/// Useful filters.
pub mod filters {
    use super::*;

    pub use rate::rate_limit;

    pub mod rate {
        use super::*;

        use std::{net::SocketAddr, sync::Arc, time::Duration};

        use warp::Filter;

        /// A rate of requests per time period.
        #[derive(Debug, Copy, Clone)]
        pub struct Rate {
            num: u64,
            per: Duration,
        }

        impl Rate {
            /// Create a new rate.
            ///
            /// # Notes
            /// This function WILL NOT panic if `num` or `per` is invalid,
            /// ie. either of them are `0`.
            pub const fn new(num: u64, per: Duration) -> Self {
                Rate { num, per }
            }
        }

        #[derive(Debug, Clone, Copy)]
        pub struct State {
            until: Instant,
            rem: u64,
        }

        impl State {
            pub fn new(rate: Rate) -> Self {
                Self {
                    until: Instant::now() + rate.per,
                    rem: rate.num,
                }
            }
        }

        /// Creates a filter that will return an `Err(error)` with `error`
        /// generated with the provided error function if rate limited.
        pub fn rate_limit<Err: CustomError + 'static>(
            rate: Rate,
            error: fn(Duration) -> Err,
        ) -> impl Filter<Extract = (), Error = warp::Rejection> + Sync + Send + Clone {
            let states = Arc::new(dashmap::DashMap::with_hasher(ahash::RandomState::new()));

            warp::addr::remote()
                .and_then(move |addr: Option<SocketAddr>| {
                    let now = Instant::now();

                    let mut state = states.entry(addr).or_insert_with(|| State::new(rate));
                    if now >= state.until {
                        state.until = now + rate.per;
                        state.rem = rate.num;
                    }

                    let res = if state.rem >= 1 {
                        state.rem -= 1;
                        Ok(())
                    } else {
                        Err(state.until - now)
                    };
                    drop(state);

                    let res =
                        res.map_err(|dur| warp::reject::custom(ServerError::Custom(error(dur))));

                    futures_util::future::ready(res)
                })
                .untuple_one()
        }

        /// Creates a filter that will return an `Err(error)` with `error`
        /// generated with the provided error function if rate limited globally,
        /// irregardless of client address.
        pub fn rate_limit_global<Err: CustomError + 'static>(
            rate: Rate,
            error: fn(Duration) -> Err,
        ) -> impl Filter<Extract = (), Error = warp::Rejection> + Sync + Send + Clone {
            let state = Arc::new(parking_lot::Mutex::new(State::new(rate)));

            warp::any()
                .and_then(move || {
                    let now = Instant::now();

                    let mut state = state.lock();
                    if now >= state.until {
                        state.until = now + rate.per;
                        state.rem = rate.num;
                    }

                    let res = if state.rem >= 1 {
                        state.rem -= 1;
                        Ok(())
                    } else {
                        Err(state.until - now)
                    };
                    drop(state);

                    let res =
                        res.map_err(|dur| warp::reject::custom(ServerError::Custom(error(dur))));

                    futures_util::future::ready(res)
                })
                .untuple_one()
        }
    }
}

#[doc(hidden)]
pub mod prelude {
    pub use super::{socket_common, unary_common, CustomError, ServerError, Socket};
    pub use crate::{IntoRequest, Request};
    pub use bytes::{Bytes, BytesMut};
    pub use futures_util::{FutureExt, SinkExt, StreamExt};
    pub use http::HeaderMap;
    pub use std::{
        collections::HashMap,
        time::{Duration, Instant},
    };
    pub use tokio::{self, sync::Mutex, try_join};
    pub use tracing::{debug, error, info, info_span, trace, warn};
    pub use warp::{
        self,
        filters::BoxedFilter,
        reject::Reject,
        reply::Response,
        ws::{Message as WsMessage, Ws},
        Filter, Reply,
    };
}

#[doc(inline)]
pub use warp::http::StatusCode;

#[doc(hidden)]
pub mod unary_common {
    use super::{error, CustomError, ServerError};
    use crate::Request;
    use bytes::BytesMut;
    use futures_util::{future, FutureExt};
    use std::{future::Future, net::SocketAddr};
    use warp::Filter;

    #[doc(hidden)]
    pub fn base_filter<Req, Resp, Err, PreFunc, HandlerFut, Handler>(
        pkg: &'static str,
        method: &'static str,
        pre: PreFunc,
        handler: Handler,
    ) -> impl Filter<Extract = (warp::reply::Response,), Error = warp::Rejection> + Clone
    where
        Req: prost::Message + Default,
        Resp: prost::Message,
        PreFunc: Filter<Extract = (), Error = warp::Rejection> + Send + Clone,
        Err: CustomError + 'static,
        HandlerFut: Future<Output = Result<Resp, Err>> + Send,
        Handler: FnOnce(Request<Req>) -> HandlerFut + Send + Clone,
    {
        warp::post()
            .and(warp::path(pkg))
            .and(warp::path(method))
            .and(pre)
            .and(warp::header::exact_ignore_case(
                "content-type",
                "application/hrpc",
            ))
            .and(warp::body::bytes())
            .map(Req::decode)
            .and_then(move |res: Result<Req, prost::DecodeError>| {
                future::ready(res.map_err(|err| {
                    error!("received invalid protobuf message: {}", pkg);
                    warp::reject::custom(ServerError::<Err>::MessageDecode(err))
                }))
            })
            .and(warp::header::headers_cloned())
            .and(warp::addr::remote())
            .and_then(move |msg, headers, addr: Option<SocketAddr>| {
                let handler = handler.clone();
                let request = Request::from_parts((msg, headers, addr));
                handler(request).map(encode)
            })
    }

    #[doc(hidden)]
    #[inline(always)]
    pub fn encode<Resp, Err>(
        resp: Result<Resp, Err>,
    ) -> Result<warp::reply::Response, warp::Rejection>
    where
        Resp: prost::Message,
        Err: CustomError + 'static,
    {
        match resp {
            Ok(resp) => {
                let mut buf = BytesMut::with_capacity(resp.encoded_len());
                crate::encode_protobuf_message_to(&mut buf, resp);
                let mut resp = warp::reply::Response::new(buf.to_vec().into());
                resp.headers_mut()
                    .insert(http::header::CONTENT_TYPE, crate::hrpc_header_value());
                Ok(resp)
            }
            Err(err) => {
                error!("{}", err);
                Err(warp::reject::custom(ServerError::Custom(err)))
            }
        }
    }
}

#[doc(hidden)]
pub mod socket_common {
    use crate::{HeaderMap, Request};

    use super::{CustomError, ServerError, Socket, SocketError};
    use futures_util::TryFutureExt;
    use std::{future::Future, time::Duration};
    use tracing::error;
    use warp::{ws::Ws, Filter, Reply};

    #[doc(hidden)]
    pub fn base_filter<
        Req,
        Resp,
        Err,
        PreFunc,
        ValidationValue,
        Validation,
        ValidationFut,
        OnUpgrade,
        Handler,
        HandlerFut,
    >(
        pkg: &'static str,
        method: &'static str,
        pre: PreFunc,
        validation: Validation,
        on_upgrade: OnUpgrade,
        handler: Handler,
    ) -> impl Filter<Extract = (warp::reply::Response,), Error = warp::Rejection> + Clone
    where
        Req: prost::Message + Default + Clone + 'static,
        Resp: prost::Message + 'static,
        PreFunc: Filter<Extract = (), Error = warp::Rejection> + Send + Clone,
        Err: CustomError + 'static,
        ValidationValue: Send + 'static,
        ValidationFut: Future<Output = Result<ValidationValue, Err>> + Send,
        Validation: FnOnce(Request<Option<Req>>) -> ValidationFut + Send + Clone,
        OnUpgrade: Fn(warp::reply::Response) -> warp::reply::Response + Send + Clone,
        HandlerFut: Future<Output = ()> + Send + 'static,
        Handler: FnOnce(ValidationValue, Request<Option<Req>>, Socket<Req, Resp>) -> HandlerFut
            + Send
            + Clone
            + 'static,
    {
        warp::path(pkg)
            .and(warp::path(method))
            .and(pre)
            .and(warp::ws())
            .and(warp::header::headers_cloned())
            .and(warp::addr::remote())
            .and_then(move |ws: Ws, headers: HeaderMap, addr| {
                let req = Request::from_parts((None, headers, addr));
                let validation = (validation.clone())(req.clone());
                validation
                    .map_err(|err| warp::reject::custom(ServerError::Custom(err)))
                    .map_ok(move |val| (val, req, ws))
            })
            .untuple_one()
            .map(move |val, req: Request<Option<Req>>, ws: Ws| {
                let handler = handler.clone();
                let reply = ws
                    .on_upgrade(move |ws| {
                        let sock = Socket::<Req, Resp>::new(ws);
                        handler(val, req, sock)
                    })
                    .into_response();
                on_upgrade(reply)
            })
    }

    #[doc(hidden)]
    pub async fn validator<Req, Resp, Err, Val, Fut, Func>(
        req: Request<Option<Req>>,
        sock: &mut Socket<Req, Resp>,
        validator_func: Func,
    ) -> Result<Val, SocketError>
    where
        Req: prost::Message + Default,
        Resp: prost::Message,
        Fut: Future<Output = Result<Val, Err>>,
        Func: FnOnce(Request<Option<Req>>) -> Fut,
        Err: CustomError + 'static,
    {
        let recv_fut = async move {
            let message = sock.receive_message().await?;

            let (_, headers, addr) = req.into_parts();
            let req = Request::from_parts((Some(message), headers, addr));

            match validator_func(req).await {
                Ok(val) => Ok(val),
                Err(err) => {
                    error!("socket validation error: {}", err);
                    Err(SocketError::ClosedNormally)
                }
            }
        };

        tokio::time::timeout(Duration::from_secs(10), recv_fut)
            .await
            .map_err(|_| {
                error!("socket validation request error: timeout");
                SocketError::ClosedNormally
            })?
    }
}

/// A web socket.
#[derive(Debug, Clone)]
pub struct Socket<Req, Resp>
where
    Req: prost::Message + Default + 'static,
    Resp: prost::Message + 'static,
{
    rx: flume::Receiver<Result<Req, SocketError>>,
    tx: flume::Sender<Resp>,
    close_chan: flume::Sender<()>,
}

impl<Req, Resp> Socket<Req, Resp>
where
    Req: prost::Message + Default + 'static,
    Resp: prost::Message + 'static,
{
    pub fn new(mut ws: warp::ws::WebSocket) -> Self {
        let (recv_msg_tx, recv_msg_rx) = flume::bounded(64);
        let (send_msg_tx, send_msg_rx) = flume::bounded(64);
        let (close_chan_tx, close_chan_rx) = flume::bounded(1);
        tokio::spawn(async move {
            let mut buf = BytesMut::new();
            loop {
                tokio::select! {
                    Some(res_msg) = ws.next() => {
                        let resp = match res_msg {
                            Ok(msg) => {
                                let res = if msg.is_binary() || msg.is_text() {
                                    let msg_bin = Bytes::from(msg.into_bytes());
                                    Req::decode(msg_bin)
                                        .map_err(SocketError::MessageDecode)
                                } else if msg.is_close() {
                                    let _ = recv_msg_tx.send_async(Err(SocketError::ClosedNormally)).await;
                                    let _ = ws.close().await;
                                    break;
                                } else {
                                    unreachable!("we handled everything");
                                };
                                res
                            }
                            Err(err) => Err(SocketError::Other(err)),
                        };
                        if recv_msg_tx.send_async(resp).await.is_err() {
                            let _ = ws.close().await;
                            break;
                        }
                    }
                    Ok(resp) = send_msg_rx.recv_async() => {
                        let resp = {
                            crate::encode_protobuf_message_to(&mut buf, resp);
                            buf.to_vec()
                        };

                        if let Err(e) = ws.send(WsMessage::binary(resp)).await {
                            error!("socket send error: {}", e);
                        } else {
                            debug!("responded to client socket");
                        }
                    }
                    // If we get *anything*, it means that either the channel is closed
                    // or we got a close message
                    _ = close_chan_rx.recv_async() => {
                        if let Err(err) = ws.close().await {
                            let _ = recv_msg_tx.send_async(Err(SocketError::Other(err))).await;
                        }
                        break;
                    }
                    else => std::hint::spin_loop(),
                }
            }
        });

        Self {
            rx: recv_msg_rx,
            tx: send_msg_tx,
            close_chan: close_chan_tx,
        }
    }

    /// Receive a message from the socket.
    ///
    /// Returns `Err(SocketError::ClosedNormally)` if the socket is closed normally.
    /// This will block until getting a message if the socket is not closed.
    pub async fn receive_message(&self) -> Result<Req, SocketError> {
        if self.is_closed() {
            Err(SocketError::ClosedNormally)
        } else {
            self.rx
                .recv_async()
                .await
                .unwrap_or(Err(SocketError::ClosedNormally))
        }
    }

    /// Send a message over the socket.
    ///
    /// This will block if the inner send buffer is filled.
    pub async fn send_message(&self, resp: Resp) -> Result<(), SocketError> {
        if self.is_closed() || self.tx.send_async(resp).await.is_err() {
            Err(SocketError::ClosedNormally)
        } else {
            Ok(())
        }
    }

    /// Return whether the socket is closed or not.
    pub fn is_closed(&self) -> bool {
        self.close_chan.is_disconnected()
    }

    /// Close the socket.
    pub async fn close(&self) {
        // We don't care about the error, it's closed either way
        let _ = self.close_chan.send_async(()).await;
    }
}

/// Trait that needs to be implemented to use an error type with a generated service server.
pub trait CustomError: Debug + Display + Send + Sync {
    /// Status code that will be used in client response.
    fn code(&self) -> StatusCode;
    /// Message that will be used in client response.
    fn message(&self) -> Vec<u8>;

    /// Status code and error body used to respond when a protobuf decode error occurs.
    const DECODE_ERROR: (StatusCode, &'static [u8]) = (
        StatusCode::BAD_REQUEST,
        r#"{ "message": "invalid protobuf message" }"#.as_bytes(),
    );
    /// Status code and error body used to respond when a not found error occurs.
    const NOT_FOUND_ERROR: (StatusCode, &'static [u8]) = (
        StatusCode::NOT_FOUND,
        r#"{ "message": "not found" }"#.as_bytes(),
    );
    /// Status code and error body used to respond when a method not allowed error occurs.
    const METHOD_NOT_ALLOWED: (StatusCode, &'static [u8]) = (
        StatusCode::METHOD_NOT_ALLOWED,
        r#"{ "message": "method not allowed" }"#.as_bytes(),
    );
    /// Status code and error body used to respond when an internal server error occurs.
    const INTERNAL_SERVER_ERROR: (StatusCode, &'static [u8]) = (
        StatusCode::INTERNAL_SERVER_ERROR,
        r#"{ "message": "internal server error" }"#.as_bytes(),
    );
}

impl CustomError for std::convert::Infallible {
    fn code(&self) -> StatusCode {
        unreachable!()
    }

    fn message(&self) -> Vec<u8> {
        unreachable!()
    }
}

/// Return if the socket is closed normally, otherwise return the result.
#[macro_export]
macro_rules! return_closed {
    ($result:expr) => {{
        let res = $result;
        if matches!(res, Err($crate::server::SocketError::ClosedNormally)) {
            return;
        } else {
            res
        }
    }};
}

/// Return if the socket is closed normally, otherwise print the error if there is one and return.
#[macro_export]
macro_rules! return_print {
    ($result:expr) => {{
        let res = $crate::return_closed!($result);
        if let Err(err) = res {
            $crate::tracing::error!("error occured: {}", err);
            return;
        }
    }};
    ($result:expr, |$val:ident| $log:expr) => {{
        let res = $crate::return_closed!($result);
        match res {
            Err(err) => {
                $crate::tracing::error!("error occured: {}", err);
                return;
            }
            Ok($val) => $log,
        }
    }};
}

#[derive(Debug)]
pub enum SocketError {
    /// The socket is closed normally. This is NOT an error.
    ClosedNormally,
    /// Error occured while decoding protobuf data.
    MessageDecode(prost::DecodeError),
    /// Some error occured in socket.
    Other(warp::Error),
}

impl Display for SocketError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            SocketError::ClosedNormally => write!(f, "socket closed normally"),
            SocketError::Other(err) => write!(f, "error occured in socket: {}", err),
            SocketError::MessageDecode(err) => write!(f, "invalid protobuf message: {}", err),
        }
    }
}

impl StdError for SocketError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            SocketError::ClosedNormally => None,
            SocketError::Other(err) => Some(err),
            SocketError::MessageDecode(err) => Some(err),
        }
    }
}

#[doc(hidden)]
#[derive(Debug)]
pub enum ServerError<Err: CustomError> {
    MessageDecode(prost::DecodeError),
    Custom(Err),
    Warp(warp::Rejection),
}

impl<Err: CustomError> Display for ServerError<Err> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            ServerError::MessageDecode(err) => write!(f, "invalid protobuf message: {}", err),
            ServerError::Custom(err) => write!(f, "error occured: {}", err),
            ServerError::Warp(err) => write!(f, "warp rejection: {:?}", err),
        }
    }
}

impl<Err: CustomError + StdError + 'static> StdError for ServerError<Err> {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            ServerError::MessageDecode(err) => Some(err),
            ServerError::Custom(err) => Some(err),
            ServerError::Warp(_) => None,
        }
    }
}

impl<Err: CustomError + 'static> warp::reject::Reject for ServerError<Err> {}

impl<Err: CustomError> From<Err> for ServerError<Err> {
    fn from(err: Err) -> Self {
        ServerError::Custom(err)
    }
}

impl<Err: CustomError> From<prost::DecodeError> for ServerError<Err> {
    fn from(err: prost::DecodeError) -> Self {
        ServerError::MessageDecode(err)
    }
}

impl<Err: CustomError> From<warp::Rejection> for ServerError<Err> {
    fn from(err: warp::Rejection) -> Self {
        ServerError::Warp(err)
    }
}

#[doc(hidden)]
pub async fn handle_rejection<Err: CustomError + 'static>(
    err: Rejection,
) -> Result<WarpResponse, Infallible> {
    fn make_response(data: (StatusCode, impl Into<warp::hyper::Body>)) -> WarpResponse {
        let mut reply = WarpResponse::new(data.1.into());
        *reply.status_mut() = data.0;
        reply
    }

    fn find_error<Err: CustomError + 'static>(rejection: &Rejection) -> WarpResponse {
        if let Some(e) = rejection.find::<ServerError<Err>>() {
            match e {
                ServerError::MessageDecode(_) => make_response(Err::DECODE_ERROR),
                ServerError::Custom(err) => make_response((err.code(), err.message())),
                ServerError::Warp(err) => find_error::<Err>(err),
            }
        } else if rejection.is_not_found() {
            make_response(Err::NOT_FOUND_ERROR)
        } else if rejection.find::<warp::reject::MethodNotAllowed>().is_some() {
            make_response(Err::METHOD_NOT_ALLOWED)
        } else {
            error!("unhandled rejection: {:?}", rejection);
            make_response(Err::INTERNAL_SERVER_ERROR)
        }
    }

    let reply = find_error::<Err>(&err);

    Ok(reply)
}

/// Creates a JSON error response from a message.
pub fn json_err_bytes(msg: &str) -> Vec<u8> {
    format!(r#"{{ "message": "{}" }}"#, msg).into_bytes()
}

/// Serves multiple services' filters on the same address.
#[macro_export]
macro_rules! serve_multiple {
    {
        addr: $address:expr,
        err: $err:ty,
        filters: $first:expr, $( $filter:expr, )+
    } => {
        async move {
            use $crate::warp::Filter;

            $crate::warp::serve(
                $first $( .or($filter) )+
                    .with($crate::warp::filters::trace::request())
                    .recover($crate::server::handle_rejection::<$err>)
            )
            .run($address)
            .await
        }
    };
}

/// Serves multiple services' filters on the same address. Supports TLS.
#[macro_export]
macro_rules! serve_multiple_tls {
    {
        addr: $address:expr,
        err: $err:ty,
        key_file: $key_file:expr,
        cert_file: $cert_file:expr,
        filters: $first:expr, $( $filter:expr, )+
    } => {
        async move {
            use $crate::warp::Filter;

            $crate::warp::serve(
                $first $( .or($filter) )+
                    .with($crate::warp::filters::trace::request())
                    .recover($crate::server::handle_rejection::<$err>)
            )
            .tls()
            .key_path($key_file)
            .cert_path($cert_file)
            .run($address)
            .await
        }
    };
}