agentmux_srv_core/backend/update/
auto.rs1use std::sync::Arc;
24use std::time::Duration;
25
26use crate::backend::update::check::{self, AppUpdateStatus};
27use crate::backend::update::download;
28use crate::backend::wconfig::ConfigState;
29
30const FIRST_CHECK_AFTER: Duration = Duration::from_secs(60);
32const FIRST_CHECK_JITTER: Duration = Duration::from_secs(30);
34const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);
36const BACKOFF_START: Duration = Duration::from_secs(15 * 60);
38const BACKOFF_MAX: Duration = Duration::from_secs(24 * 60 * 60);
39const OFF_RECHECK: Duration = Duration::from_secs(5 * 60);
41const MAX_DOWNLOAD_TRIES: u32 = 3;
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub(crate) struct Switches {
48 pub check: bool,
49 pub download: bool,
50}
51
52pub(crate) fn switches(config: &ConfigState) -> Switches {
53 let s = config.get_settings();
54 Switches { check: s.update_auto.unwrap_or(true), download: s.update_auto_download.unwrap_or(true) }
55}
56
57pub fn spawn(config: Arc<ConfigState>, headless: bool) {
59 if std::env::var_os("AGENTMUX_NO_AUTO_UPDATE").is_some_and(|v| !v.is_empty()) {
60 tracing::info!("update: background check off (AGENTMUX_NO_AUTO_UPDATE)");
61 return;
62 }
63 if headless || std::env::var_os("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER").is_some() {
65 return;
66 }
67 let channel = crate::backend::reactive::registry::local_channel_id();
68 if check::is_dev_build(&channel) {
69 return;
70 }
71 tokio::spawn(async move { run(config).await });
72}
73
74async fn run(config: Arc<ConfigState>) {
75 tokio::time::sleep(FIRST_CHECK_AFTER + FIRST_CHECK_JITTER.mul_f64(fraction())).await;
76 let mut failures = 0u32;
77 let mut tries = DownloadTries::default();
78 loop {
79 let on = switches(&config);
80 if !on.check {
81 tokio::time::sleep(OFF_RECHECK).await;
82 continue;
83 }
84 let wait = match check::check_now().await {
85 Ok(status) => {
86 failures = 0;
87 if on.download {
88 maybe_download(&status, &mut tries);
89 }
90 wait_after_good_check(after_good_check(fraction()), check::limited_for())
91 }
92 Err(e) => {
93 failures = failures.saturating_add(1);
94 tracing::info!(error = %e, failures, "update: background check failed");
95 after_failure(failures)
96 }
97 };
98 tokio::time::sleep(wait).await;
99 }
100}
101
102fn maybe_download(status: &AppUpdateStatus, tries: &mut DownloadTries) {
105 if !wants_download(status, tries) {
106 return;
107 }
108 match download::start() {
109 Ok(_) => tracing::info!(latest = ?status.latest, "update: downloading in the background"),
110 Err(e) => tracing::info!(error = %e, "update: background download not started"),
111 }
112}
113
114#[derive(Debug, Default)]
117pub(crate) struct DownloadTries {
118 version: Option<String>,
119 started: u32,
120}
121
122pub(crate) fn wants_download(status: &AppUpdateStatus, tries: &mut DownloadTries) -> bool {
127 let Some(version) = status.latest.as_deref() else { return false };
128 if status.state != "available" || !status.can_download {
129 return false;
130 }
131 if !crate::backend::update::check::is_newer(version, &status.current) {
134 tracing::info!(
135 offered = %version,
136 running = %status.current,
137 "update: not downloading {version}; it isn't newer than {}",
138 status.current
139 );
140 return false;
141 }
142 if let Some(d) = &status.download {
143 if d.version == version && d.state != "failed" {
145 return false;
146 }
147 }
148 if tries.version.as_deref() != Some(version) {
149 *tries = DownloadTries { version: Some(version.to_string()), started: 0 };
150 }
151 if tries.started >= MAX_DOWNLOAD_TRIES {
152 return false;
153 }
154 tries.started += 1;
155 true
156}
157
158pub(crate) fn after_good_check(r: f64) -> Duration {
160 CHECK_EVERY.mul_f64(0.8 + 0.4 * r.clamp(0.0, 1.0))
161}
162
163const AFTER_LIMIT: Duration = Duration::from_secs(30);
165
166pub(crate) fn wait_after_good_check(base: Duration, limited_for: Option<Duration>) -> Duration {
169 limited_for.map_or(base, |left| base.min(left + AFTER_LIMIT))
170}
171
172pub(crate) fn after_failure(failures: u32) -> Duration {
175 let doublings = failures.saturating_sub(1).min(16);
176 BACKOFF_START.saturating_mul(1u32 << doublings).min(BACKOFF_MAX)
177}
178
179fn fraction() -> f64 {
182 let ms = agentmux_common::time::now_ms_u64();
183 let mixed = ms.wrapping_mul(2_654_435_761).wrapping_add(u64::from(std::process::id()));
184 (mixed % 1_000_000) as f64 / 1_000_000.0
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190 use crate::backend::update::check::DownloadStatus;
191
192 fn offered(latest: &str) -> AppUpdateStatus {
193 AppUpdateStatus {
194 state: "available".into(),
195 current: "0.60.1".into(),
196 latest: Some(latest.into()),
197 url: None,
198 notes: None,
199 published_at: None,
200 checked_ms: 1,
201 install: "windows-portable".into(),
202 asset: None,
203 can_download: true,
204 download_blocked: None,
205 download: None,
206 install_first: None,
207 rev: 0,
208 }
209 }
210
211 fn download_in(version: &str, state: &str) -> DownloadStatus {
212 DownloadStatus {
213 version: version.into(),
214 state: state.into(),
215 received: 0,
216 total: 0,
217 error: None,
218 folder: None,
219 installer: None,
220 waiting_for: 0,
221 waiting_on: Vec::new(),
222 stopping: Vec::new(),
223 not_confirmed_at: None,
224 not_confirmed: None,
225 }
226 }
227
228 #[test]
229 fn a_limit_shortens_the_wait_to_just_after_it_lifts_and_never_lengthens_it() {
230 let base = CHECK_EVERY;
231 assert_eq!(wait_after_good_check(base, None), base);
232 assert_eq!(wait_after_good_check(base, Some(Duration::from_secs(300))), Duration::from_secs(330));
233 assert_eq!(wait_after_good_check(base, Some(base * 2)), base);
235 }
236
237 #[test]
238 fn a_good_check_waits_about_six_hours() {
239 assert_eq!(after_good_check(0.5), CHECK_EVERY);
240 assert_eq!(after_good_check(0.0), CHECK_EVERY.mul_f64(0.8));
241 assert_eq!(after_good_check(1.0), CHECK_EVERY.mul_f64(1.2));
242 assert_eq!(after_good_check(7.0), CHECK_EVERY.mul_f64(1.2));
244 }
245
246 #[test]
247 fn a_failed_check_backs_off_to_a_day() {
248 assert_eq!(after_failure(1), Duration::from_secs(15 * 60));
249 assert_eq!(after_failure(2), Duration::from_secs(30 * 60));
250 assert_eq!(after_failure(3), Duration::from_secs(60 * 60));
251 assert_eq!(after_failure(8), BACKOFF_MAX);
252 assert_eq!(after_failure(u32::MAX), BACKOFF_MAX);
253 }
254
255 #[test]
256 fn a_newer_release_is_downloaded_once_it_can_be() {
257 let mut tries = DownloadTries::default();
258 assert!(wants_download(&offered("0.60.2"), &mut tries));
259 }
260
261 #[test]
262 fn nothing_is_downloaded_that_the_install_cannot_download() {
263 let mut tries = DownloadTries::default();
264 let mut store = offered("0.60.2");
265 store.can_download = false;
266 assert!(!wants_download(&store, &mut tries), "a Store install updates through the Store");
267 let mut current = offered("0.60.1");
268 current.state = "up-to-date".into();
269 assert!(!wants_download(¤t, &mut tries));
270 let mut unchecked = offered("0.60.2");
271 unchecked.latest = None;
272 assert!(!wants_download(&unchecked, &mut tries));
273 }
274
275 #[test]
276 fn an_older_or_equal_release_is_never_downloaded_by_itself() {
277 for latest in ["0.60.0", "0.60.1"] {
278 let mut tries = DownloadTries::default();
279 let s = offered(latest);
280 assert!(!wants_download(&s, &mut tries), "{latest} vs {}", s.current);
281 }
282 }
283
284 #[test]
285 fn a_download_under_way_or_staged_is_left_alone() {
286 for state in ["downloading", "unpacking", "ready", "waiting", "restarting"] {
287 let mut tries = DownloadTries::default();
288 let mut s = offered("0.60.2");
289 s.download = Some(download_in("0.60.2", state));
290 assert!(!wants_download(&s, &mut tries), "{state}");
291 }
292 }
293
294 #[test]
295 fn a_download_of_an_older_release_does_not_block_the_newer_one() {
296 let mut tries = DownloadTries::default();
297 let mut s = offered("0.60.3");
298 s.download = Some(download_in("0.60.2", "ready"));
299 assert!(wants_download(&s, &mut tries));
300 }
301
302 #[test]
303 fn a_failing_download_is_tried_three_times_then_left_to_the_click() {
304 let mut tries = DownloadTries::default();
305 let mut s = offered("0.60.2");
306 s.download = Some(download_in("0.60.2", "failed"));
307 for _ in 0..MAX_DOWNLOAD_TRIES {
308 assert!(wants_download(&s, &mut tries));
309 }
310 assert!(!wants_download(&s, &mut tries));
311 let mut newer = offered("0.60.3");
313 newer.download = Some(download_in("0.60.2", "failed"));
314 assert!(wants_download(&newer, &mut tries));
315 }
316}