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
//! Layer for retrying rate limited requests.
//!
//! # Limitations
//!
//! - This layer will drop all extensions that aren't cloned using the
//! `clone_extensions_fn` method on the layer. The method can be used
//! to set a function that will extract the values you want to clone from
//! the original extensions into the new extensions. For example, if you
//! are using a HTTP-backed client, you should use
//! [`crate::client::transport::http::clone_http_extensions`] which will
//! clone HTTP specific extensions for you.

use std::{
    borrow::Cow,
    ops::Not,
    pin::Pin,
    task::{Context, Poll},
    time::Duration,
};

use bytes::Bytes;
use futures_util::{
    future::{Fuse, FusedFuture},
    Future, FutureExt, StreamExt,
};
use prost::Message;
use tower::{Layer, Service};

use crate::{
    body::Body,
    client::{
        prelude::ClientError,
        transport::{SocketRequestMarker, TransportError},
    },
    common::extensions::Extensions,
    proto::{Error as HrpcError, HrpcErrorIdentifier, RetryInfo},
    request::{self, BoxRequest},
};

type CloneExtensionsFn = fn(&Extensions, &mut Extensions);

/// Layer that creates [`Backoff`] services.
///
/// Please read [`Backoff`] and module documentation for more information.
#[derive(Clone)]
pub struct BackoffLayer {
    clone_exts: CloneExtensionsFn,
    max_retries: usize,
}

impl Default for BackoffLayer {
    fn default() -> Self {
        Self {
            clone_exts: |_, _| {},
            max_retries: 5,
        }
    }
}

impl BackoffLayer {
    /// Set a function to extract extensions from a request and add it to a new request.
    ///
    /// This is needed so that user extensions can be added for new requests that
    /// are created for retry. Check the module documentation for more information.
    pub fn clone_extensions_fn(mut self, f: CloneExtensionsFn) -> Self {
        self.clone_exts = f;
        self
    }

    /// Set max retry count. After this is reached, the request won't be
    /// retried anymore and a [`HrpcErrorIdentifier::ResourceExhausted`]
    /// error will be returned.
    pub fn max_retries(mut self, num: usize) -> Self {
        self.max_retries = num;
        self
    }
}

impl<S> Layer<S> for BackoffLayer {
    type Service = Backoff<S>;

    fn layer(&self, inner: S) -> Self::Service {
        Backoff {
            inner,
            clone_exts: self.clone_exts,
            max_retries: self.max_retries,
        }
    }
}

/// Retries ratelimited requests. It uses an exponential backoff algorithm.
///
/// Please read module documentation for more information.
#[derive(Clone)]
pub struct Backoff<S> {
    inner: S,
    clone_exts: CloneExtensionsFn,
    max_retries: usize,
}

impl<S> Backoff<S> {
    /// Create a new backoff service by wrapping a client.
    pub fn new(inner: S) -> Self {
        Self {
            inner,
            clone_exts: |_, _| {},
            max_retries: 5,
        }
    }

    /// Set a function to extract extensions from a request and add it to a new request.
    ///
    /// This is needed so that user extensions can be added for new requests that
    /// are created for retry. Check the module documentation for more information.
    pub fn clone_extensions_fn(mut self, f: CloneExtensionsFn) -> Self {
        self.clone_exts = f;
        self
    }

    /// Set max retry count. After this is reached, the request won't be
    /// retried anymore and a [`HrpcErrorIdentifier::ResourceExhausted`]
    /// error will be returned.
    pub fn max_retries(mut self, num: usize) -> Self {
        self.max_retries = num;
        self
    }
}

impl<S, Err> Service<BoxRequest> for Backoff<S>
where
    S: Service<BoxRequest, Error = TransportError<Err>> + Clone,
{
    type Response = S::Response;

    type Error = S::Error;

    type Future = BackoffFuture<Err, S>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Service::poll_ready(&mut self.inner, cx)
    }

    fn call(&mut self, req: BoxRequest) -> Self::Future {
        BackoffFuture::new(self.inner.clone(), self.clone_exts, req, self.max_retries)
    }
}

struct RequestFactory {
    body: Bytes,
    extensions: Extensions,
    endpoint: Cow<'static, str>,
    clone_exts: CloneExtensionsFn,
}

impl RequestFactory {
    fn from_req(req: BoxRequest, clone_exts: CloneExtensionsFn) -> Result<Self, BoxRequest> {
        let request::Parts {
            mut body,
            endpoint,
            extensions,
        } = req.into();

        let maybe_body = body
            .next()
            .now_or_never()
            .flatten()
            .transpose()
            .ok()
            .flatten();
        let body = match maybe_body {
            Some(b) => b,
            None => {
                return Err(BoxRequest::from(request::Parts {
                    body,
                    endpoint,
                    extensions,
                }));
            }
        };

        Ok(Self {
            clone_exts,
            body,
            endpoint,
            extensions,
        })
    }

    fn make_req(&self) -> BoxRequest {
        let mut extensions = Extensions::new();
        (self.clone_exts)(&self.extensions, &mut extensions);

        if let Some(marker) = self.extensions.get::<SocketRequestMarker>().cloned() {
            extensions.insert(marker);
        }

        let parts = request::Parts {
            body: Body::full(self.body.clone()),
            endpoint: self.endpoint.clone(),
            extensions,
        };

        BoxRequest::from(parts)
    }
}

pin_project_lite::pin_project! {
    /// Future for [`Backoff`] service.
    pub struct BackoffFuture<Err, S: Service<BoxRequest, Error = TransportError<Err>>> {
        maybe_request_factory: Result<RequestFactory, BoxRequest>,
        service: S,
        max_retries: usize,
        retried: usize,
        req_fut: Option<Pin<Box<Fuse<S::Future>>>>,
        wait: Option<Pin<Box<Sleep>>>,
    }
}

impl<Err, S: Service<BoxRequest, Error = TransportError<Err>>> BackoffFuture<Err, S> {
    fn new(
        service: S,
        clone_exts_fn: CloneExtensionsFn,
        request: BoxRequest,
        max_retries: usize,
    ) -> Self {
        Self {
            max_retries,
            retried: 0,
            req_fut: None,
            maybe_request_factory: RequestFactory::from_req(request, clone_exts_fn),
            service,
            wait: None,
        }
    }
}

impl<Err, S: Service<BoxRequest, Error = TransportError<Err>>> Future for BackoffFuture<Err, S> {
    type Output = <<S as Service<BoxRequest>>::Future as Future>::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();

        if let Some(req_fut) = this.req_fut.as_mut().map(|pin| pin.as_mut()) {
            if req_fut.is_terminated().not() {
                let resp = futures_util::ready!(req_fut.poll(cx));
                let mut scheduled = false;
                if let (
                    true,
                    Err(TransportError::GenericClient(ClientError::EndpointError {
                        hrpc_error,
                        ..
                    })),
                ) = ((this.retried < this.max_retries), &resp)
                {
                    // if rate limited error, wait and try again
                    if HrpcErrorIdentifier::ResourceExhausted.compare(&hrpc_error.identifier) {
                        // try to decode the retry info, if we can't we default to 5 seconds
                        let retry_after = RetryInfo::decode(hrpc_error.details.clone())
                            .map_or(3, |info| info.retry_after);
                        // exponential backoff
                        let retry_after =
                            (0..this.retried.saturating_sub(1)).fold(retry_after, |r, _| r * 2);
                        tracing::error!(
                            retry_count = %this.retried,
                            "request rate limited, scheduling for retry in {} seconds",
                            retry_after,
                        );
                        *this.wait = Some(Box::pin(sleep(Duration::from_secs(retry_after.into()))));
                        scheduled = true;
                    }
                }
                if scheduled.not() {
                    // otherwise return the result
                    return Poll::Ready(resp);
                }
            }
        }

        // wait until ratelimit is gone
        if let Some(sleep) = this.wait.as_mut().map(|pin| pin.as_mut()) {
            futures_util::ready!(Sleeper::poll(sleep, cx));
        }

        match &this.maybe_request_factory {
            Ok(request_factory) => {
                // create a new request future, and increase our retried count
                let req = request_factory.make_req();
                *this.req_fut = Some(Box::pin(Service::call(&mut this.service, req).fuse()));
                *this.retried += 1;

                tracing::debug!(retry_count = %this.retried, "retrying request");

                // wake is needed here since we want it to poll the request future
                cx.waker().wake_by_ref();
                Poll::Pending
            },
            Err(req) => {
                Poll::Ready(Err(TransportError::GenericClient(ClientError::EndpointError {
                    endpoint: Cow::Owned(req.endpoint().to_string()),
                    hrpc_error: HrpcError::default()
                        .with_message("can't do request because no body was immediately available; this might be a bug in the backoff layer")
                        .with_identifier("hrpcrs.client.backoff-no-immediate-body"),
                })))
            }
        }
    }
}

trait Sleeper {
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()>;
}

use sleeper::*;

#[cfg(all(feature = "http_hyper_client", not(target_arch = "wasm32")))]
mod sleeper {
    use super::*;

    pub(super) use ::tokio::time::Sleep;

    pub(super) fn sleep(duration: Duration) -> Sleep {
        ::tokio::time::sleep(duration)
    }

    impl Sleeper for Sleep {
        fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll<()> {
            Future::poll(self, cx)
        }
    }
}

#[cfg(all(feature = "http_wasm_client", target_arch = "wasm32"))]
mod sleeper {
    use super::*;

    use gloo_timers::future::TimeoutFuture;

    pub(super) fn sleep(duration: Duration) -> Sleep {
        Sleep {
            inner: gloo_timers::future::sleep(duration),
        }
    }

    pin_project_lite::pin_project! {
        pub(super) struct Sleep {
            #[pin]
            inner: TimeoutFuture,
        }
    }

    // Safety: this is safe on WASM (for now, at least, since there are no threads)
    unsafe impl Send for Sleep {}

    impl Sleeper for Sleep {
        fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll<()> {
            let this = self.project();
            Future::poll(this.inner, cx)
        }
    }
}