async_bulkhead/bulkhead/
tokio.rs

1use super::{Bulkhead, BulkheadError};
2use futures_lite::future::Future;
3use tokio::time::{error, timeout};
4
5impl Bulkhead {
6    /// Limits the number of concurrent calls using a semaphore with the
7    /// specified maximum concurrent calls and semaphore wait duration.
8    ///
9    /// When the semaphore permit can't be acquired before the specified duration,
10    /// the `Err(BulkheadError::Timeout)` value is returned.
11    pub async fn limit<F, R>(&self, f: F) -> Result<R, BulkheadError>
12    where
13        F: Future<Output = R>,
14    {
15        let permit_fut = self.max_concurrent_calls.acquire();
16        let _permit = timeout(self.max_wait_duration, permit_fut).await?;
17        Ok(f.await)
18    }
19}
20
21impl From<error::Elapsed> for BulkheadError {
22    fn from(_err: error::Elapsed) -> Self {
23        Self::Timeout
24    }
25}