Rust

algorithm

Module

[Algorithm]: how a balancer chooses one option, and the four it ships with: First, Last, Random and RoundRobin.

Contents

use utopia_balancer::First;
Rust
pub struct First

Always the first option.

use utopia_balancer::Last;
Rust
pub struct Last

Always the last option.

use utopia_balancer::Random;
Rust
pub struct Random

Undocumented.

Rust
use utopia_balancer::{Algorithm, Random};

let options = ["fra-1", "fra-2", "lon-1"];
let refs: Vec<&&str> = options.iter().collect();

let mut random = Random::seeded(7);
let picks: Vec<_> = (0..3).map(|_| random.pick(&refs).unwrap().unwrap()).collect();
assert_eq!(picks, [0, 1, 1]);
Also implements Default.
use utopia_balancer::RoundRobin;
Rust
pub struct RoundRobin

Each option in turn: every pick moves to the next position and wraps to the first after the last.

The index is the position picked last. It starts where it is created (-1 starts at the first option) and can be moved with RoundRobin::set_index, to share a rotation across processes.

Rust
use utopia_balancer::{Algorithm, RoundRobin};

let options = ["fra-1", "fra-2", "lon-1"];
let refs: Vec<&&str> = options.iter().collect();

let mut rr = RoundRobin::new(-1);
let picks: Vec<_> = (0..4).map(|_| rr.pick(&refs).unwrap().unwrap()).collect();
assert_eq!(picks, [0, 1, 2, 0]);
assert_eq!(rr.index(), 0);
use utopia_balancer::Algorithm;
Rust
pub trait Algorithm<T: ?Sized>

Chooses one of the options that passed a balancer's filters.

An algorithm sees the options in the order they were added and returns the position of the one it picks, or None to pick nothing. It may keep state between calls, as RoundRobin does. Implement it to add an algorithm (least connections, weighted, by latency).

Rust
use utopia_balancer::{Algorithm, Candidate, Error};

/// The option with the lowest `cpu`.
struct Idlest;

impl Algorithm<Candidate> for Idlest {
    fn name(&self) -> &str {
        "Idlest"
    }

    fn pick(&mut self, options: &[&Candidate]) -> Result<Option<usize>, Error> {
        let cpu = |c: &Candidate| c.get("cpu").map_or(i64::MAX, |v| v.to_double() as i64);
        Ok((0..options.len()).min_by_key(|&i| cpu(options[i])))
    }
}

let busy = Candidate::from([("cpu", 80.into())]);
let idle = Candidate::from([("cpu", 5.into())]);
assert_eq!(Idlest.pick(&[&busy, &idle])?, Some(1));
Implemented byBoxFirstLastRandomRoundRobin