agentmux_srv_core/backend/
teardown_hooks.rs1use std::sync::{Arc, OnceLock};
12
13use crate::backend::blockcontroller::Controller;
14
15pub trait TeardownHooks: Send + Sync {
17 fn stop_now(&self, block_id: &str, graceful: bool) -> Result<(), String>;
20
21 fn replace_now(&self, ctrl: &dyn Controller) -> Result<(), String>;
23
24 fn discard(&self, block_id: &str);
26}
27
28static HOOKS: OnceLock<Arc<dyn TeardownHooks>> = OnceLock::new();
29
30pub fn install(hooks: Arc<dyn TeardownHooks>) {
32 let _ = HOOKS.set(hooks);
33}
34
35pub(crate) fn hooks() -> Arc<dyn TeardownHooks> {
39 if let Some(h) = HOOKS.get() {
40 return h.clone();
41 }
42 #[cfg(any(test, feature = "test-support"))]
43 {
44 Arc::new(PlainEntries)
45 }
46 #[cfg(not(any(test, feature = "test-support")))]
47 {
48 Arc::new(NotReady)
49 }
50}
51
52struct NotReady;
53
54impl TeardownHooks for NotReady {
55 fn stop_now(&self, block_id: &str, _: bool) -> Result<(), String> {
56 Err(format!("NOT_RUNNING: AgentMux isn't ready to stop block {block_id} yet"))
57 }
58 fn replace_now(&self, _: &dyn Controller) -> Result<(), String> {
59 Err("AgentMux isn't ready to replace a controller yet".to_string())
60 }
61 fn discard(&self, _: &str) {}
62}
63
64#[cfg(any(test, feature = "test-support"))]
67struct PlainEntries;
68
69#[cfg(any(test, feature = "test-support"))]
70impl TeardownHooks for PlainEntries {
71 fn stop_now(&self, block_id: &str, _: bool) -> Result<(), String> {
72 Err(format!("NOT_RUNNING: no controller for block {block_id}"))
73 }
74 fn replace_now(&self, ctrl: &dyn Controller) -> Result<(), String> {
75 ctrl.stop_for_replace(crate::backend::blockcontroller::STATUS_DONE)
76 }
77 fn discard(&self, _: &str) {}
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn a_lost_registration_stops_and_drops_nothing_and_says_so() {
86 let not_ready: &dyn TeardownHooks = &NotReady;
87 let err = not_ready.stop_now("blk-hook", true).unwrap_err();
88 assert!(err.starts_with("NOT_RUNNING"), "{err}");
89 not_ready.discard("blk-hook");
90 }
91
92 #[test]
93 fn under_test_plain_entries_stand_in_until_something_registers() {
94 let err = hooks().stop_now("no-such-block-hook", false).unwrap_err();
95 assert!(err.starts_with("NOT_RUNNING: no controller for block no-such-block-hook"), "{err}");
96 hooks().discard("no-such-block-hook");
97 }
98}