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
use std::{convert::Infallible, time::Duration};

use crate::SgBody;
use futures_util::Future;
use hyper::{Request, Response};
use tokio::time::Sleep;
use tower_layer::Layer;
#[derive(Clone)]
pub struct TimeoutLayer {
    /// timeout duration
    pub timeout: Duration,
    pub timeout_response: hyper::body::Bytes,
}

impl<S> Layer<S> for TimeoutLayer {
    type Service = Timeout<S>;

    fn layer(&self, inner: S) -> Self::Service {
        Timeout {
            inner,
            timeout: self.timeout,
            timeout_response: self.timeout_response.clone(),
        }
    }
}

#[derive(Clone)]
pub struct Timeout<S> {
    inner: S,
    timeout: Duration,
    timeout_response: hyper::body::Bytes,
}

impl TimeoutLayer {
    pub fn new(timeout: Duration) -> Self {
        Self {
            timeout,
            timeout_response: hyper::body::Bytes::default(),
        }
    }
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = timeout;
    }
}

impl<S> Timeout<S> {
    pub fn new(timeout: Duration, timeout_response: hyper::body::Bytes, inner: S) -> Self {
        Self { inner, timeout, timeout_response }
    }
}

impl<S> hyper::service::Service<Request<SgBody>> for Timeout<S>
where
    S: hyper::service::Service<Request<SgBody>, Response = Response<SgBody>, Error = Infallible> + Send + 'static,
    <S as hyper::service::Service<Request<SgBody>>>::Future: std::marker::Send,
{
    type Response = Response<SgBody>;

    type Error = Infallible;

    type Future = TimeoutFuture<S::Future>;

    fn call(&self, req: Request<SgBody>) -> Self::Future {
        TimeoutFuture {
            inner: self.inner.call(req),
            timeout: tokio::time::sleep(self.timeout),
            timeout_response: self.timeout_response.clone(),
        }
    }
}

pin_project_lite::pin_project! {
    pub struct TimeoutFuture<F> {
        #[pin]
        inner: F,
        #[pin]
        timeout: Sleep,
        timeout_response: hyper::body::Bytes,
    }
}

impl<F> Future for TimeoutFuture<F>
where
    F: Future<Output = Result<Response<SgBody>, Infallible>> + Send + 'static,
{
    type Output = Result<Response<SgBody>, Infallible>;

    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        let this = self.project();
        if this.timeout.poll(cx).is_ready() {
            let response = Response::builder().status(hyper::StatusCode::GATEWAY_TIMEOUT).body(SgBody::full(this.timeout_response.clone())).expect("invalid response");
            return std::task::Poll::Ready(Ok(response));
        }
        this.inner.poll(cx)
    }
}