//! SyncKit field-version check, polls `/api/internal/synckit/client-versions` //! on a target makenotwork instance and records which SDK versions are syncing. //! //! SyncKit is client-side only, linked into mnw-cli, balanced_breakfast and //! audiofiles, so there is no deployed version to poll the way every other target //! is polled. The server records the SDK version off each sync request's //! User-Agent (`sync_devices.client_version`) and aggregates it; this reads that //! aggregate. //! //! **This check is informational, and cannot fail on what it finds.** An old //! version still syncing is a fact, not an incident: nobody can be paged into //! upgrading someone else's laptop, and there is no threshold that would make a //! version distribution "wrong". What it *can* report is that the readout itself //! is broken (endpoint gone, token rotated out from under PoM, unexpected shape), //! because then PoM has quietly stopped being able to answer the question at all. //! That is a monitoring gap, so it reads as degraded rather than down; whether the //! platform itself is up is the `health` check's business, not this one's. use std::time::Duration; use tracing::instrument; use crate::types::{SyncKitFleetCheckResult, SyncKitVersionSnapshot}; /// Longest version string we will store per row. The server already bounds what /// it accepts to 32 chars; this is the same bound applied on the way in, so a /// server that loosens its own rule cannot widen our column. const VERSION_MAX_LENGTH: usize = 32; /// Most distinct versions kept from one readout. A healthy fleet has a handful; /// hundreds would mean the server is aggregating something other than versions, /// and the row should not grow without bound on the strength of that. const MAX_VERSIONS: usize = 32; #[derive(Debug, serde::Deserialize)] struct UpstreamVersion { /// `None` is a real answer from the server: "syncing, version unknown", a /// client from before the SDK sent a User-Agent. client_version: Option, devices: i64, last_seen_at: Option, } #[derive(Debug, serde::Deserialize)] struct UpstreamFleet { window_days: i32, devices: i64, versions: Vec, } #[instrument(skip(token))] pub async fn check_synckit_fleet( target_name: &str, base_url: &str, token: &str, window_days: u32, timeout_secs: u64, ) -> SyncKitFleetCheckResult { let checked_at = chrono::Utc::now().to_rfc3339(); let url = format!( "{}/api/internal/synckit/client-versions?days={window_days}", base_url.trim_end_matches('/') ); let client = match crate::tls::https_client_builder() .timeout(Duration::from_secs(timeout_secs)) .build() { Ok(c) => c, Err(e) => return unreadable(target_name, &checked_at, format!("client build: {e}")), }; let response = match client.get(&url).bearer_auth(token).send().await { Ok(r) => r, Err(e) => return unreadable(target_name, &checked_at, format!("request: {e}")), }; let status = response.status(); if !status.is_success() { // 401/403 is called out by name because it is the failure this check will // actually hit: the endpoint is authed with the alerts ingest token, so a // credential rotation that misses PoM's config lands here, and "HTTP 401" // alone reads like a server bug rather than a stale token. let msg = match status.as_u16() { 401 | 403 => format!("HTTP {} (alerts ingest token rejected)", status.as_u16()), code => format!("HTTP {code}"), }; return unreadable(target_name, &checked_at, msg); } let body: UpstreamFleet = match response.json().await { Ok(b) => b, Err(e) => return unreadable(target_name, &checked_at, format!("parse: {e}")), }; summarize(target_name, &checked_at, body) } /// The readout could not be produced. Distinct from an empty fleet, which is a /// successful reading of zero devices. fn unreadable(target: &str, checked_at: &str, msg: String) -> SyncKitFleetCheckResult { SyncKitFleetCheckResult { target: target.to_string(), window_days: 0, devices: 0, versions: Vec::new(), checked_at: checked_at.to_string(), error: Some(msg), } } fn summarize(target: &str, checked_at: &str, body: UpstreamFleet) -> SyncKitFleetCheckResult { let versions: Vec = body .versions .into_iter() .take(MAX_VERSIONS) .map(|v| SyncKitVersionSnapshot { client_version: v .client_version .filter(|s| !s.is_empty() && s.len() <= VERSION_MAX_LENGTH), devices: v.devices, last_seen_at: v.last_seen_at, }) .collect(); SyncKitFleetCheckResult { target: target.to_string(), window_days: body.window_days, devices: body.devices, versions, checked_at: checked_at.to_string(), error: None, } } #[cfg(test)] mod tests { use super::*; fn fleet(versions: Vec<(Option<&str>, i64)>) -> UpstreamFleet { UpstreamFleet { window_days: 30, devices: versions.iter().map(|(_, d)| d).sum(), versions: versions .into_iter() .map(|(v, devices)| UpstreamVersion { client_version: v.map(str::to_string), devices, last_seen_at: Some("2026-07-29T12:00:00Z".into()), }) .collect(), } } #[test] fn a_readout_never_reports_an_error() { let r = summarize("mnw", "now", fleet(vec![(Some("0.6.0"), 12)])); assert!(r.error.is_none()); assert_eq!(r.devices, 12); assert_eq!(r.window_days, 30); } #[test] fn an_empty_fleet_is_a_reading_not_a_failure() { // Nobody syncing is a real answer, and it must not look like a broken // endpoint: pre-launch, this is the expected state. let r = summarize("mnw", "now", fleet(vec![])); assert!(r.error.is_none()); assert_eq!(r.devices, 0); assert!(r.versions.is_empty()); } #[test] fn an_old_version_in_the_field_is_still_not_an_error() { let r = summarize( "mnw", "now", fleet(vec![(Some("0.1.0"), 40), (Some("0.6.0"), 1)]), ); assert!(r.error.is_none(), "version age is a fact, not an incident"); assert_eq!(r.versions.len(), 2); } #[test] fn unknown_version_is_preserved_as_unknown() { // Clients older than the User-Agent change report nothing, and guessing // would corrupt the readout this check exists to produce. let r = summarize("mnw", "now", fleet(vec![(None, 3)])); assert_eq!(r.versions.len(), 1); assert!(r.versions[0].client_version.is_none()); assert_eq!(r.versions[0].devices, 3); } #[test] fn an_empty_version_string_reads_as_unknown() { let r = summarize("mnw", "now", fleet(vec![(Some(""), 2)])); assert!(r.versions[0].client_version.is_none()); } #[test] fn an_overlong_version_reads_as_unknown_rather_than_truncated() { let long = "9".repeat(VERSION_MAX_LENGTH + 1); let r = summarize("mnw", "now", fleet(vec![(Some(&long), 1)])); assert!( r.versions[0].client_version.is_none(), "a truncated version reads like a real one it is not" ); } #[test] fn a_version_at_the_length_bound_is_kept() { let at_max = "9".repeat(VERSION_MAX_LENGTH); let r = summarize("mnw", "now", fleet(vec![(Some(&at_max), 1)])); assert_eq!(r.versions[0].client_version.as_deref(), Some(&*at_max)); } #[test] fn the_version_list_is_bounded() { let many: Vec<(Option<&str>, i64)> = (0..MAX_VERSIONS + 10).map(|_| (Some("0.6.0"), 1)).collect(); let r = summarize("mnw", "now", fleet(many)); assert_eq!(r.versions.len(), MAX_VERSIONS); } #[test] fn an_unreadable_endpoint_carries_the_reason() { let r = unreadable( "mnw", "now", "HTTP 401 (alerts ingest token rejected)".into(), ); assert!(r.error.as_deref().unwrap().contains("401")); assert_eq!(r.devices, 0); assert!(r.versions.is_empty()); } }