use crate::services::ActionHandler;
use crate::services::RequestContext;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
pub trait LoadBalancingStrategy: Send + Sync {
fn select_handler(&self, handlers: &[ActionHandler], context: &RequestContext) -> usize;
}
#[derive(Debug)]
pub struct RoundRobinLoadBalancer {
current_index: Arc<AtomicUsize>,
}
impl Default for RoundRobinLoadBalancer {
fn default() -> Self {
Self::new()
}
}
impl RoundRobinLoadBalancer {
pub fn new() -> Self {
RoundRobinLoadBalancer {
current_index: Arc::new(AtomicUsize::new(0)),
}
}
}
impl LoadBalancingStrategy for RoundRobinLoadBalancer {
fn select_handler(&self, handlers: &[ActionHandler], _context: &RequestContext) -> usize {
if handlers.is_empty() {
return 0;
}
self.current_index.fetch_add(1, Ordering::SeqCst) % handlers.len()
}
}