redup_bootstrap/
apoptosis.rs1use crate::halt::{Halt, Stop};
4
5#[derive(Clone)]
12pub struct Apoptosis {
13 enabled: bool,
14 halt: Halt,
15}
16
17impl Apoptosis {
18 pub(crate) fn new(enabled: bool, halt: Halt) -> Self {
19 Self { enabled, halt }
20 }
21
22 pub fn is_enabled(&self) -> bool {
24 self.enabled
25 }
26
27 pub fn report(&self, reason: impl Into<String>) {
29 let reason = reason.into();
30 if !self.enabled {
31 tracing::warn!(
32 reason,
33 "a module reported an unrecoverable memory shortage, but the protection is off \
34 in the configuration"
35 );
36 return;
37 }
38 if self.halt.stop(Stop::Apoptosis(reason)) {
39 tracing::error!("apoptosis is triggered by a module report");
40 }
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use crate::apoptosis::Apoptosis;
47 use crate::halt::{Halt, Stop};
48
49 #[tokio::test]
50 async fn report_stops_the_instance_with_the_reason() {
51 let halt = Halt::new();
52 Apoptosis::new(true, halt.clone()).report("the cache cannot grow");
53 assert_eq!(
54 halt.wait().await,
55 Stop::Apoptosis("the cache cannot grow".to_owned())
56 );
57 }
58
59 #[tokio::test]
60 async fn first_report_wins() {
61 let halt = Halt::new();
62 let apoptosis = Apoptosis::new(true, halt.clone());
63 apoptosis.report("first");
64 apoptosis.report("second");
65 assert_eq!(halt.wait().await, Stop::Apoptosis("first".to_owned()));
66 }
67
68 #[tokio::test]
69 async fn report_is_ignored_when_protection_is_off() {
70 let halt = Halt::new();
71 Apoptosis::new(false, halt.clone()).report("ignored");
72 assert_eq!(halt.get(), None);
73 }
74}