use std::any::Any;
use std::sync::Mutex;
use crate::global::Locked;
pub(crate) struct ShutdownRegistry {
handles: Mutex<Vec<crate::rt::BlockingHandle>>,
threads: Mutex<Vec<std::thread::JoinHandle<()>>>,
}
impl ShutdownRegistry {
pub fn new() -> Self {
Self {
handles: Mutex::new(Vec::new()),
threads: Mutex::new(Vec::new()),
}
}
pub fn register(&self, handle: crate::rt::BlockingHandle) {
crate::sync::lock(&self.handles).push(handle);
}
pub fn register_thread(&self, handle: std::thread::JoinHandle<()>) {
crate::sync::lock(&self.threads).push(handle);
}
pub async fn join_all(&self) -> usize {
let handles = {
let mut guard = crate::sync::lock(&self.handles);
std::mem::take(&mut *guard)
};
let threads = {
let mut guard = crate::sync::lock(&self.threads);
std::mem::take(&mut *guard)
};
let count = handles.len() + threads.len();
if count > 0 {
log::info!(
"[ShutdownRegistry] Waiting for {} IPC thread(s) to finish...",
count
);
for handle in handles {
handle.await;
}
for thread in threads {
let _ = thread.join();
}
log::info!("[ShutdownRegistry] All IPC threads terminated.");
}
count
}
}
static IPC_CLEANUP_RESOURCES: Locked<Vec<Box<dyn Any + Send>>> = Locked::new();
pub fn register_ipc_cleanup(resource: Box<dyn Any + Send>) {
IPC_CLEANUP_RESOURCES.with(|resources| resources.push(resource));
}
pub fn clear_ipc_cleanup() {
let count = IPC_CLEANUP_RESOURCES.with(|resources| {
let count = resources.len();
resources.clear();
count
});
if count > 0 {
log::info!("[ice-rpc] dropped {count} registered IPC resource(s).");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_registry_join_returns_zero() {
let registry = ShutdownRegistry::new();
let count = pollster::block_on(registry.join_all());
assert_eq!(count, 0);
}
#[test]
fn register_and_join_single_handle() {
let registry = ShutdownRegistry::new();
let handle = crate::rt::spawn_blocking(|| {});
registry.register(handle);
let count = pollster::block_on(registry.join_all());
assert_eq!(count, 1);
}
#[test]
fn register_and_join_multiple_handles() {
let registry = ShutdownRegistry::new();
for _ in 0..3 {
let handle = crate::rt::spawn_blocking(|| {});
registry.register(handle);
}
let count = pollster::block_on(registry.join_all());
assert_eq!(count, 3);
}
#[test]
fn join_all_clears_registry() {
let registry = ShutdownRegistry::new();
let handle = crate::rt::spawn_blocking(|| {});
registry.register(handle);
pollster::block_on(registry.join_all());
let count = pollster::block_on(registry.join_all());
assert_eq!(count, 0);
}
#[test]
fn handles_terminate_before_join_completes() {
let registry = ShutdownRegistry::new();
let (tx, rx) = std::sync::mpsc::channel();
let handle = crate::rt::spawn_blocking(move || {
let _ = tx.send(());
});
registry.register(handle);
rx.recv().unwrap();
let count = pollster::block_on(registry.join_all());
assert_eq!(count, 1);
}
}