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
#![cfg(feature = "std")]

use std::prelude::v1::*;

use crate::{clock, Jitter, NotUntil, RateLimiter};
use crate::{
    middleware::RateLimitingMiddleware,
    state::{DirectStateStore, NotKeyed},
};
use futures::task::{Context, Poll};
use futures::{Future, Sink, Stream};
use futures_timer::Delay;
use std::pin::Pin;
use std::time::Duration;

/// Allows converting a [`futures::Stream`] combinator into a rate-limited stream.
pub trait StreamRateLimitExt<'a>: Stream {
    /// Limits the rate at which the stream produces items.
    ///
    /// Note that this combinator limits the rate at which it yields
    /// items, not necessarily the rate at which the underlying stream is polled.
    /// The combinator will buffer at most one item in order to adhere to the
    /// given limiter. I.e. if it already has an item buffered and needs to wait
    /// it will not `poll` the underlying stream.
    fn ratelimit_stream<
        D: DirectStateStore,
        C: clock::Clock,
        MW: RateLimitingMiddleware<C::Instant>,
    >(
        self,
        limiter: &'a RateLimiter<NotKeyed, D, C, MW>,
    ) -> RatelimitedStream<'a, Self, D, C, MW>
    where
        Self: Sized,
        C: clock::ReasonablyRealtime;

    /// Limits the rate at which the stream produces items, with a randomized wait period.
    ///
    /// Note that this combinator limits the rate at which it yields
    /// items, not necessarily the rate at which the underlying stream is polled.
    /// The combinator will buffer at most one item in order to adhere to the
    /// given limiter. I.e. if it already has an item buffered and needs to wait
    /// it will not `poll` the underlying stream.
    fn ratelimit_stream_with_jitter<
        D: DirectStateStore,
        C: clock::Clock,
        MW: RateLimitingMiddleware<C::Instant>,
    >(
        self,
        limiter: &'a RateLimiter<NotKeyed, D, C, MW>,
        jitter: Jitter,
    ) -> RatelimitedStream<'a, Self, D, C, MW>
    where
        Self: Sized,
        C: clock::ReasonablyRealtime;
}

impl<'a, S: Stream> StreamRateLimitExt<'a> for S {
    fn ratelimit_stream<
        D: DirectStateStore,
        C: clock::Clock,
        MW: RateLimitingMiddleware<C::Instant>,
    >(
        self,
        limiter: &'a RateLimiter<NotKeyed, D, C, MW>,
    ) -> RatelimitedStream<'a, Self, D, C, MW>
    where
        Self: Sized,
        C: clock::ReasonablyRealtime,
    {
        self.ratelimit_stream_with_jitter(limiter, Jitter::NONE)
    }

    fn ratelimit_stream_with_jitter<
        D: DirectStateStore,
        C: clock::Clock,
        MW: RateLimitingMiddleware<C::Instant>,
    >(
        self,
        limiter: &'a RateLimiter<NotKeyed, D, C, MW>,
        jitter: Jitter,
    ) -> RatelimitedStream<'a, Self, D, C, MW>
    where
        Self: Sized,
        C: clock::ReasonablyRealtime,
    {
        RatelimitedStream {
            inner: self,
            limiter,
            buf: None,
            delay: Delay::new(Duration::new(0, 0)),
            jitter,
            state: State::ReadInner,
        }
    }
}

enum State {
    ReadInner,
    NotReady,
    Wait,
}

/// A [`Stream`][futures::Stream] combinator which will limit the rate of items being received.
///
/// This is produced by the [`StreamRateLimitExt::ratelimit_stream`] and
/// [`StreamRateLimitExt::ratelimit_stream_with_jitter`] methods.
pub struct RatelimitedStream<
    'a,
    S: Stream,
    D: DirectStateStore,
    C: clock::Clock,
    MW: RateLimitingMiddleware<C::Instant>,
> {
    inner: S,
    limiter: &'a RateLimiter<NotKeyed, D, C, MW>,
    delay: Delay,
    buf: Option<S::Item>,
    jitter: Jitter,
    state: State,
}

/// Conversion methods for the stream combinator.
impl<
        'a,
        S: Stream,
        D: DirectStateStore,
        C: clock::Clock,
        MW: RateLimitingMiddleware<C::Instant>,
    > RatelimitedStream<'a, S, D, C, MW>
{
    /// Acquires a reference to the underlying stream that this combinator is pulling from.
    /// ```rust
    /// # use futures::{Stream, stream};
    /// # use governor::{prelude::*, Quota, RateLimiter};
    /// # use nonzero_ext::nonzero;
    /// let inner = stream::repeat(());
    /// let lim = RateLimiter::direct(Quota::per_second(nonzero!(10u32)));
    /// let outer = inner.clone().ratelimit_stream(&lim);
    /// assert!(outer.get_ref().size_hint().1.is_none());
    /// assert_eq!(outer.size_hint(), outer.get_ref().size_hint());
    /// ```
    pub fn get_ref(&self) -> &S {
        &self.inner
    }

    /// Acquires a mutable reference to the underlying stream that this combinator is pulling from.
    /// ```rust
    /// # use futures::{stream, StreamExt};
    /// # use futures::executor::block_on;
    /// # use governor::{prelude::*, Quota, RateLimiter};
    /// # use nonzero_ext::nonzero;
    /// let inner = stream::repeat(());
    /// let lim = RateLimiter::direct(Quota::per_second(nonzero!(10u32)));
    /// let mut outer = inner.clone().ratelimit_stream(&lim);
    /// assert_eq!(block_on(outer.get_mut().next()), Some(()));
    /// ```
    pub fn get_mut(&mut self) -> &mut S {
        &mut self.inner
    }

    /// Consumes this combinator, returning the underlying stream and any item
    /// which it has already produced but which is still being held back
    /// in order to abide by the limiter.
    /// ```rust
    /// # use futures::{stream, StreamExt};
    /// # use futures::executor::block_on;
    /// # use governor::{prelude::*, Quota, RateLimiter};
    /// # use nonzero_ext::nonzero;
    /// let inner = stream::repeat(());
    /// let lim = RateLimiter::direct(Quota::per_second(nonzero!(10u32)));
    /// let mut outer = inner.clone().ratelimit_stream(&lim);
    /// let (mut inner_again, _) = outer.into_inner();
    /// assert_eq!(block_on(inner_again.next()), Some(()));
    /// ```
    pub fn into_inner(self) -> (S, Option<S::Item>) {
        (self.inner, self.buf)
    }
}

/// Implements the [`futures::Stream`] combinator.
impl<'a, S: Stream, D: DirectStateStore, C: clock::Clock, MW> Stream
    for RatelimitedStream<'a, S, D, C, MW>
where
    S: Unpin,
    S::Item: Unpin,
    Self: Unpin,
    C: clock::ReasonablyRealtime,
    MW: RateLimitingMiddleware<C::Instant, NegativeOutcome = NotUntil<C::Instant>>,
{
    type Item = S::Item;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            match self.state {
                State::ReadInner => {
                    let inner = Pin::new(&mut self.inner);
                    match inner.poll_next(cx) {
                        Poll::Pending => return Poll::Pending,
                        Poll::Ready(None) => {
                            // never talk tome or my inner again
                            return Poll::Ready(None);
                        }
                        Poll::Ready(Some(x)) => {
                            self.buf.replace(x);
                            self.state = State::NotReady;
                        }
                    }
                }
                State::NotReady => {
                    let reference = self.limiter.reference_reading();
                    if let Err(negative) = self.limiter.check() {
                        let earliest = negative.wait_time_with_offset(reference, self.jitter);
                        self.delay.reset(earliest);
                        let future = Pin::new(&mut self.delay);
                        match future.poll(cx) {
                            Poll::Pending => {
                                self.state = State::Wait;
                                return Poll::Pending;
                            }
                            Poll::Ready(_) => {}
                        }
                    } else {
                        self.state = State::ReadInner;
                        return Poll::Ready(self.buf.take());
                    }
                }
                State::Wait => {
                    let future = Pin::new(&mut self.delay);
                    match future.poll(cx) {
                        Poll::Pending => {
                            return Poll::Pending;
                        }
                        Poll::Ready(_) => {
                            self.state = State::NotReady;
                        }
                    }
                }
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

/// Pass-through implementation for [`futures::Sink`] if the Stream also implements it.
impl<
        'a,
        Item,
        S: Stream + Sink<Item>,
        D: DirectStateStore,
        C: clock::Clock,
        MW: RateLimitingMiddleware<C::Instant>,
    > Sink<Item> for RatelimitedStream<'a, S, D, C, MW>
where
    S: Unpin,
    S::Item: Unpin,
{
    type Error = <S as Sink<Item>>::Error;

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

    fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
        let inner = Pin::new(&mut self.inner);
        inner.start_send(item)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let inner = Pin::new(&mut self.inner);
        inner.poll_flush(cx)
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let inner = Pin::new(&mut self.inner);
        inner.poll_close(cx)
    }
}