use core::{fmt::Display, str::FromStr};
use smol_bytes::Utf8Bytes;
use super::{
Registry, RegistryCounts, RegistryOptions, RegistryOverride, RootKey, RootState,
state::{RetireOrigin, Stamp},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct KeyDoesNotParse;
pub(crate) trait DynRegistry: Send + Sync {
fn state(&self, key: &str) -> RootState;
fn counts(&self) -> RegistryCounts;
fn options(&self) -> RegistryOptions;
fn apply_knobs(&self, over: &RegistryOverride);
fn recent(&self, limit: usize) -> Vec<(Utf8Bytes, RootState)>;
fn retire(&self, key: &str, origin: RetireOrigin) -> Result<RootState, KeyDoesNotParse>;
fn restore(&self, key: &str) -> Result<RootState, KeyDoesNotParse>;
fn reanalyze(&self, key: &str) -> Result<RootState, KeyDoesNotParse>;
}
impl<Root> DynRegistry for Registry<Root>
where
Root: RootKey + Display + FromStr,
{
fn state(&self, key: &str) -> RootState {
key
.parse::<Root>()
.map_or(RootState::Idle, |root| Registry::state(self, &root))
}
fn counts(&self) -> RegistryCounts {
Registry::counts(self)
}
fn options(&self) -> RegistryOptions {
Registry::options(self)
}
fn apply_knobs(&self, over: &RegistryOverride) {
Registry::apply_knobs(self, over);
}
fn recent(&self, limit: usize) -> Vec<(Utf8Bytes, RootState)> {
Registry::snapshot(self, limit)
.into_iter()
.map(|(root, state)| (Utf8Bytes::from(root.to_string()), state))
.collect()
}
fn retire(&self, key: &str, origin: RetireOrigin) -> Result<RootState, KeyDoesNotParse> {
let root = key.parse::<Root>().map_err(|_| KeyDoesNotParse)?;
let _advance = Registry::retire(self, &root, origin, Stamp::now());
Ok(Registry::state(self, &root))
}
fn restore(&self, key: &str) -> Result<RootState, KeyDoesNotParse> {
let root = key.parse::<Root>().map_err(|_| KeyDoesNotParse)?;
let _advance = Registry::restore(self, &root, Stamp::now());
Ok(Registry::state(self, &root))
}
fn reanalyze(&self, key: &str) -> Result<RootState, KeyDoesNotParse> {
let root = key.parse::<Root>().map_err(|_| KeyDoesNotParse)?;
let _advance = Registry::intake(self, &root, Stamp::now());
Ok(Registry::state(self, &root))
}
}
#[cfg(test)]
mod tests;