Skip to main content

subc_daemon/supervise/
roster.rs

1use super::*;
2
3/// Narrow process-liveness signal published by supervisors and consumed by passive liveness polls.
4pub trait ModuleProcessLiveness: Send + Sync {
5    fn process_live(&self, module_id: &str) -> Option<bool>;
6
7    /// Whether the supervisor is replacing this module's process right now: an
8    /// operator restart or reload, a health restart, or a crash respawn whose
9    /// backoff is running. A module in that state is not live, but a consumer
10    /// refused now should retry shortly rather than treat the target as gone.
11    /// Stopped, failed, and disabled modules are not replacing.
12    fn process_replacing(&self, _module_id: &str) -> bool {
13        false
14    }
15}
16
17/// Shared process-liveness registry keyed by supervised `module_id`.
18#[derive(Debug, Clone, Default)]
19pub struct SupervisorProcessLiveness {
20    snapshots: Arc<Mutex<HashMap<String, SharedSnapshot>>>,
21}
22
23impl SupervisorProcessLiveness {
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    pub(super) fn track(&self, module_id: String, snapshot: SharedSnapshot) {
29        let mut snapshots = self
30            .snapshots
31            .lock()
32            .unwrap_or_else(|poisoned| poisoned.into_inner());
33        snapshots.insert(module_id, snapshot);
34    }
35
36    pub(super) fn untrack_if_current(&self, module_id: &str, snapshot: &SharedSnapshot) {
37        let mut snapshots = self
38            .snapshots
39            .lock()
40            .unwrap_or_else(|poisoned| poisoned.into_inner());
41        let is_current = snapshots
42            .get(module_id)
43            .map(|tracked| Arc::ptr_eq(tracked, snapshot))
44            .unwrap_or(false);
45        if is_current {
46            snapshots.remove(module_id);
47        }
48    }
49}
50
51impl ModuleProcessLiveness for SupervisorProcessLiveness {
52    fn process_live(&self, module_id: &str) -> Option<bool> {
53        let snapshot = {
54            let snapshots = self
55                .snapshots
56                .lock()
57                .unwrap_or_else(|poisoned| poisoned.into_inner());
58            snapshots.get(module_id).cloned()
59        }?;
60        let snapshot = snapshot
61            .lock()
62            .unwrap_or_else(|poisoned| poisoned.into_inner());
63        Some(snapshot.state == ModuleState::Running && snapshot.process_alive)
64    }
65
66    fn process_replacing(&self, module_id: &str) -> bool {
67        let Some(snapshot) = self
68            .snapshots
69            .lock()
70            .unwrap_or_else(|poisoned| poisoned.into_inner())
71            .get(module_id)
72            .cloned()
73        else {
74            return false;
75        };
76        let snapshot = snapshot
77            .lock()
78            .unwrap_or_else(|poisoned| poisoned.into_inner());
79        snapshot.enabled
80            && match snapshot.state {
81                ModuleState::Restarting => true,
82                ModuleState::Draining => snapshot.draining_to_replace,
83                ModuleState::Starting
84                | ModuleState::Running
85                | ModuleState::Unresponsive
86                | ModuleState::Stopped
87                | ModuleState::Failed
88                | ModuleState::Disabled => false,
89            }
90    }
91}
92
93impl SupervisorHandle {
94    pub fn insert(&self, module: SupervisedModule) -> Option<SupervisedModule> {
95        // Normally already marked before the process was spawned; marking here
96        // too keeps `configured_ids` a superset of the roster for any caller
97        // that inserts a module directly.
98        self.mark_configured(module.module_id());
99        let mut modules = self
100            .modules
101            .lock()
102            .unwrap_or_else(|poisoned| poisoned.into_inner());
103        modules.insert(module.module_id().to_string(), module)
104    }
105
106    /// Record that the supervisor has taken on `module_id`. Called before the
107    /// module's first process is spawned, so that by the time that process can
108    /// register, [`Self::is_configured`] already answers true.
109    pub(super) fn mark_configured(&self, module_id: &str) {
110        self.update_configured_ids(|ids| {
111            ids.insert(module_id.to_string());
112        });
113    }
114
115    pub(super) fn publish_configured_ids(&self, ids: Option<&HashSet<String>>) {
116        let owner = self
117            .gate_runtime
118            .lock()
119            .unwrap_or_else(|p| p.into_inner())
120            .clone()
121            .and_then(|owner| owner.upgrade());
122        if let Some(owner) = owner {
123            owner.observe_supervisor_configured_ids(ids, Arc::downgrade(&self.configured_ids));
124        }
125    }
126
127    fn update_configured_ids(&self, update: impl FnOnce(&mut HashSet<String>)) {
128        match self.configured_ids.lock() {
129            Ok(mut ids) => {
130                update(&mut ids);
131                // Publish while this roster mutation is serialized, so an
132                // older snapshot can never overwrite a later configured id.
133                self.publish_configured_ids(Some(&ids));
134            }
135            Err(poisoned) => {
136                update(&mut poisoned.into_inner());
137                self.publish_configured_ids(None);
138            }
139        }
140    }
141
142    /// Undo [`Self::mark_configured`] for a module whose first spawn failed
143    /// before it was ever put on the roster. A module already on the roster
144    /// keeps its mark: only [`Self::retire`] takes a rostered module off.
145    pub(super) fn unmark_configured_unless_rostered(&self, module_id: &str) {
146        let modules = self
147            .modules
148            .lock()
149            .unwrap_or_else(|poisoned| poisoned.into_inner());
150        if !modules.contains_key(module_id) {
151            self.update_configured_ids(|ids| {
152                ids.remove(module_id);
153            });
154        }
155    }
156
157    /// Whether `module_id` is a module this daemon supervises: on the roster,
158    /// or about to be (its process is being spawned right now).
159    ///
160    /// This, not `get(..).is_some()`, is what "the owner is configured" means
161    /// for scopes: a supervised module's process can register and sync before
162    /// [`Self::get`] can return it, and in that window it is still a module
163    /// that will sync, not one that never will.
164    pub(crate) fn is_configured(&self, module_id: &str) -> bool {
165        self.configured_ids
166            .lock()
167            .unwrap_or_else(|poisoned| poisoned.into_inner())
168            .contains(module_id)
169    }
170
171    pub fn get(&self, module_id: &str) -> Option<SupervisedModule> {
172        let modules = self
173            .modules
174            .lock()
175            .unwrap_or_else(|poisoned| poisoned.into_inner());
176        modules.get(module_id).cloned()
177    }
178}
179
180impl SupervisorHandle {
181    pub fn list(&self) -> Vec<SupervisedModule> {
182        let modules = self
183            .modules
184            .lock()
185            .unwrap_or_else(|poisoned| poisoned.into_inner());
186        let mut modules = modules.values().cloned().collect::<Vec<_>>();
187        modules.sort_by(|left, right| left.module_id().cmp(right.module_id()));
188        modules
189    }
190
191    pub(crate) fn retire(&self, module_id: &str) -> Option<SupervisedModule> {
192        self.activity_images
193            .lock()
194            .unwrap_or_else(|p| p.into_inner())
195            .remove(module_id);
196        self.spawn_nonces
197            .lock()
198            .unwrap_or_else(|poisoned| poisoned.into_inner())
199            .remove(module_id);
200        self.close_swap(module_id);
201        let mut reserved_nonces = self
202            .reserved_nonces
203            .lock()
204            .unwrap_or_else(|poisoned| poisoned.into_inner());
205        if reserved_nonces.contains_key(module_id) {
206            // The old nonce must die with the removed process, but the exact-id
207            // gate remains until an operator explicitly releases it.
208            reserved_nonces.insert(module_id.to_string(), None);
209        }
210        drop(reserved_nonces);
211        self.reserved_prefix_owners
212            .lock()
213            .unwrap_or_else(|poisoned| poisoned.into_inner())
214            .retain(|_, owner| owner != module_id);
215        let removed = self
216            .modules
217            .lock()
218            .unwrap_or_else(|poisoned| poisoned.into_inner())
219            .remove(module_id);
220        self.update_configured_ids(|ids| {
221            ids.remove(module_id);
222        });
223        self.remove_program_binding_records(module_id);
224        removed
225    }
226
227    /// Remember a module removed by a non-preview rescan so route.open can
228    /// distinguish that intentional removal from an unknown id.
229    pub(crate) fn record_rescan_removal(&self, module_id: &str) {
230        self.removal_tombstones
231            .lock()
232            .unwrap_or_else(|poisoned| poisoned.into_inner())
233            .insert(module_id.to_string(), unix_ms_now());
234    }
235
236    /// Return how long ago a rescan removed this module in milliseconds.
237    pub(crate) fn removal_tombstone_age_ms(&self, module_id: &str) -> Option<u64> {
238        self.removal_tombstones
239            .lock()
240            .unwrap_or_else(|poisoned| poisoned.into_inner())
241            .get(module_id)
242            .copied()
243            .map(|removed_at_ms| unix_ms_now().saturating_sub(removed_at_ms))
244    }
245
246    /// Retire a reserved-id gate only after its module has left supervision.
247    ///
248    /// A retained gate has no live nonce (`None`), so releasing any other entry
249    /// would weaken a currently configured or otherwise active reservation.
250    pub(crate) fn release_retained_reserved_gate(&self, module_id: &str) -> bool {
251        if self.get(module_id).is_some() {
252            return false;
253        }
254        let mut reserved_nonces = self
255            .reserved_nonces
256            .lock()
257            .unwrap_or_else(|poisoned| poisoned.into_inner());
258        if !matches!(reserved_nonces.get(module_id), Some(None)) {
259            return false;
260        }
261        reserved_nonces.remove(module_id);
262        self.implicit_protocol_none
263            .lock()
264            .unwrap_or_else(|p| p.into_inner())
265            .remove(module_id);
266        true
267    }
268}