opendal-layer-concurrent-limit 0.57.0

Apache OpenDAL concurrent limit layer
Documentation
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! Concurrent request limit layer implementation for Apache OpenDAL.

#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_docs)]

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;

use futures::Stream;
use futures::StreamExt;
use mea::semaphore::OwnedSemaphorePermit;
use mea::semaphore::Semaphore;
use opendal_core::raw::*;
use opendal_core::*;

/// ConcurrentLimitSemaphore abstracts a semaphore-like concurrency primitive
/// that yields an owned permit released on drop.
pub trait ConcurrentLimitSemaphore: Send + Sync + Clone + Unpin + 'static {
    /// The owned permit type associated with the semaphore. Dropping it
    /// must release the permit back to the semaphore.
    type Permit: Send + Sync + 'static;

    /// Acquire an owned permit asynchronously.
    fn acquire(&self) -> impl Future<Output = Self::Permit> + MaybeSend;
}

impl ConcurrentLimitSemaphore for Arc<Semaphore> {
    type Permit = OwnedSemaphorePermit;

    async fn acquire(&self) -> Self::Permit {
        self.clone().acquire_owned(1).await
    }
}

/// Add concurrent request limit.
///
/// # Notes
///
/// Users can control how many concurrent connections could be established
/// between OpenDAL and underlying storage services.
///
/// All operators wrapped by this layer will share a common semaphore. This
/// allows you to reuse the same layer across multiple operators, ensuring
/// that the total number of concurrent requests across the entire
/// application does not exceed the limit.
///
/// # Examples
///
/// Add a concurrent limit layer to the operator:
///
/// ```no_run
/// # use opendal_core::services;
/// # use opendal_core::Operator;
/// # use opendal_core::Result;
/// # use opendal_layer_concurrent_limit::ConcurrentLimitLayer;
/// #
/// # fn main() -> Result<()> {
/// let _ = Operator::new(services::Memory::default())?
///     .layer(ConcurrentLimitLayer::new(1024))
///     .finish();
/// # Ok(())
/// # }
/// ```
///
/// Share a concurrent limit layer between the operators:
///
/// ```no_run
/// # use opendal_core::services;
/// # use opendal_core::Operator;
/// # use opendal_core::Result;
/// # use opendal_layer_concurrent_limit::ConcurrentLimitLayer;
/// #
/// # fn main() -> Result<()> {
/// let limit = ConcurrentLimitLayer::new(1024);
///
/// let _operator_a = Operator::new(services::Memory::default())?
///     .layer(limit.clone())
///     .finish();
/// let _operator_b = Operator::new(services::Memory::default())?
///     .layer(limit.clone())
///     .finish();
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct ConcurrentLimitLayer<S: ConcurrentLimitSemaphore = Arc<Semaphore>> {
    operation_semaphore: S,
    http_semaphore: Option<S>,
}

impl ConcurrentLimitLayer<Arc<Semaphore>> {
    /// Create a new `ConcurrentLimitLayer` with the specified number of
    /// permits.
    ///
    /// These permits will be applied to all operations.
    pub fn new(permits: usize) -> Self {
        Self::with_semaphore(Arc::new(Semaphore::new(permits)))
    }

    /// Set a concurrent limit for HTTP requests.
    ///
    /// This convenience helper constructs a new semaphore with the specified
    /// number of permits and calls [`ConcurrentLimitLayer::with_http_semaphore`].
    /// Use [`ConcurrentLimitLayer::with_http_semaphore`] directly when reusing
    /// a shared semaphore.
    pub fn with_http_concurrent_limit(self, permits: usize) -> Self {
        self.with_http_semaphore(Arc::new(Semaphore::new(permits)))
    }
}

impl<S: ConcurrentLimitSemaphore> ConcurrentLimitLayer<S> {
    /// Create a layer with any ConcurrentLimitSemaphore implementation.
    ///
    /// ```
    /// # use std::sync::Arc;
    /// # use mea::semaphore::Semaphore;
    /// # use opendal_layer_concurrent_limit::ConcurrentLimitLayer;
    /// let semaphore = Arc::new(Semaphore::new(1024));
    /// let _layer = ConcurrentLimitLayer::with_semaphore(semaphore);
    /// ```
    pub fn with_semaphore(operation_semaphore: S) -> Self {
        Self {
            operation_semaphore,
            http_semaphore: None,
        }
    }

    /// Provide a custom HTTP concurrency semaphore instance.
    pub fn with_http_semaphore(mut self, semaphore: S) -> Self {
        self.http_semaphore = Some(semaphore);
        self
    }
}

impl<A: Access, S: ConcurrentLimitSemaphore> Layer<A> for ConcurrentLimitLayer<S>
where
    S::Permit: Unpin,
{
    type LayeredAccess = ConcurrentLimitAccessor<A, S>;

    fn layer(&self, inner: A) -> Self::LayeredAccess {
        let info = inner.info();

        // Update http client with concurrent limit http fetcher.
        info.update_http_client(|client| {
            HttpClient::with(ConcurrentLimitHttpFetcher::<S> {
                inner: client.into_inner(),
                http_semaphore: self.http_semaphore.clone(),
            })
        });

        ConcurrentLimitAccessor {
            inner,
            semaphore: self.operation_semaphore.clone(),
        }
    }
}

#[doc(hidden)]
pub struct ConcurrentLimitHttpFetcher<S: ConcurrentLimitSemaphore> {
    inner: HttpFetcher,
    http_semaphore: Option<S>,
}

impl<S: ConcurrentLimitSemaphore> HttpFetch for ConcurrentLimitHttpFetcher<S>
where
    S::Permit: Unpin,
{
    async fn fetch(&self, req: http::Request<Buffer>) -> Result<http::Response<HttpBody>> {
        let Some(semaphore) = self.http_semaphore.clone() else {
            return self.inner.fetch(req).await;
        };

        let permit = semaphore.acquire().await;

        let resp = self.inner.fetch(req).await?;
        let (parts, body) = resp.into_parts();
        let body = body.map_inner(|s| {
            Box::new(ConcurrentLimitStream::<_, S::Permit> {
                inner: s,
                _permit: permit,
            })
        });
        Ok(http::Response::from_parts(parts, body))
    }
}

struct ConcurrentLimitStream<S, P> {
    inner: S,
    // Hold on this permit until this reader has been dropped.
    _permit: P,
}

impl<S, P> Stream for ConcurrentLimitStream<S, P>
where
    S: Stream<Item = Result<Buffer>> + Unpin + 'static,
    P: Unpin,
{
    type Item = Result<Buffer>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // Safe due to Unpin bounds on S and P (thus on Self).
        let this = self.get_mut();
        this.inner.poll_next_unpin(cx)
    }
}

#[doc(hidden)]
#[derive(Clone)]
pub struct ConcurrentLimitAccessor<A: Access, S: ConcurrentLimitSemaphore> {
    inner: A,
    semaphore: S,
}

impl<A: Access, S: ConcurrentLimitSemaphore> std::fmt::Debug for ConcurrentLimitAccessor<A, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConcurrentLimitAccessor")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<A: Access, S: ConcurrentLimitSemaphore> LayeredAccess for ConcurrentLimitAccessor<A, S>
where
    S::Permit: Unpin,
{
    type Inner = A;
    type Reader = ConcurrentLimitWrapper<A::Reader, S::Permit>;
    type Writer = ConcurrentLimitWrapper<A::Writer, S::Permit>;
    type Lister = ConcurrentLimitWrapper<A::Lister, S::Permit>;
    type Deleter = ConcurrentLimitWrapper<A::Deleter, S::Permit>;
    type Copier = ConcurrentLimitWrapper<A::Copier, S::Permit>;

    fn inner(&self) -> &Self::Inner {
        &self.inner
    }

    async fn create_dir(&self, path: &str, args: OpCreateDir) -> Result<RpCreateDir> {
        let _permit = self.semaphore.acquire().await;

        self.inner.create_dir(path, args).await
    }

    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
        let permit = self.semaphore.acquire().await;

        self.inner
            .read(path, args)
            .await
            .map(|(rp, r)| (rp, ConcurrentLimitWrapper::new(r, permit)))
    }

    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
        let permit = self.semaphore.acquire().await;

        self.inner
            .write(path, args)
            .await
            .map(|(rp, w)| (rp, ConcurrentLimitWrapper::new(w, permit)))
    }

    async fn copy(
        &self,
        from: &str,
        to: &str,
        args: OpCopy,
        opts: OpCopier,
    ) -> Result<(RpCopy, Self::Copier)> {
        let permit = self.semaphore.acquire().await;

        self.inner
            .copy(from, to, args, opts.clone())
            .await
            .map(|(rp, c)| (rp, ConcurrentLimitWrapper::new(c, permit)))
    }

    async fn rename(&self, from: &str, to: &str, args: OpRename) -> Result<RpRename> {
        let _permit = self.semaphore.acquire().await;

        self.inner.rename(from, to, args).await
    }

    async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
        let _permit = self.semaphore.acquire().await;

        self.inner.stat(path, args).await
    }

    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
        let permit = self.semaphore.acquire().await;

        self.inner
            .delete()
            .await
            .map(|(rp, w)| (rp, ConcurrentLimitWrapper::new(w, permit)))
    }

    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
        let permit = self.semaphore.acquire().await;

        self.inner
            .list(path, args)
            .await
            .map(|(rp, s)| (rp, ConcurrentLimitWrapper::new(s, permit)))
    }
}

#[doc(hidden)]
pub struct ConcurrentLimitWrapper<R, P> {
    inner: R,

    // Hold on this permit until this reader has been dropped.
    _permit: P,
}

impl<R, P> ConcurrentLimitWrapper<R, P> {
    fn new(inner: R, permit: P) -> Self {
        Self {
            inner,
            _permit: permit,
        }
    }
}

impl<R: oio::Read, P: Send + Sync + 'static + Unpin> oio::Read for ConcurrentLimitWrapper<R, P> {
    async fn read(&mut self) -> Result<Buffer> {
        self.inner.read().await
    }
}

impl<R: oio::Write, P: Send + Sync + 'static + Unpin> oio::Write for ConcurrentLimitWrapper<R, P> {
    async fn write(&mut self, bs: Buffer) -> Result<()> {
        self.inner.write(bs).await
    }

    async fn close(&mut self) -> Result<Metadata> {
        self.inner.close().await
    }

    async fn abort(&mut self) -> Result<()> {
        self.inner.abort().await
    }
}

impl<R: oio::List, P: Send + Sync + 'static + Unpin> oio::List for ConcurrentLimitWrapper<R, P> {
    async fn next(&mut self) -> Result<Option<oio::Entry>> {
        self.inner.next().await
    }
}

impl<R: oio::Delete, P: Send + Sync + 'static + Unpin> oio::Delete
    for ConcurrentLimitWrapper<R, P>
{
    async fn delete(&mut self, path: &str, args: OpDelete) -> Result<()> {
        self.inner.delete(path, args).await
    }

    async fn close(&mut self) -> Result<()> {
        self.inner.close().await
    }
}

impl<C: oio::Copy, P: Send + Sync + 'static + Unpin> oio::Copy for ConcurrentLimitWrapper<C, P> {
    async fn next(&mut self) -> Result<Option<usize>> {
        self.inner.next().await
    }

    async fn close(&mut self) -> Result<Metadata> {
        self.inner.close().await
    }

    async fn abort(&mut self) -> Result<()> {
        self.inner.abort().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use opendal_core::Operator;
    use opendal_core::OperatorBuilder;
    use opendal_core::services;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::time::timeout;

    use futures::stream;
    use http::Response;

    #[tokio::test]
    async fn operation_semaphore_can_be_shared() {
        let semaphore = Arc::new(Semaphore::new(1));
        let layer = ConcurrentLimitLayer::with_semaphore(semaphore.clone());

        let permit = semaphore.clone().acquire_owned(1).await;

        let op = Operator::new(services::Memory::default())
            .expect("operator must build")
            .layer(layer)
            .finish();

        let blocked = timeout(Duration::from_millis(50), op.stat("any")).await;
        assert!(
            blocked.is_err(),
            "operation should be limited by shared semaphore"
        );

        drop(permit);

        let completed = timeout(Duration::from_millis(50), op.stat("any")).await;
        assert!(
            completed.is_ok(),
            "operation should proceed once permit is released"
        );
    }

    #[tokio::test]
    async fn operation_semaphore_limits_copy_and_rename() {
        #[derive(Clone, Debug)]
        struct CopyRenameBackend {
            info: Arc<AccessorInfo>,
        }

        impl Access for CopyRenameBackend {
            type Reader = ();
            type Writer = ();
            type Lister = ();
            type Deleter = ();
            type Copier = oio::Copier;

            fn info(&self) -> Arc<AccessorInfo> {
                self.info.clone()
            }

            async fn copy(
                &self,
                _: &str,
                _: &str,
                _: OpCopy,
                _: OpCopier,
            ) -> Result<(RpCopy, Self::Copier)> {
                Ok((RpCopy::default(), Box::new(())))
            }

            async fn rename(&self, _: &str, _: &str, _: OpRename) -> Result<RpRename> {
                Ok(RpRename::default())
            }
        }

        let semaphore = Arc::new(Semaphore::new(1));
        let layer = ConcurrentLimitLayer::with_semaphore(semaphore.clone());
        let info = Arc::new(AccessorInfo::default());
        info.set_native_capability(Capability {
            copy: true,
            rename: true,
            ..Default::default()
        });
        let op = OperatorBuilder::new(CopyRenameBackend { info })
            .layer(layer)
            .finish();

        let permit = semaphore.clone().acquire_owned(1).await;

        let copy = timeout(Duration::from_millis(50), op.copy("from", "to")).await;
        assert!(copy.is_err(), "copy should wait for the operation permit");

        let rename = timeout(Duration::from_millis(50), op.rename("from", "to")).await;
        assert!(
            rename.is_err(),
            "rename should wait for the operation permit"
        );

        drop(permit);

        timeout(Duration::from_millis(50), op.copy("from", "to"))
            .await
            .expect("copy should proceed once permit is released")
            .expect("copy should succeed");
        timeout(Duration::from_millis(50), op.rename("from", "to"))
            .await
            .expect("rename should proceed once permit is released")
            .expect("rename should succeed");
    }

    #[tokio::test]
    async fn operation_semaphore_held_until_copier_dropped() {
        #[derive(Clone, Debug)]
        struct CopierBackend {
            info: Arc<AccessorInfo>,
        }

        impl Access for CopierBackend {
            type Reader = ();
            type Writer = ();
            type Lister = ();
            type Deleter = ();
            type Copier = oio::Copier;

            fn info(&self) -> Arc<AccessorInfo> {
                self.info.clone()
            }

            async fn copy(
                &self,
                _: &str,
                _: &str,
                _: OpCopy,
                _: OpCopier,
            ) -> Result<(RpCopy, Self::Copier)> {
                Ok((RpCopy::default(), Box::new(())))
            }

            async fn stat(&self, _: &str, _: OpStat) -> Result<RpStat> {
                Ok(RpStat::new(Metadata::new(EntryMode::FILE)))
            }
        }

        let semaphore = Arc::new(Semaphore::new(1));
        let layer = ConcurrentLimitLayer::with_semaphore(semaphore.clone());
        let info = Arc::new(AccessorInfo::default());
        info.set_native_capability(Capability {
            copy: true,
            stat: true,
            ..Default::default()
        });
        let op = OperatorBuilder::new(CopierBackend { info })
            .layer(layer)
            .finish();

        let copier = timeout(Duration::from_millis(50), op.copier("from", "to"))
            .await
            .expect("copier setup should not block")
            .expect("copier should be created");

        // The permit is held by the live copier, so concurrent operations
        // must time out until the copier is dropped.
        let blocked = timeout(Duration::from_millis(50), op.stat("any")).await;
        assert!(
            blocked.is_err(),
            "stat should wait while the copier holds the permit"
        );

        drop(copier);

        timeout(Duration::from_millis(50), op.stat("any"))
            .await
            .expect("stat should proceed once the copier is dropped")
            .expect("stat should succeed");
    }

    #[tokio::test]
    async fn concurrent_chunked_read_with_http_limit() {
        use opendal_core::raw::*;

        struct EchoFetcher;

        impl HttpFetch for EchoFetcher {
            async fn fetch(&self, req: http::Request<Buffer>) -> Result<http::Response<HttpBody>> {
                let data = req.into_body();
                let len = data.len() as u64;
                let body =
                    HttpBody::new(Box::pin(stream::once(async move { Ok(data) })), Some(len));
                Ok(http::Response::builder()
                    .status(http::StatusCode::OK)
                    .body(body)
                    .unwrap())
            }
        }

        #[derive(Clone, Debug)]
        struct HttpBackend {
            info: Arc<AccessorInfo>,
            content: Buffer,
        }

        impl Access for HttpBackend {
            type Reader = HttpBody;
            type Writer = ();
            type Lister = ();
            type Deleter = ();
            type Copier = oio::Copier;

            fn info(&self) -> Arc<AccessorInfo> {
                self.info.clone()
            }

            async fn read(&self, _: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
                let range = args.range();
                let start = range.offset() as usize;
                let data = match range.size() {
                    Some(sz) => self.content.slice(start..start + sz as usize),
                    None => self.content.slice(start..),
                };
                let req = http::Request::get("http://fake").body(data).unwrap();
                let resp = self.info.http_client().fetch(req).await?;
                Ok((
                    RpRead::new(Metadata::new(EntryMode::FILE).with_content_length(0)),
                    resp.into_body(),
                ))
            }

            async fn stat(&self, _: &str, _: OpStat) -> Result<RpStat> {
                Ok(RpStat::new(
                    Metadata::new(EntryMode::FILE).with_content_length(self.content.len() as u64),
                ))
            }

            async fn write(&self, _: &str, _: OpWrite) -> Result<(RpWrite, Self::Writer)> {
                Err(Error::new(ErrorKind::Unsupported, "not needed"))
            }
            async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
                Err(Error::new(ErrorKind::Unsupported, "not needed"))
            }
            async fn list(&self, _: &str, _: OpList) -> Result<(RpList, Self::Lister)> {
                Err(Error::new(ErrorKind::Unsupported, "not needed"))
            }
        }

        let content = Buffer::from(vec![0u8; 4096]);
        let info = Arc::new(AccessorInfo::default());
        info.update_http_client(|_| HttpClient::with(EchoFetcher));

        let op = OperatorBuilder::new(HttpBackend {
            info,
            content: content.clone(),
        })
        .layer(ConcurrentLimitLayer::new(1024).with_http_concurrent_limit(2))
        .finish();

        // chunk=256 ⇒ 16 HTTP requests, concurrent=4, but only 2 HTTP permits.
        let result = timeout(Duration::from_secs(5), async {
            op.reader_with("test")
                .chunk(256)
                .concurrent(4)
                .await
                .expect("reader must build")
                .read(..)
                .await
        })
        .await;

        let buf = result
            .expect("read must not deadlock (timeout)")
            .expect("read must succeed");
        assert_eq!(buf.to_bytes(), content.to_bytes());
    }

    #[tokio::test]
    async fn http_semaphore_holds_until_body_dropped() {
        struct DummyFetcher;

        impl HttpFetch for DummyFetcher {
            async fn fetch(&self, _req: http::Request<Buffer>) -> Result<Response<HttpBody>> {
                let body = HttpBody::new(stream::empty(), None);
                Ok(Response::builder()
                    .status(http::StatusCode::OK)
                    .body(body)
                    .expect("response must build"))
            }
        }

        let semaphore = Arc::new(Semaphore::new(1));
        let layer = ConcurrentLimitLayer::new(1).with_http_semaphore(semaphore.clone());
        let fetcher = ConcurrentLimitHttpFetcher::<Arc<Semaphore>> {
            inner: HttpClient::with(DummyFetcher).into_inner(),
            http_semaphore: layer.http_semaphore.clone(),
        };

        let request = http::Request::builder()
            .uri("http://example.invalid/")
            .body(Buffer::new())
            .expect("request must build");
        let _resp = fetcher
            .fetch(request)
            .await
            .expect("first fetch should succeed");

        let request = http::Request::builder()
            .uri("http://example.invalid/")
            .body(Buffer::new())
            .expect("request must build");
        let blocked = timeout(Duration::from_millis(50), fetcher.fetch(request)).await;
        assert!(
            blocked.is_err(),
            "http fetch should block while the body holds the permit"
        );
    }
}