Skip to content

Implemented StreamExt::throttle #356

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Nov 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
a239350
Implemented StreamExt::throttle
Wassasin Oct 16, 2019
ced5281
Merge remote-tracking branch 'upstream/master' into 342-stream-throttle
Wassasin Oct 20, 2019
1c843a8
Re-implemented Throttle to keep last value in memory
Wassasin Oct 23, 2019
1fd05a1
Reset delay to prevent poll after ready
Wassasin Oct 23, 2019
14d7d3b
Merge remote-tracking branch 'upstream/master' into 342-stream-throttle
Wassasin Nov 11, 2019
b591fc6
Changed semantics of throttle to non-dropping variant with backpressure
Wassasin Nov 11, 2019
139a34b
Make throttle an unstable feature
Wassasin Nov 11, 2019
ef958f0
Use pin_project_lite instead for throttle
Wassasin Nov 11, 2019
7c73867
Wrap around throttle comment
Wassasin Nov 12, 2019
6f6d5e9
Updated throttle fn comments.
Wassasin Nov 12, 2019
88cbf2c
Change throttle test to run in milliseconds
Wassasin Nov 12, 2019
a722de1
Merge remote-tracking branch 'upstream/master' into 342-stream-throttle
Wassasin Nov 12, 2019
77a1849
Merge branch '342-stream-throttle' of github.com:Wassasin/async-std i…
Wassasin Nov 12, 2019
6990c14
Reimplemented throttle to never drop Delay, added boolean flag
Wassasin Nov 12, 2019
4ab7b21
Updated example to be consistent; added timing measurements to throttle
Wassasin Nov 12, 2019
c5b3a98
Increased throttle test to 10x time
Wassasin Nov 12, 2019
90c67c2
Decreased throttle test time to original values; only test lower bound
Wassasin Nov 14, 2019
dda65cb
Start throttle measurement before initialisation
Wassasin Nov 14, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions examples/throttle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//! Spawns a timed task which gets throttled.

fn main() {
#[cfg(feature = "unstable")]
{
use async_std::prelude::*;
use async_std::task;

task::block_on(async {
use async_std::stream;
use std::time::Duration;

// emit value every 1 second
let s = stream::interval(Duration::from_secs(1)).enumerate();

// throttle for 2 seconds
let s = s.throttle(Duration::from_secs(2));

s.for_each(|(n, _)| {
dbg!(n);
})
.await;
// => 0 .. 1 .. 2 .. 3
// with a pause of 2 seconds between each print
})
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we could convert this to an actual test that would be ideal. I don't think it might be a bit too specific to have as a standalone example like this.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still don't think we quite need this example here, but I'll file a follow-up PR to do so. Thanks heaps!

52 changes: 52 additions & 0 deletions src/stream/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,13 @@ cfg_unstable! {
pub use flatten::Flatten;
pub use flat_map::FlatMap;
pub use timeout::{TimeoutError, Timeout};
pub use throttle::Throttle;

mod merge;
mod flatten;
mod flat_map;
mod timeout;
mod throttle;
}

extension_trait! {
Expand Down Expand Up @@ -313,6 +315,56 @@ extension_trait! {
TakeWhile::new(self, predicate)
}

#[doc = r#"
Limit the amount of items yielded per timeslice in a stream.

This stream does not drop any items, but will only limit the rate at which items pass through.
# Examples
```
# fn main() { async_std::task::block_on(async {
#
use async_std::prelude::*;
use async_std::stream;
use std::time::{Duration, Instant};

let start = Instant::now();

// emit value every 5 milliseconds
let s = stream::interval(Duration::from_millis(5))
.enumerate()
.take(3);

// throttle for 10 milliseconds
let mut s = s.throttle(Duration::from_millis(10));

assert_eq!(s.next().await, Some((0, ())));
let duration_ms = start.elapsed().as_millis();
assert!(duration_ms >= 5);

assert_eq!(s.next().await, Some((1, ())));
let duration_ms = start.elapsed().as_millis();
assert!(duration_ms >= 15);

assert_eq!(s.next().await, Some((2, ())));
let duration_ms = start.elapsed().as_millis();
assert!(duration_ms >= 25);

assert_eq!(s.next().await, None);
let duration_ms = start.elapsed().as_millis();
assert!(duration_ms >= 35);
#
# }) }
```
"#]
#[cfg(all(feature = "default", feature = "unstable"))]
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
fn throttle(self, d: Duration) -> Throttle<Self>
where
Self: Sized,
{
Throttle::new(self, d)
}

#[doc = r#"
Creates a stream that yields each `step`th element.

Expand Down
70 changes: 70 additions & 0 deletions src/stream/stream/throttle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use std::future::Future;
use std::pin::Pin;
use std::time::{Duration, Instant};

use futures_timer::Delay;
use pin_project_lite::pin_project;

use crate::stream::Stream;
use crate::task::{Context, Poll};

pin_project! {
/// A stream that only yields one element once every `duration`.
///
/// This `struct` is created by the [`throttle`] method on [`Stream`]. See its
/// documentation for more.
///
/// [`throttle`]: trait.Stream.html#method.throttle
/// [`Stream`]: trait.Stream.html
#[doc(hidden)]
#[allow(missing_debug_implementations)]
pub struct Throttle<S> {
#[pin]
stream: S,
duration: Duration,
#[pin]
blocked: bool,
#[pin]
delay: Delay,
}
}

impl<S: Stream> Throttle<S> {
pub(super) fn new(stream: S, duration: Duration) -> Self {
Throttle {
stream,
duration,
blocked: false,
delay: Delay::new(Duration::default()),
}
}
}

impl<S: Stream> Stream for Throttle<S> {
type Item = S::Item;

fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
let mut this = self.project();
if *this.blocked {
let d = this.delay.as_mut();
if d.poll(cx).is_ready() {
*this.blocked = false;
} else {
return Poll::Pending;
}
}

match this.stream.poll_next(cx) {
Poll::Pending => {
cx.waker().wake_by_ref(); // Continue driving even though emitting Pending
Poll::Pending
}
Poll::Ready(None) => Poll::Ready(None),
Poll::Ready(Some(v)) => {
*this.blocked = true;
this.delay.reset(Instant::now() + *this.duration);
Poll::Ready(Some(v))
}
}
}
}