pub struct Balancer<T, A> { /* private fields */ }Expand description
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.
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()));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-1Implementations§
Source§impl<T, A: Algorithm<T>> Balancer<T, A>
impl<T, A: Algorithm<T>> Balancer<T, A>
Sourcepub fn new(algorithm: A) -> Self
pub fn new(algorithm: A) -> Self
A balancer without options, choosing with algorithm.
PHP: new Balancer($algo).
Sourcepub fn algorithm_mut(&mut self) -> &mut A
pub fn algorithm_mut(&mut self) -> &mut A
The algorithm, to change its state (such as a
RoundRobin index).
PHP: getAlgo(), which returns the object itself.
Sourcepub fn add_option(&mut self, option: T) -> &mut Self
pub fn add_option(&mut self, option: T) -> &mut Self
Adds an option after the others.
PHP: addOption($option).
Sourcepub fn options(&self) -> &[T]
pub fn options(&self) -> &[T]
Every option, in the order they were added, filtered or not.
PHP: getOptions().
Sourcepub fn add_filter(
&mut self,
filter: impl Fn(&T) -> bool + Send + Sync + 'static,
) -> &mut Self
pub fn add_filter( &mut self, filter: impl Fn(&T) -> bool + Send + Sync + 'static, ) -> &mut Self
Adds a filter: only options every filter accepts can be chosen.
PHP: addFilter($callable).
Sourcepub fn filtered(&self) -> Vec<&T>
pub fn filtered(&self) -> Vec<&T>
Every option every filter accepts, in the order they were added: what the algorithm chooses from, for callers that act on all of them.
PHP: getFilteredOptions().