Skip to content

Commit

Permalink
balancer: add HashRingSelector (#1650)
Browse files Browse the repository at this point in the history
  • Loading branch information
dyc3 authored Apr 9, 2024
1 parent 0257028 commit a952d2d
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ figment = { version = "0.10.15", features = ["toml", "env"] }
futures-util = "0.3.30"
harness = { path = "crates/harness" }
harness_macros = { path = "crates/harness_macros" }
hashring = "0.3.3"
hickory-resolver = { version = "0.24.0", features = ["system-config"] }
humantime-serde = "1.1"
hyper = { version = "1.2.0", features = ["full"] }
Expand Down
1 change: 1 addition & 0 deletions crates/ott-balancer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ console-subscriber.workspace = true
enum_dispatch.workspace = true
figment.workspace = true
futures-util.workspace = true
hashring.workspace = true
hyper.workspace = true
hyper-util.workspace = true
http-body-util.workspace = true
Expand Down
24 changes: 24 additions & 0 deletions crates/ott-balancer/src/selection.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::monolith::BalancerMonolith;
use enum_dispatch::enum_dispatch;
use hashring::HashRing;
use ott_balancer_protocol::RoomName;
use rand::seq::IteratorRandom;
use serde::Deserialize;
Expand Down Expand Up @@ -28,6 +29,7 @@ pub trait MonolithSelection: std::fmt::Debug {
#[enum_dispatch]
pub enum MonolithSelectionStrategy {
MinRooms(MinRoomsSelector),
HashRing(HashRingSelector),
}

impl Default for MonolithSelectionStrategy {
Expand Down Expand Up @@ -57,6 +59,28 @@ impl MonolithSelection for MinRoomsSelector {
}
}

#[derive(Debug, Default, Deserialize, Copy, Clone)]
pub struct HashRingSelector;

impl MonolithSelection for HashRingSelector {
fn select_monolith<'a>(
&'a self,
room: &RoomName,
monoliths: Vec<&'a BalancerMonolith>,
) -> anyhow::Result<&BalancerMonolith> {
let mut ring = HashRing::new();
ring.batch_add(monoliths.iter().map(|m| m.id()).collect());

let id = ring.get(room).ok_or(anyhow::anyhow!("ring hash empty"))?;
let i = monoliths
.iter()
.position(|m| m.id() == *id)
.ok_or(anyhow::anyhow!("monolith not found"))?;

Ok(monoliths[i])
}
}

#[cfg(test)]
mod test {
use std::net::Ipv4Addr;
Expand Down

0 comments on commit a952d2d

Please sign in to comment.