Skip to main content

Algorithm

Trait Algorithm 

Source
pub trait Algorithm<T: ?Sized> {
    // Required methods
    fn name(&self) -> &str;
    fn pick(&mut self, options: &[&T]) -> Result<Option<usize>, Error>;
}
Expand description

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.

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

Required Methods§

Source

fn name(&self) -> &str

The algorithm’s name, such as RoundRobin.

PHP: getName().

Source

fn pick(&mut self, options: &[&T]) -> Result<Option<usize>, Error>

The position in options of the option to use, or None for none.

PHP: run($options).

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<T: ?Sized, A: Algorithm<T> + ?Sized> Algorithm<T> for Box<A>

Source§

fn name(&self) -> &str

The boxed algorithm’s name.

Source§

fn pick(&mut self, options: &[&T]) -> Result<Option<usize>, Error>

Picks with the boxed algorithm.

Implementors§

Source§

impl<T: ?Sized> Algorithm<T> for First

Source§

impl<T: ?Sized> Algorithm<T> for Last

Source§

impl<T: ?Sized> Algorithm<T> for Random

Source§

impl<T: ?Sized> Algorithm<T> for RoundRobin