Apply the update through « Redémarrer » or at the next launch (#59)
The settings show « Redémarrer » next to « Mise à jour prête ». It verifies the kept package of the chosen channel again, hands exactly that file to Velopack with `Update.exe apply --waitPid <pid> --package <file>`, then quits as « Quitter » does (WM_QUIT, never hidden in the notification area). Velopack 1.2.161 reads the file in place, waits for the app to exit, replaces current\ and opens the new version once, or the old one again after a failure. After « Quitter », the next launch does the same before loading the app, offline too, but only in the single instance: a shortcut launched while the app runs still just brings its window back (#50). An attempt record, <channel>-<version>.attempt next to the package folder, holds the installer's process id. A launch that finds it never retries on its own: it waits for a running installer (a close second launch, or the old version reopened after a failure), then either leaves the app to the new version or opens the current one with a one-time notice. « Redémarrer » retries; a newer release starts fresh. The record survives a new download of the same version, since Velopack deletes a package it cannot open. Velopack's swap has no rollback between its two renames; this residual risk is recorded in ADR-0005 and docs/paquets-windows.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8e12abf7f4
commit
ab3c6964a5
10 files changed
+549
-47
No files matched your search
@@ -41,6 +41,8 @@ pub enum Error {
|
||||
Config(String),
|
||||
UnknownSeason(String),
|
||||
InvalidUpdate(String),
|
||||
/// The version whose installation did not happen.
|
||||
UpdateFailed(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
@@ -54,6 +56,10 @@ impl fmt::Display for Error {
|
||||
Error::Config(msg) => write!(f, "Configuration invalide : {msg}"),
|
||||
Error::UnknownSeason(name) => write!(f, "Saison inconnue : « {name} »."),
|
||||
Error::InvalidUpdate(why) => write!(f, "Mise à jour refusée : {why}."),
|
||||
Error::UpdateFailed(version) => write!(
|
||||
f,
|
||||
"La mise à jour vers la version {version} n’a pas pu être installée ; la version actuelle reste en place."
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,4 +34,4 @@ pub use statistics::{
|
||||
Statistics, sort_rows,
|
||||
};
|
||||
pub use tracker::{MatchHistorySource, Tracker};
|
||||
pub use update_package::{download_update, verify_release};
|
||||
pub use update_package::{download_update, restart_to_update, update_at_launch, verify_release};
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::fs::{self, File};
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::io::{self, Read};
|
||||
use std::ops::ControlFlow;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::prelude::{BASE64_STANDARD, Engine};
|
||||
@@ -14,6 +15,13 @@ use crate::{Error, SourceError, UpdateChannel};
|
||||
const MAX_DOWNLOAD: u64 = 256 << 20;
|
||||
/// A connection or a read that stalls this long fails; a slow download does not.
|
||||
const STALL: Duration = Duration::from_secs(30);
|
||||
/// Suffix of the file `<channel>-<version>.attempt`, written next to a kept package's folder when
|
||||
/// the package is handed to the installer. It holds the installer's process id, `REPORTED` once
|
||||
/// a failure was shown, or anything else when the launch stopped before knowing the process.
|
||||
/// It outlives a new download of the same version (Velopack deletes a package it cannot open):
|
||||
/// no launch retries that version on its own, only « Redémarrer » does.
|
||||
const ATTEMPT: &str = ".attempt";
|
||||
const REPORTED: &str = "reported";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Manifest {
|
||||
@@ -107,6 +115,122 @@ fn version_order(version: &str) -> Option<[u64; 4]> {
|
||||
parts.next().is_none().then_some(order)
|
||||
}
|
||||
|
||||
/// The order of `version` when `channel` takes it over `installed`: above it, and of its kind.
|
||||
fn newer(version: &str, installed: [u64; 4], channel: UpdateChannel) -> Option<[u64; 4]> {
|
||||
let order = version_order(version)?;
|
||||
// Betas end below u64::MAX, stables at it: a channel only takes its own versions.
|
||||
let beta = channel == UpdateChannel::Beta;
|
||||
(order > installed && (order[3] < u64::MAX) == beta).then_some(order)
|
||||
}
|
||||
|
||||
/// The newest package folder of `channel` kept in `dir` above `installed`, with its version.
|
||||
/// Another channel's folder, which a check may not have removed yet, never counts.
|
||||
fn kept_update(dir: &Path, channel: UpdateChannel, installed: &str) -> Option<(String, PathBuf)> {
|
||||
let installed = version_order(installed)?;
|
||||
let prefix = format!("{}-", channel.name());
|
||||
fs::read_dir(dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let name = entry.file_name().into_string().ok()?;
|
||||
let version = name.strip_prefix(&prefix)?;
|
||||
Some((
|
||||
newer(version, installed, channel)?,
|
||||
version.to_owned(),
|
||||
entry.path(),
|
||||
))
|
||||
})
|
||||
.max_by_key(|(order, ..)| *order)
|
||||
.map(|(_, version, folder)| (version, folder))
|
||||
}
|
||||
|
||||
/// The attempt record of the kept package folder `folder` (see `ATTEMPT`).
|
||||
fn attempt_file(folder: &Path) -> PathBuf {
|
||||
let mut path = folder.as_os_str().to_owned();
|
||||
path.push(ATTEMPT);
|
||||
path.into()
|
||||
}
|
||||
|
||||
/// Authenticates the kept package in `folder` again, then hands exactly that file to `start`,
|
||||
/// which starts the installer on it and returns the installer's process id.
|
||||
fn hand_over(
|
||||
folder: &Path,
|
||||
public_key: &[u8],
|
||||
channel: UpdateChannel,
|
||||
version: &str,
|
||||
start: impl FnOnce(&Path) -> io::Result<u32>,
|
||||
) -> Result<(), Error> {
|
||||
let name = channel.name();
|
||||
verify_release(folder, public_key, name, version)?;
|
||||
let attempt = attempt_file(folder);
|
||||
// Written first: whatever happens next, no launch retries this package on its own.
|
||||
fs::write(&attempt, "").map_err(storage)?;
|
||||
let package = folder.join(format!("ArenaTracker-{version}-{name}-full.nupkg"));
|
||||
let installer = start(&package).map_err(|_| {
|
||||
let _ = fs::write(&attempt, REPORTED);
|
||||
Error::UpdateFailed(version.into())
|
||||
})?;
|
||||
// Lets a launch during the installation wait for it rather than report a failure.
|
||||
let _ = fs::write(&attempt, installer.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs before the app loads, by the single instance only. Hands the kept package of `channel`
|
||||
/// above `installed` to the installer once, through `start` (see `hand_over`). `outcome` waits
|
||||
/// for the installer process with the given id and returns its exit code, or `None` when no such
|
||||
/// installer runs any more. `Break`: the installer replaces this version and opens the app.
|
||||
/// `Continue`: load the app, showing the error if there is one. A failed attempt is reported
|
||||
/// once and never retried from here, so a failing update cannot keep the app from opening.
|
||||
pub fn update_at_launch(
|
||||
dir: &Path,
|
||||
public_key: &[u8],
|
||||
channel: UpdateChannel,
|
||||
installed: &str,
|
||||
start: impl FnOnce(&Path) -> io::Result<u32>,
|
||||
outcome: impl FnOnce(u32) -> Option<u32>,
|
||||
) -> ControlFlow<(), Option<Error>> {
|
||||
let Some((version, folder)) = kept_update(dir, channel, installed) else {
|
||||
return ControlFlow::Continue(None);
|
||||
};
|
||||
let attempt = attempt_file(&folder);
|
||||
let text = match fs::read_to_string(&attempt) {
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
return match hand_over(&folder, public_key, channel, &version, start) {
|
||||
Ok(()) => ControlFlow::Break(()),
|
||||
Err(error) => ControlFlow::Continue(Some(error)),
|
||||
};
|
||||
}
|
||||
// Unreadable: never retried from here, and nothing more is known.
|
||||
Err(_) => return ControlFlow::Continue(None),
|
||||
Ok(text) => text,
|
||||
};
|
||||
if text == REPORTED {
|
||||
return ControlFlow::Continue(None);
|
||||
}
|
||||
// Launched during the installation, or by the installer itself once it is over.
|
||||
if let Ok(installer) = text.parse()
|
||||
&& outcome(installer) == Some(0)
|
||||
{
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
let _ = fs::write(&attempt, REPORTED);
|
||||
ControlFlow::Continue(Some(Error::UpdateFailed(version)))
|
||||
}
|
||||
|
||||
/// « Redémarrer »: hands the kept package of `channel` above `installed` to the installer like
|
||||
/// `update_at_launch`, even after a failed attempt. The app must then quit for the installer.
|
||||
pub fn restart_to_update(
|
||||
dir: &Path,
|
||||
public_key: &[u8],
|
||||
channel: UpdateChannel,
|
||||
installed: &str,
|
||||
start: impl FnOnce(&Path) -> io::Result<u32>,
|
||||
) -> Result<(), Error> {
|
||||
let (version, folder) = kept_update(dir, channel, installed)
|
||||
.ok_or_else(|| Error::InvalidUpdate("paquet introuvable".into()))?;
|
||||
hand_over(&folder, public_key, channel, &version, start)
|
||||
}
|
||||
|
||||
/// Removes the entries of `dir` whose name `matches`, as far as it can: an entry another program
|
||||
/// holds open stays until a later check, and must not hide an authenticated package.
|
||||
fn remove_entries(dir: &Path, matches: impl Fn(&str) -> bool) {
|
||||
@@ -123,7 +247,8 @@ fn remove_entries(dir: &Path, matches: impl Fn(&str) -> bool) {
|
||||
|
||||
/// Keeps the newest release of `channel` above `installed` downloaded and authenticated in
|
||||
/// `dir/<channel>-<version>` and returns its version, or `None` when there is none. Anything
|
||||
/// else in `dir` is removed; another channel's package goes before any network access, so it can
|
||||
/// else in `dir` but that version's attempt record is removed; another channel's package goes
|
||||
/// before any network access, so it can
|
||||
/// never be taken for this channel's. Bytes are downloaded into `dir/partial` and renamed only
|
||||
/// once `verify_release` accepts them. A kept package is verified again instead of downloaded.
|
||||
/// `releases_url` is a Gitea releases API endpoint, where betas are pre-releases.
|
||||
@@ -176,11 +301,9 @@ pub fn download_update(
|
||||
let rest = asset.name.strip_prefix("ArenaTracker-")?;
|
||||
rest.strip_suffix(&format!("-{name}-full.nupkg"))
|
||||
})?;
|
||||
let order = version_order(version)?;
|
||||
// Betas end below u64::MAX, stables at it: a channel only takes its own versions.
|
||||
let order = newer(version, installed, channel)?;
|
||||
let complete = manifest_files.iter().all(|file| has(file));
|
||||
(order > installed && (order[3] < u64::MAX) == beta && complete)
|
||||
.then_some((order, version, release))
|
||||
complete.then_some((order, version, release))
|
||||
})
|
||||
.max_by_key(|(order, ..)| *order);
|
||||
let Some((_, version, release)) = newest else {
|
||||
@@ -189,8 +312,10 @@ pub fn download_update(
|
||||
};
|
||||
|
||||
let kept = format!("{name}-{version}");
|
||||
let attempt = format!("{kept}{ATTEMPT}");
|
||||
let others = |entry: &str| entry != kept && entry != attempt;
|
||||
if verify_release(&dir.join(&kept), public_key, name, version).is_ok() {
|
||||
remove_entries(dir, |entry| entry != kept);
|
||||
remove_entries(dir, others);
|
||||
return Ok(Some(version.into()));
|
||||
}
|
||||
// An older package of this channel stays until the newer one is ready.
|
||||
@@ -220,7 +345,7 @@ pub fn download_update(
|
||||
return Err(error);
|
||||
}
|
||||
fs::rename(&partial, dir.join(&kept)).map_err(storage)?;
|
||||
remove_entries(dir, |entry| entry != kept);
|
||||
remove_entries(dir, others);
|
||||
Ok(Some(version.into()))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::path::Path;
|
||||
use std::ops::ControlFlow;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::thread;
|
||||
|
||||
use arena_tracker_core::{Error, UpdateChannel, download_update, verify_release};
|
||||
use arena_tracker_core::{
|
||||
Error, UpdateChannel, download_update, restart_to_update, update_at_launch, verify_release,
|
||||
};
|
||||
use base64::prelude::{BASE64_STANDARD, Engine};
|
||||
use ring::digest;
|
||||
use ring::signature::{Ed25519KeyPair, KeyPair};
|
||||
@@ -367,3 +370,181 @@ fn network_and_signature_failures_leave_no_update_ready() {
|
||||
unsigned.files.remove(0);
|
||||
assert_eq!(check(&serve(vec![unsigned], false).0).unwrap(), None);
|
||||
}
|
||||
|
||||
/// Keeps `version` of `channel` in `dir` as a finished download would, and returns its package.
|
||||
fn keep(dir: &Path, key: &Ed25519KeyPair, channel: &str, version: &str) -> PathBuf {
|
||||
let folder = dir.join(format!("{channel}-{version}"));
|
||||
fs::create_dir(&folder).unwrap();
|
||||
for (name, bytes) in publish(key, channel, version).files {
|
||||
fs::write(folder.join(name), bytes).unwrap();
|
||||
}
|
||||
folder.join(format!("ArenaTracker-{version}-{channel}-full.nupkg"))
|
||||
}
|
||||
|
||||
type Start<'a> = &'a mut dyn FnMut(&Path) -> std::io::Result<u32>;
|
||||
type Outcome<'a> = &'a mut dyn FnMut(u32) -> Option<u32>;
|
||||
|
||||
fn never_started(_: &Path) -> std::io::Result<u32> {
|
||||
panic!("the installer must not start")
|
||||
}
|
||||
|
||||
fn no_installer(_: u32) -> Option<u32> {
|
||||
panic!("no installer was started")
|
||||
}
|
||||
|
||||
/// Records each package handed to the installer, which gets process id `pid`.
|
||||
fn recording(started: &mut Vec<PathBuf>, pid: u32) -> impl FnMut(&Path) -> std::io::Result<u32> {
|
||||
move |package| {
|
||||
started.push(package.to_owned());
|
||||
Ok(pid)
|
||||
}
|
||||
}
|
||||
|
||||
type Launch = ControlFlow<(), Option<Error>>;
|
||||
|
||||
/// The installer replaces this version and opens the app.
|
||||
fn applying(launch: &Launch) -> bool {
|
||||
matches!(launch, ControlFlow::Break(()))
|
||||
}
|
||||
|
||||
fn loads_quietly(launch: &Launch) -> bool {
|
||||
matches!(launch, ControlFlow::Continue(None))
|
||||
}
|
||||
|
||||
fn reports_failed(launch: &Launch, version: &str) -> bool {
|
||||
matches!(launch, ControlFlow::Continue(Some(Error::UpdateFailed(failed))) if failed == version)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_launch_hands_the_chosen_channels_package_to_the_installer_once() {
|
||||
let key = key();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let public = key.public_key().as_ref();
|
||||
let stable = keep(dir.path(), &key, "stable", "1.1.0");
|
||||
keep(dir.path(), &key, "stable", "1.0.1");
|
||||
// Left from before a change to Stable, until the next check removes it.
|
||||
let beta = keep(dir.path(), &key, "beta", "1.2.0-beta.1");
|
||||
let launch = |channel, installed, start: Start, outcome: Outcome| {
|
||||
update_at_launch(dir.path(), public, channel, installed, start, outcome)
|
||||
};
|
||||
let stable_launch =
|
||||
|start: Start, outcome: Outcome| launch(UpdateChannel::Stable, "1.0.0", start, outcome);
|
||||
|
||||
let mut started = Vec::new();
|
||||
let first = stable_launch(&mut recording(&mut started, 42), &mut no_installer);
|
||||
assert!(applying(&first), "{first:?}");
|
||||
assert_eq!(started, [stable]);
|
||||
|
||||
// A launch while the installer runs waits for it and leaves the app to the version it opens.
|
||||
let succeeded = stable_launch(&mut never_started, &mut |pid| (pid == 42).then_some(0));
|
||||
assert!(applying(&succeeded), "{succeeded:?}");
|
||||
// After a failure the version in place loads and says so once, then never retries on its own.
|
||||
let failed = stable_launch(&mut never_started, &mut |_| Some(1));
|
||||
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
|
||||
let next = stable_launch(&mut never_started, &mut no_installer);
|
||||
assert!(loads_quietly(&next), "{next:?}");
|
||||
|
||||
// « Redémarrer » retries it; an installer that is gone counts as failed.
|
||||
let restart = restart_to_update(dir.path(), public, UpdateChannel::Stable, "1.0.0", |_| {
|
||||
Ok(43)
|
||||
});
|
||||
assert!(restart.is_ok());
|
||||
let gone = stable_launch(&mut never_started, &mut |pid| (pid != 43).then_some(0));
|
||||
assert!(reports_failed(&gone, "1.1.0"), "{gone:?}");
|
||||
|
||||
// Once the new version is installed, nothing is left to apply.
|
||||
let installed = launch(
|
||||
UpdateChannel::Stable,
|
||||
"1.1.0",
|
||||
&mut never_started,
|
||||
&mut no_installer,
|
||||
);
|
||||
assert!(loads_quietly(&installed), "{installed:?}");
|
||||
// The Bêta channel takes only its own package.
|
||||
let mut started = Vec::new();
|
||||
let beta_launch = launch(
|
||||
UpdateChannel::Beta,
|
||||
"1.1.0",
|
||||
&mut recording(&mut started, 44),
|
||||
&mut no_installer,
|
||||
);
|
||||
assert!(applying(&beta_launch), "{beta_launch:?}");
|
||||
assert_eq!(started, [beta]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_altered_package_or_an_installer_that_cannot_start_leaves_the_installed_version() {
|
||||
let key = key();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let public = key.public_key().as_ref();
|
||||
let package = keep(dir.path(), &key, "stable", "1.1.0");
|
||||
let launch = |start: Start| {
|
||||
update_at_launch(
|
||||
dir.path(),
|
||||
public,
|
||||
UpdateChannel::Stable,
|
||||
"1.0.0",
|
||||
start,
|
||||
no_installer,
|
||||
)
|
||||
};
|
||||
|
||||
// Altered between the download and this launch: refused before the installer sees it.
|
||||
fs::write(&package, b"altered").unwrap();
|
||||
let refused = launch(&mut never_started);
|
||||
assert!(
|
||||
matches!(
|
||||
refused,
|
||||
ControlFlow::Continue(Some(Error::InvalidUpdate(_)))
|
||||
),
|
||||
"{refused:?}"
|
||||
);
|
||||
let restart = restart_to_update(
|
||||
dir.path(),
|
||||
public,
|
||||
UpdateChannel::Stable,
|
||||
"1.0.0",
|
||||
never_started,
|
||||
);
|
||||
assert!(matches!(restart, Err(Error::InvalidUpdate(_))));
|
||||
|
||||
// Downloaded again, then the installer cannot start: reported, and no launch loops on it.
|
||||
fs::write(&package, b"package 1.1.0").unwrap();
|
||||
let failed = launch(&mut |_| Err(std::io::ErrorKind::NotFound.into()));
|
||||
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
|
||||
let next = launch(&mut never_started);
|
||||
assert!(loads_quietly(&next), "{next:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_downloaded_again_after_a_failed_installation_is_not_retried_at_launch() {
|
||||
let key = key();
|
||||
let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let public = key.public_key().as_ref();
|
||||
let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
|
||||
let launch = |start: Start, outcome: Outcome| {
|
||||
update_at_launch(
|
||||
dir.path(),
|
||||
public,
|
||||
UpdateChannel::Stable,
|
||||
"1.0.0",
|
||||
start,
|
||||
outcome,
|
||||
)
|
||||
};
|
||||
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
|
||||
assert!(applying(&launch(&mut |_| Ok(42), &mut no_installer)));
|
||||
|
||||
// Velopack deletes a package it cannot open, then reopens the version in place.
|
||||
let package = dir
|
||||
.path()
|
||||
.join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg");
|
||||
fs::remove_file(&package).unwrap();
|
||||
let failed = launch(&mut never_started, &mut |_| Some(1));
|
||||
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
|
||||
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
|
||||
assert_eq!(downloads.load(Ordering::SeqCst), 2);
|
||||
let next = launch(&mut never_started, &mut no_installer);
|
||||
assert!(loads_quietly(&next), "{next:?}");
|
||||
}
|
||||
Reference in new issue
Block a user