BlueGit

ict rusty-teams

Files

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

updater.rs

updater.rs 9.5 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);
18
19pub fn running_version() -> &'static str {
20 VERSION_MARKER.trim_start_matches("teams-build:")
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum UpdateStatus {
25 UpToDate,
26 Ready,
27 Failed(String),
28}
29
30#[derive(Debug, Clone, Copy)]
31pub struct IdleInputs {
32 pub window_active: bool,
33 pub composer_empty: bool,
34 pub send_in_flight: bool,
35}
36
37pub fn is_idle(inputs: IdleInputs) -> bool {
38 !inputs.window_active && inputs.composer_empty && !inputs.send_in_flight
39}
40
41pub fn update_is_ready(running: &str, published: Option<&str>, update_exe_exists: bool) -> bool {
42 update_exe_exists
43 && published.is_some_and(|version| {
44 let version = version.trim();
45 !version.is_empty() && version != running
46 })
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct UpdatePaths {
51 pub exe: PathBuf,
52 pub old_exe: PathBuf,
53 pub update_exe: PathBuf,
54 pub version_file: PathBuf,
55}
56
57impl UpdatePaths {
58 pub fn beside(exe: &Path) -> UpdatePaths {
59 let directory = exe.parent().unwrap_or_else(|| Path::new("."));
60 let update_directory = directory.join(UPDATE_DIRECTORY);
61 UpdatePaths {
62 exe: exe.to_owned(),
63 old_exe: directory.join(OLD_EXE_NAME),
64 update_exe: update_directory.join(EXE_NAME),
65 version_file: update_directory.join(VERSION_FILE_NAME),
66 }
67 }
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub enum FileOperation {
72 RemoveIfExists(PathBuf),
73 Rename { from: PathBuf, to: PathBuf },
74}
75
76pub trait FileSystem {
77 fn exists(&self, path: &Path) -> bool;
78 fn rename(&self, from: &Path, to: &Path) -> io::Result<()>;
79 fn remove_file(&self, path: &Path) -> io::Result<()>;
80}
81
82pub struct RealFileSystem;
83
84impl FileSystem for RealFileSystem {
85 fn exists(&self, path: &Path) -> bool {
86 path.exists()
87 }
88
89 fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
90 std::fs::rename(from, to)
91 }
92
93 fn remove_file(&self, path: &Path) -> io::Result<()> {
94 std::fs::remove_file(path)
95 }
96}
97
98pub fn swap_plan(paths: &UpdatePaths) -> Vec<FileOperation> {
99 vec![
100 FileOperation::RemoveIfExists(paths.old_exe.clone()),
101 FileOperation::Rename {
102 from: paths.exe.clone(),
103 to: paths.old_exe.clone(),
104 },
105 FileOperation::Rename {
106 from: paths.update_exe.clone(),
107 to: paths.exe.clone(),
108 },
109 FileOperation::RemoveIfExists(paths.version_file.clone()),
110 ]
111}
112
113fn apply_operation(files: &dyn FileSystem, operation: &FileOperation) -> io::Result<()> {
114 match operation {
115 FileOperation::RemoveIfExists(path) => {
116 if files.exists(path) {
117 files.remove_file(path)?;
118 }
119 Ok(())
120 }
121 FileOperation::Rename { from, to } => files.rename(from, to),
122 }
123}
124
125/// Runs the plan. On failure undoes the completed renames and returns the error.
126pub fn apply_plan(
127 files: &dyn FileSystem,
128 plan: &[FileOperation],
129) -> Result<Vec<FileOperation>, String> {
130 let mut completed = Vec::new();
131 for operation in plan {
132 if let Err(error) = apply_operation(files, operation) {
133 roll_back(files, &completed);
134 return Err(format!("{operation:?}: {error}"));
135 }
136 completed.push(operation.clone());
137 }
138 Ok(completed)
139}
140
141pub fn roll_back(files: &dyn FileSystem, completed: &[FileOperation]) {
142 for operation in completed.iter().rev() {
143 if let FileOperation::Rename { from, to } = operation {
144 let _ = files.rename(to, from);
145 }
146 }
147}
148
149pub fn check(paths: &UpdatePaths) -> bool {
150 let published = std::fs::read_to_string(&paths.version_file).ok();
151 update_is_ready(
152 running_version(),
153 published.as_deref(),
154 paths.update_exe.exists(),
155 )
156}
157
158pub fn current_paths() -> Option<UpdatePaths> {
159 std::env::current_exe()
160 .ok()
161 .map(|exe| UpdatePaths::beside(&exe))
162}
163
164pub fn install_and_relaunch(paths: &UpdatePaths) -> Result<(), String> {
165 let files = RealFileSystem;
166 let completed = apply_plan(&files, &swap_plan(paths))?;
167 match Command::new(&paths.exe)
168 .args(std::env::args_os().skip(1))
169 .env(RELAUNCH_ENV, "1")
170 .spawn()
171 {
172 Ok(_) => Ok(()),
173 Err(error) => {
174 roll_back(&files, &completed);
175 Err(format!("Start: {error}"))
176 }
177 }
178}
179
180pub fn clean_up_old_binary() {
181 let Some(paths) = current_paths() else {
182 return;
183 };
184 if !paths.old_exe.exists() {
185 return;
186 }
187 std::thread::spawn(move || {
188 for _ in 0..CLEANUP_ATTEMPTS {
189 if std::fs::remove_file(&paths.old_exe).is_ok() || !paths.old_exe.exists() {
190 return;
191 }
192 std::thread::sleep(CLEANUP_INTERVAL);
193 }
194 });
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200 use std::fs;
201
202 fn idle() -> IdleInputs {
203 IdleInputs {
204 window_active: false,
205 composer_empty: true,
206 send_in_flight: false,
207 }
208 }
209
210 #[test]
211 fn idle_needs_all_three_conditions() {
212 assert!(is_idle(idle()));
213 assert!(!is_idle(IdleInputs {
214 window_active: true,
215 ..idle()
216 }));
217 assert!(!is_idle(IdleInputs {
218 composer_empty: false,
219 ..idle()
220 }));
221 assert!(!is_idle(IdleInputs {
222 send_in_flight: true,
223 ..idle()
224 }));
225 }
226
227 #[test]
228 fn update_needs_a_different_version_and_an_exe() {
229 assert!(update_is_ready("a-1", Some("b-2\n"), true));
230 assert!(!update_is_ready("a-1", Some("a-1\n"), true));
231 assert!(!update_is_ready("a-1", Some("b-2"), false));
232 assert!(!update_is_ready("a-1", None, true));
233 assert!(!update_is_ready("a-1", Some(" \n"), true));
234 }
235
236 #[test]
237 fn plan_lists_the_operations_in_order() {
238 let paths = UpdatePaths::beside(Path::new("/app/teams.exe"));
239 assert_eq!(paths.update_exe, Path::new("/app/update/teams.exe"));
240 let plan = swap_plan(&paths);
241 assert_eq!(plan.len(), 4);
242 assert_eq!(
243 plan[1],
244 FileOperation::Rename {
245 from: paths.exe.clone(),
246 to: paths.old_exe.clone()
247 }
248 );
249 assert_eq!(
250 plan[2],
251 FileOperation::Rename {
252 from: paths.update_exe.clone(),
253 to: paths.exe.clone()
254 }
255 );
256 }
257
258 fn install(directory: &Path) -> UpdatePaths {
259 let paths = UpdatePaths::beside(&directory.join("teams.exe"));
260 fs::create_dir_all(paths.update_exe.parent().unwrap()).unwrap();
261 fs::write(&paths.exe, "old").unwrap();
262 fs::write(&paths.update_exe, "new").unwrap();
263 fs::write(&paths.version_file, "b-2").unwrap();
264 paths
265 }
266
267 #[test]
268 fn swap_replaces_the_exe_and_keeps_the_old_one() {
269 let directory = tempfile::tempdir().unwrap();
270 let paths = install(directory.path());
271 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
272 assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "new");
273 assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old");
274 assert!(!paths.update_exe.exists());
275 assert!(!paths.version_file.exists());
276 }
277
278 #[test]
279 fn swap_replaces_a_leftover_old_exe() {
280 let directory = tempfile::tempdir().unwrap();
281 let paths = install(directory.path());
282 fs::write(&paths.old_exe, "stale").unwrap();
283 apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap();
284 assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old");
285 }
286
287 struct FailingRename {
288 fail_on: PathBuf,
289 }
290
291 impl FileSystem for FailingRename {
292 fn exists(&self, path: &Path) -> bool {
293 path.exists()
294 }
295
296 fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
297 if from == self.fail_on {
298 return Err(io::Error::other("locked"));
299 }
300 std::fs::rename(from, to)
301 }
302
303 fn remove_file(&self, path: &Path) -> io::Result<()> {
304 std::fs::remove_file(path)
305 }
306 }
307
308 #[test]
309 fn failed_step_rolls_back_so_teams_exe_survives() {
310 let directory = tempfile::tempdir().unwrap();
311 let paths = install(directory.path());
312 let files = FailingRename {
313 fail_on: paths.update_exe.clone(),
314 };
315 let error = apply_plan(&files, &swap_plan(&paths)).unwrap_err();
316 assert!(error.contains("locked"));
317 assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "old");
318 assert!(!paths.old_exe.exists());
319 assert_eq!(fs::read_to_string(&paths.update_exe).unwrap(), "new");
320 assert!(paths.version_file.exists());
321 }
322
323 #[test]
324 fn running_version_has_no_marker_prefix() {
325 assert!(!running_version().starts_with("teams-build:"));
326 assert!(!running_version().is_empty());
327 }
328}