1use 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 struct SizedFut<Fut> {
25 #[pin]
26 inner: Fut,
27 _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 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 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 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 self.inflight.push(sized_fut);
109 }
110
111 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 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 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 assert!(size_limited.try_push(make_future(1), 1).is_err());
188
189 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 let good_fut = size_limited
207 .try_push(good_fut, 5)
208 .expect_err("try_push should fail");
209
210 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 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 stream
236 .push(
237 Box::pin(async {
238 futures::future::pending::<Vec<u8>>().await
240 }),
241 5,
242 )
243 .await;
244
245 stream.push(Box::pin(async { vec![1u8; 3] }), 3).await;
247
248 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 stream.push(Box::pin(async { vec![0u8; 10] }), 10).await;
264
265 let result = stream.try_push(Box::pin(async { vec![1u8] }), 1);
267 assert!(result.is_err());
268
269 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 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 assert_eq!(stream.bytes_available(), 50);
292
293 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}