| 1 | //! The startup update check: resolving a latest-release tag from the |
| 2 | //! configured source and turning it into a version hint. |
| 3 | //! |
| 4 | //! Moved verbatim out of `ui.rs`. |
| 5 | |
| 6 | use super::*; |
| 7 | |
| 8 | pub(crate) fn startup_version_check_source(config: &UpdateConfig) -> StartupVersionCheckSource { |
| 9 | if codewhale_release::autoupdate::resolve_mode(config.mode.as_deref(), config.check_for_updates) |
| 10 | .mode |
| 11 | == codewhale_release::autoupdate::UpdateMode::Off |
| 12 | { |
| 13 | return StartupVersionCheckSource::Disabled; |
| 14 | } |
| 15 | resolve_version_check_source(config, codewhale_release::suppression_reason()) |
| 16 | } |
| 17 | |
| 18 | /// Pure form of [`startup_version_check_source`]: the environment is read once |
| 19 | /// by the caller and passed in, so the decision itself is testable without |
| 20 | /// mutating process-global state (and so this crate's own CI run does not |
| 21 | /// change the answer). |
| 22 | pub(crate) fn resolve_version_check_source( |
| 23 | config: &UpdateConfig, |
| 24 | suppression: Option<codewhale_release::SuppressionReason>, |
| 25 | ) -> StartupVersionCheckSource { |
| 26 | if !config.check_for_updates { |
| 27 | return StartupVersionCheckSource::Disabled; |
| 28 | } |
| 29 | // CI runners and explicit opt-outs never reach the network: there is |
| 30 | // nobody at the terminal to read the notice, and an unexplained outbound |
| 31 | // request from a build agent is a support ticket waiting to happen. |
| 32 | if let Some(reason) = suppression { |
| 33 | tracing::debug!( |
| 34 | variable = reason.variable(), |
| 35 | "skipping startup update check" |
| 36 | ); |
| 37 | return StartupVersionCheckSource::Disabled; |
| 38 | } |
| 39 | if let Some(update_uri) = config.update_uri() { |
| 40 | return StartupVersionCheckSource::ConfiguredUrl(update_uri.to_string()); |
| 41 | } |
| 42 | StartupVersionCheckSource::ReleaseResolver |
| 43 | } |
| 44 | |
| 45 | /// Where the throttling cache for the startup check lives. |
| 46 | /// |
| 47 | /// `None` when the CodeWhale home cannot be resolved — the check still runs, |
| 48 | /// it just cannot be throttled, which is the right tradeoff for a homeless |
| 49 | /// install (rare, and better than never checking). |
| 50 | pub(crate) fn update_check_cache_path() -> Option<PathBuf> { |
| 51 | codewhale_config::codewhale_home() |
| 52 | .ok() |
| 53 | .map(|home| codewhale_release::check::cache_path_in(&home)) |
| 54 | } |
| 55 | |
| 56 | pub(crate) fn spawn_startup_version_check( |
| 57 | config: UpdateConfig, |
| 58 | ) -> Option<tokio::task::JoinHandle<Option<UpdateNotice>>> { |
| 59 | let source = startup_version_check_source(&config); |
| 60 | if source == StartupVersionCheckSource::Disabled { |
| 61 | return None; |
| 62 | } |
| 63 | |
| 64 | let current = env!("CARGO_PKG_VERSION").to_string(); |
| 65 | let cache_path = update_check_cache_path(); |
| 66 | let interval_hours = config.check_interval_hours; |
| 67 | let auto = codewhale_release::autoupdate::resolve_mode( |
| 68 | config.mode.as_deref(), |
| 69 | config.check_for_updates, |
| 70 | ) |
| 71 | .mode |
| 72 | == codewhale_release::autoupdate::UpdateMode::Auto; |
| 73 | Some(tokio::spawn(async move { |
| 74 | let mut notice = |
| 75 | cached_version_hint(source, ¤t, cache_path.as_deref(), interval_hours).await?; |
| 76 | if auto { |
| 77 | let latest = notice.latest.clone(); |
| 78 | notice.staged = tokio::task::spawn_blocking(move || { |
| 79 | staged_or_start_staging(&latest, interval_hours) |
| 80 | }) |
| 81 | .await |
| 82 | .ok() |
| 83 | .flatten(); |
| 84 | } |
| 85 | Some(notice) |
| 86 | })) |
| 87 | } |
| 88 | |
| 89 | fn staged_or_start_staging(latest: &str, interval_hours: u64) -> Option<bool> { |
| 90 | use codewhale_release::autoupdate; |
| 91 | let home = codewhale_config::codewhale_home().ok()?; |
| 92 | if let Some(staged) = autoupdate::load_staged(&home) |
| 93 | && staged.version == latest |
| 94 | { |
| 95 | return Some(staged.signed); |
| 96 | } |
| 97 | let exe = std::env::current_exe().ok()?; |
| 98 | if !codewhale_release::InstallMethod::detect(&exe).supports_self_update() |
| 99 | || !matches!( |
| 100 | exe.file_stem().and_then(|stem| stem.to_str()), |
| 101 | Some("codewhale" | "codew") |
| 102 | ) |
| 103 | { |
| 104 | return None; |
| 105 | } |
| 106 | let state = autoupdate::load_state(&home); |
| 107 | let retry_after = interval_hours.clamp(1, 24) * 3600; |
| 108 | if state.skip_version.as_deref() == Some(latest) |
| 109 | || (state.last_stage_version.as_deref() == Some(latest) |
| 110 | && codewhale_release::check::now_unix().saturating_sub(state.last_stage_attempt_unix) |
| 111 | < retry_after) |
| 112 | { |
| 113 | return None; |
| 114 | } |
| 115 | let mut command = std::process::Command::new(exe); |
| 116 | command |
| 117 | .args(["update", "--stage"]) |
| 118 | .stdin(std::process::Stdio::null()) |
| 119 | .stdout(std::process::Stdio::null()) |
| 120 | .stderr(std::process::Stdio::null()); |
| 121 | match command.spawn() { |
| 122 | Ok(mut child) => { |
| 123 | let latest = latest.to_string(); |
| 124 | std::thread::spawn(move || match child.wait() { |
| 125 | Ok(status) if status.success() => {} |
| 126 | Ok(status) => { |
| 127 | if autoupdate::load_state(&home).last_failure.is_none() { |
| 128 | let reason = format!("background update staging exited with {status}"); |
| 129 | tracing::warn!(%reason, version = %latest); |
| 130 | autoupdate::record_failure(&home, Some(reason)); |
| 131 | } |
| 132 | } |
| 133 | Err(error) => { |
| 134 | let reason = format!("could not wait for background update staging: {error}"); |
| 135 | tracing::warn!(%reason, version = %latest); |
| 136 | autoupdate::record_failure(&home, Some(reason)); |
| 137 | } |
| 138 | }); |
| 139 | } |
| 140 | Err(error) => { |
| 141 | let reason = format!("could not start background update staging: {error}"); |
| 142 | tracing::warn!(%reason, version = %latest); |
| 143 | autoupdate::record_failure(&home, Some(reason)); |
| 144 | } |
| 145 | } |
| 146 | None |
| 147 | } |
| 148 | |
| 149 | /// Resolve the update notice, reaching for the network at most once per |
| 150 | /// configured interval. |
| 151 | /// |
| 152 | /// The cache holds the *tag we last saw*, not a "checked recently" flag, so a |
| 153 | /// user who relaunches all afternoon still sees the notice every time while |
| 154 | /// GitHub is asked once. A cached `None` means "we asked, there was nothing" — |
| 155 | /// also a valid answer worth not re-asking for. |
| 156 | pub(crate) async fn cached_version_hint( |
| 157 | source: StartupVersionCheckSource, |
| 158 | current: &str, |
| 159 | cache_path: Option<&Path>, |
| 160 | interval_hours: u64, |
| 161 | ) -> Option<UpdateNotice> { |
| 162 | let now = codewhale_release::check::now_unix(); |
| 163 | if let Some(path) = cache_path |
| 164 | && let Some(entry) = codewhale_release::UpdateCheckCache::load(path) |
| 165 | && entry.is_fresh(now, interval_hours) |
| 166 | { |
| 167 | return entry |
| 168 | .latest_tag |
| 169 | .as_deref() |
| 170 | .and_then(|tag| version_hint_from_latest_tag(tag, current)); |
| 171 | } |
| 172 | |
| 173 | let latest_tag = latest_tag_from_startup_source(source).await; |
| 174 | |
| 175 | if let Some(path) = cache_path |
| 176 | && latest_tag.is_some() |
| 177 | && let Err(err) = codewhale_release::UpdateCheckCache::now(latest_tag.clone()).store(path) |
| 178 | { |
| 179 | tracing::debug!(error = %err, "failed to persist update-check cache"); |
| 180 | } |
| 181 | if latest_tag.is_none() |
| 182 | && interval_hours > 1 |
| 183 | && let Some(path) = cache_path |
| 184 | && let Some(previous) = codewhale_release::UpdateCheckCache::load(path) |
| 185 | { |
| 186 | let retry = codewhale_release::UpdateCheckCache { |
| 187 | checked_at_unix: now.saturating_sub(interval_hours.saturating_sub(1) * 3600), |
| 188 | latest_tag: previous.latest_tag.clone(), |
| 189 | }; |
| 190 | let _ = retry.store(path); |
| 191 | return previous |
| 192 | .latest_tag |
| 193 | .as_deref() |
| 194 | .and_then(|tag| version_hint_from_latest_tag(tag, current)); |
| 195 | } |
| 196 | |
| 197 | latest_tag |
| 198 | .as_deref() |
| 199 | .and_then(|tag| version_hint_from_latest_tag(tag, current)) |
| 200 | } |
| 201 | |
| 202 | /// The latest publishable release tag for this source, or `None` when the |
| 203 | /// lookup failed or the release is not one we would offer. |
| 204 | pub(crate) async fn latest_tag_from_startup_source( |
| 205 | source: StartupVersionCheckSource, |
| 206 | ) -> Option<String> { |
| 207 | match source { |
| 208 | StartupVersionCheckSource::Disabled => None, |
| 209 | StartupVersionCheckSource::ConfiguredUrl(url) => { |
| 210 | match latest_tag_from_configured_update_uri(&url).await { |
| 211 | Ok(tag) => tag, |
| 212 | Err(_) => latest_tag_from_release_mirror_env().await, |
| 213 | } |
| 214 | } |
| 215 | StartupVersionCheckSource::ReleaseResolver => { |
| 216 | if release_mirror_env_configured() { |
| 217 | return latest_tag_from_release_mirror_env().await; |
| 218 | } |
| 219 | |
| 220 | let body = codewhale_release::fetch_release_json_async( |
| 221 | codewhale_release::LATEST_RELEASE_URL, |
| 222 | "latest release", |
| 223 | ) |
| 224 | .await |
| 225 | .ok()?; |
| 226 | let json: serde_json::Value = serde_json::from_str(&body).ok()?; |
| 227 | publishable_release_tag(&json).map(str::to_string) |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | pub(crate) async fn latest_tag_from_release_mirror_env() -> Option<String> { |
| 233 | if !release_mirror_env_configured() { |
| 234 | return None; |
| 235 | } |
| 236 | codewhale_release::latest_release_tag_async(codewhale_release::ReleaseChannel::Stable) |
| 237 | .await |
| 238 | .ok() |
| 239 | } |
| 240 | |
| 241 | pub(crate) fn release_mirror_env_configured() -> bool { |
| 242 | let version = codewhale_release::update_version_from_env() |
| 243 | .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string()); |
| 244 | codewhale_release::release_base_url_from_env(&version).is_some() |
| 245 | } |
| 246 | |
| 247 | pub(crate) async fn latest_tag_from_configured_update_uri( |
| 248 | update_uri: &str, |
| 249 | ) -> Result<Option<String>> { |
| 250 | let body = codewhale_release::fetch_release_json_async(update_uri, "configured latest release") |
| 251 | .await?; |
| 252 | let json: serde_json::Value = serde_json::from_str(&body).with_context(|| { |
| 253 | format!("failed to parse release JSON from configured URI {update_uri}") |
| 254 | })?; |
| 255 | Ok(custom_release_tag(&json).map(str::to_string)) |
| 256 | } |
| 257 | |
| 258 | /// Tag of a GitHub release we would actually offer: published, and with every |
| 259 | /// asset the updater needs already uploaded. |
| 260 | pub(crate) fn publishable_release_tag(json: &serde_json::Value) -> Option<&str> { |
| 261 | if !release_has_required_assets(json) { |
| 262 | return None; |
| 263 | } |
| 264 | json["tag_name"].as_str() |
| 265 | } |
| 266 | |
| 267 | /// Tag from a user-configured release endpoint. Asset completeness is only |
| 268 | /// enforced when the payload advertises assets at all, since a custom mirror |
| 269 | /// may legitimately publish metadata in a different shape. |
| 270 | pub(crate) fn custom_release_tag(json: &serde_json::Value) -> Option<&str> { |
| 271 | if !release_is_publishable(json) { |
| 272 | return None; |
| 273 | } |
| 274 | if json.get("assets").is_some() && !release_has_required_assets(json) { |
| 275 | return None; |
| 276 | } |
| 277 | json["tag_name"].as_str() |
| 278 | } |
| 279 | |
| 280 | /// Test-only shorthand pairing tag extraction with the newness comparison. |
| 281 | /// Production code splits the two so the tag can be cached independently of |
| 282 | /// the version we happen to be running. |
| 283 | #[cfg(test)] |
| 284 | pub(crate) fn version_hint_from_release_json( |
| 285 | json: &serde_json::Value, |
| 286 | current: &str, |
| 287 | ) -> Option<UpdateNotice> { |
| 288 | version_hint_from_latest_tag(publishable_release_tag(json)?, current) |
| 289 | } |
| 290 | |
| 291 | #[cfg(test)] |
| 292 | pub(crate) fn version_hint_from_custom_release_json( |
| 293 | json: &serde_json::Value, |
| 294 | current: &str, |
| 295 | ) -> Option<UpdateNotice> { |
| 296 | version_hint_from_latest_tag(custom_release_tag(json)?, current) |
| 297 | } |
| 298 | |
| 299 | pub(crate) fn version_hint_from_latest_tag(tag: &str, current: &str) -> Option<UpdateNotice> { |
| 300 | let latest = tag.trim_start_matches('v'); |
| 301 | if !codewhale_release::compare_release_versions(current, tag).is_ok_and(|order| order.is_lt()) { |
| 302 | return None; |
| 303 | } |
| 304 | |
| 305 | Some(UpdateNotice { |
| 306 | current: current.to_string(), |
| 307 | latest: latest.to_string(), |
| 308 | staged: None, |
| 309 | }) |
| 310 | } |
| 311 | |
| 312 | pub(crate) fn release_has_required_assets(json: &serde_json::Value) -> bool { |
| 313 | if !release_is_publishable(json) { |
| 314 | return false; |
| 315 | } |
| 316 | |
| 317 | REQUIRED_RELEASE_ASSETS |
| 318 | .iter() |
| 319 | .all(|required| release_has_uploaded_asset(json, required)) |
| 320 | } |
| 321 | |
| 322 | pub(crate) fn release_is_publishable(json: &serde_json::Value) -> bool { |
| 323 | !json |
| 324 | .get("draft") |
| 325 | .and_then(serde_json::Value::as_bool) |
| 326 | .unwrap_or(false) |
| 327 | && !json |
| 328 | .get("prerelease") |
| 329 | .and_then(serde_json::Value::as_bool) |
| 330 | .unwrap_or(false) |
| 331 | } |
| 332 | |
| 333 | pub(crate) fn release_has_uploaded_asset(json: &serde_json::Value, required: &str) -> bool { |
| 334 | let Some(assets) = json.get("assets").and_then(serde_json::Value::as_array) else { |
| 335 | return false; |
| 336 | }; |
| 337 | assets.iter().any(|asset| { |
| 338 | asset.get("name").and_then(serde_json::Value::as_str) == Some(required) |
| 339 | && asset.get("state").and_then(serde_json::Value::as_str) == Some("uploaded") |
| 340 | }) |
| 341 | } |
| 342 | |
| 343 | #[cfg(test)] |
| 344 | mod version_tests { |
| 345 | use super::version_hint_from_latest_tag; |
| 346 | |
| 347 | #[test] |
| 348 | fn version_hint_keeps_a_newer_development_or_stamped_build() { |
| 349 | for current in ["0.9.12-pre", "0.9.12-beta.2", "0.9.12 (abc123)", "0.9.12"] { |
| 350 | assert!( |
| 351 | version_hint_from_latest_tag("v0.9.11", current).is_none(), |
| 352 | "{current}" |
| 353 | ); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | #[test] |
| 358 | fn version_hint_offers_stable_after_its_prerelease() { |
| 359 | let notice = version_hint_from_latest_tag("v0.9.12", "0.9.12-beta.2") |
| 360 | .expect("the stable release is newer than its beta"); |
| 361 | assert_eq!(notice.latest, "0.9.12"); |
| 362 | assert_eq!(notice.current, "0.9.12-beta.2"); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn version_hint_does_not_replace_stable_with_a_prerelease() { |
| 367 | assert!(version_hint_from_latest_tag("v0.9.12-beta.2", "0.9.12").is_none()); |
| 368 | assert!(version_hint_from_latest_tag("v0.9.12", "0.9.12 (abc123)").is_none()); |
| 369 | } |
| 370 | |
| 371 | #[test] |
| 372 | fn version_hint_does_not_guess_when_a_version_is_invalid() { |
| 373 | for (latest, current) in [("nightly", "0.9.12"), ("0.9.12", "unknown")] { |
| 374 | assert!(version_hint_from_latest_tag(latest, current).is_none()); |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 |