BlueGit

ict rusty-teams

Files

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

updater.rs

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