pub struct ShardRouter;
impl ShardRouter {
pub fn route(key: &str, num_shards: u16) -> u16 {
if num_shards == 0 {
return 0;
}
let hash = seahash::hash(key.as_bytes());
(hash % num_shards as u64) as u16
}
pub fn is_shard_replica(
shard_id: u16,
node_index: usize,
replication_factor: u16,
num_nodes: usize,
) -> bool {
if num_nodes == 0 || replication_factor == 0 {
return false;
}
let primary_node = (shard_id as usize) % num_nodes;
for r in 0..replication_factor {
let replica_node = (primary_node + r as usize) % num_nodes;
if replica_node == node_index {
return true;
}
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_route_consistency() {
let shard1 = ShardRouter::route("key1", 10);
let shard2 = ShardRouter::route("key1", 10);
assert_eq!(shard1, shard2);
}
#[test]
fn test_is_shard_replica() {
assert!(ShardRouter::is_shard_replica(0, 0, 2, 3));
assert!(ShardRouter::is_shard_replica(0, 1, 2, 3));
assert!(!ShardRouter::is_shard_replica(0, 2, 2, 3));
}
}