Rust

Crate root

Module
What utopia_balancer defines at its root.

Contents

use utopia_balancer::Balancer;
Rust
pub struct Balancer<T, A> {
    // private fields
}

Chooses one of its options with an Algorithm, among those every filter accepts.

Options are any type: Candidate for PHP's state bags, or your own endpoint type. Filters run on every Balancer::run, so they see the options' current state.

PHP: Utopia\Balancer\Balancer.

Rust
use utopia_balancer::{Balancer, Candidate, RoundRobin};

let mut balancer = Balancer::new(RoundRobin::new(-1));
balancer
    .add_option(Candidate::from([("hostname", "worker-1".into()), ("online", true.into())]))
    .add_option(Candidate::from([("hostname", "worker-2".into()), ("online", false.into())]))
    .add_option(Candidate::from([("hostname", "worker-3".into()), ("online", true.into())]))
    .add_filter(|c| c.get("online").is_some_and(|v| v.truthy()));

let host = |b: &mut Balancer<Candidate, RoundRobin>| b.run().unwrap().and_then(|c| c.get("hostname").cloned());
assert_eq!(host(&mut balancer), Some("worker-1".into()));
assert_eq!(host(&mut balancer), Some("worker-3".into()));
assert_eq!(host(&mut balancer), Some("worker-1".into()));
PHP
use Utopia\Balancer\Algorithm\RoundRobin;
use Utopia\Balancer\Balancer;
use Utopia\Balancer\Option;

$balancer = new Balancer(new RoundRobin(-1));
$balancer
    ->addOption(new Option(['hostname' => 'worker-1', 'online' => true]))
    ->addOption(new Option(['hostname' => 'worker-2', 'online' => false]))
    ->addOption(new Option(['hostname' => 'worker-3', 'online' => true]))
    ->addFilter(fn (Option $o) => $o->getState('online') === true);

echo $balancer->run()->getState('hostname'), "\n"; // worker-1
echo $balancer->run()->getState('hostname'), "\n"; // worker-3
echo $balancer->run()->getState('hostname'), "\n"; // worker-1
Also implements Clone, Debug.
use utopia_balancer::Candidate;
Rust
pub struct Candidate {
    // private fields
}

One option to balance between, described by a bag of named values (its state): a hostname, whether it is online, its load.

Keys follow PHP array rules: a decimal key such as "0" is stored as the integer 0, so Candidate::states is the array PHP would hold.

PHP: Utopia\Balancer\Option.

Rust
use php_std::Value;
use utopia_balancer::Candidate;

let mut worker = Candidate::default();
worker.set("hostname", Value::from("worker-1")).set("cpu", Value::from(35));

assert_eq!(worker.get("cpu"), Some(&Value::Int(35)));
assert_eq!(worker.get_or("memory", &Value::Int(0)), &Value::Int(0));
assert_eq!(worker.states().len(), 2);
PHP
use Utopia\Balancer\Option;

$worker = new Option([]);
$worker->setState('hostname', 'worker-1')->setState('cpu', 35);

var_dump($worker->getState('cpu'));         // int(35)
var_dump($worker->getState('memory', 0));   // int(0)
var_dump(\count($worker->getStates()));     // int(2)
Also implements From<[(&str, Value); N]>, From<Array>.
use utopia_balancer::First;
Rust
pub struct First;

Always the first option.

PHP: Utopia\Balancer\Algorithm\First.

Also implements Algorithm<T>.
use utopia_balancer::Last;
Rust
pub struct Last;

Always the last option.

PHP: Utopia\Balancer\Algorithm\Last.

Also implements Algorithm<T>.
use utopia_balancer::Random;
Rust
pub struct Random {
    // private fields
}

A uniformly random option, from PHP's Mersenne Twister.

Random::seeded replays exactly what PHP picks after mt_srand($seed), so a choice can be reproduced in tests and compared with PHP.

PHP: Utopia\Balancer\Algorithm\Random (array_rand() on the default engine).

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]);
PHP
use Utopia\Balancer\Algorithm\Random;
use Utopia\Balancer\Option;

$options = [new Option(['dc' => 'fra-1']), new Option(['dc' => 'fra-2']), new Option(['dc' => 'lon-1'])];

mt_srand(7);
$random = new Random();
foreach ([1, 2, 3] as $_) {
    echo $random->run($options)->getState('dc'), "\n"; // fra-1, fra-2, fra-2
}
Also implements Default, Algorithm<T>.
use utopia_balancer::RoundRobin;
Rust
pub struct RoundRobin {
    // private fields
}

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.

PHP: Utopia\Balancer\Algorithm\RoundRobin.

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);
PHP
use Utopia\Balancer\Algorithm\RoundRobin;
use Utopia\Balancer\Option;

$options = [new Option(['dc' => 'fra-1']), new Option(['dc' => 'fra-2']), new Option(['dc' => 'lon-1'])];

$rr = new RoundRobin(-1);
foreach ([1, 2, 3, 4] as $_) {
    echo $rr->run($options)->getState('dc'), "\n"; // fra-1, fra-2, lon-1, fra-1
}
echo $rr->getIndex(), "\n"; // 0
Also implements Algorithm<T>.
use utopia_balancer::Error;
Rust
pub enum Error {
    Value(String),
    Type(String),
    Custom {
        class: &'static str,
        message: String,
    },
}

Why choosing an option failed.

PHP: one variant per PHP exception class (see Error::php_class).

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).

PHP: Utopia\Balancer\Algorithm; pick() is run(), returning the position instead of the option.

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));
PHP
use Utopia\Balancer\Algorithm;
use Utopia\Balancer\Option;

final class Idlest extends Algorithm
{
    public function getName(): string
    {
        return 'Idlest';
    }

    public function run(array $options): ?Option
    {
        usort($options, fn (Option $a, Option $b) => $a->getState('cpu') <=> $b->getState('cpu'));

        return $options[0] ?? null;
    }
}

$busy = new Option(['cpu' => 80]);
$idle = new Option(['cpu' => 5]);
var_dump((new Idlest())->run([$busy, $idle]) === $idle); // bool(true)
Rust
pub type Filter<T> = Arc<dyn Fn(&T) -> bool + Send + Sync>;

A filter: whether an option may be chosen.