BlueGit

ict rusty-teams

Files

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

updater.rs

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