| 1 | #![cfg_attr(not(windows), allow(dead_code))] |
| 2 | |
| 3 | use std::io; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::process::Command; |
| 6 | use std::time::Duration; |
| 7 | |
| 8 | pub const POLL_INTERVAL: Duration = Duration::from_secs(15); |
| 9 | |
| 10 | const VERSION_MARKER: &str = concat!("teams-build:", env!("TEAMS_BUILD_VERSION")); |
| 11 | const UPDATE_DIRECTORY: &str = "update"; |
| 12 | const EXE_NAME: &str = "teams.exe"; |
| 13 | const OLD_EXE_NAME: &str = "teams.old.exe"; |
| 14 | const VERSION_FILE_NAME: &str = "version.txt"; |
| 15 | const CLEANUP_ATTEMPTS: u32 = 30; |
| 16 | const CLEANUP_INTERVAL: Duration = Duration::from_secs(1); |
| 17 | |
| 18 | pub fn running_version() -> &'static str { |
| 19 | VERSION_MARKER.trim_start_matches("teams-build:") |
| 20 | } |
| 21 | |
| 22 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 23 | pub enum UpdateStatus { |
| 24 | UpToDate, |
| 25 | Ready, |
| 26 | Failed(String), |
| 27 | } |
| 28 | |
| 29 | #[derive(Debug, Clone, Copy)] |
| 30 | pub struct IdleInputs { |
| 31 | pub window_active: bool, |
| 32 | pub composer_empty: bool, |
| 33 | pub send_in_flight: bool, |
| 34 | } |
| 35 | |
| 36 | pub fn is_idle(inputs: IdleInputs) -> bool { |
| 37 | !inputs.window_active && inputs.composer_empty && !inputs.send_in_flight |
| 38 | } |
| 39 | |
| 40 | pub fn update_is_ready(running: &str, published: Option<&str>, update_exe_exists: bool) -> bool { |
| 41 | update_exe_exists |
| 42 | && published.is_some_and(|version| { |
| 43 | let version = version.trim(); |
| 44 | !version.is_empty() && version != running |
| 45 | }) |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 49 | pub struct UpdatePaths { |
| 50 | pub exe: PathBuf, |
| 51 | pub old_exe: PathBuf, |
| 52 | pub update_exe: PathBuf, |
| 53 | pub version_file: PathBuf, |
| 54 | } |
| 55 | |
| 56 | impl UpdatePaths { |
| 57 | pub fn beside(exe: &Path) -> UpdatePaths { |
| 58 | let directory = exe.parent().unwrap_or_else(|| Path::new(".")); |
| 59 | let update_directory = directory.join(UPDATE_DIRECTORY); |
| 60 | UpdatePaths { |
| 61 | exe: exe.to_owned(), |
| 62 | old_exe: directory.join(OLD_EXE_NAME), |
| 63 | update_exe: update_directory.join(EXE_NAME), |
| 64 | version_file: update_directory.join(VERSION_FILE_NAME), |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 70 | pub enum FileOperation { |
| 71 | RemoveIfExists(PathBuf), |
| 72 | Rename { from: PathBuf, to: PathBuf }, |
| 73 | } |
| 74 | |
| 75 | pub trait FileSystem { |
| 76 | fn exists(&self, path: &Path) -> bool; |
| 77 | fn rename(&self, from: &Path, to: &Path) -> io::Result<()>; |
| 78 | fn remove_file(&self, path: &Path) -> io::Result<()>; |
| 79 | } |
| 80 | |
| 81 | pub struct RealFileSystem; |
| 82 | |
| 83 | impl FileSystem for RealFileSystem { |
| 84 | fn exists(&self, path: &Path) -> bool { |
| 85 | path.exists() |
| 86 | } |
| 87 | |
| 88 | fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { |
| 89 | std::fs::rename(from, to) |
| 90 | } |
| 91 | |
| 92 | fn remove_file(&self, path: &Path) -> io::Result<()> { |
| 93 | std::fs::remove_file(path) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub fn swap_plan(paths: &UpdatePaths) -> Vec<FileOperation> { |
| 98 | vec![ |
| 99 | FileOperation::RemoveIfExists(paths.old_exe.clone()), |
| 100 | FileOperation::Rename { |
| 101 | from: paths.exe.clone(), |
| 102 | to: paths.old_exe.clone(), |
| 103 | }, |
| 104 | FileOperation::Rename { |
| 105 | from: paths.update_exe.clone(), |
| 106 | to: paths.exe.clone(), |
| 107 | }, |
| 108 | FileOperation::RemoveIfExists(paths.version_file.clone()), |
| 109 | ] |
| 110 | } |
| 111 | |
| 112 | fn apply_operation(files: &dyn FileSystem, operation: &FileOperation) -> io::Result<()> { |
| 113 | match operation { |
| 114 | FileOperation::RemoveIfExists(path) => { |
| 115 | if files.exists(path) { |
| 116 | files.remove_file(path)?; |
| 117 | } |
| 118 | Ok(()) |
| 119 | } |
| 120 | FileOperation::Rename { from, to } => files.rename(from, to), |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// Runs the plan. On failure undoes the completed renames and returns the error. |
| 125 | pub fn apply_plan( |
| 126 | files: &dyn FileSystem, |
| 127 | plan: &[FileOperation], |
| 128 | ) -> Result<Vec<FileOperation>, String> { |
| 129 | let mut completed = Vec::new(); |
| 130 | for operation in plan { |
| 131 | if let Err(error) = apply_operation(files, operation) { |
| 132 | roll_back(files, &completed); |
| 133 | return Err(format!("{operation:?}: {error}")); |
| 134 | } |
| 135 | completed.push(operation.clone()); |
| 136 | } |
| 137 | Ok(completed) |
| 138 | } |
| 139 | |
| 140 | pub fn roll_back(files: &dyn FileSystem, completed: &[FileOperation]) { |
| 141 | for operation in completed.iter().rev() { |
| 142 | if let FileOperation::Rename { from, to } = operation { |
| 143 | let _ = files.rename(to, from); |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | pub fn check(paths: &UpdatePaths) -> bool { |
| 149 | let published = std::fs::read_to_string(&paths.version_file).ok(); |
| 150 | update_is_ready( |
| 151 | running_version(), |
| 152 | published.as_deref(), |
| 153 | paths.update_exe.exists(), |
| 154 | ) |
| 155 | } |
| 156 | |
| 157 | pub fn current_paths() -> Option<UpdatePaths> { |
| 158 | std::env::current_exe() |
| 159 | .ok() |
| 160 | .map(|exe| UpdatePaths::beside(&exe)) |
| 161 | } |
| 162 | |
| 163 | pub fn install_and_relaunch(paths: &UpdatePaths) -> Result<(), String> { |
| 164 | let files = RealFileSystem; |
| 165 | let completed = apply_plan(&files, &swap_plan(paths))?; |
| 166 | match Command::new(&paths.exe) |
| 167 | .args(std::env::args_os().skip(1)) |
| 168 | .spawn() |
| 169 | { |
| 170 | Ok(_) => Ok(()), |
| 171 | Err(error) => { |
| 172 | roll_back(&files, &completed); |
| 173 | Err(format!("Start: {error}")) |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | pub fn clean_up_old_binary() { |
| 179 | let Some(paths) = current_paths() else { |
| 180 | return; |
| 181 | }; |
| 182 | if !paths.old_exe.exists() { |
| 183 | return; |
| 184 | } |
| 185 | std::thread::spawn(move || { |
| 186 | for _ in 0..CLEANUP_ATTEMPTS { |
| 187 | if std::fs::remove_file(&paths.old_exe).is_ok() || !paths.old_exe.exists() { |
| 188 | return; |
| 189 | } |
| 190 | std::thread::sleep(CLEANUP_INTERVAL); |
| 191 | } |
| 192 | }); |
| 193 | } |
| 194 | |
| 195 | #[cfg(test)] |
| 196 | mod tests { |
| 197 | use super::*; |
| 198 | use std::fs; |
| 199 | |
| 200 | fn idle() -> IdleInputs { |
| 201 | IdleInputs { |
| 202 | window_active: false, |
| 203 | composer_empty: true, |
| 204 | send_in_flight: false, |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | #[test] |
| 209 | fn idle_needs_all_three_conditions() { |
| 210 | assert!(is_idle(idle())); |
| 211 | assert!(!is_idle(IdleInputs { |
| 212 | window_active: true, |
| 213 | ..idle() |
| 214 | })); |
| 215 | assert!(!is_idle(IdleInputs { |
| 216 | composer_empty: false, |
| 217 | ..idle() |
| 218 | })); |
| 219 | assert!(!is_idle(IdleInputs { |
| 220 | send_in_flight: true, |
| 221 | ..idle() |
| 222 | })); |
| 223 | } |
| 224 | |
| 225 | #[test] |
| 226 | fn update_needs_a_different_version_and_an_exe() { |
| 227 | assert!(update_is_ready("a-1", Some("b-2\n"), true)); |
| 228 | assert!(!update_is_ready("a-1", Some("a-1\n"), true)); |
| 229 | assert!(!update_is_ready("a-1", Some("b-2"), false)); |
| 230 | assert!(!update_is_ready("a-1", None, true)); |
| 231 | assert!(!update_is_ready("a-1", Some(" \n"), true)); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn plan_lists_the_operations_in_order() { |
| 236 | let paths = UpdatePaths::beside(Path::new("/app/teams.exe")); |
| 237 | assert_eq!(paths.update_exe, Path::new("/app/update/teams.exe")); |
| 238 | let plan = swap_plan(&paths); |
| 239 | assert_eq!(plan.len(), 4); |
| 240 | assert_eq!( |
| 241 | plan[1], |
| 242 | FileOperation::Rename { |
| 243 | from: paths.exe.clone(), |
| 244 | to: paths.old_exe.clone() |
| 245 | } |
| 246 | ); |
| 247 | assert_eq!( |
| 248 | plan[2], |
| 249 | FileOperation::Rename { |
| 250 | from: paths.update_exe.clone(), |
| 251 | to: paths.exe.clone() |
| 252 | } |
| 253 | ); |
| 254 | } |
| 255 | |
| 256 | fn install(directory: &Path) -> UpdatePaths { |
| 257 | let paths = UpdatePaths::beside(&directory.join("teams.exe")); |
| 258 | fs::create_dir_all(paths.update_exe.parent().unwrap()).unwrap(); |
| 259 | fs::write(&paths.exe, "old").unwrap(); |
| 260 | fs::write(&paths.update_exe, "new").unwrap(); |
| 261 | fs::write(&paths.version_file, "b-2").unwrap(); |
| 262 | paths |
| 263 | } |
| 264 | |
| 265 | #[test] |
| 266 | fn swap_replaces_the_exe_and_keeps_the_old_one() { |
| 267 | let directory = tempfile::tempdir().unwrap(); |
| 268 | let paths = install(directory.path()); |
| 269 | apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap(); |
| 270 | assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "new"); |
| 271 | assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old"); |
| 272 | assert!(!paths.update_exe.exists()); |
| 273 | assert!(!paths.version_file.exists()); |
| 274 | } |
| 275 | |
| 276 | #[test] |
| 277 | fn swap_replaces_a_leftover_old_exe() { |
| 278 | let directory = tempfile::tempdir().unwrap(); |
| 279 | let paths = install(directory.path()); |
| 280 | fs::write(&paths.old_exe, "stale").unwrap(); |
| 281 | apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap(); |
| 282 | assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old"); |
| 283 | } |
| 284 | |
| 285 | struct FailingRename { |
| 286 | fail_on: PathBuf, |
| 287 | } |
| 288 | |
| 289 | impl FileSystem for FailingRename { |
| 290 | fn exists(&self, path: &Path) -> bool { |
| 291 | path.exists() |
| 292 | } |
| 293 | |
| 294 | fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { |
| 295 | if from == self.fail_on { |
| 296 | return Err(io::Error::other("locked")); |
| 297 | } |
| 298 | std::fs::rename(from, to) |
| 299 | } |
| 300 | |
| 301 | fn remove_file(&self, path: &Path) -> io::Result<()> { |
| 302 | std::fs::remove_file(path) |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn failed_step_rolls_back_so_teams_exe_survives() { |
| 308 | let directory = tempfile::tempdir().unwrap(); |
| 309 | let paths = install(directory.path()); |
| 310 | let files = FailingRename { |
| 311 | fail_on: paths.update_exe.clone(), |
| 312 | }; |
| 313 | let error = apply_plan(&files, &swap_plan(&paths)).unwrap_err(); |
| 314 | assert!(error.contains("locked")); |
| 315 | assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "old"); |
| 316 | assert!(!paths.old_exe.exists()); |
| 317 | assert_eq!(fs::read_to_string(&paths.update_exe).unwrap(), "new"); |
| 318 | assert!(paths.version_file.exists()); |
| 319 | } |
| 320 | |
| 321 | #[test] |
| 322 | fn running_version_has_no_marker_prefix() { |
| 323 | assert!(!running_version().starts_with("teams-build:")); |
| 324 | assert!(!running_version().is_empty()); |
| 325 | } |
| 326 | } |