1use std::sync::Arc;
17use std::time::Duration;
18
19use axum::extract::State;
20use axum::http::StatusCode;
21use axum::response::{IntoResponse, Json};
22use serde_json::json;
23
24use super::app_api::fleet::shared_channel_for;
25use super::AppState;
26use crate::backend::jobs::remote::RemoteStop;
27use crate::backend::jobs::RunLedger;
28use agentmux_common::AUTH_KEY_HEADER;
29
30pub(crate) const STOP_RUN_PATH: &str = "/agentmux/jobs/stop-run";
32
33const ASK_TIMEOUT: Duration = Duration::from_secs(10);
35
36type Resolve = Arc<dyn Fn(&str) -> Option<(String, String)> + Send + Sync>;
38
39fn registry_resolver(state: &AppState) -> Resolve {
41 let state = state.clone();
42 Arc::new(move |block_id: &str| shared_channel_for(&state, block_id).map(|e| (e.local_url, e.auth_key)))
43}
44
45async fn forward(http: &reqwest::Client, resolve: &Resolve, stop: &RemoteStop) -> Result<(), String> {
47 let (url, auth_key) = resolve(&stop.block_id)
48 .ok_or_else(|| "the AgentMux that follows this run is not listed on this computer".to_string())?;
49 post_stop(http, &url, &auth_key, stop).await
50}
51
52async fn post_stop(http: &reqwest::Client, url: &str, auth_key: &str, stop: &RemoteStop) -> Result<(), String> {
54 let mut req = http
55 .post(format!("{url}{STOP_RUN_PATH}"))
56 .timeout(ASK_TIMEOUT)
57 .json(&json!({
58 "run_id": stop.run_id,
59 "block_id": stop.block_id,
60 "from_channel": stop.from_channel,
61 }));
62 if !auth_key.is_empty() {
63 req = req.header(AUTH_KEY_HEADER, auth_key);
64 }
65 let resp = req.send().await.map_err(|e| format!("could not reach the AgentMux that follows this run: {e}"))?;
66 match resp.status() {
67 s if s.is_success() => {}
68 StatusCode::NOT_FOUND => return Err("the AgentMux that follows this run is too old to take a stop".to_string()),
69 s => return Err(format!("the AgentMux that follows this run answered HTTP {s}")),
70 }
71 let body: serde_json::Value = resp.json().await.map_err(|e| format!("unreadable answer from the AgentMux that follows this run: {e}"))?;
72 if body["success"].as_bool() == Some(true) {
73 Ok(())
74 } else {
75 Err(body["error"].as_str().unwrap_or("the AgentMux that follows this run refused the stop").to_string())
76 }
77}
78
79pub(crate) fn install(state: &AppState, ledger: &Arc<RunLedger>) {
81 install_with(state.http_client.clone(), registry_resolver(state), ledger);
82}
83
84fn install_with(http: reqwest::Client, resolve: Resolve, ledger: &Arc<RunLedger>) {
86 let weak = Arc::downgrade(ledger);
87 let Ok(rt) = tokio::runtime::Handle::try_current() else { return };
88 ledger.install_remote_stop(Arc::new(move |stop: RemoteStop| {
89 let (http, resolve, weak) = (http.clone(), resolve.clone(), weak.clone());
90 rt.spawn(async move {
91 let outcome = forward(&http, &resolve, &stop).await;
92 let Some(ledger) = weak.upgrade() else { return };
93 let _ = tokio::task::spawn_blocking(move || match outcome {
94 Ok(()) => ledger.remote_stop_done(&stop.run_id),
95 Err(e) => ledger.remote_stop_failed(&stop.run_id, &e),
96 })
97 .await;
98 });
99 }));
100}
101
102#[derive(serde::Deserialize)]
103pub(crate) struct StopRunRequest {
104 run_id: String,
105 block_id: String,
106 from_channel: String,
109}
110
111pub(crate) async fn handle_jobs_stop_run(
117 State(state): State<AppState>,
118 caller: Option<axum::Extension<super::caller::Caller>>,
119 Json(req): Json<StopRunRequest>,
120) -> impl IntoResponse {
121 let refuse = |status: StatusCode, error: &str| (status, Json(json!({ "success": false, "error": error }))).into_response();
122 if caller.as_deref().and_then(super::caller::Caller::uid).is_some() {
124 return refuse(StatusCode::FORBIDDEN, "FORBIDDEN: only another AgentMux asks this");
125 }
126 let Some(ledger) = state.cron_scheduler.runs().cloned() else {
127 return refuse(StatusCode::OK, "the run ledger isn't ready");
128 };
129 let outcome = tokio::task::spawn_blocking(move || {
130 ledger.stop_followed_here(&req.run_id, &req.block_id, &req.from_channel)
131 })
132 .await
133 .unwrap_or_else(|e| Err(e.to_string()));
134 match outcome {
135 Ok(closed) => (StatusCode::OK, Json(json!({ "success": true, "closed": closed }))).into_response(),
136 Err(e) => refuse(StatusCode::OK, &e),
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143 use crate::server::tests::test_state;
144
145 fn stop() -> RemoteStop {
146 RemoteStop {
147 run_id: "r1".into(),
148 block_id: "b1".into(),
149 from_channel: "chan-a".into(),
150 infra: "timeout".into(),
151 reason: "timeout".into(),
152 summary: "stopped after 5 minutes (timeout_minutes)".into(),
153 }
154 }
155
156 async fn peer(status: StatusCode, body: &'static str) -> (String, Arc<std::sync::Mutex<Vec<(Option<String>, serde_json::Value)>>>, tokio_util::sync::DropGuard) {
158 let seen: Arc<std::sync::Mutex<Vec<(Option<String>, serde_json::Value)>>> = Arc::default();
159 let sink = seen.clone();
160 let app = axum::Router::new().route(
161 STOP_RUN_PATH,
162 axum::routing::post(move |headers: axum::http::HeaderMap, Json(req): Json<serde_json::Value>| {
163 let sink = sink.clone();
164 async move {
165 let key = headers.get(AUTH_KEY_HEADER).and_then(|v| v.to_str().ok()).map(str::to_string);
166 sink.lock().unwrap().push((key, req));
167 (status, [(axum::http::header::CONTENT_TYPE, "application/json")], body)
168 }
169 }),
170 );
171 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
172 let addr = listener.local_addr().unwrap();
173 let token = tokio_util::sync::CancellationToken::new();
174 let child = token.clone();
175 tokio::spawn(async move {
176 let _ = axum::serve(listener, app).with_graceful_shutdown(async move { child.cancelled().await }).await;
177 });
178 (format!("http://{addr}"), seen, token.drop_guard())
179 }
180
181 #[tokio::test]
182 async fn the_ask_carries_the_run_the_pane_and_the_stop_with_the_peers_key() {
183 let (url, seen, _guard) = peer(StatusCode::OK, r#"{"success":true,"closed":true}"#).await;
184 assert_eq!(post_stop(&reqwest::Client::new(), &url, "k-b", &stop()).await, Ok(()));
185 let seen = seen.lock().unwrap();
186 assert_eq!(seen[0].0.as_deref(), Some("k-b"));
187 assert_eq!(seen[0].1, json!({"run_id": "r1", "block_id": "b1", "from_channel": "chan-a"}));
189 }
190
191 #[test]
194 fn the_route_is_not_open_to_containers() {
195 assert!(!crate::backend::container::credential::container_route_allowed(STOP_RUN_PATH, crate::server::route_table::serves));
196 }
197
198 #[tokio::test]
199 async fn what_the_peer_says_is_the_outcome() {
200 let http = reqwest::Client::new();
201 let (url, _, _g1) = peer(StatusCode::OK, r#"{"success":false,"error":"this AgentMux does not follow that run"}"#).await;
202 assert_eq!(post_stop(&http, &url, "", &stop()).await, Err("this AgentMux does not follow that run".to_string()));
203 let (url, _, _g2) = peer(StatusCode::NOT_FOUND, "").await;
204 assert!(post_stop(&http, &url, "", &stop()).await.unwrap_err().contains("too old"));
205 let (url, _, _g3) = peer(StatusCode::INTERNAL_SERVER_ERROR, "").await;
206 assert!(post_stop(&http, &url, "", &stop()).await.unwrap_err().contains("500"));
207 let (url, _, _g4) = peer(StatusCode::OK, "not json").await;
208 assert!(post_stop(&http, &url, "", &stop()).await.unwrap_err().contains("unreadable"));
209 assert!(post_stop(&http, "http://127.0.0.1:9", "", &stop()).await.unwrap_err().contains("could not reach"));
211 }
212
213 #[tokio::test(flavor = "multi_thread")]
217 async fn a_timeout_on_the_firing_side_interrupts_the_pane_of_the_other_instance_over_http() {
218 use crate::backend::cron::test_job;
219 use crate::backend::jobs::{Begin, BY_SCHEDULER, TRIGGER_SCHEDULE};
220 use crate::backend::storage::job_runs::{infra, reason, state as run_state};
221 use crate::backend::storage::store::Store;
222
223 let dir = tempfile::tempdir().unwrap();
224 let store = Arc::new(Store::open_identity_store(&dir.path().join("identity-store.db")).unwrap());
225
226 let state_b = test_state();
228 let ledger_b = RunLedger::new_in(store.clone(), Some(state_b.mstore.clone()), state_b.broker.clone(), "chan-b");
229 let interrupted: Arc<std::sync::Mutex<Vec<String>>> = Arc::default();
230 let sink = interrupted.clone();
231 ledger_b.install_interrupt(Arc::new(move |block: &str| sink.lock().unwrap().push(block.to_string())));
232 state_b.cron_scheduler.install_runs(ledger_b.clone());
233 let app = axum::Router::new().route(STOP_RUN_PATH, axum::routing::post(handle_jobs_stop_run)).with_state(state_b);
234 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
235 let url = format!("http://{}", listener.local_addr().unwrap());
236 let token = tokio_util::sync::CancellationToken::new();
237 let child = token.clone();
238 tokio::spawn(async move {
239 let _ = axum::serve(listener, app).with_graceful_shutdown(async move { child.cancelled().await }).await;
240 });
241 let _guard = token.drop_guard();
242
243 let state_a = test_state();
245 let ledger_a = RunLedger::new_in(store.clone(), Some(state_a.mstore.clone()), state_a.broker.clone(), "chan-a");
246 let looked_up: Arc<std::sync::Mutex<Vec<String>>> = Arc::default();
247 let seen = looked_up.clone();
248 let resolve: Resolve = Arc::new(move |block: &str| {
249 seen.lock().unwrap().push(block.to_string());
250 Some((url.clone(), "k-b".to_string()))
251 });
252 install_with(reqwest::Client::new(), resolve, &ledger_a);
253
254 let job = test_job("j-live", "check the build", "AgentY", "uid-y", "uid-creator");
256 let Begin::Run(run_id) = ledger_a.begin_cron(&job, TRIGGER_SCHEDULE, Some(1), BY_SCHEDULER) else { panic!("no run") };
257 assert!(ledger_b.follow_forwarded(&run_id, "b-remote", agentmux_common::time::now_ms()));
258 let run = store.job_run_get(&run_id).unwrap().unwrap();
259 assert_eq!(run.state, run_state::RUNNING);
260
261 assert!(!ledger_a.stop_run(&run, infra::TIMEOUT, reason::TIMEOUT, "stopped after 1 minutes (timeout_minutes)"));
263 let mut closed = None;
264 for _ in 0..200 {
265 let r = store.job_run_get(&run_id).unwrap().unwrap();
266 if r.state == run_state::FINISHED {
267 closed = Some(r);
268 break;
269 }
270 tokio::time::sleep(Duration::from_millis(25)).await;
271 }
272 let r = closed.expect("the run never closed");
273 assert_eq!((r.infra.as_str(), r.reason.as_str()), (infra::TIMEOUT, reason::TIMEOUT));
274 assert_eq!(r.summary, "stopped after 1 minutes (timeout_minutes)");
275 assert_eq!(*interrupted.lock().unwrap(), ["b-remote"], "the pane on B was interrupted once");
276 assert_eq!(*looked_up.lock().unwrap(), ["b-remote"]);
277 assert!(r.links.get("stop_error").is_none(), "{:?}", r.links);
278
279 let ledger_c = RunLedger::new_in(store, None, state_a.broker.clone(), "chan-c");
281 assert!(ledger_c.stop_followed_here(&run_id, "b-remote", "chan-c").is_err());
282 assert_eq!(interrupted.lock().unwrap().len(), 1);
283 }
284
285 fn request(run_id: &str) -> Json<StopRunRequest> {
286 Json(StopRunRequest {
287 run_id: run_id.into(),
288 block_id: "b1".into(),
289 from_channel: "chan-a".into(),
290 })
291 }
292
293 async fn answer(response: impl IntoResponse) -> (StatusCode, serde_json::Value) {
294 let response = response.into_response();
295 let status = response.status();
296 let bytes = axum::body::to_bytes(response.into_body(), 1 << 20).await.unwrap();
297 (status, serde_json::from_slice(&bytes).unwrap())
298 }
299
300 #[tokio::test]
301 async fn the_route_answers_for_a_run_it_does_not_follow() {
302 let state = test_state();
303 let (status, body) = answer(handle_jobs_stop_run(State(state.clone()), None, request("r1")).await).await;
305 assert_eq!((status, body["success"].as_bool()), (StatusCode::OK, Some(false)));
306 assert!(body["error"].as_str().unwrap().contains("isn't ready"));
307 let ledger = RunLedger::new(state.work_store.clone(), None, state.broker.clone());
309 state.cron_scheduler.install_runs(ledger);
310 let (status, body) = answer(handle_jobs_stop_run(State(state), None, request("r1")).await).await;
311 assert_eq!((status, body["success"].as_bool(), body["error"].as_str()), (StatusCode::OK, Some(false), Some("no such run")));
312 }
313}