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 general;
57pub mod interval;
58pub mod ip;
59pub mod limit;
60pub mod random;
61pub mod simple;
62pub mod threshold;
63pub use anyhow;
64pub use get_if_addrs;
65
66use async_trait::async_trait;
67use std::future::Future;
68
69pub trait LoadBalancer<T>: Send + Sync + Clone + 'static {
70 fn alloc(&self) -> impl Future<Output = T> + Send;
71 fn try_alloc(&self) -> Option<T>;
72}
73
74#[async_trait]
75pub trait BoxLoadBalancer<T>: Send + Sync + Clone + 'static {
76 async fn alloc(&self) -> T;
77 fn try_alloc(&self) -> Option<T>;
78}