use once_cell::sync::Lazy;
use parking_lot::Mutex;
use regex::Regex;
use serde::Serialize;
use staged_builder::staged_builder;
use std::collections::btree_map;
use std::collections::hash_map;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
static TYPE_PATTERN: Lazy<Regex> = Lazy::new(|| Regex::new("^[A-Z_]+$").unwrap());
pub trait ReadinessCheck: 'static + Sync + Send {
fn type_(&self) -> &str;
fn result(&self) -> ReadinessCheckResult;
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[staged_builder]
pub struct ReadinessCheckResult {
successful: bool,
}
impl ReadinessCheckResult {
#[inline]
pub fn successful(&self) -> bool {
self.successful
}
}
pub struct ReadinessCheckRegistry {
checks: Mutex<HashMap<String, Arc<dyn ReadinessCheck>>>,
}
impl ReadinessCheckRegistry {
pub(crate) fn new() -> Self {
ReadinessCheckRegistry {
checks: Mutex::new(HashMap::new()),
}
}
pub fn register<T>(&self, check: T)
where
T: ReadinessCheck,
{
self.register_inner(Arc::new(check))
}
fn register_inner(&self, check: Arc<dyn ReadinessCheck>) {
let type_ = check.type_();
assert!(
TYPE_PATTERN.is_match(type_),
"{type_} must `SCREAMING_SNAKE_CASE",
);
match self.checks.lock().entry(type_.to_string()) {
hash_map::Entry::Occupied(_) => {
panic!("a check has already been registered for type {type_}")
}
hash_map::Entry::Vacant(e) => {
e.insert(check);
}
}
}
pub(crate) fn run_checks(&self) -> BTreeMap<String, ReadinessCheckMetadata> {
let mut results = BTreeMap::new();
let mut progress = true;
while progress {
progress = false;
let checks = self.checks.lock().clone();
for (type_, check) in checks {
if let btree_map::Entry::Vacant(e) = results.entry(type_.clone()) {
let result = check.result();
e.insert(ReadinessCheckMetadata {
r#type: type_,
successful: result.successful,
});
progress = true;
}
}
}
results
}
}
#[derive(Serialize)]
pub(crate) struct ReadinessCheckMetadata {
r#type: String,
pub(crate) successful: bool,
}