load_balancer/
lib.rs

1//! # Load Balancer Library
2//!
3//! This library provides a set of generic load balancer implementations for distributing
4//! workloads across multiple targets, such as clients, network endpoints, or resources.
5//!
6//! ## Traits
7//!
8//! ### `LoadBalancer<T>`
9//!
10//! A generic trait for asynchronous or synchronous load balancing. Implementors provide
11//! methods to allocate a resource from the pool.
12//!
13//! ```rust
14//! use std::future::Future;
15//!
16//! pub trait LoadBalancer<T>: Send + Sync + Clone + 'static {
17//!     /// Asynchronously allocate a resource.
18//!     /// Returns `Some(T)` if successful, or `None` if no resource is available.
19//!     fn alloc(&self) -> impl Future<Output = Option<T>> + Send;
20//!
21//!     /// Attempt to allocate a resource synchronously without awaiting.
22//!     /// Returns `Some(T)` if successful, or `None` if no resource is available.
23//!     fn try_alloc(&self) -> Option<T>;
24//! }
25//! ```
26//!
27//! ### `BoxLoadBalancer<T>`
28//!
29//! An async trait variant that can be used with `async_trait` for boxed trait objects
30//! or dynamic dispatch. Provides similar functionality to `LoadBalancer` but supports
31//! fully `async` method signatures.
32//!
33//! ```rust
34//! use async_trait::async_trait;
35//!
36//! #[async_trait]
37//! pub trait BoxLoadBalancer<T>: Send + Sync + Clone + 'static {
38//!     /// Asynchronously allocate a resource.
39//!     /// Returns `Some(T)` if successful, or `None` if no resource is available.
40//!     async fn alloc(&self) -> Option<T>;
41//!
42//!     /// Attempt to allocate a resource synchronously without awaiting.
43//!     /// Returns `Some(T)` if successful, or `None` if no resource is available.
44//!     fn try_alloc(&self) -> Option<T>;
45//! }
46//! ```
47//! 
48//! ## Notes
49//!
50//! - All load balancers are `Send`, `Sync`, and `Clone`, making them suitable for multi-threaded
51//!   asynchronous environments.
52//! - The `alloc` method returns `Option<T>` rather than `Result`, reflecting that allocation
53//!   failure is expected under normal conditions and not necessarily an error.
54//! - `try_alloc` is non-blocking and will return `None` immediately if no resource is available.
55
56pub mod ip;
57pub mod limit;
58pub mod random;
59pub mod simple;
60pub mod threshold;
61pub mod interval;
62pub use anyhow;
63pub use get_if_addrs;
64
65use async_trait::async_trait;
66use std::future::Future;
67
68pub trait LoadBalancer<T>: Send + Sync + Clone + 'static {
69    fn alloc(&self) -> impl Future<Output = T> + Send;
70    fn try_alloc(&self) -> Option<T>;
71}
72
73#[async_trait]
74pub trait BoxLoadBalancer<T>: Send + Sync + Clone + 'static {
75    async fn alloc(&self) -> T;
76    fn try_alloc(&self) -> Option<T>;
77}