Skip to main content

agentmux_srv_core/backend/container/
reap.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! Stopping a provider-CLI install whose turn was cancelled.
4
5use std::sync::Arc;
6
7use tokio::sync::Mutex;
8
9use super::ContainerManager;
10
11/// Reaps the install running in `container_name` when dropped, unless
12/// [disarmed](Self::disarm). A stop drops the start-up future while the install
13/// is still running in the container; nothing else would end it.
14///
15/// The reap runs under the same per-container lock as an install. A turn that
16/// follows the stopped one therefore either reaps the orphan itself first and
17/// finishes its install before this runs (which then finds nothing), or waits
18/// for this: the reap never lands on the successor's install.
19pub(super) struct ReapOnDrop {
20    target: Option<(ContainerManager, String)>,
21}
22
23impl ReapOnDrop {
24    pub(super) fn new(cm: &ContainerManager, container_name: &str) -> Self {
25        Self { target: Some((cm.clone(), container_name.to_string())) }
26    }
27
28    pub(super) fn disarm(mut self) {
29        self.target = None;
30    }
31}
32
33impl Drop for ReapOnDrop {
34    fn drop(&mut self) {
35        let Some((cm, name)) = self.target.take() else { return };
36        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
37            runtime.spawn(async move {
38                let lock = {
39                    let mut locks = cm.inner.cli_locks.lock().await;
40                    locks.entry(name.clone()).or_insert_with(|| Arc::new(Mutex::new(()))).clone()
41                };
42                let held = lock.lock().await;
43                cm.reap_cli_install(&name).await;
44                drop(held);
45                let mut locks = cm.inner.cli_locks.lock().await;
46                if Arc::strong_count(&lock) <= 2 {
47                    locks.remove(&name);
48                }
49            });
50        }
51    }
52}