use super::persist::SurrogateHwmPersist;
use super::registry::SurrogateRegistry;
pub fn bootstrap_registry(persist: &dyn SurrogateHwmPersist) -> crate::Result<SurrogateRegistry> {
let hwm = persist.load()?;
Ok(SurrogateRegistry::from_persisted_hwm(hwm))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use nodedb_types::Surrogate;
use super::super::persist::SystemCatalogHwm;
use super::*;
use crate::control::security::catalog::SystemCatalog;
#[test]
fn fresh_database_starts_at_one() {
let dir = tempfile::tempdir().unwrap();
let catalog = Arc::new(SystemCatalog::open(&dir.path().join("system.redb")).unwrap());
let persist = SystemCatalogHwm::new(catalog);
let reg = bootstrap_registry(&persist).unwrap();
assert_eq!(reg.alloc_one().unwrap(), Surrogate::new(1));
}
#[test]
fn restart_round_trip_via_catalog() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("system.redb");
{
let catalog = Arc::new(SystemCatalog::open(&path).unwrap());
let persist = SystemCatalogHwm::new(catalog);
let reg = bootstrap_registry(&persist).unwrap();
let _ = reg.alloc(5000).unwrap();
assert_eq!(reg.current_hwm(), 5000);
reg.flush(&persist).unwrap();
}
{
let catalog = Arc::new(SystemCatalog::open(&path).unwrap());
let persist = SystemCatalogHwm::new(catalog);
let reg = bootstrap_registry(&persist).unwrap();
assert_eq!(reg.alloc_one().unwrap(), Surrogate::new(5001));
}
}
#[test]
fn wal_record_round_trip_restores_hwm() {
use nodedb_wal::record::SurrogateAllocPayload;
let payload = SurrogateAllocPayload::new(9_999);
let bytes = payload.to_bytes();
let decoded = SurrogateAllocPayload::from_bytes(&bytes).unwrap();
assert_eq!(decoded.hi, 9_999);
struct ReplayPersist(u32);
impl SurrogateHwmPersist for ReplayPersist {
fn checkpoint(&self, _: u32) -> crate::Result<()> {
Ok(())
}
fn load(&self) -> crate::Result<u32> {
Ok(self.0)
}
}
let reg = bootstrap_registry(&ReplayPersist(decoded.hi)).unwrap();
assert_eq!(reg.alloc_one().unwrap(), Surrogate::new(10_000));
}
}