Skip to main content

soma_provider_adapters/python/supervisor/
cancellation.rs

1use std::{sync::atomic::Ordering, time::Duration};
2
3use super::{PythonWorkerSupervisor, terminate_process_tree};
4
5impl PythonWorkerSupervisor {
6    /// Cooperatively marks the active invocation cancelled, then terminates
7    /// its complete process tree after a short grace period. The next
8    /// invocation starts a fresh worker.
9    pub fn cancel_active(&self) -> bool {
10        self.cancel_active_with(terminate_process_tree)
11    }
12
13    pub(super) fn cancel_active_with(
14        &self,
15        terminator: impl FnOnce(Option<u32>) -> bool + Send + 'static,
16    ) -> bool {
17        if !self.busy.load(Ordering::Acquire) {
18            return false;
19        }
20        let pid = self.active_pid.load(Ordering::Acquire);
21        if pid == 0 {
22            return false;
23        }
24        self.host.cancel_invocation();
25        self.cancel_epoch.fetch_add(1, Ordering::AcqRel);
26        self.discard_worker.store(true, Ordering::Release);
27        std::thread::spawn(move || {
28            std::thread::sleep(Duration::from_millis(100));
29            let _ = terminator(Some(pid));
30        });
31        true
32    }
33}