use std::sync::{Arc, PoisonError, RwLock};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct InfallibleCallFailure<'a> {
pub component: &'a str,
pub method: &'a str,
pub status: i32,
pub message: &'a str,
}
impl<'a> InfallibleCallFailure<'a> {
#[must_use]
pub fn new(component: &'a str, method: &'a str, status: i32, message: &'a str) -> Self {
Self {
component,
method,
status,
message,
}
}
}
type Hook = Arc<dyn Fn(&InfallibleCallFailure<'_>) + Send + Sync>;
static HOOK: RwLock<Option<Hook>> = RwLock::new(None);
pub fn set_infallible_failure_hook(hook: impl Fn(&InfallibleCallFailure<'_>) + Send + Sync + 'static) {
*HOOK.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(hook));
}
pub fn report_infallible_failure(failure: &InfallibleCallFailure<'_>) {
let hook = HOOK.read().unwrap_or_else(PoisonError::into_inner).clone();
match hook {
Some(hook) => hook(failure),
None => eprintln!(
"alef component `{}`: method `{}` failed with status {}: {}; returning its default value",
failure.component, failure.method, failure.status, failure.message
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[test]
fn the_hook_receives_each_failure() {
let seen = Arc::new(Mutex::new(Vec::new()));
{
let seen = Arc::clone(&seen);
set_infallible_failure_hook(move |failure| {
seen.lock().unwrap().push((
failure.component.to_owned(),
failure.method.to_owned(),
failure.status,
failure.message.to_owned(),
));
});
}
report_infallible_failure(&InfallibleCallFailure::new("demo", "name", 5, "broken"));
assert!(
seen.lock()
.unwrap()
.contains(&("demo".to_owned(), "name".to_owned(), 5, "broken".to_owned()))
);
}
}