spacegate_kernel/helper_layers/
balancer.rs

1pub mod ip_hash;
2pub use ip_hash::IpHash;
3pub mod random;
4pub use random::Random;
5#[derive(Debug, Clone, Default)]
6pub struct Balancer<P, S> {
7    pub policy: P,
8    pub instances: Vec<S>,
9    pub fallback: S,
10}
11
12impl<P, S> Balancer<P, S> {
13    pub fn new(policy: P, instances: Vec<S>, fallback: S) -> Self {
14        Self { policy, instances, fallback }
15    }
16}
17
18pub trait BalancePolicy<S, R> {
19    fn pick<'s>(&self, instances: &'s [S], req: &R) -> Option<&'s S>;
20}
21
22impl<P, R, S> hyper::service::Service<R> for Balancer<P, S>
23where
24    P: BalancePolicy<S, R>,
25    S: hyper::service::Service<R>,
26    S::Future: std::marker::Send,
27{
28    type Response = S::Response;
29
30    type Error = S::Error;
31
32    type Future = S::Future;
33
34    fn call(&self, req: R) -> Self::Future {
35        self.policy.pick(&self.instances, &req).unwrap_or(&self.fallback).call(req)
36    }
37}