added adaptive weight balancing algorithm

This commit is contained in:
psun256
2025-12-09 18:31:22 -05:00
parent a3f50c1f0a
commit 20b51c2562
13 changed files with 274 additions and 26 deletions

View File

@@ -1,22 +1,53 @@
pub mod health;
use core::fmt;
use std::net::SocketAddr;
use std::sync::RwLock;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
// Physical server information
#[derive(Debug)]
pub struct Server {
pub endpoints: Arc<Vec<Arc<Backend>>>,
pub metrics: Arc<RwLock<ServerHealth>>,
}
// Physical server health statistics, used for certain load balancing algorithms
#[derive(Debug, Default)]
pub struct ServerHealth {
pub cpu: f64,
pub mem: f64,
pub net: f64,
pub io: f64,
}
impl ServerHealth {
pub fn update(&mut self, cpu: f64, mem: f64, net: f64, io: f64) {
self.cpu = cpu;
self.mem = mem;
self.net = net;
self.io = io;
}
}
// A possible endpoint for a proxied connection.
// Note that multiple may live on the same server, hence the Arc<RwLock<ServerMetric>>
#[derive(Debug)]
pub struct Backend {
pub id: String,
pub address: SocketAddr,
pub active_connections: AtomicUsize,
pub metrics: Arc<RwLock<ServerHealth>>,
}
impl Backend {
pub fn new(id: String, address: SocketAddr) -> Self {
pub fn new(id: String, address: SocketAddr, server_metrics: Arc<RwLock<ServerHealth>>) -> Self {
Self {
id: id.to_string(),
address,
active_connections: AtomicUsize::new(0),
metrics: server_metrics,
}
}
@@ -40,19 +71,18 @@ impl fmt::Display for Backend {
}
}
// A set of endpoints that can be load balanced around.
// Each Balancer owns one of these. Backend instances may be shared
// with other Balancer instances, hence Arc<Backend>.
#[derive(Clone, Debug)]
pub struct BackendPool {
pub backends: Arc<RwLock<Vec<Arc<Backend>>>>,
pub backends: Arc<Vec<Arc<Backend>>>,
}
impl BackendPool {
pub fn new() -> Self {
pub fn new(backends: Vec<Arc<Backend>>) -> Self {
BackendPool {
backends: Arc::new(RwLock::new(Vec::new())),
backends: Arc::new(backends),
}
}
pub fn add(&self, backend: Backend) {
self.backends.write().unwrap().push(Arc::new(backend));
}
}
}