use crate::{Error, Result, task::Cleanup};
use std::sync::{Arc, Mutex};
struct Registry {
open: bool,
cleanups: Vec<Cleanup>,
checks: Vec<crate::health::Check>,
}
#[derive(Clone)]
pub(crate) struct Resources(Arc<Mutex<Registry>>);
impl Resources {
pub(crate) fn new() -> Self {
Self(Arc::new(Mutex::new(Registry {
open: true,
cleanups: Vec::new(),
checks: Vec::new(),
})))
}
pub(crate) fn register(
&self,
name: String,
factory: crate::task::CleanupFactory,
) -> Result<()> {
let mut registry = self.0.lock().unwrap_or_else(|error| error.into_inner());
if !registry.open {
return Err(Error::Registration("managed registration is closed".into()));
}
if name.trim().is_empty() || name.len() > 128 || registry.cleanups.len() >= 64 {
return Err(Error::Registration(
"managed cleanup requires a nonempty name up to 128 bytes and at most 64 resources"
.into(),
));
}
let name = format!("managed:{name}");
if registry.cleanups.iter().any(|cleanup| cleanup.name == name) {
return Err(Error::Registration(
"managed cleanup names must be unique".into(),
));
}
registry.cleanups.push(Cleanup { name, factory });
Ok(())
}
pub(crate) fn readiness(&self, check: crate::health::Check) -> Result<()> {
check.validate()?;
let mut registry = self.0.lock().unwrap_or_else(|error| error.into_inner());
if !registry.open {
return Err(Error::Registration("managed registration is closed".into()));
}
if registry.checks.len() >= crate::health::MAX_CHECKS
|| registry
.checks
.iter()
.any(|existing| existing.name == check.name)
{
return Err(Error::Registration(
"managed readiness requires unique names and at most 64 checks".into(),
));
}
registry.checks.push(check);
Ok(())
}
pub(crate) fn take_checks(&self) -> Vec<crate::health::Check> {
let mut registry = self.0.lock().unwrap_or_else(|error| error.into_inner());
registry.open = false;
std::mem::take(&mut registry.checks)
}
pub(crate) fn seal(&self) {
self.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.open = false;
}
pub(crate) fn take(&self) -> Vec<Cleanup> {
let mut registry = self.0.lock().unwrap_or_else(|error| error.into_inner());
registry.open = false;
std::mem::take(&mut registry.cleanups)
}
}
#[cfg(test)]
#[path = "resources_test.rs"]
mod resources_test;