BlueGit

ict rusty-teams

Files

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

updater.rs

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