use super::*;
use std::time::Duration;
pub(super) async fn rebalance_loop(rt: Arc<GroupRuntime>) {
let period = Duration::from_millis(rt.cfg.rebalance_ms);
let mut tick = tokio::time::interval(period);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tokio::select! {
_ = rt.bg_cancel.cancelled() => {
return;
}
_ = tick.tick() => {
}
}
if let Err(e) = rebalance_once(&rt).await {
tracing::warn!(err = %e, "再平衡轮次失败,下轮重试");
}
}
}
pub(super) async fn rebalance_once(rt: &Arc<GroupRuntime>) -> Result<()> {
let _guard = match rt.rebalance_lock.try_lock() {
Ok(g) => g,
Err(_) => return Ok(()),
};
let nodes_key = rt.layout.nodes();
let now_ms: f64 = if rt.client.profile() == crate::config::CompatibilityProfile::RustV2 {
super::command::redis_now(&rt.client).await? as f64
} else {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("墙钟早于 epoch")
.as_millis() as f64
};
let expire_at = now_ms + (3 * rt.cfg.rebalance_ms) as f64;
rt.client
.z_add(&nodes_key, expire_at, rt.node_id.as_str())
.await?;
rt.client
.z_rem_range_by_score(&nodes_key, f64::NEG_INFINITY, now_ms)
.await?;
let alive = rt.client.z_card(&nodes_key).await?.max(1);
let fair = u64::from(rt.count).div_ceil(alive).max(1) as u32;
let owned: Vec<u32> = rt.claimed.read().expect("claimed").clone();
if (owned.len() as u32) < fair {
let mut acquired = 0u32;
let need = fair - owned.len() as u32;
for p in 0..rt.count {
if acquired >= need || rt.bg_cancel.is_cancelled() {
break;
}
if owned.contains(&p) {
continue;
}
if let Some(guard) = rt.lock.try_lock(&rt.layout.lock_business_key(p)).await? {
acquired += 1;
let _ = rt
.event_tx
.send(Event::ClaimAcquired {
p,
guard,
})
.await;
}
}
} else if (owned.len() as u32) > fair {
let _ = rt
.event_tx
.send(Event::RetainShare {
target: fair as usize,
})
.await;
}
Ok(())
}