BlueGit

ict rusty-teams

Files

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

updater.rs

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