agentmux_srv/server/remote_ops/
upgrade_watch.rs1use std::collections::HashSet;
23use std::sync::{LazyLock, Mutex};
24use std::time::Duration;
25
26use serde_json::{json, Value};
27
28use super::op::{OpStatus, RemoteOpResult};
29use super::send;
30use crate::server::AppState;
31
32const POLL_YOUNG: Duration = Duration::from_secs(20);
34const POLL_OLD: Duration = Duration::from_secs(300);
36const YOUNG_FOR: Duration = Duration::from_secs(15 * 60);
37const GIVE_UP_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
39const MAX_WATCHES: usize = 32;
41
42const READ_REASON: &str = "read how my upgrade request ended, to tell the agent that asked";
43
44#[derive(Debug, Clone, PartialEq, Eq)]
46pub(super) enum Ended {
47 Denied,
49 Vetoed,
51 Cancelled,
53 Expired,
55 Failed,
57 NotDownloaded,
59 NotConfirmed { why: String, at_ms: u64 },
61 Restarted,
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub(super) enum Phase {
68 Open,
70 Ran,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub(super) enum Step {
77 Wait(Phase),
78 CheckVersion,
81 End(Ended),
82}
83
84pub(super) fn read_status(phase: Phase, answer: &RemoteOpResult, version: &str) -> Step {
86 if answer.status != OpStatus::Done {
87 return Step::CheckVersion;
90 }
91 let r = &answer.result;
92 match r.get("status").and_then(Value::as_str).unwrap_or_default() {
93 "asked" | "pending" | "running" => Step::Wait(Phase::Open),
94 "denied" => Step::End(Ended::Denied),
95 "vetoed" => Step::End(Ended::Vetoed),
96 "cancelled" => Step::End(Ended::Cancelled),
97 "expired" => Step::End(Ended::Expired),
98 "failed" => Step::End(Ended::Failed),
99 "done" => {
100 let restart = &r["restart"];
101 let this_release = restart["version"].as_str() == Some(version);
102 match (restart["state"].as_str(), restart["not_confirmed"].as_str(), restart["not_confirmed_at"].as_u64()) {
103 (Some("ready"), Some(why), Some(at_ms)) if this_release => Step::End(Ended::NotConfirmed { why: why.to_string(), at_ms }),
104 (Some("failed"), _, _) if this_release => Step::End(Ended::NotDownloaded),
105 _ => Step::Wait(Phase::Ran),
106 }
107 }
108 _ => Step::Wait(phase),
109 }
110}
111
112pub(super) fn read_version(answer: &RemoteOpResult, version: &str) -> bool {
114 answer.status == OpStatus::Done && answer.result["version"].as_str() == Some(version)
115}
116
117fn clock(ms: u64) -> String {
119 chrono::DateTime::from_timestamp_millis(ms as i64).map_or_else(|| "an unknown time".into(), |t| t.format("%H:%M UTC").to_string())
120}
121
122fn why_words(why: &str) -> &'static str {
123 match why {
124 "no" => "the person answered No",
125 "timed_out" => "nobody answered the prompt before it closed itself",
126 "too_late" => "an answer came after the prompt had lapsed",
127 "unanswered" => "the launcher did not restart AgentMux in time",
128 _ => "the restart was declined",
129 }
130}
131
132pub(super) fn note_for(host: &str, version: &str, ended: &Ended, seen_ms: u64) -> String {
135 use crate::backend::reactive::sanitize::quote_in_system_note as q;
136 let (host, version) = (q(host), q(version));
137 let at = clock(seen_ms);
138 match ended {
139 Ended::Denied => format!("[AgentMux] Your request to upgrade {host} to {version} was denied (seen at {at}). Nothing was installed."),
140 Ended::Vetoed => format!("[AgentMux] The person at {host} stopped your request to upgrade it to {version} (seen at {at}). Nothing was installed."),
141 Ended::Cancelled => format!("[AgentMux] Your request to upgrade {host} to {version} was withdrawn (seen at {at})."),
142 Ended::Expired => format!("[AgentMux] Nobody decided your request to upgrade {host} to {version} in time (seen at {at}). Nothing was installed."),
143 Ended::Failed => format!("[AgentMux] Your request to upgrade {host} to {version} could not go ahead (seen at {at}). Read it with App upgrade, host {host}, for the reason."),
144 Ended::NotDownloaded => format!("[AgentMux] {host} could not download or verify {version} (seen at {at}), so it was not installed. Ask again if it is still wanted."),
145 Ended::NotConfirmed { why, at_ms } => format!(
146 "[AgentMux] The upgrade of {host} to {version} did not happen: the restart did not go ahead at {}: {}. The release is downloaded and waiting there. Ask again if it is still wanted.",
147 clock(*at_ms),
148 why_words(why)
149 ),
150 Ended::Restarted => format!("[AgentMux] {host} restarted and now runs {version} (seen at {at})."),
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Hash)]
156pub(super) struct Watch {
157 pub slug: String,
159 pub uid: String,
161 pub host: String,
164 pub id: String,
165 pub version: String,
166}
167
168static WATCHING: LazyLock<Mutex<HashSet<(String, String, String)>>> = LazyLock::new(Default::default);
169
170fn key(w: &Watch) -> (String, String, String) {
171 (w.uid.clone(), w.host.to_ascii_lowercase(), w.id.clone())
172}
173
174fn register_in(set: &mut HashSet<(String, String, String)>, w: &Watch, max: usize) -> bool {
176 if set.len() >= max {
177 return false;
178 }
179 set.insert(key(w))
180}
181
182fn register(w: &Watch) -> bool {
183 register_in(&mut WATCHING.lock().unwrap_or_else(|e| e.into_inner()), w, MAX_WATCHES)
184}
185
186fn unregister(w: &Watch) {
187 WATCHING.lock().unwrap_or_else(|e| e.into_inner()).remove(&key(w));
188}
189
190pub(super) fn watch_for(slug: &str, uid: &str, host: &str, params: &Value, answer: &RemoteOpResult) -> Option<Watch> {
193 if params.get("status").is_some() || answer.status != OpStatus::Done {
194 return None;
195 }
196 let r = &answer.result;
197 if r["status"].as_str() != Some("requested") {
198 return None;
199 }
200 let (id, version) = (r["id"].as_str()?.trim(), r["version"].as_str()?.trim());
201 if id.is_empty() || version.is_empty() {
202 return None;
203 }
204 Some(Watch { slug: slug.to_string(), uid: uid.to_string(), host: host.trim().to_string(), id: id.to_string(), version: version.to_string() })
205}
206
207pub(super) fn note_asked(state: &AppState, slug: &str, uid: &str, host: &str, params: &Value, answer: &RemoteOpResult) {
209 let Some(w) = watch_for(slug, uid, host, params, answer) else { return };
210 if !register(&w) {
211 return;
212 }
213 tracing::info!(agent = %w.slug, host = %w.host, request = %w.id, "upgrade: following a request on another machine to tell its agent how it ends");
214 let state = state.clone();
215 tokio::spawn(async move {
216 run(&state, &w).await;
217 unregister(&w);
218 });
219}
220
221fn tell(w: &Watch, note: &str) -> bool {
223 crate::sagas::sensitive_window::tell_one(&w.uid, note)
224}
225
226async fn run(state: &AppState, w: &Watch) {
227 let began = tokio::time::Instant::now();
228 let mut phase = Phase::Open;
229 let mut ended: Option<Ended> = None;
230 loop {
231 let waited = began.elapsed();
232 if waited >= GIVE_UP_AFTER {
233 tracing::info!(agent = %w.slug, host = %w.host, request = %w.id, "upgrade: gave up telling the agent how its request on another machine ended");
234 return;
235 }
236 tokio::time::sleep(if waited < YOUNG_FOR { POLL_YOUNG } else { POLL_OLD }).await;
237 if ended.is_none() {
238 let answer = send::call(state, &w.slug, &w.host, "app.upgrade", json!({ "status": w.id }), READ_REASON).await;
239 match read_status(phase, &answer, &w.version) {
240 Step::Wait(next) => phase = next,
241 Step::End(e) => ended = Some(e),
242 Step::CheckVersion => {
243 let version = send::call(state, &w.slug, &w.host, "app.version", json!({}), READ_REASON).await;
244 if read_version(&version, &w.version) {
245 ended = Some(Ended::Restarted);
246 }
247 }
248 }
249 }
250 if let Some(e) = &ended {
251 if tell(w, ¬e_for(&w.host, &w.version, e, agentmux_common::time::now_ms_u64())) {
252 return;
253 }
254 }
255 }
256}
257
258#[cfg(test)]
259#[path = "upgrade_watch_tests.rs"]
260mod tests;