weighted_rs_1/
lib.rs

1//! A libray for weighted balancing algorithm.
2//! It provides three weighted balancing (elect) algorithm.
3//! One is random algorithm.
4//! Another is weighted balancing algorithm used by LVS.
5//! The third is smooth weighted balancing algorithm used by Nginx.
6//!
7//! The LVS weighted round-robin scheduling is introduced at http://kb.linuxvirtualserver.org/wiki/Weighted_Round-Robin_Scheduling.
8//! The Nginx smooth weighted round-robin balancing algorithm is introduced at https://github.com/phusion/nginx/commit/27e94984486058d73157038f7950a0a36ecc6e35.
9//! The random algorithm is not smooth although it follows weight configuration.
10//! Using it is simple:
11//! ```rust
12//!     use weighted_rs_wasm::{SmoothWeight, Weight};
13//!     use std::collections::HashMap;
14//!
15//!     let mut sw: SmoothWeight<&str> = SmoothWeight::new();
16//!     sw.add("server1", 5);
17//!     sw.add("server2", 2);
18//!     sw.add("server3", 3);
19//!
20//!     for _ in 0..100 {
21//!         let s = sw.next().unwrap();
22//!         println!("{}", s);
23//!     }
24//! ```
25
26use std::collections::HashMap;
27
28pub mod roundrobin_weight;
29pub mod smooth_weight;
30
31pub use roundrobin_weight::*;
32pub use smooth_weight::*;
33
34// A common trait for weight algorithm.
35pub trait Weight {
36    type Item;
37
38    // next gets next selected item.
39    fn next(&mut self) -> Option<Self::Item>;
40    // add adds a weighted item for selection.
41    fn add(&mut self, item: Self::Item, weight: isize);
42
43    // all returns all items.
44    fn all(&self) -> HashMap<Self::Item, isize>;
45
46    // remove_all removes all weighted items.
47    fn remove_all(&mut self);
48
49    // reset resets the balancing algorithm.
50    fn reset(&mut self);
51}