BlueGit

ict rusty-teams

Files

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

updater.rs

updater.rs 13.9 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.
270pub fn self_update_allowed() -> bool {
271 #[cfg(target_os = "linux")]
272 {
273 return std::env::current_exe().is_ok_and(|executable| {
274 crate::linux_desktop::Layout::current()
275 .is_some_and(|layout| crate::linux_desktop::is_installed(&executable, &layout))
276 });
277 }
278 #[cfg(target_os = "macos")]
279 {
280 return std::env::current_exe().is_ok_and(|executable| {
281 executable
282 .components()
283 .any(|part| part.as_os_str().to_string_lossy().ends_with(".app"))
284 });
285 }
286 #[cfg(windows)]
287 {
288 return true;
289 }
290 #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
291 {
292 false
293 }
294}
295
296/// Reading the new exe once lets the virus scanner finish before the restart, which otherwise blocks process start for seconds.
297pub fn prescan(update_exe: &Path) {
298 if let Ok(mut file) = std::fs::File::open(update_exe) {
299 let _ = io::copy(&mut file, &mut io::sink());
300 }
301}
302
303pub fn clean_up_old_binary() {
304 let Some(paths) = current_paths() else {
305 return;
306 };
307 if !paths.old_exe.exists() {
308 return;
309 }
310 std::thread::spawn(move || {
311 for _ in 0..CLEANUP_ATTEMPTS {
312 if std::fs::remove_file(&paths.old_exe).is_ok() || !paths.old_exe.exists() {
313 return;
314 }
315 std::thread::sleep(CLEANUP_INTERVAL);
316 }
317 });
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323 use std::fs;
324
325 fn idle() -> IdleInputs {
326 IdleInputs {
327 window_active: false,
328 composer_empty: true,
329 send_in_flight: false,
330 in_call: false,
331 }
332 }
333
334 #[test]
335 fn idle_needs_all_conditions_and_no_call() {
336 assert!(is_idle(idle()));
337 assert!(!is_idle(IdleInputs {
338 window_active: true,
339 ..idle()
340 }));
341 assert!(!is_idle(IdleInputs {
342 composer_empty: false,
343 ..idle()
344 }));
345 assert!(!is_idle(IdleInputs {
346 send_in_flight: true,
347 ..idle()
348 }));
349 assert!(!is_idle(IdleInputs {
350 in_call: true,
351 ..idle()
352 }));
353 }
354
355 #[test]
356 fn update_needs_a_different_version_and_an_exe() {
357 assert!(update_is_ready("a-1", Some("b-2\n"), true));
358 assert!(!update_is_ready("a-1", Some("a-1\n"), true));
359 assert!(!update_is_ready("a-1", Some("b-2"), false));
360 assert!(!update_is_ready("a-1", None, true));
361 assert!(!update_is_ready("a-1", Some(" \n"), true));
362 }
363
364 #[test]
365 fn plan_lists_the_operations_in_order() {
366 let paths = UpdatePaths::beside(&Path::new("/app").join(EXE_NAME));
367 assert_eq!(paths.update_exe, Path::new("/app/update").join(EXE_NAME));
368 let plan = swap_plan(&paths);
369 assert_eq!(plan.len(), 5);
370 assert_eq!(
371 plan[1],
372 FileOperation::Rename {
373 from: paths.exe.clone(),
374 to: paths.old_exe.clone()
375 }
376 );
377 assert_eq!(
378 plan[2],
379 FileOperation::Rename {
380 from: paths.update_exe.clone(),
381 to: paths.exe.clone()
382 }
383 );
384 }
385
386 fn install(directory: &Path) -> UpdatePaths {
387 let paths = UpdatePaths::beside(&directory.join(EXE_NAME));
388 fs::create_dir_all(paths.update_exe.parent().unwrap()).unwrap();
389 fs::write(&paths.exe, "old").unwrap();
390 fs::write(&paths.update_exe, "new").unwrap();
391 fs::write(&paths.version_file, "b-2").unwrap();
392 paths
393 }
394
395 #[test]
396 fn swap_replaces_the_exe_and_keeps_the_old_one() {
397 let directory = tempfile::tempdir().unwrap();
398 let paths = install(directory.path());
399 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
400 assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "new");
401 assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old");
402 assert!(!paths.update_exe.exists());
403 assert!(!paths.version_file.exists());
404 }
405
406 #[test]
407 fn swap_moves_the_symbols_along_and_works_without_them() {
408 let directory = tempfile::tempdir().unwrap();
409 let paths = install(directory.path());
410 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
411 assert!(!paths.pdb.exists());
412 let paths = install(directory.path());
413 fs::write(&paths.pdb, "old symbols").unwrap();
414 fs::write(&paths.update_pdb, "new symbols").unwrap();
415 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
416 assert_eq!(fs::read_to_string(&paths.pdb).unwrap(), "new symbols");
417 assert!(!paths.update_pdb.exists());
418 }
419
420 #[test]
421 fn swap_replaces_a_leftover_old_exe() {
422 let directory = tempfile::tempdir().unwrap();
423 let paths = install(directory.path());
424 fs::write(&paths.old_exe, "stale").unwrap();
425 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
426 assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old");
427 }
428
429 struct FailingRename {
430 fail_on: PathBuf,
431 }
432
433 impl FileSystem for FailingRename {
434 fn exists(&self, path: &Path) -> bool {
435 path.exists()
436 }
437
438 fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
439 if from == self.fail_on {
440 return Err(io::Error::other("locked"));
441 }
442 std::fs::rename(from, to)
443 }
444
445 fn remove_file(&self, path: &Path) -> io::Result<()> {
446 std::fs::remove_file(path)
447 }
448 }
449
450 #[test]
451 fn failed_step_rolls_back_so_teams_exe_survives() {
452 let directory = tempfile::tempdir().unwrap();
453 let paths = install(directory.path());
454 let files = FailingRename {
455 fail_on: paths.update_exe.clone(),
456 };
457 let error = apply_plan(&files, &swap_plan(&paths)).unwrap_err();
458 assert!(error.contains("locked"));
459 assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "old");
460 assert!(!paths.old_exe.exists());
461 assert_eq!(fs::read_to_string(&paths.update_exe).unwrap(), "new");
462 assert!(paths.version_file.exists());
463 }
464
465 #[test]
466 fn relaunch_value_carries_the_previous_process_id() {
467 assert_eq!(previous_process_id("4242"), Some(4242));
468 assert_eq!(previous_process_id(""), None);
469 }
470
471 #[test]
472 fn running_version_is_set() {
473 assert!(!running_version().is_empty());
474 }
475}