Rust Stream::buffer_unordered where each future can have a different weight.

Overview

buffer-unordered-weighted

buffer-unordered-weighted on crates.io Documentation (latest release) Documentation (main) Changelog License License

buffer_unordered_weighted is a variant of buffer_unordered, where each future can be assigned a different weight.

This crate is part of the nextest organization on GitHub, and is designed to serve the needs of cargo-nextest.

Motivation

Async programming in Rust often uses an adaptor called buffer_unordered: this adaptor takes a stream of futures1, and executes all the futures limited to a maximum amount of concurrency.

  • Futures are started in the order the stream returns them in.
  • Once started, futures are polled simultaneously, and completed future outputs are returned in arbitrary order (hence the unordered).

Common use cases for buffer_unordered include:

  • Sending network requests concurrently, but limiting the amount of concurrency to avoid overwhelming the remote server.
  • Running tests with a tool like cargo-nextest.

buffer_unordered works well for many use cases. However, one issue with it is that it treats all futures as equally taxing: there's no way to say that some futures consume more resources than others. For nextest in particular, some tests can be much heavier than others, and fewer of those tests should be run simultaneously.

About this crate

This crate provides an adaptor on streams called buffer_unordered_weighted, which can run several futures simultaneously, limiting the concurrency to a maximum weight.

Rather than taking a stream of futures, this adaptor takes a stream of (usize, future) pairs, where the usize indicates the weight of each future. This adaptor will schedule and buffer futures to be run until the maximum weight is exceeded. Once that happens, this adaptor will wait until some of the currently executing futures complete, and the current weight of running futures drops below the maximum weight, before scheduling new futures.

Note that in some cases, the current weight may exceed the maximum weight. For example:

  • Let's say the maximum weight is 24, and the current weight is 20.
  • If the next future has weight 6, then it will be scheduled and the current weight will become 26.
  • No new futures will be scheduled until the current weight falls to 23 or below.

It is possible to have a variant of this adaptor which always stays below the limit and holds the next future in abeyance; however, the implementation for that variant is a bit more complicated, and is also not the behavior desired by nextest. This variant may be provided in the future.

The weight of a future can be zero, in which case it doesn't count towards the maximum weight.

If all weights are 1, then buffer_unordered_weighted is exactly the same as buffer_unordered.

Examples

use futures::{channel::oneshot, stream, StreamExt as _};
use buffer_unordered_weighted::{StreamExt as _};

let (send_one, recv_one) = oneshot::channel();
let (send_two, recv_two) = oneshot::channel();

let stream_of_futures = stream::iter(vec![(1, recv_one), (2, recv_two)]);
let mut buffered = stream_of_futures.buffer_unordered_weighted(10);

send_two.send("hello")?;
assert_eq!(buffered.next().await, Some(Ok("hello")));

send_one.send("world")?;
assert_eq!(buffered.next().await, Some(Ok("world")));

assert_eq!(buffered.next().await, None);

Minimum supported Rust version (MSRV)

The minimum supported Rust version is Rust 1.56.

The MSRV will likely not change in the medium term, but while this crate is a pre-release (0.x.x) it may have its MSRV bumped in a patch release. Once this crate has reached 1.x, any MSRV bump will be accompanied with a new minor version.

Contributing

See the CONTRIBUTING file for how to help out.

License

This project is available under the terms of either the Apache 2.0 license or the MIT license.

The code is derived from futures-rs, and is used under the Apache 2.0 and MIT licenses.

Footnotes

  1. This adaptor takes a stream of futures for maximum generality. In practice this is often an iterator of futures, converted over using stream::iter.

You might also like...
A VtubeStudio plugin that allows iFacialMocap to stream data to the app, enabling full apple ARkit facial tracking to be used for 2D Vtuber models.

facelink_rs A VtubeStudio plugin that allows iFacialMocap to stream data to the app, enabling full apple ARkit facial tracking to be used for 2D Vtube

Stream-based FSEvents API bindings.

fsevent-stream Stream-based FSEvents API bindings. Features Support directory-granular and file-granular events. Retrieve related file inode with kFSE

Adaptors from AsyncRead/AsyncWrite to Stream/Sink using futures.

async-codec-lite Adaptors from AsyncRead/AsyncWrite to Stream/Sink using futures. async-codec-lite Adaptors from AsyncRead/AsyncWrite to Stream/Sink u

Alternative StreamMap fork of tokio-stream

streammap-ext This is a fork of StreamMap from tokio-stream crate. The only difference between the implementations is that this version of StreamMap n

A lending version of the `Stream` trait

lending-stream A lending version of Stream API Docs | Releases | Contributing Installation $ cargo add lending-stream Safety This crate uses #![deny(u

Framework is a detector for different frameworks in one projects

Framework is a detector for different frameworks in one projects Usage use

Modeling is a tools to analysis different languages by Ctags

Modeling Modeling is a tools to analysis different languages by Ctags process: generate to opt call ctags with opt analysis ctags logs output resulse

Fibonacci, but different

n-days Fibonacci, but different? Problem You're given a workout in the 12 Days of Christmas style: 1. Burpee Bar Muscle-Up 2. Thrusters 3. Power Clean

A compatibility layer to smooth the transition between different versions of embedded-hal

Embedded HAL Compatibility Layer A compatibility layer to smooth the transition between different versions of embedded-hal (specifically 0.2.x and 1.0

Comments
  • Add documentation note that future_queue (and buffer_unordered) don't limit concurrency in certain cases

    Add documentation note that future_queue (and buffer_unordered) don't limit concurrency in certain cases

    These limit the number of concurrently running futures, which often but doesn't always limit overall concurrency. Add a note about this.

    From @hawkw:

    if your stream is returning tokio::spawn(do_stuff()) and you group them into a queue, the concurrency isn't limited, but if your stream is returning async move { tokio::spawn(do_stuff()).await } then the task isn't spawned until the future is actually polled for the first time

    documentation 
    opened by sunshowers 0
Releases(0.2.2)
Owner
A next-generation test runner for Rust.
null
Mononym is a library for creating unique type-level names for each value in Rust.

Mononym is a library for creating unique type-level names for each value in Rust.

MaybeVoid 52 Dec 16, 2022
Derive with constructor for each field in struct.

A custom derive implementation for #[derive(with)] Get started 1.Generate with constructor for each field use derive_with::with; #[derive(with, Defau

SystemX Labs 4 Oct 22, 2023
🌌⭐ Git tooling of the future.

❯ Glitter Git tooling of the future. ❯ ?? Features Config files Fast Easy to use Friendly errors ❯ ?? Documentation For proper docs, see here ❯ ✋ What

Milo 229 Dec 22, 2022
async-alloc-counter measures max allocations in a future invocation

async-alloc-counter measures max allocations in a future invocation see examples/ for usage This allocator can be used as follows: use async_alloc_cou

Geoffroy Couprie 2 Dec 3, 2021
Lupus is a utility to administer backups with future integration with rsync

Lupus is a utility to administer backups with future integration with rsync. Many other features are either included or planned such as chat bridges using rcon and or parsing the pipe output from programs/games.

null 3 Sep 19, 2022
An iterator adapter to peek at future elements without advancing the cursor of the underlying iterator.

multipeek An iterator adapter to peek at future elements without advancing the cursor of the underlying iterator. Check out the documentation for more

Luca Palmieri 20 Jul 16, 2022
A future version of Pokétwo

poketwo-next Pokétwo brings the Pokémon experience to Discord. Catch randomly-spawning pokémon in your servers, trade them to expand your collection,

Pokétwo 13 Aug 20, 2022
Alternative future adapters that provide cancel safety.

cancel-safe-futures Alternative futures adapters that are more cancel-safe. What is this crate? The futures library contains many adapters that make w

Oxide Computer Company 12 Jul 2, 2023
This crate allows writing a struct in Rust and have it derive a struct of arrays layed out in memory according to the arrow format.

Arrow2-derive - derive for Arrow2 This crate allows writing a struct in Rust and have it derive a struct of arrays layed out in memory according to th

Jorge Leitao 29 Dec 27, 2022
Check Have I Been Pwned and see if it's time for you to change passwords.

checkpwn Check Have I Been Pwned and see if it's time for you to change passwords. Getting started Install: cargo install checkpwn Update: cargo inst

Johannes 93 Dec 13, 2022