use crate::halt::{Halt, Stop};
#[derive(Clone)]
pub struct Apoptosis {
enabled: bool,
halt: Halt,
}
impl Apoptosis {
pub(crate) fn new(enabled: bool, halt: Halt) -> Self {
Self { enabled, halt }
}
pub fn is_enabled(&self) -> bool {
self.enabled
}
pub fn report(&self, reason: impl Into<String>) {
let reason = reason.into();
if !self.enabled {
tracing::warn!(
reason,
"a module reported an unrecoverable memory shortage, but the protection is off \
in the configuration"
);
return;
}
if self.halt.stop(Stop::Apoptosis(reason)) {
tracing::error!("apoptosis is triggered by a module report");
}
}
}
#[cfg(test)]
mod tests {
use crate::apoptosis::Apoptosis;
use crate::halt::{Halt, Stop};
#[tokio::test]
async fn report_stops_the_instance_with_the_reason() {
let halt = Halt::new();
Apoptosis::new(true, halt.clone()).report("the cache cannot grow");
assert_eq!(
halt.wait().await,
Stop::Apoptosis("the cache cannot grow".to_owned())
);
}
#[tokio::test]
async fn first_report_wins() {
let halt = Halt::new();
let apoptosis = Apoptosis::new(true, halt.clone());
apoptosis.report("first");
apoptosis.report("second");
assert_eq!(halt.wait().await, Stop::Apoptosis("first".to_owned()));
}
#[tokio::test]
async fn report_is_ignored_when_protection_is_off() {
let halt = Halt::new();
Apoptosis::new(false, halt.clone()).report("ignored");
assert_eq!(halt.get(), None);
}
}