BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / updater.rs

updater.rs

c9c819d4 History
updater.rs 13.7 KiB Download Raw
1#![cfg_attr(
2 not(any(windows, target_os = "linux", target_os = "macos")),
3 allow(dead_code)
4)]
5
6use std::io;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9use std::time::Duration;
10
11pub const POLL_INTERVAL: Duration = Duration::from_secs(15);
12
13const UPDATE_DIRECTORY: &str = "update";
14#[cfg(windows)]
15const EXE_NAME: &str = "teams.exe";
16#[cfg(windows)]
17const OLD_EXE_NAME: &str = "teams.old.exe";
18#[cfg(not(windows))]
19const EXE_NAME: &str = "teams";
20#[cfg(not(windows))]
21const OLD_EXE_NAME: &str = "teams.old";
22const PDB_NAME: &str = "teams.pdb";
23const VERSION_FILE_NAME: &str = "version.txt";
24pub const RELAUNCH_ENV: &str = "RUSTY_TEAMS_RELAUNCH";
25const CLEANUP_ATTEMPTS: u32 = 30;
26const CLEANUP_INTERVAL: Duration = Duration::from_secs(1);
27const QUIT_GRACE: Duration = Duration::from_secs(3);
28const PREVIOUS_EXIT_TIMEOUT: Duration = Duration::from_secs(30);
29
30pub fn running_version() -> &'static str {
31 crate::version::build_version()
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum UpdateStatus {
36 UpToDate,
37 Ready,
38 Installing,
39 Failed(String),
40}
41
42#[derive(Debug, Clone, Copy)]
43pub struct IdleInputs {
44 pub window_active: bool,
45 pub composer_empty: bool,
46 pub send_in_flight: bool,
47 pub in_call: bool,
48}
49
50pub fn is_idle(inputs: IdleInputs) -> bool {
51 !inputs.window_active && inputs.composer_empty && !inputs.send_in_flight && !inputs.in_call
52}
53
54pub fn update_is_ready(running: &str, published: Option<&str>, update_exe_exists: bool) -> bool {
55 update_exe_exists
56 && published.is_some_and(|version| {
57 let version = version.trim();
58 !version.is_empty() && version != running
59 })
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct UpdatePaths {
64 pub exe: PathBuf,
65 pub old_exe: PathBuf,
66 pub update_exe: PathBuf,
67 pub version_file: PathBuf,
68 pub pdb: PathBuf,
69 pub update_pdb: PathBuf,
70}
71
72impl UpdatePaths {
73 pub fn beside(exe: &Path) -> UpdatePaths {
74 let directory = exe.parent().unwrap_or_else(|| Path::new("."));
75 let update_directory = directory.join(UPDATE_DIRECTORY);
76 UpdatePaths {
77 exe: exe.to_owned(),
78 old_exe: directory.join(OLD_EXE_NAME),
79 update_exe: update_directory.join(EXE_NAME),
80 version_file: update_directory.join(VERSION_FILE_NAME),
81 pdb: directory.join(PDB_NAME),
82 update_pdb: update_directory.join(PDB_NAME),
83 }
84 }
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum FileOperation {
89 RemoveIfExists(PathBuf),
90 Rename { from: PathBuf, to: PathBuf },
91 ReplaceIfPresent { from: PathBuf, to: PathBuf },
92}
93
94pub trait FileSystem {
95 fn exists(&self, path: &Path) -> bool;
96 fn rename(&self, from: &Path, to: &Path) -> io::Result<()>;
97 fn remove_file(&self, path: &Path) -> io::Result<()>;
98}
99
100pub struct RealFileSystem;
101
102impl FileSystem for RealFileSystem {
103 fn exists(&self, path: &Path) -> bool {
104 path.exists()
105 }
106
107 fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
108 std::fs::rename(from, to)
109 }
110
111 fn remove_file(&self, path: &Path) -> io::Result<()> {
112 std::fs::remove_file(path)
113 }
114}
115
116pub fn swap_plan(paths: &UpdatePaths) -> Vec<FileOperation> {
117 vec![
118 FileOperation::RemoveIfExists(paths.old_exe.clone()),
119 FileOperation::Rename {
120 from: paths.exe.clone(),
121 to: paths.old_exe.clone(),
122 },
123 FileOperation::Rename {
124 from: paths.update_exe.clone(),
125 to: paths.exe.clone(),
126 },
127 FileOperation::ReplaceIfPresent {
128 from: paths.update_pdb.clone(),
129 to: paths.pdb.clone(),
130 },
131 FileOperation::RemoveIfExists(paths.version_file.clone()),
132 ]
133}
134
135fn apply_operation(files: &dyn FileSystem, operation: &FileOperation) -> io::Result<()> {
136 match operation {
137 FileOperation::RemoveIfExists(path) => {
138 if files.exists(path) {
139 files.remove_file(path)?;
140 }
141 Ok(())
142 }
143 FileOperation::Rename { from, to } => files.rename(from, to),
144 FileOperation::ReplaceIfPresent { from, to } => {
145 if files.exists(from) {
146 if files.exists(to) {
147 let _ = files.remove_file(to);
148 }
149 let _ = files.rename(from, to);
150 }
151 Ok(())
152 }
153 }
154}
155
156/// Runs the plan. On failure undoes the completed renames and returns the error.
157pub fn apply_plan(
158 files: &dyn FileSystem,
159 plan: &[FileOperation],
160) -> Result<Vec<FileOperation>, String> {
161 let mut completed = Vec::new();
162 for operation in plan {
163 if let Err(error) = apply_operation(files, operation) {
164 roll_back(files, &completed);
165 return Err(format!("{operation:?}: {error}"));
166 }
167 completed.push(operation.clone());
168 }
169 Ok(completed)
170}
171
172pub fn roll_back(files: &dyn FileSystem, completed: &[FileOperation]) {
173 for operation in completed.iter().rev() {
174 if let FileOperation::Rename { from, to } = operation {
175 let _ = files.rename(to, from);
176 }
177 }
178}
179
180pub fn check(paths: &UpdatePaths) -> bool {
181 let published = std::fs::read_to_string(&paths.version_file).ok();
182 update_is_ready(
183 running_version(),
184 published.as_deref(),
185 paths.update_exe.exists(),
186 )
187}
188
189pub fn current_paths() -> Option<UpdatePaths> {
190 std::env::current_exe()
191 .ok()
192 .map(|exe| UpdatePaths::beside(&exe))
193}
194
195pub fn install_and_relaunch(paths: &UpdatePaths) -> Result<(), String> {
196 let files = RealFileSystem;
197 let completed = apply_plan(&files, &swap_plan(paths))?;
198 match Command::new(&paths.exe)
199 .args(std::env::args_os().skip(1))
200 .env(RELAUNCH_ENV, std::process::id().to_string())
201 .spawn()
202 {
203 Ok(_) => Ok(()),
204 Err(error) => {
205 roll_back(&files, &completed);
206 Err(format!("Start: {error}"))
207 }
208 }
209}
210
211pub fn previous_process_id(relaunch_value: &str) -> Option<u32> {
212 relaunch_value.trim().parse().ok()
213}
214
215pub fn wait_for_previous_exit(relaunch_value: &str) {
216 if let Some(process_id) = previous_process_id(relaunch_value) {
217 platform::wait_for_exit(process_id, PREVIOUS_EXIT_TIMEOUT);
218 }
219}
220
221pub fn exit_after_grace() {
222 std::thread::spawn(|| {
223 std::thread::sleep(QUIT_GRACE);
224 exit_now();
225 });
226}
227
228/// Skips DLL unload, which takes seconds with WebRTC and WebView2 loaded and keeps the database locked.
229pub fn exit_now() -> ! {
230 platform::terminate_current();
231 std::process::exit(0)
232}
233
234#[cfg(windows)]
235mod platform {
236 use std::time::Duration;
237
238 use windows::Win32::Foundation::CloseHandle;
239 use windows::Win32::System::Threading::{
240 GetCurrentProcess, OpenProcess, PROCESS_SYNCHRONIZE, TerminateProcess, WaitForSingleObject,
241 };
242
243 pub fn terminate_current() {
244 let _ = unsafe { TerminateProcess(GetCurrentProcess(), 0) };
245 }
246
247 pub fn wait_for_exit(process_id: u32, timeout: Duration) {
248 let Ok(handle) = (unsafe { OpenProcess(PROCESS_SYNCHRONIZE, false, process_id) }) else {
249 return;
250 };
251 unsafe {
252 WaitForSingleObject(handle, timeout.as_millis() as u32);
253 let _ = CloseHandle(handle);
254 }
255 }
256}
257
258#[cfg(not(windows))]
259mod platform {
260 use std::time::Duration;
261
262 pub fn wait_for_exit(_process_id: u32, _timeout: Duration) {}
263
264 pub fn terminate_current() {}
265}
266
267/// Whether this build may replace itself from GitHub releases. On Linux only the copy
268/// installed in `~/.local/share/rusty-teams` updates; a binary run from a
269/// build folder or a package location is left alone. macOS ships a `.app` and does not
270/// swap its Mach-O in place.
271pub fn self_update_allowed() -> bool {
272 #[cfg(target_os = "linux")]
273 {
274 return std::env::current_exe().is_ok_and(|executable| {
275 crate::linux_desktop::Layout::current()
276 .is_some_and(|layout| crate::linux_desktop::is_installed(&executable, &layout))
277 });
278 }
279 #[cfg(windows)]
280 {
281 return true;
282 }
283 #[cfg(not(any(windows, target_os = "linux")))]
284 {
285 false
286 }
287}
288
289/// Reading the new exe once lets the virus scanner finish before the restart, which otherwise blocks process start for seconds.
290pub fn prescan(update_exe: &Path) {
291 if let Ok(mut file) = std::fs::File::open(update_exe) {
292 let _ = io::copy(&mut file, &mut io::sink());
293 }
294}
295
296pub fn clean_up_old_binary() {
297 let Some(paths) = current_paths() else {
298 return;
299 };
300 if !paths.old_exe.exists() {
301 return;
302 }
303 std::thread::spawn(move || {
304 for _ in 0..CLEANUP_ATTEMPTS {
305 if std::fs::remove_file(&paths.old_exe).is_ok() || !paths.old_exe.exists() {
306 return;
307 }
308 std::thread::sleep(CLEANUP_INTERVAL);
309 }
310 });
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316 use std::fs;
317
318 fn idle() -> IdleInputs {
319 IdleInputs {
320 window_active: false,
321 composer_empty: true,
322 send_in_flight: false,
323 in_call: false,
324 }
325 }
326
327 #[test]
328 fn idle_needs_all_conditions_and_no_call() {
329 assert!(is_idle(idle()));
330 assert!(!is_idle(IdleInputs {
331 window_active: true,
332 ..idle()
333 }));
334 assert!(!is_idle(IdleInputs {
335 composer_empty: false,
336 ..idle()
337 }));
338 assert!(!is_idle(IdleInputs {
339 send_in_flight: true,
340 ..idle()
341 }));
342 assert!(!is_idle(IdleInputs {
343 in_call: true,
344 ..idle()
345 }));
346 }
347
348 #[test]
349 fn update_needs_a_different_version_and_an_exe() {
350 assert!(update_is_ready("a-1", Some("b-2\n"), true));
351 assert!(!update_is_ready("a-1", Some("a-1\n"), true));
352 assert!(!update_is_ready("a-1", Some("b-2"), false));
353 assert!(!update_is_ready("a-1", None, true));
354 assert!(!update_is_ready("a-1", Some(" \n"), true));
355 }
356
357 #[test]
358 fn plan_lists_the_operations_in_order() {
359 let paths = UpdatePaths::beside(&Path::new("/app").join(EXE_NAME));
360 assert_eq!(paths.update_exe, Path::new("/app/update").join(EXE_NAME));
361 let plan = swap_plan(&paths);
362 assert_eq!(plan.len(), 5);
363 assert_eq!(
364 plan[1],
365 FileOperation::Rename {
366 from: paths.exe.clone(),
367 to: paths.old_exe.clone()
368 }
369 );
370 assert_eq!(
371 plan[2],
372 FileOperation::Rename {
373 from: paths.update_exe.clone(),
374 to: paths.exe.clone()
375 }
376 );
377 }
378
379 fn install(directory: &Path) -> UpdatePaths {
380 let paths = UpdatePaths::beside(&directory.join(EXE_NAME));
381 fs::create_dir_all(paths.update_exe.parent().unwrap()).unwrap();
382 fs::write(&paths.exe, "old").unwrap();
383 fs::write(&paths.update_exe, "new").unwrap();
384 fs::write(&paths.version_file, "b-2").unwrap();
385 paths
386 }
387
388 #[test]
389 fn swap_replaces_the_exe_and_keeps_the_old_one() {
390 let directory = tempfile::tempdir().unwrap();
391 let paths = install(directory.path());
392 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
393 assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "new");
394 assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old");
395 assert!(!paths.update_exe.exists());
396 assert!(!paths.version_file.exists());
397 }
398
399 #[test]
400 fn swap_moves_the_symbols_along_and_works_without_them() {
401 let directory = tempfile::tempdir().unwrap();
402 let paths = install(directory.path());
403 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
404 assert!(!paths.pdb.exists());
405 let paths = install(directory.path());
406 fs::write(&paths.pdb, "old symbols").unwrap();
407 fs::write(&paths.update_pdb, "new symbols").unwrap();
408 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
409 assert_eq!(fs::read_to_string(&paths.pdb).unwrap(), "new symbols");
410 assert!(!paths.update_pdb.exists());
411 }
412
413 #[test]
414 fn swap_replaces_a_leftover_old_exe() {
415 let directory = tempfile::tempdir().unwrap();
416 let paths = install(directory.path());
417 fs::write(&paths.old_exe, "stale").unwrap();
418 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
419 assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old");
420 }
421
422 struct FailingRename {
423 fail_on: PathBuf,
424 }
425
426 impl FileSystem for FailingRename {
427 fn exists(&self, path: &Path) -> bool {
428 path.exists()
429 }
430
431 fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
432 if from == self.fail_on {
433 return Err(io::Error::other("locked"));
434 }
435 std::fs::rename(from, to)
436 }
437
438 fn remove_file(&self, path: &Path) -> io::Result<()> {
439 std::fs::remove_file(path)
440 }
441 }
442
443 #[test]
444 fn failed_step_rolls_back_so_teams_exe_survives() {
445 let directory = tempfile::tempdir().unwrap();
446 let paths = install(directory.path());
447 let files = FailingRename {
448 fail_on: paths.update_exe.clone(),
449 };
450 let error = apply_plan(&files, &swap_plan(&paths)).unwrap_err();
451 assert!(error.contains("locked"));
452 assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "old");
453 assert!(!paths.old_exe.exists());
454 assert_eq!(fs::read_to_string(&paths.update_exe).unwrap(), "new");
455 assert!(paths.version_file.exists());
456 }
457
458 #[test]
459 fn relaunch_value_carries_the_previous_process_id() {
460 assert_eq!(previous_process_id("4242"), Some(4242));
461 assert_eq!(previous_process_id(""), None);
462 }
463
464 #[test]
465 fn running_version_is_set() {
466 assert!(!running_version().is_empty());
467 }
468}