use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use parking_lot::Mutex as ParkingMutex;
use crate::domain::id::Id;
const SEED_BATCH: usize = 100_000;
const LOW_WATER: usize = 20_000;
const TARGET: usize = 100_000;
const REFILL_INTERVAL_MS: u64 = 30_000;
struct GlobalIdGen {
generator: nebulaid::sdk::IdGenerator,
workspace: String,
group: String,
pool: Arc<ParkingMutex<VecDeque<Id>>>,
refilling: AtomicBool,
}
static GLOBAL: OnceLock<Arc<GlobalIdGen>> = OnceLock::new();
fn try_begin_refill(flag: &AtomicBool) -> bool {
flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
}
struct RefillGuard<'a>(&'a AtomicBool);
impl Drop for RefillGuard<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
fn drain_batch_into_pool(
pool: &mut VecDeque<Id>,
ids: Vec<nebulaid::core::Id>,
target: usize,
) -> usize {
let mut inserted = 0;
for id in ids {
if pool.len() >= target {
break;
}
pool.push_back(Id::from(id));
inserted += 1;
}
inserted
}
impl GlobalIdGen {
fn pop_one(&self) -> Option<Id> {
self.pool.lock().pop_front()
}
fn pool_len(&self) -> usize {
self.pool.lock().len()
}
async fn refill(&self) -> usize {
if !try_begin_refill(&self.refilling) {
log::debug!("id pool refill already in flight, skip");
return 0;
}
let _guard = RefillGuard(&self.refilling);
self.refill_locked().await
}
async fn refill_locked(&self) -> usize {
let need = TARGET.saturating_sub(self.pool_len());
if need == 0 {
return 0;
}
match self
.generator
.batch_generate(&self.workspace, &self.group, "refill", need)
.await
{
Ok(batch) => {
let mut pool = self.pool.lock();
drain_batch_into_pool(&mut pool, batch.ids, TARGET)
}
Err(e) => {
log::error!(
"{}",
crate::i18n::tr_log_args("id-refill-failed", &[("error", e.to_string())],)
);
0
}
}
}
}
pub async fn init(
generator: nebulaid::sdk::IdGenerator,
workspace: String,
group: String,
) -> anyhow::Result<()> {
let pool_arc = Arc::new(ParkingMutex::new(VecDeque::new()));
let batch = generator
.batch_generate(&workspace, &group, "bootstrap", SEED_BATCH)
.await
.map_err(|e| anyhow::anyhow!("NebulaId seed batch_generate failed: {e}"))?;
{
let mut pool = pool_arc.lock();
for id in batch.ids {
pool.push_back(Id::from(id));
}
}
let global = Arc::new(GlobalIdGen {
generator,
workspace,
group,
pool: pool_arc,
refilling: AtomicBool::new(false),
});
let first = GLOBAL.set(global.clone()).is_ok();
if first {
log::info!(
"{}",
crate::i18n::tr_log_args(
"id-global-generator-initialized",
&[
("workspace", global.workspace.as_str().to_string(),),
("group", global.group.as_str().to_string()),
],
)
);
tokio::spawn(async move {
loop {
tokio::time::sleep(std::time::Duration::from_millis(REFILL_INTERVAL_MS)).await;
if global.pool_len() < LOW_WATER {
let inserted = global.refill().await;
log::debug!("id pool refill inserted {inserted} ids");
}
}
});
}
Ok(())
}
#[inline]
pub fn generate() -> Id {
match GLOBAL.get() {
Some(global) => match global.pop_one() {
Some(id) => {
if global.pool_len() < LOW_WATER && tokio::runtime::Handle::try_current().is_ok() {
let g = global.clone();
tokio::spawn(async move {
let inserted = g.refill().await;
log::debug!("id pool refill inserted {inserted} ids");
});
}
id
}
None => Id::test_new(),
},
None => Id::test_new(),
}
}
#[inline]
pub fn is_initialized() -> bool {
GLOBAL.get().is_some()
}
#[cfg(test)]
mod tests {
use super::*;
fn nebula_batch(size: usize) -> Vec<nebulaid::core::Id> {
(0..size).map(|_| Id::test_new().as_nebulaid()).collect()
}
#[test]
fn refill_counts_only_inserted_ids() {
let mut pool = VecDeque::new();
for _ in 0..TARGET - 1 {
pool.push_back(Id::test_new());
}
let inserted = drain_batch_into_pool(&mut pool, nebula_batch(64), TARGET);
assert_eq!(inserted, 1, "only one free slot must be reported");
assert_eq!(pool.len(), TARGET);
}
#[test]
fn refill_counts_all_ids_when_pool_has_room() {
let mut pool = VecDeque::new();
let inserted = drain_batch_into_pool(&mut pool, nebula_batch(8), TARGET);
assert_eq!(inserted, 8);
assert_eq!(pool.len(), 8);
}
#[test]
fn refill_gate_allows_only_one_in_flight() {
let flag = AtomicBool::new(false);
assert!(try_begin_refill(&flag), "first caller must acquire");
assert!(!try_begin_refill(&flag), "second caller must be rejected");
flag.store(false, Ordering::Release);
assert!(try_begin_refill(&flag), "released gate must be acquirable");
}
#[test]
fn refill_guard_releases_on_drop() {
let flag = AtomicBool::new(false);
assert!(try_begin_refill(&flag));
{
let _guard = RefillGuard(&flag);
}
assert!(try_begin_refill(&flag), "guard drop must release the gate");
}
}