Skip to main content

PeerBandwidthManager

Struct PeerBandwidthManager 

Source
pub struct PeerBandwidthManager {
    pub config: BandwidthManagerConfig,
    pub peers: HashMap<String, PeerBandwidthState>,
    pub usage_snapshots: HashMap<String, VecDeque<(u64, u64, u64)>>,
    pub total_bytes_sent: u64,
    pub total_bytes_recv: u64,
    /* private fields */
}
Expand description

Manages per-peer bandwidth state, rate limiting, and fairness scheduling.

All timestamps are provided by the caller as milliseconds since an arbitrary epoch (e.g. SystemTime::UNIX_EPOCH or Instant-derived). This makes the manager fully testable without real-time dependencies.

Fields§

§config: BandwidthManagerConfig

Manager configuration.

§peers: HashMap<String, PeerBandwidthState>

Per-peer token-bucket state keyed by peer ID.

§usage_snapshots: HashMap<String, VecDeque<(u64, u64, u64)>>

Sliding-window snapshots per peer: (timestamp_ms, bytes_sent, bytes_recv).

§total_bytes_sent: u64

Total bytes sent across all peers since manager creation.

§total_bytes_recv: u64

Total bytes received across all peers since manager creation.

Implementations§

Source§

impl PeerBandwidthManager

Source

pub fn new(config: BandwidthManagerConfig) -> Self

Create a new manager with the given configuration.

Source

pub fn register_peer(&mut self, peer_id: String, now: u64)

Register a peer with the default limits from the manager configuration.

If the peer is already registered, the call is a no-op. If max_peers would be exceeded, the oldest registered peer is evicted.

Source

pub fn set_peer_limits( &mut self, peer_id: &str, upload: BandwidthLimit, download: BandwidthLimit, ) -> bool

Override the upload and download limits for an already-registered peer.

Returns true on success, false if the peer is not registered.

Source

pub fn remove_peer(&mut self, peer_id: &str) -> bool

Remove a peer from the manager.

Returns true if the peer existed and was removed.

Source

pub fn refill_tokens(state: &mut PeerBandwidthState, now: u64)

Refill the token buckets for state based on elapsed time since the last refill.

elapsed_s = (now_ms - last_refill_ms) / 1000.0

New tokens are calculated as elapsed_s * bytes_per_second and added to the current token count, clamped to burst_bytes.

Source

pub fn try_consume( &mut self, peer_id: &str, bytes: u64, direction: BandwidthDirection, now: u64, ) -> bool

Attempt to consume bytes from the appropriate token bucket(s).

Tokens are refilled before checking. Returns true if the transfer is permitted, false if there are insufficient tokens.

Source

pub fn record_transfer( &mut self, peer_id: &str, bytes_sent: u64, bytes_recv: u64, now: u64, )

Record an unconditional transfer for a peer (no token consumption).

The snapshot is pushed to the sliding window and the manager-wide totals are updated. Snapshots older than usage_window_ms are dropped.

Source

pub fn peer_usage(&self, peer_id: &str, now: u64) -> Option<BandwidthUsage>

Compute BandwidthUsage for a peer by summing all snapshots within the configured window ending at now.

Returns None if the peer is not registered.

Source

pub fn top_uploaders(&self, k: usize, now: u64) -> Vec<BandwidthUsage>

Return the top-k peers by upload rate, descending.

Source

pub fn top_downloaders(&self, k: usize, now: u64) -> Vec<BandwidthUsage>

Return the top-k peers by download rate, descending.

Source

pub fn apply_fairness(&mut self, now: u64)

Apply the configured fairness policy to all registered peers.

Source

pub fn evict_idle_peers(&mut self, now: u64, idle_threshold_ms: u64) -> usize

Remove peers that have no snapshot newer than now - idle_threshold_ms.

Returns the number of peers evicted.

Source

pub fn manager_stats(&self) -> BandwidthManagerStats

Collect aggregate statistics for the manager.

Average rates are computed from the usage window of each registered peer at the current moment (passing now = 0 gives a snapshot of accumulated counters without rate computation).

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Allocation for T
where T: RefUnwindSafe + Send + Sync,

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<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more