Skip to main content

Bulkhead

Struct Bulkhead 

Source
pub struct Bulkhead { /* private fields */ }
Expand description

A concurrency limiter: a counting semaphore that caps in-flight operations.

Bulkhead is a small, Copy value holding a fixed capacity and the number of permits currently held (in_flight). try_acquire takes permits when room exists and reports whether it succeeded; release returns them.

The capacity is clamped to at least 1 at construction, so a bulkhead can always admit one operation. The invariant in_flight <= capacity holds on every public path, so available never underflows.

Implementations§

Source§

impl Bulkhead

Source

pub const fn new(capacity: usize) -> Self

Creates a bulkhead allowing at most capacity concurrent permits.

capacity is clamped to a minimum of 1: a bulkhead always admits at least one operation, so a 0 would only ever reject and is treated as 1.

Examples found in repository?
examples/basic.rs (line 15)
13fn main() {
14    // Allow at most three concurrent calls to a downstream service.
15    let mut bulkhead = Bulkhead::new(3);
16
17    // Six requests arrive while none have finished yet.
18    println!("capacity: {}", bulkhead.capacity());
19    for request in 0..6 {
20        if bulkhead.try_acquire_one() {
21            println!(
22                "request {request}: admitted ({} in flight)",
23                bulkhead.in_flight()
24            );
25        // ... start the work; release the permit when it completes ...
26        } else {
27            println!("request {request}: rejected (bulkhead full), shed load");
28        }
29    }
30
31    // Two of the in-flight operations finish and return their permits.
32    bulkhead.release(2);
33    println!(
34        "\nafter two completions: {} available",
35        bulkhead.available()
36    );
37
38    // Room exists again, so the next request is admitted.
39    if bulkhead.try_acquire_one() {
40        println!("retry: admitted ({} in flight)", bulkhead.in_flight());
41    }
42}
Source

pub const fn capacity(&self) -> usize

Returns the maximum number of concurrent permits.

Examples found in repository?
examples/basic.rs (line 18)
13fn main() {
14    // Allow at most three concurrent calls to a downstream service.
15    let mut bulkhead = Bulkhead::new(3);
16
17    // Six requests arrive while none have finished yet.
18    println!("capacity: {}", bulkhead.capacity());
19    for request in 0..6 {
20        if bulkhead.try_acquire_one() {
21            println!(
22                "request {request}: admitted ({} in flight)",
23                bulkhead.in_flight()
24            );
25        // ... start the work; release the permit when it completes ...
26        } else {
27            println!("request {request}: rejected (bulkhead full), shed load");
28        }
29    }
30
31    // Two of the in-flight operations finish and return their permits.
32    bulkhead.release(2);
33    println!(
34        "\nafter two completions: {} available",
35        bulkhead.available()
36    );
37
38    // Room exists again, so the next request is admitted.
39    if bulkhead.try_acquire_one() {
40        println!("retry: admitted ({} in flight)", bulkhead.in_flight());
41    }
42}
Source

pub const fn in_flight(&self) -> usize

Returns the number of permits currently held.

Examples found in repository?
examples/basic.rs (line 23)
13fn main() {
14    // Allow at most three concurrent calls to a downstream service.
15    let mut bulkhead = Bulkhead::new(3);
16
17    // Six requests arrive while none have finished yet.
18    println!("capacity: {}", bulkhead.capacity());
19    for request in 0..6 {
20        if bulkhead.try_acquire_one() {
21            println!(
22                "request {request}: admitted ({} in flight)",
23                bulkhead.in_flight()
24            );
25        // ... start the work; release the permit when it completes ...
26        } else {
27            println!("request {request}: rejected (bulkhead full), shed load");
28        }
29    }
30
31    // Two of the in-flight operations finish and return their permits.
32    bulkhead.release(2);
33    println!(
34        "\nafter two completions: {} available",
35        bulkhead.available()
36    );
37
38    // Room exists again, so the next request is admitted.
39    if bulkhead.try_acquire_one() {
40        println!("retry: admitted ({} in flight)", bulkhead.in_flight());
41    }
42}
Source

pub const fn available(&self) -> usize

Returns how many more permits can be acquired right now.

Examples found in repository?
examples/basic.rs (line 35)
13fn main() {
14    // Allow at most three concurrent calls to a downstream service.
15    let mut bulkhead = Bulkhead::new(3);
16
17    // Six requests arrive while none have finished yet.
18    println!("capacity: {}", bulkhead.capacity());
19    for request in 0..6 {
20        if bulkhead.try_acquire_one() {
21            println!(
22                "request {request}: admitted ({} in flight)",
23                bulkhead.in_flight()
24            );
25        // ... start the work; release the permit when it completes ...
26        } else {
27            println!("request {request}: rejected (bulkhead full), shed load");
28        }
29    }
30
31    // Two of the in-flight operations finish and return their permits.
32    bulkhead.release(2);
33    println!(
34        "\nafter two completions: {} available",
35        bulkhead.available()
36    );
37
38    // Room exists again, so the next request is admitted.
39    if bulkhead.try_acquire_one() {
40        println!("retry: admitted ({} in flight)", bulkhead.in_flight());
41    }
42}
Source

pub const fn is_full(&self) -> bool

Returns true when no further permits are available.

Source

pub const fn is_empty(&self) -> bool

Returns true when no permits are held.

Source

pub fn try_acquire(&mut self, permits: usize) -> bool

Tries to acquire permits permits at once.

Returns true and reserves them if at least permits are available; otherwise returns false and changes nothing (no partial acquire). A request for more than capacity always fails. Acquiring 0 permits always succeeds and reserves nothing.

Source

pub fn try_acquire_one(&mut self) -> bool

Tries to acquire a single permit. See try_acquire.

Examples found in repository?
examples/basic.rs (line 20)
13fn main() {
14    // Allow at most three concurrent calls to a downstream service.
15    let mut bulkhead = Bulkhead::new(3);
16
17    // Six requests arrive while none have finished yet.
18    println!("capacity: {}", bulkhead.capacity());
19    for request in 0..6 {
20        if bulkhead.try_acquire_one() {
21            println!(
22                "request {request}: admitted ({} in flight)",
23                bulkhead.in_flight()
24            );
25        // ... start the work; release the permit when it completes ...
26        } else {
27            println!("request {request}: rejected (bulkhead full), shed load");
28        }
29    }
30
31    // Two of the in-flight operations finish and return their permits.
32    bulkhead.release(2);
33    println!(
34        "\nafter two completions: {} available",
35        bulkhead.available()
36    );
37
38    // Room exists again, so the next request is admitted.
39    if bulkhead.try_acquire_one() {
40        println!("retry: admitted ({} in flight)", bulkhead.in_flight());
41    }
42}
Source

pub fn release(&mut self, permits: usize)

Releases permits permits back to the bulkhead.

Saturates at zero, so releasing more than are held simply empties the bulkhead rather than underflowing — a release without a matching acquire cannot drive in_flight negative or panic.

Examples found in repository?
examples/basic.rs (line 32)
13fn main() {
14    // Allow at most three concurrent calls to a downstream service.
15    let mut bulkhead = Bulkhead::new(3);
16
17    // Six requests arrive while none have finished yet.
18    println!("capacity: {}", bulkhead.capacity());
19    for request in 0..6 {
20        if bulkhead.try_acquire_one() {
21            println!(
22                "request {request}: admitted ({} in flight)",
23                bulkhead.in_flight()
24            );
25        // ... start the work; release the permit when it completes ...
26        } else {
27            println!("request {request}: rejected (bulkhead full), shed load");
28        }
29    }
30
31    // Two of the in-flight operations finish and return their permits.
32    bulkhead.release(2);
33    println!(
34        "\nafter two completions: {} available",
35        bulkhead.available()
36    );
37
38    // Room exists again, so the next request is admitted.
39    if bulkhead.try_acquire_one() {
40        println!("retry: admitted ({} in flight)", bulkhead.in_flight());
41    }
42}
Source

pub fn release_one(&mut self)

Releases a single permit. See release.

Source

pub fn reset(&mut self)

Releases every held permit, returning the bulkhead to empty.

Trait Implementations§

Source§

impl Clone for Bulkhead

Source§

fn clone(&self) -> Bulkhead

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Bulkhead

Source§

impl Debug for Bulkhead

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Bulkhead

Source§

impl Hash for Bulkhead

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Bulkhead

Source§

fn eq(&self, other: &Bulkhead) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Bulkhead

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.