Skip to main content

vortex_io/
limit.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::task::Context;
8use std::task::Poll;
9use std::task::ready;
10
11use futures::Stream;
12use futures::stream::FuturesUnordered;
13use pin_project_lite::pin_project;
14use tokio::sync::OwnedSemaphorePermit;
15use tokio::sync::Semaphore;
16use tokio::sync::TryAcquireError;
17use vortex_error::VortexExpect;
18
19pin_project! {
20    /// [`Future`] that carries the amount of memory it will require to hold the completed value.
21    ///
22    /// The `OwnedSemaphorePermit` ensures permits are automatically returned when this future
23    /// is dropped, either after completion or if cancelled/aborted.
24    struct SizedFut<Fut> {
25        #[pin]
26        inner: Fut,
27        // Owned permit that will be automatically dropped when the future completes or is dropped
28        _permits: OwnedSemaphorePermit,
29    }
30}
31
32impl<Fut: Future> Future for SizedFut<Fut> {
33    type Output = Fut::Output;
34
35    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
36        let this = self.project();
37        let result = ready!(this.inner.poll(cx));
38        Poll::Ready(result)
39    }
40}
41
42pin_project! {
43    /// A [`Stream`] that can work on several simultaneous requests, capping the amount of memory it
44    /// uses at any given point.
45    ///
46    /// It is meant to serve as a buffer between a producer and consumer of IO requests, with built-in
47    /// backpressure that prevents the producer from materializing more than a specified maximum
48    /// amount of memory.
49    ///
50    /// This crate internally makes use of tokio's [Semaphore], and thus is only available with
51    /// the `tokio` feature enabled.
52    pub struct SizeLimitedStream<Fut> {
53        #[pin]
54        inflight: FuturesUnordered<SizedFut<Fut>>,
55        bytes_available: Arc<Semaphore>,
56        max_bytes: usize,
57    }
58}
59
60impl<Fut> SizeLimitedStream<Fut> {
61    pub fn new(max_bytes: usize) -> Self {
62        Self {
63            inflight: FuturesUnordered::new(),
64            bytes_available: Arc::new(Semaphore::new(max_bytes)),
65            max_bytes,
66        }
67    }
68
69    pub fn bytes_available(&self) -> usize {
70        self.bytes_available.available_permits()
71    }
72}
73
74impl<Fut> SizeLimitedStream<Fut>
75where
76    Fut: Future,
77{
78    /// Push a future into the queue after reserving `bytes` of capacity.
79    ///
80    /// This call may need to wait until there is sufficient capacity available in the stream to
81    /// begin work on this future.
82    ///
83    /// # Panics
84    ///
85    /// Panics if `bytes` exceeds the stream's configured `max_bytes` capacity or does not fit in a
86    /// `u32`.
87    pub async fn push(&self, fut: Fut, bytes: usize) {
88        assert!(
89            bytes <= self.max_bytes,
90            "cannot reserve {bytes} bytes in a stream with max_bytes {}",
91            self.max_bytes
92        );
93
94        // Attempt to acquire enough permits to begin working on a request that will occupy
95        // `bytes` amount of memory when it completes.
96        // Acquiring the permits is what creates backpressure for the producer.
97        let permits = Arc::clone(&self.bytes_available)
98            .acquire_many_owned(bytes.try_into().vortex_expect("bytes must fit in u32"))
99            .await
100            .unwrap_or_else(|_| unreachable!("pushing to closed semaphore"));
101
102        let sized_fut = SizedFut {
103            inner: fut,
104            _permits: permits,
105        };
106
107        // push into the pending queue
108        self.inflight.push(sized_fut);
109    }
110
111    /// Synchronous push method. This method will attempt to push if there is enough capacity
112    /// to begin work on the future immediately.
113    ///
114    /// If there is not enough capacity, the original future is returned to the caller. If `bytes`
115    /// exceeds the stream's configured `max_bytes` capacity, `Err(fut)` is permanent and retrying
116    /// will never succeed.
117    pub fn try_push(&self, fut: Fut, bytes: usize) -> Result<(), Fut> {
118        match Arc::clone(&self.bytes_available)
119            .try_acquire_many_owned(bytes.try_into().vortex_expect("bytes must fit in u32"))
120        {
121            Ok(permits) => {
122                let sized_fut = SizedFut {
123                    inner: fut,
124                    _permits: permits,
125                };
126
127                self.inflight.push(sized_fut);
128                Ok(())
129            }
130            Err(acquire_err) => match acquire_err {
131                TryAcquireError::Closed => {
132                    unreachable!("try_pushing to closed semaphore");
133                }
134
135                // No permits available, return the future back to the client so they can
136                // try again.
137                TryAcquireError::NoPermits => Err(fut),
138            },
139        }
140    }
141}
142
143impl<Fut> Stream for SizeLimitedStream<Fut>
144where
145    Fut: Future,
146{
147    type Item = Fut::Output;
148
149    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
150        let this = self.project();
151        match ready!(this.inflight.poll_next(cx)) {
152            None => Poll::Ready(None),
153            Some(result) => {
154                // Permits are automatically returned when the SizedFut is dropped
155                // after being polled to completion by FuturesUnordered
156                Poll::Ready(Some(result))
157            }
158        }
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use std::future;
165    use std::io;
166    use std::sync::Arc;
167    use std::time::Duration;
168
169    use bytes::Bytes;
170    use futures::FutureExt;
171    use futures::StreamExt;
172    use futures::future::BoxFuture;
173
174    use crate::limit::SizeLimitedStream;
175
176    async fn make_future(len: usize) -> Bytes {
177        "a".as_bytes().iter().copied().cycle().take(len).collect()
178    }
179
180    #[tokio::test]
181    async fn test_size_limit() {
182        let mut size_limited = SizeLimitedStream::new(10);
183        size_limited.push(make_future(5), 5).await;
184        size_limited.push(make_future(5), 5).await;
185
186        // Pushing last request should fail, because we have 10 bytes outstanding.
187        assert!(size_limited.try_push(make_future(1), 1).is_err());
188
189        // but, we can pop off a finished work item, and then enqueue.
190        assert!(size_limited.next().await.is_some());
191        assert!(size_limited.try_push(make_future(1), 1).is_ok());
192    }
193
194    #[tokio::test]
195    async fn test_does_not_leak_permits() {
196        let bad_fut: BoxFuture<'static, io::Result<Bytes>> =
197            future::ready(Err(io::Error::other("badness"))).boxed();
198
199        let good_fut: BoxFuture<'static, io::Result<Bytes>> =
200            future::ready(Ok(Bytes::from("aaaaa"))).boxed();
201
202        let mut size_limited = SizeLimitedStream::new(10);
203        size_limited.push(bad_fut, 10).await;
204
205        // attempt to push should fail, as all 10 bytes of capacity is occupied by bad_fut.
206        let good_fut = size_limited
207            .try_push(good_fut, 5)
208            .expect_err("try_push should fail");
209
210        // Even though the result was an error, the 10 bytes of capacity should be returned back to
211        // the stream, allowing us to push the next request.
212        let next = size_limited.next().await.unwrap();
213        assert!(next.is_err());
214
215        assert_eq!(size_limited.bytes_available(), 10);
216        assert!(size_limited.try_push(good_fut, 5).is_ok());
217    }
218
219    #[tokio::test]
220    async fn test_size_limited_stream_zero_capacity() {
221        let stream = SizeLimitedStream::new(0);
222
223        // Should not be able to push anything
224        let result = stream.try_push(async { vec![1u8] }, 1);
225        assert!(result.is_err());
226    }
227
228    #[tokio::test]
229    async fn test_size_limited_stream_dropped_future_releases_permits() {
230        use futures::future::BoxFuture;
231
232        let stream = SizeLimitedStream::<BoxFuture<'static, Vec<u8>>>::new(10);
233
234        // Push a future that will never complete
235        stream
236            .push(
237                Box::pin(async {
238                    // This future will be dropped before completion
239                    futures::future::pending::<Vec<u8>>().await
240                }),
241                5,
242            )
243            .await;
244
245        // Push another future
246        stream.push(Box::pin(async { vec![1u8; 3] }), 3).await;
247
248        // We should have 2 bytes available now
249        assert_eq!(stream.bytes_available(), 2);
250
251        let permits = Arc::clone(&stream.bytes_available);
252        drop(stream);
253        assert_eq!(permits.available_permits(), 10);
254    }
255
256    #[tokio::test]
257    async fn test_size_limited_stream_exact_capacity() {
258        use futures::future::BoxFuture;
259
260        let mut stream = SizeLimitedStream::<BoxFuture<'static, Vec<u8>>>::new(10);
261
262        // Push exactly the capacity
263        stream.push(Box::pin(async { vec![0u8; 10] }), 10).await;
264
265        // Should not be able to push more
266        let result = stream.try_push(Box::pin(async { vec![1u8] }), 1);
267        assert!(result.is_err());
268
269        // After consuming, should be able to push again
270        stream
271            .next()
272            .await
273            .expect("The 10 byte vector ought to be in there!");
274        assert_eq!(stream.bytes_available(), 10);
275
276        let result = stream.try_push(Box::pin(async { vec![1u8; 5] }), 5);
277        assert!(result.is_ok());
278    }
279
280    #[tokio::test]
281    async fn test_size_limited_stream_multiple_small_pushes() {
282        let mut stream = SizeLimitedStream::new(100);
283
284        // Push many small items
285        for i in 0..10 {
286            #[expect(clippy::cast_possible_truncation)]
287            stream.push(async move { vec![i as u8; 5] }, 5).await;
288        }
289
290        // Should have used 50 bytes
291        assert_eq!(stream.bytes_available(), 50);
292
293        // Consume all
294        let mut count = 0;
295        while stream.next().await.is_some() {
296            count += 1;
297            if count == 10 {
298                break;
299            }
300        }
301
302        assert_eq!(count, 10);
303        assert_eq!(stream.bytes_available(), 100);
304    }
305
306    #[cfg(target_pointer_width = "64")]
307    #[test]
308    #[should_panic(expected = "bytes must fit in u32")]
309    fn test_size_overflow_protection() {
310        let stream = SizeLimitedStream::new(100);
311        let _result = stream.try_push(async {}, (u32::MAX as usize) + 1);
312    }
313
314    #[tokio::test]
315    #[should_panic(expected = "cannot reserve 11 bytes")]
316    async fn test_push_above_capacity_panics() {
317        let stream = SizeLimitedStream::new(10);
318        tokio::time::timeout(Duration::from_secs(1), stream.push(make_future(11), 11))
319            .await
320            .expect("push above capacity should panic immediately, not wait");
321    }
322}