Merge storytold main into next (17 Nov sync)

storytold main 83cb1133dd (291 commits) into the integration head bab1a99b85; 47 conflicted files.

- Domain test files (metafile, prepress, pdf plates, settings store, heif, media-testkit, atomic): tests next cut stay cut; tests new on main are kept, as trials where the crate's test target runs trials.
- atomic: main's group-bits test and Faulty::set_group go to src/tests.rs. audio: main's GSM and SBC oracles join tests/main.rs. cms constructors, pdf knockout_backdrop and testing_pdf join their crates' one test binary; timeline's preflight tests become src/preflight_tests.rs trials.
- update: main's changes to detect, install (linux, macos) and the tests land in next's split modules. The app's own offer is inspected on a thread of its own, picked up by tick's polling; settle_for_tests settles offers too. Later on a ready update drops the close it asked for. updater_pin_tests.rs stays deleted; its new pin test is in tests/it/update.rs.
- craft-color: main added a different crate at crates/color (the colour tags of compositor and display frames); it is next's craft-color module `tags`, re-exported at the root.
- Old crates/ui (combo, docking, testing, README) and keymap's ui/view.rs stay deleted; main's new crates/ui/src/testing files are dropped with them.
- New crates in the craft facade: ai, control, dds, frame, ipc, media-source, palette, press-print, score, ssip. testkit and xtask are listed outside it.
- Cargo.lock: the union of both locks, resolved by cargo metadata. Workflow: main's nextest Windows leg, with next's --keep-going clippy.
This commit is contained in:
aiongg
2026-11-17 12:44:52 +00:00
581 changed files with 77998 additions and 3002 deletions
+3
View File
@@ -68,6 +68,9 @@ fn from_manifest(app: &App, manifest: &Manifest) -> Option<Installed> {
source: InstallSource::Launcher,
location: rec.path.display().to_string(),
package: None,
externally_managed: false,
origin: None,
installation: None,
})
}
+9 -1
View File
@@ -10,7 +10,15 @@ pub fn detect(app: &App) -> Option<Installed> {
if !bin.exists() {
return None;
}
Some(Installed { version: binary_version(&bin, app), source: InstallSource::Binary, location: bin.display().to_string(), package: None })
Some(Installed {
version: binary_version(&bin, app),
source: InstallSource::Binary,
location: bin.display().to_string(),
package: None,
externally_managed: true,
origin: None,
installation: None,
})
}
/// `<app> --version` prints `<app> 0.5.0 (sha, date)`.
+67 -10
View File
@@ -20,7 +20,14 @@ pub fn packages() -> Vec<Package> {
let t = Duration::from_secs(10);
let mut out = Vec::new();
let mut add = |manager, list: Vec<(String, String)>| {
out.extend(list.into_iter().filter(|(n, _)| ours(n)).map(|(name, version)| Package { manager, name, version }));
out.extend(list.into_iter().filter(|(n, _)| ours(n)).map(|(name, version)| Package {
manager,
name,
version,
user: false,
origin: None,
installation: None,
}));
};
if let Some(list) = capture("dpkg-query", &["-W", "-f", "${Package}|${db:Status-Status}|${Version}\n"], t) {
add(InstallSource::Deb, packages::parse_dpkg(&list));
@@ -36,15 +43,28 @@ pub fn packages() -> Vec<Package> {
add(InstallSource::Pacman, packages::parse_pacman(&list));
}
let arch = format!("--arch={}", std::env::consts::ARCH);
if let Some(list) = crate::process::capture_flatpak(&["list", "--app", &arch, "--columns=application,version"], t) {
let mut flatpaks = packages::parse_flatpak_list(&list);
if let Some(list) = crate::process::capture_flatpak(&["list", "--app", &arch, "--columns=application,version,origin,installation"], t) {
let mut flatpaks = packages::parse_flatpak_list_with_origin(&list);
// Bundles built from a release tarball often list no version: ask Flatpak directly.
for (id, version) in flatpaks.iter_mut().filter(|(id, v)| v.is_empty() && id.starts_with("ai.storyteller.")) {
if let Some(v) = crate::process::capture_flatpak(&["info", &arch, id], t).as_deref().and_then(packages::parse_flatpak_info) {
for (id, version, _, installation) in flatpaks.iter_mut().filter(|(id, v, _, _)| v.is_empty() && id.starts_with("ai.storyteller.")) {
let custom_scope;
let scope_arg = match installation.as_deref() {
Some("user") => vec!["--user"],
Some("system") | None => vec!["--system"],
Some(named) => {
custom_scope = format!("--installation={named}");
vec![custom_scope.as_str()]
}
};
let info_args = [&["info"][..], &scope_arg, &[&arch, id]].concat();
if let Some(v) = crate::process::capture_flatpak(&info_args, t).as_deref().and_then(packages::parse_flatpak_info) {
*version = v;
}
}
add(InstallSource::Flatpak, flatpaks);
out.extend(flatpaks.into_iter().filter(|(n, _, _, _)| ours(n)).map(|(name, version, origin, installation)| {
let is_user = installation.as_deref() == Some("user");
Package { manager: InstallSource::Flatpak, name, version, user: is_user, origin, installation }
}));
}
out
}
@@ -121,12 +141,41 @@ pub fn appimages(app: &App) -> Vec<(PathBuf, Option<version::Version>)> {
/// Flatpak package, then a binary on `PATH`.
pub fn detect(app: &App, snapshot: &Snapshot) -> Option<Installed> {
if let Some((path, version)) = appimages(app).into_iter().next() {
return Some(Installed { version, source: InstallSource::AppImage, location: path.display().to_string(), package: None });
return Some(Installed {
version,
source: InstallSource::AppImage,
location: path.display().to_string(),
package: None,
externally_managed: false,
origin: None,
installation: None,
});
}
let order = [InstallSource::Deb, InstallSource::Rpm, InstallSource::Pacman, InstallSource::Flatpak];
if let Some(p) = packages::find(app, &snapshot.packages, &order) {
let location = if p.manager == InstallSource::Flatpak { app.bundle_id() } else { binary_on_path(app.id) };
return Some(Installed { version: packages::version_of(p), source: p.manager, location, package: Some(p.name.clone()) });
let location = if p.manager == InstallSource::Flatpak { p.name.clone() } else { binary_on_path(app.id) };
let externally_managed = p.manager == InstallSource::Flatpak
&& p.origin.as_deref().is_none_or(|origin| {
if packages::is_flatpark_origin(origin) {
return true;
}
let scope = match p.installation.as_deref() {
Some("user") => "--user".to_string(),
Some("system") | None => "--system".to_string(),
Some(name) => format!("--installation={name}"),
};
crate::process::capture_flatpak(&["remotes", &scope, "--show-disabled", "--columns=name,url"], Duration::from_secs(10))
.is_none_or(|remotes| packages::remote_manages_flatpak(origin, &remotes))
});
return Some(Installed {
version: packages::version_of(p),
source: p.manager,
location,
package: Some(p.name.clone()),
externally_managed,
origin: p.origin.clone(),
installation: p.installation.clone(),
});
}
detect_system_install(app)
}
@@ -137,7 +186,15 @@ pub fn detect(app: &App, snapshot: &Snapshot) -> Option<Installed> {
/// to whatever installed it, since it can't tell which package manager that was.
fn detect_system_install(app: &App) -> Option<Installed> {
let bin = find_binary(app.id)?;
Some(Installed { version: binary_version(&bin, app), source: InstallSource::Binary, location: bin.display().to_string(), package: None })
Some(Installed {
version: binary_version(&bin, app),
source: InstallSource::Binary,
location: bin.display().to_string(),
package: None,
externally_managed: true,
origin: None,
installation: None,
})
}
fn find_binary(id: &str) -> Option<PathBuf> {
+9 -1
View File
@@ -30,5 +30,13 @@ pub fn read_bundle(app: &App, path: &Path) -> Option<Installed> {
let full_key = format!("{}Version", app.name);
let text =
[full_key.as_str(), "CFBundleShortVersionString", "CFBundleVersion"].iter().find_map(|k| dict.get(k).and_then(plist::Value::as_string));
Some(Installed { version: text.and_then(version::parse), source: InstallSource::MacApp, location: path.display().to_string(), package: None })
Some(Installed {
version: text.and_then(version::parse),
source: InstallSource::MacApp,
location: path.display().to_string(),
package: None,
externally_managed: false,
origin: None,
installation: None,
})
}
+107
View File
@@ -127,3 +127,110 @@ fn recognises_appimage_names_conservatively() {
assert_eq!(v(other), None, "{other}");
}
}
/// The launcher's own record is the first thing detection trusts, and its source is the
/// launcher rather than whatever installed the file underneath.
#[trial]
fn a_manifest_record_for_a_file_that_is_there_is_a_launcher_install() {
let app = App::by_id("photocraft").unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("photocraft.AppImage");
std::fs::write(&path, b"").unwrap();
let mut manifest = crate::manifest::Manifest::default();
manifest.apps.insert(
app.id.to_string(),
crate::manifest::Record {
version: "0.6.1".into(),
kind: crate::PackageKind::AppImage,
path: path.clone(),
installed_at: 0,
files: Vec::new(),
needs_root: false,
},
);
let found = from_manifest(app, &manifest).expect("the record names a file that is there");
assert_eq!(found.source, InstallSource::Launcher);
assert_eq!(found.version.map(|v| v.to_string()).as_deref(), Some("0.6.1"));
assert_eq!(found.location, path.display().to_string());
assert!(!found.externally_managed);
assert_eq!(found.origin, None);
assert_eq!(found.installation, None);
}
/// A record whose file the user removed is not an install, so detection keeps looking.
#[trial]
fn a_manifest_record_for_a_file_that_is_gone_is_not_an_install() {
let app = App::by_id("photocraft").unwrap();
let dir = tempfile::tempdir().unwrap();
let mut manifest = crate::manifest::Manifest::default();
manifest.apps.insert(
app.id.to_string(),
crate::manifest::Record {
version: "0.6.0".into(),
kind: crate::PackageKind::AppImage,
path: dir.path().join("gone.AppImage"),
installed_at: 0,
files: Vec::new(),
needs_root: false,
},
);
assert!(from_manifest(app, &manifest).is_none());
}
/// A package the snapshot already found, as the launcher sees it after a package-manager
/// query: only the fields detection reads are varied.
#[cfg(target_os = "linux")]
fn injected(manager: InstallSource, installation: Option<&str>, origin: Option<&str>) -> crate::packages::Package {
crate::packages::Package {
manager,
name: match manager {
InstallSource::Flatpak => "ai.storyteller.photocraft".to_string(),
_ => "photocraft".to_string(),
},
version: "0.6.2".into(),
user: installation == Some("user"),
origin: origin.map(str::to_string),
installation: installation.map(str::to_string),
}
}
#[cfg(target_os = "linux")]
#[trial]
fn a_deb_package_is_reported_with_its_manager_and_version() {
let app = App::by_id("photocraft").unwrap();
let snapshot = Snapshot { packages: vec![injected(InstallSource::Deb, None, None)] };
let found = linux::detect(app, &snapshot).expect("the injected package is installed");
assert_eq!(found.source, InstallSource::Deb);
assert_eq!(found.version.map(|v| v.to_string()).as_deref(), Some("0.6.2"));
assert_eq!(found.package.as_deref(), Some("photocraft"));
assert!(!found.externally_managed);
assert_eq!(found.installation, None);
}
/// A Flatpak from a remote the launcher doesn't drive stays externally managed, in every
/// scope the `flatpak remotes` query can need.
#[cfg(target_os = "linux")]
#[trial]
fn a_flatpak_from_a_repository_remote_is_externally_managed() {
let app = App::by_id("photocraft").unwrap();
for installation in [Some("user"), Some("system"), Some("custom"), None] {
let snapshot = Snapshot { packages: vec![injected(InstallSource::Flatpak, installation, Some("flathub"))] };
let found = linux::detect(app, &snapshot).expect("the injected Flatpak is installed");
assert_eq!(found.source, InstallSource::Flatpak);
assert!(found.externally_managed, "{installation:?}");
assert_eq!(found.location, "ai.storyteller.photocraft");
assert_eq!(found.origin.as_deref(), Some("flathub"));
assert_eq!(found.installation.as_deref(), installation);
}
}
/// FlatPark's own remote is known to manage the copy without asking flatpak again.
#[cfg(target_os = "linux")]
#[trial]
fn a_flatpark_flatpak_is_externally_managed_without_asking_its_remotes() {
let app = App::by_id("photocraft").unwrap();
let snapshot = Snapshot { packages: vec![injected(InstallSource::Flatpak, Some("user"), Some("flatpark"))] };
let found = linux::detect(app, &snapshot).expect("the injected Flatpak is installed");
assert!(found.externally_managed);
assert_eq!(found.origin.as_deref(), Some("flatpark"));
}
+3
View File
@@ -102,5 +102,8 @@ pub fn detect(app: &App) -> Option<Installed> {
source: InstallSource::Msi,
location: m.exe.map_or_else(|| app.name.to_string(), |p| p.display().to_string()),
package: Some(m.product_code),
externally_managed: false,
origin: None,
installation: None,
})
}
+43 -2
View File
@@ -99,6 +99,11 @@ pub fn install_at(
{
not_running(app, process::running(Path::new(&inst.location)))?;
}
if kind == PackageKind::Flatpak
&& let Some(installed) = existing.filter(|installed| installed.source == InstallSource::Flatpak && installed.externally_managed)
{
return Err(managed_elsewhere(app, installed, false).unwrap_or_else(|| "Update this app through its Flatpak repository".into()));
}
bind_artifact_version(app, release, asset)?;
if !job.replace
&& let Some(inst) = existing
@@ -109,6 +114,16 @@ pub fn install_at(
}
check_download_link(app, release, asset)?;
log::info!("{}: starting {} to {} ({})", app.name, if existing.is_some() { "update" } else { "install" }, release.version_label(), kind.label());
#[cfg(all(target_os = "linux", feature = "oci_migration"))]
if kind == PackageKind::Flatpak
&& !job.replace
&& !release.prerelease
&& let Some(installed) = existing
&& let Some(expected) = release.version.as_ref()
&& linux::migrate_bundle_to_oci(app, installed, expected, job.stop)?
{
return Ok(None);
}
let file = download(release, asset, job)?;
log::info!("{}: download ready ({}), running installer...", app.name, file.display());
// Past this point the install can't be interrupted halfway.
@@ -366,6 +381,9 @@ pub(crate) fn choose_kinds_with(
// opens and removes them but never replaces them.
InstallSource::Pacman if is_release_arch_package(app, inst) => Some(PackageKind::ArchPkg),
InstallSource::Pacman => return Vec::new(),
// Repository-managed Flatpaks are externally managed: the launcher will not
// replace them with a downloaded local .flatpak bundle.
InstallSource::Flatpak if inst.externally_managed => return Vec::new(),
InstallSource::Flatpak => Some(PackageKind::Flatpak),
InstallSource::AppImage => Some(PackageKind::AppImage),
InstallSource::Binary => Some(PackageKind::TarGz),
@@ -466,6 +484,16 @@ fn managed_elsewhere_with(app: &App, installed: &Installed, uninstall: bool, rep
let pkg = installed.package.clone().unwrap_or_else(|| app.id.to_string());
Some(pacman_update_hint(app, &pkg, repo_fn(&pkg).as_deref()))
}
InstallSource::Flatpak if !uninstall && installed.externally_managed => {
let default_pkg = app.bundle_id();
let pkg = installed.package.as_deref().unwrap_or(&default_pkg);
let scope = match installed.installation.as_deref() {
Some("user") => "--user".to_string(),
Some("system") | None => "--system".to_string(),
Some(name) => format!("--installation={name}"),
};
Some(format!("{} was installed from a Flatpak repository. Update it with flatpak update {scope} {pkg}", app.name))
}
InstallSource::Binary => Some(format!("{} was installed outside the launcher. Update or remove it the way it was installed.", app.name)),
_ => None,
}
@@ -656,12 +684,18 @@ fn prepare_home(home: &Path) {
}
}
/// The start of the name of the folder [`staging_dir`] makes. Six random letters and digits
/// follow it.
#[cfg(target_os = "linux")]
const STAGING: &str = ".artcraft-launcher-";
/// A new folder of our own inside `dir`, removed when dropped: a predictable name there may be
/// the user's.
#[cfg(target_os = "linux")]
fn staging_dir(dir: &Path) -> Result<tempfile::TempDir, String> {
tempfile::Builder::new()
.prefix(".artcraft-launcher-")
.prefix(STAGING)
.rand_bytes(6)
.tempdir_in(dir)
.map_err(|e| format!("couldn't create a staging folder in {} ({e})", dir.display()))
}
@@ -808,8 +842,15 @@ fn cancelled(stop: &Stop) -> impl Fn() -> bool + '_ {
|| stop.check().is_err_and(|e| e == crate::protocol::CANCELLED)
}
/// For a running helper command: only CANCELLED ends it. PAUSED lets the current command finish
/// (callers check `stop` before starting the next one).
#[cfg(target_os = "linux")]
pub(crate) mod linux;
fn kill_on_cancel(stop: &Stop) -> impl Fn() -> Result<(), String> + '_ {
|| if cancelled(stop)() { Err(crate::protocol::CANCELLED.into()) } else { Ok(()) }
}
#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(target_os = "macos")]
pub mod macos;
+168 -1
View File
@@ -10,7 +10,7 @@ use crate::version::{self, Version};
use super::{
App, INSTALLER, InstallSource, Installed, JobPhase, PackageKind, Path, PathBuf, Paths, Record, SHARED_CALL, SYSTEM_BIN_DIRS, Stop, cancelled,
find_in, pkexec, process, run_as_root, swap_into_place, tree, turn,
find_in, kill_on_cancel, pkexec, process, run_as_root, swap_into_place, tree, turn,
};
/// apt waits this long for another package tool (a software centre, automatic updates) to
@@ -262,6 +262,125 @@ fn install_flatpak_bundle_via(
root.queue.alone(&cancelled(stop), &mut turn(phase, JobPhase::Installing), install).unwrap_or(Err(CANCELLED.into()))
}
/// Opt-in OCI migration; only an absent ref permits bundle fallback.
#[cfg(feature = "oci_migration")]
pub fn migrate_bundle_to_oci(app: &App, installed: &Installed, expected: &super::version::Version, stop: &Stop) -> Result<bool, String> {
if installed.source != InstallSource::Flatpak || installed.externally_managed || !app.repo.starts_with("storytold/") {
return Ok(false);
}
// Only bundle-created origins qualify; never redirect another repository's install.
if !installed.origin.as_deref().is_some_and(|origin| origin.ends_with("-origin")) {
return Ok(false);
}
let id = installed.package.as_deref().ok_or("Flatpak installation has no package ID")?;
let scope = match installed.installation.as_deref() {
Some("user") => "--user".to_string(),
Some("system") => "--system".to_string(),
Some(name) => format!("--installation={name}"),
None => return Err("Flatpak installation scope is unknown".into()),
};
// `cancellable` is false for steps that must not stop part-way: killing flatpak-spawn
// doesn't wait for the host transaction, and `--reinstall` removes the old ref first.
let flatpak = |args: &[&str], cancellable: bool| -> Result<String, String> {
let mut cmd = if process::in_sandbox() {
let mut cmd = process::command("flatpak-spawn");
cmd.args(["--host", "--watch-bus", "flatpak"]);
cmd
} else {
process::command("flatpak")
};
cmd.arg(&scope).args(args);
if cancellable {
stop.check()?; // paused or cancelled: start no further command
}
let end = kill_on_cancel(stop);
let output = process::cancellable_output(cmd, || if cancellable { end() } else { Ok(()) })?;
if !output.status.success() {
return Err(format!("Flatpak OCI migration failed: {}", String::from_utf8_lossy(&output.stderr).trim()));
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
};
let run = |args: &[&str]| flatpak(args, true);
let reference = run(&["info", "--show-ref", id])?;
let reference = reference.trim();
if !reference.starts_with(&format!("app/{id}/")) || !reference.ends_with("/stable") {
return Ok(false);
}
let remotes = run(&["remotes", "--show-disabled", "--columns=name,url"])?;
let remote = remotes.lines().find_map(|line| {
let (name, _) = line.split_once('\t')?;
crate::packages::is_artcraft_remote(name, line).then(|| name.to_string())
});
let remote = match remote {
Some(remote) => remote,
None => {
if remotes.lines().any(|line| line.split('\t').next() == Some("artcraft-oci")) {
return Err("The artcraft-oci remote points to a different repository".into());
}
// Another app's migration may add the remote first; the URL is checked below.
run(&["remote-add", "--if-not-exists", "artcraft-oci", "https://getartcraft.com/artcraft-oci.flatpakrepo"])?;
let remotes = run(&["remotes", "--show-disabled", "--columns=name,url"])?;
if !crate::packages::is_artcraft_remote("artcraft-oci", &remotes) {
return Err("The ArtCraft OCI descriptor configured an unexpected repository".into());
}
"artcraft-oci".to_string()
}
};
// The Version column comes from the remote's AppStream catalog, which Flatpak only fetches
// on demand; without a refresh a new remote lists refs with empty versions.
run(&["update", "--appstream", &remote])?;
let refs = run(&["remote-ls", "--app", "--columns=ref,version", &remote])?;
if !crate::packages::oci_ref_available(reference, expected, &refs)? {
return Ok(false);
}
stop.check()?;
if let Err(e) = flatpak(&["install", "--reinstall", "-y", "--noninteractive", &remote, reference], false) {
// The bundle origin has no repository to restore from, so point at the bundle itself.
if flatpak(&["info", id], false).is_err() {
return Err(format!("{e}. {} is no longer installed; reinstall it from the .flatpak bundle at {}", app.name, app.releases_url()));
}
return Err(e);
}
let origin = run(&["info", "--show-origin", id])?;
if origin.trim() != remote {
return Err("Flatpak did not switch the installed app to the ArtCraft OCI remote".into());
}
Ok(true)
}
/// Updates an installed Flatpak from its remote repository (such as FlatPark).
pub fn update_flatpak_app(app: &App, id: &str, installation: Option<&str>, stop: &Stop, phase: &mut dyn FnMut(JobPhase)) -> Result<(), String> {
phase(JobPhase::Installing);
stop.check()?;
let scope_arg = match installation {
Some("user") => "--user".to_string(),
Some("system") | None => "--system".to_string(),
Some(named) => format!("--installation={named}"),
};
// Let Flatpak's system helper authorize system updates through polkit.
// watch-bus also terminates the host command if the sandbox proxy exits.
let mut cmd = if process::in_sandbox() {
let mut command = process::command("flatpak-spawn");
command.args(["--host", "--watch-bus", "flatpak"]);
command
} else {
process::command("flatpak")
};
cmd.args(["update", &scope_arg, "-y", "--noninteractive", id]);
let output = process::cancellable_output(cmd, kill_on_cancel(stop))?;
if output.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&output.stderr);
let err = stderr.trim();
if err.is_empty() {
Err(format!("Flatpak couldn't update {}", app.name))
} else {
let clean = err.strip_prefix("error: ").or_else(|| err.strip_prefix("Error: ")).unwrap_or(err);
Err(format!("Flatpak couldn't update {}: {clean}", app.name))
}
}
/// Whether a bundle install of `id` failed because the installation already has the bundle's
/// commit: Flatpak's "already installed", in the C locale. Any other failure leaves the app alone.
pub(crate) fn already_installed(err: &str, id: &str) -> bool {
@@ -365,6 +484,7 @@ pub fn install_appimage(
if std::fs::symlink_metadata(&dest).is_ok_and(|m| m.is_dir() || !(replace || ours && m.is_file())) {
return Err(format!("{} already exists and wasn't installed by ArtCraft Launcher", dest.display()));
}
clear_staging(&dir, std::time::SystemTime::now());
let staging = super::staging_dir(&dir)?;
let partial = staging.path().join(name);
std::fs::copy(file, &partial).map_err(|e| format!("couldn't copy the AppImage ({e})"))?;
@@ -381,6 +501,53 @@ pub fn install_appimage(
Ok((dest, removed))
}
/// How long a staging folder stays unchanged before it counts as left by an AppImage install
/// that ended partway.
const STAGING_AGE: Duration = Duration::from_secs(24 * 60 * 60);
/// Removes the staging folders in `dir` of AppImage installs that ended partway, with the
/// partial copies in them: folders named as [`super::STAGING`] describes that hold nothing or
/// only one regular file named `*.AppImage`, and have not changed for [`STAGING_AGE`] before
/// `now`. Other folders, backup folders included, are left alone. Failures are logged and the
/// install goes on.
pub(crate) fn clear_staging(dir: &Path, now: std::time::SystemTime) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let random = |rest: &str| rest.len() == 6 && rest.bytes().all(|b| b.is_ascii_alphanumeric());
for folder in entries.flatten() {
let path = folder.path();
let ours = folder.file_name().to_str().and_then(|n| n.strip_prefix(super::STAGING)).is_some_and(random);
if !ours || !folder.file_type().is_ok_and(|t| t.is_dir()) || !left_by_install(&path, now) {
continue;
}
match std::fs::remove_dir_all(&path) {
Ok(()) => log::info!("removed {}, left by an install that ended partway", path.display()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => log::warn!("couldn't remove {}, left by an install that ended partway ({e})", path.display()),
}
}
}
/// Whether `folder` holds nothing or only one regular file named `*.AppImage`, and neither the
/// folder nor that file has changed for [`STAGING_AGE`] before `now`.
fn left_by_install(folder: &Path, now: std::time::SystemTime) -> bool {
let unchanged = |path: &Path| {
std::fs::symlink_metadata(path).and_then(|m| m.modified()).is_ok_and(|at| now.duration_since(at).is_ok_and(|age| age >= STAGING_AGE))
};
let Ok(entries) = std::fs::read_dir(folder) else { return false };
let names: Vec<_> = entries.take(2).map(|e| e.map(|e| e.file_name())).collect();
let partial = match names.as_slice() {
[] => true,
[Ok(only)] => {
let copy = folder.join(only);
Path::new(only).extension().is_some_and(|ext| ext.eq_ignore_ascii_case("AppImage"))
&& std::fs::symlink_metadata(&copy).is_ok_and(|m| m.is_file())
&& unchanged(&copy)
}
_ => false,
};
partial && unchanged(folder)
}
/// Unpacks a release tarball (`bin/<app>`, `share/…`) into `<data>/apps/<app>`, a folder
/// only the launcher owns, and returns the app's binary. This is the fallback for the
/// Flatpak launcher when the host has no usable Flatpak: the app then runs inside the
+31
View File
@@ -64,6 +64,37 @@ impl<'a> Expect<'a> {
/// `hdiutil create` too), since it turns concurrent requests away.
pub(crate) static DISK_IMAGES: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Blocks until no other test process (nor another thread here) holds the lock file that the
/// tests take around their disk-image work, and holds it until the file is dropped.
#[cfg(test)]
pub(crate) fn other_test_processes_wait() -> std::fs::File {
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(std::env::temp_dir().join("craft-update-tests-disk-images.lock"))
.unwrap();
file.lock().unwrap();
file
}
/// A test's turn at the disk-image helper, taken from other test processes and from the
/// other threads of this one, until dropped.
#[cfg(test)]
pub(crate) struct DiskImageTurn {
_in_process: std::sync::MutexGuard<'static, ()>,
_other_processes: std::fs::File,
}
/// Waits for [`DiskImageTurn`]. The lock file comes first: a test that holds only the file
/// around an install waits for [`DISK_IMAGES`] inside it.
#[cfg(test)]
pub(crate) fn disk_image_turn() -> DiskImageTurn {
let other_processes = other_test_processes_wait();
let in_process = DISK_IMAGES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
DiskImageTurn { _in_process: in_process, _other_processes: other_processes }
}
/// Deep signature checks wait their turn here. `codesign --deep` reads every file of the
/// bundle, so checks that overlap compete for the disk and all slow down. The time limit
/// starts when a check's turn comes.
+321 -53
View File
@@ -3,6 +3,51 @@
use super::*;
use craft_ui::testing::trial;
#[cfg(target_os = "linux")]
#[trial]
fn appimage_staging_left_by_an_install_that_ended_partway_is_removed() {
let dir = tempfile::tempdir().unwrap();
let folder = dir.path();
let staging = |name: &str, files: &[&str]| {
let path = folder.join(name);
std::fs::create_dir(&path).unwrap();
for file in files {
std::fs::write(path.join(file), "partial").unwrap();
}
path
};
let left = [
staging(".artcraft-launcher-Ab12Cd", &["photocraft-0.6.0-linux-x86_64.AppImage"]),
staging(".artcraft-launcher-Ef34Gh", &["pdfcraft.appimage"]),
staging(".artcraft-launcher-Ij56Kl", &[]),
];
let link = staging(".artcraft-launcher-Fg78Hi", &[]);
std::os::unix::fs::symlink(folder.join("elsewhere.AppImage"), link.join("linked.AppImage")).unwrap();
let file = folder.join(".artcraft-launcher-Jk90Lm");
std::fs::write(&file, "the user's").unwrap();
let now = std::time::SystemTime::now();
let day = std::time::Duration::from_secs(24 * 60 * 60);
// An install still copying: its folder is old, its partial copy changed later.
let copying = staging(".artcraft-launcher-No12Pq", &["vectorcraft.AppImage"]);
std::fs::File::options().write(true).open(copying.join("vectorcraft.AppImage")).unwrap().set_modified(now + day).unwrap();
let kept = [
staging(".artcraft-launcher-Mn78Op", &["a.AppImage", "notes.txt"]),
staging(".artcraft-launcher-Qr90St", &["notes.txt"]),
staging(".artcraft-launcher-backup-Uv12Wx", &["old"]),
staging(".artcraft-launcher-Yz34A", &["a.AppImage"]),
staging(".artcraft-launcher-Bc56De7", &["a.AppImage"]),
staging("Cd78Ef", &["a.AppImage"]),
link,
file,
copying,
];
linux::clear_staging(folder, now);
assert!(left.iter().chain(&kept).all(|p| p.exists()), "a folder changed within a day was removed");
linux::clear_staging(folder, now + day + std::time::Duration::from_secs(60));
assert!(left.iter().all(|p| !p.exists()), "a partial copy was left behind");
assert!(kept.iter().all(|p| p.exists()), "a folder that isn't a partial install was removed");
}
#[trial]
fn swap_keeps_the_old_copy_until_the_new_one_is_in_place() {
let dir = tempfile::tempdir().unwrap();
@@ -219,6 +264,213 @@ fn a_self_update_never_uninstalls_the_app_it_runs_from() {
}
}
#[trial]
fn flatpark_flatpaks_are_externally_managed_and_not_updated_via_bundle() {
let app = crate::App::by_id("photocraft").unwrap();
let flatpark_installed = Installed {
version: version::parse("0.19.0"),
source: InstallSource::Flatpak,
location: "ai.storyteller.photocraft".into(),
package: Some("ai.storyteller.photocraft".into()),
externally_managed: true,
origin: Some("flatpark".into()),
installation: Some("user".into()),
};
assert!(flatpark_installed.is_externally_managed());
assert_eq!(choose_kinds_with(app, Some(&flatpark_installed), None, &[], &[PackageKind::Flatpak], false), Vec::<PackageKind>::new());
let hint = managed_elsewhere_with(app, &flatpark_installed, false, |_| None);
assert_eq!(
hint.as_deref(),
Some("PhotoCraft was installed from a Flatpak repository. Update it with flatpak update --user ai.storyteller.photocraft")
);
// During uninstall, managed_elsewhere returns None so it can be removed
assert_eq!(managed_elsewhere_with(app, &flatpark_installed, true, |_| None), None);
// When installed under a former bundle ID, the hint targets that detected ID
let former_installed = Installed {
version: version::parse("0.19.0"),
source: InstallSource::Flatpak,
location: "ai.storyteller.photocraft-old".into(),
package: Some("ai.storyteller.photocraft-old".into()),
externally_managed: true,
origin: Some("flatpark".into()),
installation: Some("system".into()),
};
let hint_former = managed_elsewhere_with(app, &former_installed, false, |_| None);
assert_eq!(
hint_former.as_deref(),
Some("PhotoCraft was installed from a Flatpak repository. Update it with flatpak update --system ai.storyteller.photocraft-old")
);
let bundle_installed = Installed {
version: version::parse("0.19.0"),
source: InstallSource::Flatpak,
location: "ai.storyteller.photocraft".into(),
package: Some("ai.storyteller.photocraft".into()),
externally_managed: false,
origin: Some("photocraft-origin".into()),
installation: Some("user".into()),
};
assert!(!bundle_installed.is_externally_managed());
assert_eq!(choose_kinds_with(app, Some(&bundle_installed), None, &[], &[PackageKind::Flatpak], false), vec![PackageKind::Flatpak]);
assert_eq!(managed_elsewhere_with(app, &bundle_installed, false, |_| None), None);
}
/// A copy in a named Flatpak installation is addressed through that installation, not the
/// default system scope.
#[trial]
fn a_named_flatpak_installation_is_addressed_by_name() {
let app = crate::App::by_id("photocraft").unwrap();
let installed = Installed {
version: version::parse("0.19.0"),
source: InstallSource::Flatpak,
location: "ai.storyteller.photocraft".into(),
package: Some("ai.storyteller.photocraft".into()),
externally_managed: true,
origin: Some("flatpark".into()),
installation: Some("work".into()),
};
assert_eq!(
managed_elsewhere_with(app, &installed, false, |_| None).as_deref(),
Some("PhotoCraft was installed from a Flatpak repository. Update it with flatpak update --installation=work ai.storyteller.photocraft")
);
}
/// A Flatpak the user installed from a repository is never replaced by the launcher's bundle:
/// the refusal names the repository's own update command, and nothing is downloaded.
#[cfg(target_os = "linux")]
#[trial]
fn a_repository_flatpak_is_not_replaced_by_a_bundle_install() {
let app = crate::App::by_id("photocraft").unwrap();
let dir = tempfile::tempdir().unwrap();
let paths = Paths::under(dir.path());
let http = Http::new(crate::TEST_AGENT).unwrap();
let mut phases = Vec::new();
let mut phase = |p: JobPhase| phases.push(p);
let mut job = Job {
http: &http,
paths: &paths,
stop: &Stop::default(),
phase: &mut phase,
install_locations: &InstallLocations::default(),
replace: false,
};
let release = Release { version: version::parse("0.20.0"), tag: "v0.20.0".into(), ..Release::default() };
let asset = Asset { name: "photocraft-0.20.0-linux-x86_64.flatpak".into(), ..Asset::default() };
let installed = Installed {
version: version::parse("0.19.0"),
source: InstallSource::Flatpak,
location: app.bundle_id(),
package: Some(app.bundle_id()),
externally_managed: true,
origin: Some("flatpark".into()),
installation: Some("work".into()),
};
let error = install(app, &release, &asset, PackageKind::Flatpak, Some(&installed), None, &mut job).unwrap_err();
assert_eq!(
error,
"PhotoCraft was installed from a Flatpak repository. Update it with flatpak update --installation=work ai.storyteller.photocraft"
);
assert!(phases.is_empty(), "the bundle installer started for a Flatpak the user manages");
assert!(!paths.cache.exists(), "the refusal must come before anything is downloaded");
}
/// `update_flatpak_app` drives the user's own copy: the scope flag for the installation it sits
/// in, a successful update, and Flatpak's error text with its `error: ` prefix removed. A
/// stand-in `flatpak` on PATH reports what it was asked to run; the test runs in child
/// processes so that PATH stays private to it (as `updater`'s pretend-version test does).
#[cfg(target_os = "linux")]
#[trial]
fn a_flatpak_from_a_repository_is_updated_through_its_own_installation() {
const NAME: &str = "install::tests::a_flatpak_from_a_repository_is_updated_through_its_own_installation";
const DIR: &str = "CRAFT_UPDATE_FAKE_FLATPAK_DIR";
if std::env::var_os(DIR).is_none() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let script = r#"#!/bin/sh
echo "$(basename "$0") $*" >> "$CRAFT_UPDATE_FAKE_FLATPAK_CALLS"
case "$*" in
*denied.app*) echo "error: Permission denied" >&2; exit 1 ;;
*diskfull.app*) echo "Error: Disk full" >&2; exit 1 ;;
*silent.app*) exit 1 ;;
esac
exit 0
"#;
for program in ["flatpak", "flatpak-spawn"] {
let path = dir.path().join(program);
std::fs::write(&path, script).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let path = format!("{}:{}", dir.path().display(), std::env::var("PATH").unwrap_or_default());
for sandboxed in [false, true] {
let calls = dir.path().join(format!("calls-{sandboxed}"));
let mut cmd = std::process::Command::new(std::env::current_exe().unwrap());
cmd.args(["--exact", NAME, "--nocapture"])
.env(DIR, dir.path())
.env("CRAFT_UPDATE_FAKE_FLATPAK_CALLS", &calls)
.env("PATH", &path)
.env_remove("FLATPAK_ID");
if sandboxed {
cmd.env("FLATPAK_ID", "ai.storyteller.photocraft");
}
let status = cmd.status().unwrap();
assert!(status.success(), "the sandboxed={sandboxed} run failed");
}
return;
}
let calls = std::env::var_os("CRAFT_UPDATE_FAKE_FLATPAK_CALLS").map(PathBuf::from).unwrap();
let app = crate::App::by_id("photocraft").unwrap();
let stop = Stop::default();
let mut phase = |_| ();
let id = app.bundle_id();
assert_eq!(linux::update_flatpak_app(app, &id, None, &stop, &mut phase), Ok(()));
assert_eq!(
linux::update_flatpak_app(app, "denied.app", Some("user"), &stop, &mut phase),
Err("Flatpak couldn't update PhotoCraft: Permission denied".to_string())
);
assert_eq!(
linux::update_flatpak_app(app, "diskfull.app", Some("work"), &stop, &mut phase),
Err("Flatpak couldn't update PhotoCraft: Disk full".to_string())
);
assert_eq!(
linux::update_flatpak_app(app, "silent.app", Some("system"), &stop, &mut phase),
Err("Flatpak couldn't update PhotoCraft".to_string())
);
let prefix = if process::in_sandbox() { "flatpak-spawn --host --watch-bus flatpak" } else { "flatpak" };
let expected: Vec<String> = vec![
format!("{prefix} update --system -y --noninteractive {id}"),
format!("{prefix} update --user -y --noninteractive denied.app"),
format!("{prefix} update --installation=work -y --noninteractive diskfull.app"),
format!("{prefix} update --system -y --noninteractive silent.app"),
];
let calls = std::fs::read_to_string(&calls).unwrap();
assert_eq!(calls.lines().map(str::to_string).collect::<Vec<_>>(), expected);
}
#[cfg(target_os = "linux")]
#[trial]
fn update_flatpak_app_respects_cancellation() {
let app = crate::App::by_id("photocraft").unwrap();
let stop = Stop::default();
stop.cancel();
let mut phase = |_| ();
assert_eq!(linux::update_flatpak_app(app, "ai.storyteller.photocraft", Some("user"), &stop, &mut phase), Err(CANCELLED.into()));
}
#[cfg(target_os = "linux")]
#[trial]
fn pause_lets_a_running_flatpak_command_finish_and_only_cancel_ends_it() {
let stop = Stop::default();
stop.pause();
assert_eq!(kill_on_cancel(&stop)(), Ok(()));
let app = crate::App::by_id("photocraft").unwrap();
let mut phase = |_| ();
// A paused job starts no further command.
assert_eq!(linux::update_flatpak_app(app, "ai.storyteller.photocraft", Some("user"), &stop, &mut phase), Err(crate::protocol::PAUSED.into()));
stop.cancel();
assert_eq!(kill_on_cancel(&stop)(), Err(CANCELLED.into()));
}
/// An asset whose file name, link tag or link file name isn't the release's is refused before
/// the download, and so is one in another app's releases or with a foreign `SHA256SUMS.txt`.
#[trial]
@@ -371,8 +623,15 @@ fn a_download_that_fails_its_checksum_replaces_nothing() {
let old = dir.path().join("Apps").join("PhotoCraft.AppImage");
std::fs::create_dir_all(old.parent().unwrap()).unwrap();
std::fs::write(&old, b"the installed 0.4.0").unwrap();
let installed =
Installed { version: version::parse("0.4.0"), source: InstallSource::Launcher, location: old.display().to_string(), package: None };
let installed = Installed {
externally_managed: false,
origin: None,
installation: None,
version: version::parse("0.4.0"),
source: InstallSource::Launcher,
location: old.display().to_string(),
package: None,
};
let previous = record("0.4.0", PackageKind::AppImage, old.clone(), vec![], false);
let mut phases = Vec::new();
let mut phase = |p: JobPhase| phases.push(p);
@@ -413,7 +672,15 @@ fn install_refuses_while_the_installed_copy_is_running() {
#[cfg(unix)]
let _probe = crate::process::tests::RunningProbe::start(&location);
assert!(process::is_running(Path::new(&location)), "{location} should be seen as running");
let installed = Installed { version: version::parse("0.4.0"), source: InstallSource::Launcher, location, package: None };
let installed = Installed {
externally_managed: false,
origin: None,
installation: None,
version: version::parse("0.4.0"),
source: InstallSource::Launcher,
location,
package: None,
};
let stop = Stop::default();
stop.cancel();
let mut job = Job { http: &http, paths: &paths, stop: &stop, phase, install_locations: &locations, replace: false };
@@ -452,33 +719,23 @@ mod macos_checks {
app
}
/// A release-style disk image holding a `PhotoCraft.app` that reports `version`. The
/// disk-image helper turns requests away while it is busy (`attach` retries for the same
/// reason), so `hdiutil create` is tried a few times, and what it said is kept for the
/// failure message.
/// A release-style disk image holding a `PhotoCraft.app` that reports `version`. The tests,
/// in this process and in others, ask the disk-image helper one at a time; when a program
/// that is not one of these tests keeps it busy, the test fails with what `hdiutil create`
/// said.
fn dmg(dir: &Path, version: &str) -> PathBuf {
let src = dir.join(format!("src-{version}"));
bundle(&src, version);
let dmg = dir.join(format!("photocraft-{version}-macos-universal.dmg"));
let _one_at_a_time = super::macos::DISK_IMAGES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut said = String::new();
for attempt in 0..5u64 {
if attempt > 0 {
std::thread::sleep(std::time::Duration::from_millis(400 * attempt));
let _ = std::fs::remove_file(&dmg);
}
let output = std::process::Command::new("hdiutil")
.args(["create", "-quiet", "-format", "UDZO", "-volname", "PhotoCraft", "-srcfolder"])
.arg(&src)
.arg(&dmg)
.output()
.unwrap();
if output.status.success() {
return dmg;
}
said = String::from_utf8_lossy(&output.stderr).trim().to_string();
}
panic!("hdiutil create failed after 5 tries: {said}");
let _one_at_a_time = macos::disk_image_turn();
let output = std::process::Command::new("hdiutil")
.args(["create", "-quiet", "-format", "UDZO", "-volname", "PhotoCraft", "-srcfolder"])
.arg(&src)
.arg(&dmg)
.output()
.unwrap();
assert!(output.status.success(), "hdiutil create failed: {}", String::from_utf8_lossy(&output.stderr).trim());
dmg
}
#[trial]
@@ -544,7 +801,15 @@ mod macos_checks {
}
fn found_at(bundle: &Path) -> Installed {
Installed { version: None, source: InstallSource::MacApp, location: bundle.display().to_string(), package: None }
Installed {
version: None,
source: InstallSource::MacApp,
location: bundle.display().to_string(),
package: None,
externally_managed: false,
origin: None,
installation: None,
}
}
/// Runs `behind` while a signature check of another app holds the turn, and frees the turn
@@ -629,7 +894,15 @@ mod macos_checks {
let dir = tempfile::tempdir().unwrap();
let apps = dir.path().join("Applications");
let current = bundle(&apps, "0.5.0");
let existing = Installed { version: None, source: InstallSource::MacApp, location: current.display().to_string(), package: None };
let existing = Installed {
version: None,
source: InstallSource::MacApp,
location: current.display().to_string(),
package: None,
externally_managed: false,
origin: None,
installation: None,
};
let paths = Paths::under(dir.path());
let image = dmg(dir.path(), "0.6.0");
@@ -640,31 +913,18 @@ mod macos_checks {
ended.wait().unwrap();
let mount = paths.cache.join(format!("mount-photocraft-{pid}-1"));
std::fs::create_dir_all(&mount).unwrap();
// The disk-image helper turns requests away while it is busy, as in `dmg`.
let attached = {
let _one_at_a_time = super::macos::DISK_IMAGES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut said = String::new();
let mut attached = false;
for attempt in 0..5u64 {
if attempt > 0 {
std::thread::sleep(std::time::Duration::from_millis(400 * attempt));
}
let output = std::process::Command::new("hdiutil")
.args(["attach", "-nobrowse", "-readonly", "-noautoopen", "-noverify", "-mountpoint"])
.arg(&mount)
.arg(&image)
.output()
.unwrap();
if output.status.success() {
attached = true;
break;
}
said = String::from_utf8_lossy(&output.stderr).trim().to_string();
}
attached.then_some(()).ok_or(said)
// One request at a time, as in `dmg`.
let output = {
let _one_at_a_time = macos::disk_image_turn();
std::process::Command::new("hdiutil")
.args(["attach", "-nobrowse", "-readonly", "-noautoopen", "-noverify", "-mountpoint"])
.arg(&mount)
.arg(&image)
.output()
.unwrap()
};
let _attached = Attached(mount.clone());
assert_eq!(attached, Ok(()), "hdiutil attach failed after 5 tries");
assert!(output.status.success(), "hdiutil attach failed: {}", String::from_utf8_lossy(&output.stderr).trim());
let staging = apps.join(format!(".artcraft-launcher-staging-{pid}-Ab12Cd"));
bundle(&staging, "0.6.0");
std::fs::write(staging.join(".artcraft-launcher-staging"), "").unwrap();
@@ -732,7 +992,12 @@ mod macos_checks {
other
},
];
let now = std::time::SystemTime::now();
// The earlier launcher versions' folders last changed at a fixed time, which stands
// for now.
let now = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000);
for copy in [&old].into_iter().chain(&old_kept) {
std::fs::File::open(copy.parent().unwrap()).unwrap().set_modified(now).unwrap();
}
super::macos::clear_staging(photocraft(), &apps, |pid| pid == ended, now);
assert!(!left.exists(), "the partial copy of an install that ended is still there");
@@ -742,8 +1007,11 @@ mod macos_checks {
}
assert_eq!(std::fs::read_to_string(elsewhere.join("Contents/MacOS/PhotoCraft")).unwrap(), "0.4.0");
// A day later, with every process still in the same state.
// A minute short of a day later, and then a day later, with every process still in the
// same state.
let day = std::time::Duration::from_secs(24 * 60 * 60);
super::macos::clear_staging(photocraft(), &apps, |pid| pid == ended, now + day - std::time::Duration::from_secs(60));
assert!(old.exists(), "the copy of an earlier launcher version's install was removed before a day had passed");
super::macos::clear_staging(photocraft(), &apps, |pid| pid == ended, now + day + std::time::Duration::from_secs(60));
assert!(!old.exists(), "the partial copy of an earlier launcher version's install is still there");
for path in kept.iter().chain([&file, &link]).chain(&old_kept) {
+86 -6
View File
@@ -14,6 +14,12 @@ pub struct Package {
pub name: String,
/// As the package manager reports it (`0.5.0-1`); empty when it doesn't say.
pub version: String,
/// Whether this is a user installation (`true`) or system installation (`false`).
pub user: bool,
/// The origin remote (`flatpark`, `<app>-origin`, `flathub`), when known.
pub origin: Option<String>,
/// The installation scope or name (`user`, `system`, or a named installation), for Flatpak installs.
pub installation: Option<String>,
}
/// `dpkg-query -W -f '${Package}|${db:Status-Status}|${Version}\n'`: installed packages only.
@@ -47,18 +53,35 @@ pub fn parse_pacman(text: &str) -> Vec<(String, String)> {
.collect()
}
/// `flatpak list --app --columns=application,version`: the version column is often empty for
/// bundles built from a release tarball.
pub fn parse_flatpak_list(text: &str) -> Vec<(String, String)> {
/// `flatpak list --app --columns=application,version,origin,installation`: parses id, version, origin, and installation.
pub fn parse_flatpak_list_with_origin(text: &str) -> Vec<(String, String, Option<String>, Option<String>)> {
text.lines()
.filter_map(|line| {
let mut f = line.split('\t');
let id = f.next()?.trim();
(!id.is_empty()).then(|| (id.to_string(), f.next().unwrap_or("").trim().to_string()))
if id.is_empty() {
return None;
}
let version = f.next().unwrap_or("").trim().to_string();
let origin = f.next().map(str::trim).filter(|o| !o.is_empty()).map(ToString::to_string);
let installation = f.next().map(str::trim).filter(|i| !i.is_empty()).map(ToString::to_string);
Some((id.to_string(), version, origin, installation))
})
.collect()
}
/// `flatpak list --app --columns=application,version`: the version column is often empty for
/// bundles built from a release tarball.
pub fn parse_flatpak_list(text: &str) -> Vec<(String, String)> {
parse_flatpak_list_with_origin(text).into_iter().map(|(id, v, _, _)| (id, v)).collect()
}
/// Whether an origin string indicates an install from FlatPark.
pub fn is_flatpark_origin(origin: &str) -> bool {
let o = origin.trim();
o.eq_ignore_ascii_case("flatpark") || o.to_ascii_lowercase().contains("flatpark")
}
/// The `Version:` line of `flatpak info <id>`.
pub fn parse_flatpak_info(text: &str) -> Option<String> {
text.lines().find_map(|l| l.trim().strip_prefix("Version:").map(|v| v.trim().to_string())).filter(|v| !v.is_empty())
@@ -79,11 +102,14 @@ pub fn candidate_names(app: &App, manager: InstallSource) -> Vec<String> {
}
}
/// The package of `app` among `installed`, preferring the manager listed first in `order`.
/// The package of `app` among `installed`, preferring the manager listed first in `order`. A user
/// install beats a system one under any of the app's ids; within a scope the current id wins.
pub fn find<'a>(app: &App, installed: &'a [Package], order: &[InstallSource]) -> Option<&'a Package> {
order.iter().find_map(|manager| {
let names = candidate_names(app, *manager);
names.iter().find_map(|n| installed.iter().find(|p| p.manager == *manager && p.name == *n))
[true, false]
.into_iter()
.find_map(|user| names.iter().find_map(|n| installed.iter().find(|p| p.manager == *manager && p.user == user && p.name == *n)))
})
}
@@ -91,3 +117,57 @@ pub fn find<'a>(app: &App, installed: &'a [Package], order: &[InstallSource]) ->
pub fn version_of(p: &Package) -> Option<version::Version> {
version::parse_package(&p.version)
}
#[cfg(test)]
mod tests {
use super::*;
use craft_ui::testing::trial;
#[trial]
fn parses_flatpak_list_with_origin_and_spots_flatpark() {
let text = "ai.storyteller.photocraft\t0.19.0\tflatpark\tuser\nai.storyteller.cadcraft\t0.16.0\tcadcraft-origin\tsystem\nai.storyteller.wordcraft\t0.14.0\t\t\n";
let list = parse_flatpak_list_with_origin(text);
assert_eq!(
list,
[
("ai.storyteller.photocraft".into(), "0.19.0".into(), Some("flatpark".into()), Some("user".into())),
("ai.storyteller.cadcraft".into(), "0.16.0".into(), Some("cadcraft-origin".into()), Some("system".into())),
("ai.storyteller.wordcraft".into(), "0.14.0".into(), None, None),
]
);
assert!(is_flatpark_origin("flatpark"));
assert!(is_flatpark_origin("FlatPark"));
assert!(is_flatpark_origin("flatpark-origin"));
assert!(!is_flatpark_origin("cadcraft-origin"));
assert!(!is_flatpark_origin("flathub"));
assert!(!is_flatpark_origin(""));
}
#[trial]
fn flatpak_find_prioritizes_user_over_system() {
let photo = App::by_id("photocraft").unwrap();
let installed = vec![
Package {
manager: InstallSource::Flatpak,
name: "ai.storyteller.photocraft".into(),
version: "0.18.0".into(),
user: false,
origin: Some("flathub".into()),
installation: Some("system".into()),
},
Package {
manager: InstallSource::Flatpak,
name: "ai.storyteller.photocraft".into(),
version: "0.19.0".into(),
user: true,
origin: Some("flatpark".into()),
installation: Some("user".into()),
},
];
let found = find(photo, &installed, &[InstallSource::Flatpak]).unwrap();
assert!(found.user);
assert_eq!(found.version, "0.19.0");
assert_eq!(found.origin.as_deref(), Some("flatpark"));
assert_eq!(found.installation.as_deref(), Some("user"));
}
}
+188 -75
View File
@@ -95,7 +95,41 @@ pub fn run_command(cmd: Command, program: &str, timeout: Duration) -> Result<Str
run_command_detailed(cmd, program, timeout).map_err(HelperFailure::into_reason)
}
fn run_command_detailed(mut cmd: Command, program: &str, timeout: Duration) -> Result<String, HelperFailure> {
fn run_command_detailed(cmd: Command, program: &str, timeout: Duration) -> Result<String, HelperFailure> {
let mut start = None;
run_command_until(cmd, program, timeout, move |_| {
let start = *start.get_or_insert_with(Instant::now);
let more = within(start, Instant::now(), timeout);
if more {
std::thread::sleep(Duration::from_millis(15));
}
more
})
}
/// Whether a helper run that started waiting at `start` may still wait at `now`.
fn within(start: Instant, now: Instant, timeout: Duration) -> bool {
now.saturating_duration_since(start) < timeout
}
/// What a helper run still waits for when it asks whether to keep waiting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Pending {
/// The helper is still running.
Helper,
/// The helper has exited, and a process it started still holds its output open.
Output,
}
/// [`run_command_detailed`], asking `keep_waiting` each time the run finds the helper or its
/// output unfinished. `keep_waiting` returns `false` when the time limit has passed; `timeout` is
/// the limit the error message names.
fn run_command_until(
mut cmd: Command,
program: &str,
timeout: Duration,
mut keep_waiting: impl FnMut(Pending) -> bool,
) -> Result<String, HelperFailure> {
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::piped())
@@ -113,11 +147,10 @@ fn run_command_detailed(mut cmd: Command, program: &str, timeout: Duration) -> R
}
};
let timed_out = || HelperFailure::Unfinished(format!("{program} didn't finish within {} seconds", timeout.as_secs()));
let start = Instant::now();
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if start.elapsed() < timeout => std::thread::sleep(Duration::from_millis(15)),
Ok(None) if keep_waiting(Pending::Helper) => {}
_ => {
let _ = child.kill();
let _ = child.wait();
@@ -128,10 +161,9 @@ fn run_command_detailed(mut cmd: Command, program: &str, timeout: Duration) -> R
// A descendant may retain a pipe after the direct child exits. Keep reader completion
// under the same deadline; on timeout the readers detach, as in the child timeout path.
while !stdout.is_finished() || !stderr.is_finished() {
if start.elapsed() >= timeout {
if !keep_waiting(Pending::Output) {
return Err(timed_out());
}
std::thread::sleep(Duration::from_millis(15));
}
let text = |pipe: std::thread::JoinHandle<Vec<u8>>| String::from_utf8_lossy(&pipe.join().unwrap_or_default()).into_owned();
let (out, err) = (text(stdout), text(stderr));
@@ -547,6 +579,17 @@ mod run_tests {
#[cfg(unix)]
const NO_LIMIT: Duration = Duration::from_secs(86_400);
#[craft_ui::testing::trial]
fn a_time_limit_ends_when_its_length_has_passed() {
let start = Instant::now();
let second = Duration::from_secs(1);
assert!(within(start, start, second));
assert!(within(start, start + Duration::from_millis(999), second));
assert!(!within(start, start + second, second));
assert!(!within(start, start + Duration::from_secs(60), second));
assert!(!within(start, start, Duration::ZERO));
}
/// Callers such as the signature check read an exit code as the helper's answer, so a helper
/// that timed out, couldn't start or was stopped by a signal must not look like one.
#[cfg(unix)]
@@ -590,103 +633,173 @@ mod run_tests {
mod inherited_pipe_tests {
use super::*;
use craft_ui::testing::trial;
use std::io::Write;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
fn fixture_args(name: &str, marker: &str) -> Vec<String> {
let (_, module) = module_path!().split_once("::").unwrap();
// libtest accepts arbitrary skip filters; this one carries our private fixture path.
// libtest accepts arbitrary skip filters; this one carries the test's address.
vec!["--ignored".into(), "--exact".into(), format!("{module}::{name}"), "--nocapture".into(), "--skip".into(), marker.into()]
}
fn fixture_dir() -> std::path::PathBuf {
fn fixture_address() -> String {
let args: Vec<String> = std::env::args().collect();
std::path::PathBuf::from(&args[args.iter().position(|arg| arg == "--skip").unwrap() + 1])
args[args.iter().position(|arg| arg == "--skip").unwrap() + 1].clone()
}
/// Stops a broken test: how long the descendant holds the pipes when the test neither answers
/// nor closes its connection, as when a capture waits for the pipes instead of timing out, and
/// how long the test waits for each step of the fixtures.
const HOLD: Duration = Duration::from_secs(60);
#[trial]
#[ignore = "self-spawned subprocess fixture"]
fn pipe_holder() {
let dir = fixture_dir();
let mut test = TcpStream::connect(fixture_address()).unwrap();
let buffer = [b'x'; 64 << 10];
// Both streams exceed the capture cap before the direct child exits.
// Both streams exceed the capture cap before the test lets the time limit pass.
for _ in 0..144 {
std::io::stdout().write_all(&buffer).unwrap();
std::io::stderr().write_all(&buffer).unwrap();
}
std::fs::write(dir.join("ready"), []).unwrap();
// Hold the pipes far longer than any deadline the test tries, so a capture that waited
// for them would show; the test's guard stops this early.
let start = Instant::now();
while !dir.join("stop").exists() && start.elapsed() < HOLD {
std::thread::sleep(Duration::from_millis(10));
}
std::fs::write(dir.join("done"), []).unwrap();
std::io::stdout().flush().unwrap();
test.write_all(b"ready\n").unwrap();
// Holds the pipes until the test closes its side of the connection. Closing this side
// tells the test that the pipes are about to close.
test.set_read_timeout(Some(HOLD)).unwrap();
let _ = test.read(&mut [0; 1]);
drop(test);
}
#[trial]
#[ignore = "self-spawned subprocess fixture"]
fn pipe_parent() {
let dir = fixture_dir();
let descendant = command(std::env::current_exe().unwrap()).args(fixture_args("pipe_holder", dir.to_str().unwrap())).spawn().unwrap();
std::fs::write(dir.join("spawned"), []).unwrap();
// No deadline of its own: run() kills this process at its deadline if it is too slow.
let start = Instant::now();
while !dir.join("ready").exists() && start.elapsed() < HOLD {
std::thread::sleep(Duration::from_millis(10));
}
assert!(dir.join("ready").exists(), "descendant did not fill both captured pipes");
std::fs::write(dir.join("parent-returning"), []).unwrap();
// Dropping Child leaves the finite fixture running with inherited stdout/stderr.
drop(descendant);
}
/// How long the descendant holds the pipes when nothing stops it.
const HOLD: Duration = Duration::from_secs(120);
struct StopHolder(tempfile::TempDir);
impl Drop for StopHolder {
fn drop(&mut self) {
let _ = std::fs::write(self.0.path().join("stop"), []);
if !self.0.path().join("spawned").exists() {
return;
}
let start = Instant::now();
while !self.0.path().join("done").exists() && start.elapsed() < Duration::from_secs(30) {
std::thread::sleep(Duration::from_millis(10));
}
}
let address = fixture_address();
// Dropping Child leaves the descendant running with the inherited stdout and stderr.
drop(command(std::env::current_exe().unwrap()).args(fixture_args("pipe_holder", &address)).spawn().unwrap());
}
#[trial]
fn exited_helper_does_not_wait_past_deadline_for_inherited_pipes() {
let exe = std::env::current_exe().unwrap();
// The direct child has to start a second test process and fill both pipes before the
// deadline, which can take seconds on a slow or emulated machine. An attempt where it
// didn't get that far says nothing about inherited pipes: retry with a longer deadline.
let mut deadline = Duration::from_secs(1);
loop {
let holder = StopHolder(tempfile::tempdir().unwrap());
let args = fixture_args("pipe_parent", holder.0.path().to_str().unwrap());
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let start = Instant::now();
let result = run(exe.to_str().unwrap(), &args, deadline);
let elapsed = start.elapsed();
if !holder.0.path().join("parent-returning").exists() && deadline < Duration::from_secs(16) {
deadline *= 4;
continue;
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let mut cmd = command(std::env::current_exe().unwrap());
cmd.args(fixture_args("pipe_parent", &listener.local_addr().unwrap().to_string()));
let mut holder = None;
// Only stops a broken test: a direct child that never exits, or a descendant that never
// connects.
let guard = Instant::now();
let result = run_command_until(cmd, "the fixture", Duration::from_secs(5), |pending| match pending {
Pending::Helper => {
std::thread::yield_now();
guard.elapsed() < HOLD
}
assert!(holder.0.path().join("parent-returning").exists(), "direct child did not exit its fixture within {deadline:?}");
assert!(
matches!(&result, Err(error) if error.contains("didn't finish within")),
"expected a pipe deadline error; helper returned success: {}, elapsed: {elapsed:?}",
result.is_ok()
);
// The descendant would hold the pipes for HOLD, far past this bound.
assert!(deadline * 2 < HOLD);
assert!(elapsed < deadline * 2, "capture exceeded its caller deadline {deadline:?}: {elapsed:?}");
// The guard stops the finite descendant and waits for its completion marker on failures too.
break;
// The direct child has exited and the descendant holds the helper's pipes. Once the
// descendant has filled both, the time limit passes.
Pending::Output => {
assert!(holder.is_none(), "the run kept waiting after its time limit passed");
let stream = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock && guard.elapsed() < HOLD => std::thread::yield_now(),
Err(e) => panic!("the descendant didn't connect ({e})"),
}
};
stream.set_nonblocking(false).unwrap();
stream.set_read_timeout(Some(HOLD)).unwrap();
let mut ready = String::new();
BufReader::new(&stream).read_line(&mut ready).unwrap();
assert_eq!(ready, "ready\n");
holder = Some(stream);
false
}
});
// The output is more than 8 MB, so a failure shows only its length.
assert_eq!(result.map(|output| output.len()), Err(HelperFailure::Unfinished("the fixture didn't finish within 5 seconds".into())));
// Lets the descendant go and waits until it has closed its end. The read time limit only
// stops a broken test.
let mut holder = holder.expect("the direct child didn't exit while the descendant held its output");
holder.shutdown(std::net::Shutdown::Write).unwrap();
holder.set_read_timeout(Some(HOLD)).unwrap();
assert_eq!(holder.read_to_end(&mut Vec::new()).unwrap(), 0);
}
}
/// Runs a helper while polling cancellation and draining its bounded output.
#[cfg(target_os = "linux")]
pub(crate) fn cancellable_output(mut cmd: Command, check: impl Fn() -> Result<(), String>) -> Result<std::process::Output, String> {
check()?;
let mut child =
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| format!("couldn't run flatpak ({e})"))?;
let stdout = read_all(child.stdout.take()).map_err(|e| format!("couldn't read flatpak output ({e})"))?;
let stderr = read_all(child.stderr.take()).map_err(|e| format!("couldn't read flatpak output ({e})"))?;
let started = Instant::now();
let status = loop {
if started.elapsed() >= Duration::from_secs(60 * 60) {
let _ = child.kill();
let _ = child.wait();
return Err("Flatpak did not finish within one hour".into());
}
if let Err(e) = check() {
let _ = child.kill();
let _ = child.wait();
return Err(e);
}
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => std::thread::sleep(Duration::from_millis(25)),
Err(e) => {
let _ = child.kill();
let _ = child.wait();
return Err(format!("couldn't wait for flatpak ({e})"));
}
}
};
let deadline = Instant::now();
while !stdout.is_finished() || !stderr.is_finished() {
check()?;
if deadline.elapsed() > Duration::from_secs(5) {
return Err("Flatpak output did not close after completion".into());
}
std::thread::sleep(Duration::from_millis(25));
}
Ok(std::process::Output { status, stdout: stdout.join().unwrap_or_default(), stderr: stderr.join().unwrap_or_default() })
}
#[cfg(all(test, target_os = "linux"))]
mod update_cancel_tests {
use super::*;
use craft_ui::testing::trial;
#[trial]
fn cancels_a_running_helper_promptly() {
let mut cmd = command("sleep");
cmd.arg("30");
let start = Instant::now();
let result = cancellable_output(cmd, || if start.elapsed() >= Duration::from_millis(100) { Err("cancelled".into()) } else { Ok(()) });
assert_eq!(result.unwrap_err(), "cancelled");
assert!(start.elapsed() < Duration::from_secs(5));
}
/// A descendant that outlives the helper keeps the pipes open; the caller gets an error at
/// the deadline instead of waiting for it.
#[trial]
fn output_held_open_by_a_descendant_fails_at_the_deadline() {
let mut cmd = command("sh");
cmd.args(["-c", "sleep 8 &"]);
let start = Instant::now();
let err = cancellable_output(cmd, || Ok(())).expect_err("a descendant holding the pipes should time out");
assert!(err.contains("did not close after completion"), "{err}");
assert!(start.elapsed() < Duration::from_secs(8), "{:?}", start.elapsed());
}
#[trial]
fn retains_both_output_streams_and_exit_status() {
let mut cmd = command("sh");
cmd.args(["-c", "printf output; printf error >&2; exit 7"]);
let output = cancellable_output(cmd, || Ok(())).unwrap();
assert_eq!(output.status.code(), Some(7));
assert_eq!(output.stdout, b"output");
assert_eq!(output.stderr, b"error");
}
}
+9 -1
View File
@@ -241,7 +241,15 @@ pub fn prepare_update_with_options(
match install {
#[cfg(target_os = "macos")]
Install::MacApp(bundle) => {
let existing = Installed { version: None, source: InstallSource::MacApp, location: bundle.display().to_string(), package: None };
let existing = Installed {
version: None,
source: InstallSource::MacApp,
location: bundle.display().to_string(),
package: None,
externally_managed: false,
origin: None,
installation: None,
};
let wait = install::macos::CheckTurn { stop, phase: &mut *phase };
let placed =
install::macos::install_dmg(app, &file, Some(&existing), None, false, paths, &install::macos::Expect::self_update(release), wait);
+4 -2
View File
@@ -456,7 +456,7 @@ fn a_copy_on_a_read_only_image_gets_the_download_link() {
let (src, image, mount) = (dir.path().join("src"), dir.path().join("test.dmg"), dir.path().join("mount"));
launcher_bundle(&src);
std::fs::create_dir(&mount).unwrap();
let _one_at_a_time = crate::install::macos::DISK_IMAGES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let _one_at_a_time = crate::install::macos::disk_image_turn();
let text = std::ffi::OsStr::new;
let created = hdiutil(
&[text("create"), text("-quiet"), text("-format"), text("UDZO"), text("-srcfolder"), src.as_os_str(), image.as_os_str()],
@@ -758,7 +758,7 @@ fn unsigned_launcher_dmg(dir: &Path, version: &str) -> Vec<u8> {
.unwrap();
std::fs::write(contents.join("MacOS/ArtCraft Launcher"), version).unwrap();
let dmg = dir.join(format!("built-{version}.dmg"));
let one_at_a_time = install::macos::DISK_IMAGES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let one_at_a_time = install::macos::disk_image_turn();
let ok = std::process::Command::new("hdiutil")
.args(["create", "-quiet", "-format", "UDZO", "-volname", "ArtCraft Launcher", "-srcfolder"])
.arg(dir.join(format!("src-{version}")))
@@ -820,6 +820,8 @@ fn a_failed_self_update_keeps_its_download_for_the_next_try() {
let (url, requests) = serve(body.clone(), vec![Reply::Full, Reply::Full]);
let release = launcher_release("0.2.0", &body, url, dir.path());
let kept = install::download_path(&paths, &release.assets[0]);
// The updates below open the disk image.
let _other_processes = install::macos::other_test_processes_wait();
for _ in 0..2 {
let error =
prepare_update(&crate::suite::LAUNCHER, &install, &release, platform, &http, &paths, &stop, &mut phase, &|| Ok(()), None).unwrap_err();
+17
View File
@@ -63,4 +63,21 @@ pub struct Installed {
/// The package that installed it, for package-manager installs (`photocraft-bin`).
#[serde(default)]
pub package: Option<String>,
/// Whether this copy is managed externally (such as a Flatpak from FlatPark) and
/// will not be replaced with a downloaded bundle.
#[serde(default)]
pub externally_managed: bool,
/// The remote repository or origin (`flatpark`, `<app>-origin`), when known.
#[serde(default)]
pub origin: Option<String>,
/// The installation scope or name (`user`, `system`, or a named installation), for Flatpak installs.
#[serde(default)]
pub installation: Option<String>,
}
impl Installed {
/// Whether this copy is managed externally and should not be replaced by a downloaded bundle.
pub fn is_externally_managed(&self) -> bool {
self.externally_managed
}
}
+148 -25
View File
@@ -91,7 +91,7 @@ type Found = Result<Option<(Release, bool)>, String>;
type InstallProbe = Arc<dyn Fn(&'static App, &Release) -> bool + Send + Sync>;
/// Whether this copy can install `release` itself. It reads the installed files, which can take
/// long on slow storage, so the check's thread calls it, never a pass.
/// long on slow storage, so the check's thread and the offer's thread call it, never a pass.
fn can_install_itself(app: &'static App, release: &Release) -> bool {
self_update::is_self_updating(app) && self_update::release_installs(app, release)
}
@@ -212,7 +212,16 @@ pub struct Updater {
/// The last update's outcome record was read ([`Updater::read_last_update`]).
outcome_read: bool,
check: Option<Receiver<Found>>,
/// Replaces [`can_install_itself`] on the check's thread (tests).
/// A release the app offered ([`Self::offer`]) while its thread reads whether this copy can
/// install it itself; `tick` opens the prompt with the answer.
offered: Option<Receiver<(Release, bool)>>,
/// The newest release offered while `offered` was still being inspected; it is inspected
/// next, in place of the earlier one.
next_offer: Option<Release>,
/// An installation failed while `offered` was still being inspected: its answer opens no
/// prompt over the one that says why the installation failed.
offer_outdated: bool,
/// Replaces [`can_install_itself`] on the check's and the offer's thread (tests).
probe: Option<InstallProbe>,
/// Whether the copy could install the release that is installing itself, as the prompt that
/// started the installation said. A failed installation reopens the prompt with it.
@@ -230,7 +239,8 @@ pub struct Updater {
/// An update is ready and waits for the app to exit; nothing starts a second one.
installed: bool,
/// [`Self::run`] returns [`Action::Close`] at its next pass that may close: once when an
/// installation finishes, and again for each [`Self::restart_to_update`].
/// installation finishes, and again for each [`Self::restart_to_update`]. Later on the prompt
/// clears it.
close_wanted: bool,
/// The folders that hold the outcome records ([`self_update::take_outcome`]) in place of the
/// app's own (tests).
@@ -264,6 +274,9 @@ impl Updater {
started: false,
outcome_read: false,
check: None,
offered: None,
next_offer: None,
offer_outdated: false,
probe: None,
installing_itself: false,
install: None,
@@ -320,8 +333,8 @@ impl Updater {
self
}
/// Replaces [`can_install_itself`], which the check's thread calls for a release it found
/// (tests).
/// Replaces [`can_install_itself`], which the check's thread calls for a release it found and
/// the offer's thread for a release the app offered (tests).
#[cfg(test)]
fn with_probe(mut self, probe: InstallProbe) -> Self {
self.probe = Some(probe);
@@ -418,18 +431,67 @@ impl Updater {
self.close_wanted = true;
}
/// Opens the startup prompt for a release the app found itself. After a failed update the
/// prompt says why it failed, like the one a check opens. Opening the prompt sets
/// [`Self::status`] to [`Status::Idle`]. It reads the installed files on the calling thread to
/// decide whether the prompt offers Update and Restart; a release found by a check is
/// inspected on the check's thread instead.
/// Offers a release the app found itself: the startup prompt opens at a later [`Self::tick`],
/// once a thread of its own has read the installed files to decide whether the prompt offers
/// Update and Restart, as a check does for a release it finds. After a failed update the
/// prompt says why it failed, like the one a check opens. An offer sets [`Self::status`] to
/// [`Status::Idle`] when it is made, and a requested check that answers afterwards reports as
/// usual. A later offer replaces one that has not opened yet; while an inspection runs, only
/// the newest offer waits for the next one, so one thread at most reads the files. An offer
/// closes the prompt for an earlier release, which calls off a Save and Update that has not
/// started its installation yet. An offer still being inspected when an installation fails
/// opens no prompt.
pub fn offer(&mut self, release: Release) {
let installs_itself = can_install_itself(self.app, &release);
if self.install.is_some() || self.installed || self.read_choice() {
return;
}
self.status = Status::Idle;
// The prompt for an earlier release closes while this one is inspected: nothing installs
// the earlier release from it, and a save it asked for installs nothing.
self.drop_prompt();
if self.offered.is_some() {
self.next_offer = Some(release);
return;
}
self.inspect_offer(release);
}
/// Starts the thread that reads whether this copy can install the offered `release` itself;
/// [`Self::tick`] picks up its answer.
fn inspect_offer(&mut self, release: Release) {
self.offer_outdated = false;
let (tx, rx) = channel();
let (probe, app) = (self.probe.clone(), self.app);
// Kept for the prompt in case the thread cannot start.
let fallback = release.clone();
let spawned = std::thread::Builder::new().name("update-offer".into()).spawn(move || {
let inspect = || match &probe {
Some(probe) => probe(app, &release),
None => can_install_itself(app, &release),
};
// A panicking inspection offers Download rather than nothing.
let installs_itself = std::panic::catch_unwind(std::panic::AssertUnwindSafe(inspect)).unwrap_or(false);
let _ = tx.send((release, installs_itself));
});
match spawned {
Ok(_) => self.offered = Some(rx),
Err(e) => {
// Without the thread the prompt offers Download, without reading the files here.
log::warn!("{} couldn't inspect the install for an offered update ({e})", self.app.name);
self.offered = None;
self.finish_offer(fallback, false);
}
}
}
/// Opens the prompt for an offered release once its thread has answered, unless an
/// installation started or the launcher took the app over meanwhile. The status stays as a
/// requested check left it.
fn finish_offer(&mut self, release: Release, installs_itself: bool) {
self.known = Some((release.clone(), installs_itself));
// The launcher may have pinned the app while the files were read, as during a check.
if self.install.is_none() && !self.installed && !self.read_choice() {
self.drop_prompt();
self.open_offer(release, installs_itself);
self.status = Status::Idle;
}
}
@@ -569,6 +631,8 @@ impl Updater {
Ok(Some((release, installs_itself))) => {
self.known = Some((release.clone(), installs_itself));
match &mut self.prompt {
// An offer still being inspected opens its own prompt, with the failure's reason.
None if self.offered.is_some() => {}
None => self.open_offer(release, installs_itself),
// A prompt the app opened before (`offer`) says why the last update failed.
Some(offer) => {
@@ -593,8 +657,8 @@ impl Updater {
}
}
/// Picks up a finished check or installation. Call once per frame, before [`Self::run`]. It
/// asks for the next pass every `POLL_SECONDS` while either is running.
/// Picks up a finished check, offer or installation. Call once per frame, before
/// [`Self::run`]. It asks for the next pass every `POLL_SECONDS` while any of them is running.
pub fn tick(&mut self, ctx: &egui::Context) {
if let Some(rx) = &self.check {
match rx.try_recv() {
@@ -609,6 +673,36 @@ impl Updater {
}
}
}
if let Some(rx) = &self.offered {
let answer = match rx.try_recv() {
Ok(answer) => Some(answer),
Err(TryRecvError::Empty) => {
request_repaint_after(ctx, POLL_SECONDS);
None
}
Err(TryRecvError::Disconnected) => {
log::warn!("{} stopped inspecting the install for an offered update", self.app.name);
self.offered = None;
None
}
};
if let Some((release, installs_itself)) = answer {
self.offered = None;
// A newer offer replaces this one before its prompt opens, and an installation
// that failed meanwhile keeps its own prompt.
let outdated = std::mem::take(&mut self.offer_outdated);
if self.next_offer.is_none() && !outdated {
self.finish_offer(release, installs_itself);
}
}
// The newer offer that waited for this inspection is inspected now.
if self.offered.is_none()
&& let Some(release) = self.next_offer.take()
{
self.inspect_offer(release);
request_repaint_after(ctx, POLL_SECONDS);
}
}
if let Some((rx, _)) = &self.install {
let outcome = match rx.try_recv() {
Ok(outcome) => Some(outcome),
@@ -643,6 +737,12 @@ impl Updater {
if matches!(self.status, Status::Installing) {
self.status = Status::Idle;
}
// An offer made before the installation started, still being inspected or
// waiting for it, would replace the prompt that says why: it opens nothing.
if self.offered.is_some() {
self.offer_outdated = true;
}
self.next_offer = None;
// The prompt may have been dismissed meanwhile: bring it back with the reason.
if self.prompt.is_none()
&& let Some(release) = release
@@ -735,8 +835,10 @@ impl Updater {
self.prompt = None;
}
UpdateChoice::Later => {
// An installation carries on and reports through `tick`.
// An installation carries on and reports through `tick`. A ready update drops the
// close it asked for: it installs at the exit, or Restart to Update asks again.
self.prompt = None;
self.close_wanted = false;
}
}
}
@@ -966,17 +1068,38 @@ fn prompt_id() -> craft_ui::dialog::DialogId {
#[cfg(feature = "screen-testing")]
impl Updater {
/// Waits for the running check's answer on its channel (its thread always sends one, or ends
/// and closes the channel), then hands it to `tick` as a pass would (tests).
/// and closes the channel), then hands it to `tick` as a pass would; then does the same for
/// each offer still being inspected, until none is left (tests).
pub fn settle_for_tests(&mut self, ctx: &egui::Context) {
let Some(rx) = self.check.take() else { return };
let (tx, answer) = channel();
if let Ok(checked) = rx.recv() {
let _ = tx.send(checked);
if let Some(rx) = self.check.take() {
let (tx, answer) = channel();
if let Ok(checked) = rx.recv() {
let _ = tx.send(checked);
}
// Without an answer `tx` is dropped here, and `tick` sees a check that stopped.
drop(tx);
self.check = Some(answer);
self.tick(ctx);
}
self.settle_offers(ctx);
}
}
#[cfg(any(test, feature = "screen-testing"))]
impl Updater {
/// Waits for each offer's thread to answer on its channel (it always sends one, or ends and
/// closes the channel), then hands the answer to `tick` as a pass would, until no offer is
/// left to inspect.
fn settle_offers(&mut self, ctx: &egui::Context) {
while let Some(rx) = self.offered.take() {
let (tx, answer) = channel();
if let Ok(offered) = rx.recv() {
let _ = tx.send(offered);
}
drop(tx);
self.offered = Some(answer);
self.tick(ctx);
}
// Without an answer `tx` is dropped here, and `tick` sees a check that stopped.
drop(tx);
self.check = Some(answer);
self.tick(ctx);
}
}
+215 -20
View File
@@ -21,6 +21,18 @@ fn newer() -> Release {
Release { tag: "v9.0.0".into(), version: crate::version::parse("9.0.0"), ..Release::default() }
}
/// Every offer's prompt, as the passes after the offers' threads answered would open it.
fn settle_offer(updater: &mut Updater) {
updater.settle_offers(&egui::Context::default());
assert!(updater.next_offer.is_none(), "every offer has answered");
}
/// Offers [`newer`] as the app would and waits for its prompt.
fn offer_now(updater: &mut Updater) {
updater.offer(newer());
settle_offer(updater);
}
/// One pass of the updater on a dialog host.
fn frame(u: &mut Updater, _ctx: &egui::Context, can_start: bool) -> Action {
u.run(&mut DialogHost::new(), can_start)
@@ -40,7 +52,7 @@ fn the_helper_starts_once_when_the_app_exits() {
use std::sync::atomic::{AtomicUsize, Ordering};
let ctx = egui::Context::default();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
let starts = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&starts);
let (tx, rx) = channel();
@@ -72,7 +84,7 @@ fn a_canceled_close_keeps_the_update_ready() {
use std::sync::atomic::Ordering;
let ctx = egui::Context::default();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
let (starts, restart) = counted_restart();
let (tx, rx) = channel();
u.install = Some((rx, newer()));
@@ -312,7 +324,7 @@ fn a_check_answering_during_an_update_reports_the_update() {
let ctx = egui::Context::default();
for answer in [Ok(None), Err("offline".to_owned()), Ok(Some((newer(), false)))] {
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
u.check_now();
assert_eq!(u.status(), &Status::Checking);
let (check_tx, check_rx) = channel();
@@ -327,7 +339,7 @@ fn a_check_answering_during_an_update_reports_the_update() {
assert_eq!(u.status(), &Status::Ready, "after {answer:?}");
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
u.check_now();
let (check_tx, check_rx) = channel();
u.check = Some(check_rx);
@@ -363,7 +375,7 @@ fn a_failed_install_ends_the_installing_status() {
fn a_requested_check_finds_a_helper_failure_while_the_app_still_runs() {
let ctx = egui::Context::default();
let (_dir, paths, mut u) = with_records("0.1.0");
u.offer(newer());
offer_now(&mut u);
let (tx, rx) = channel();
u.install = Some((rx, newer()));
assert!(tx.send(Ok(Restart::scheduled())).is_ok());
@@ -400,7 +412,7 @@ fn a_retry_after_a_helper_failure_while_the_app_runs_waits_for_the_exit() {
use std::sync::atomic::Ordering;
let ctx = egui::Context::default();
let (_dir, paths, mut u) = with_records("0.1.0");
u.offer(newer());
offer_now(&mut u);
let (tx, rx) = channel();
u.install = Some((rx, newer()));
assert!(tx.send(Ok(Restart::scheduled())).is_ok());
@@ -466,13 +478,13 @@ fn an_offer_before_the_check_at_start_says_why_the_last_update_failed() {
let ctx = egui::Context::default();
let (_dir, paths, mut u) = with_records("0.1.0");
self_update::record_failure(&paths, "disk full");
u.offer(newer());
offer_now(&mut u);
assert_eq!(u.prompt.as_ref().and_then(Offer::message), None, "the failure is not read before the check at start");
start_answered(&mut u, &ctx, Ok(Some(newer())));
assert_eq!(u.status(), &Status::Idle, "the prompt carries the reason");
assert_eq!(u.prompt.as_ref().and_then(Offer::message).as_deref(), Some("The update could not be installed: disk full"));
u.prompt = None;
u.offer(newer());
offer_now(&mut u);
assert_eq!(u.prompt.as_ref().and_then(Offer::message), None, "the reason is shown once");
}
@@ -649,7 +661,7 @@ fn prompt_message(u: &Updater) -> String {
/// An updater whose install has finished and waits for the app to close.
fn installed(ctx: &egui::Context) -> Updater {
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
let (tx, rx) = channel();
u.install = Some((rx, newer()));
assert!(tx.send(Ok(Restart::scheduled())).is_ok());
@@ -663,7 +675,7 @@ fn installed(ctx: &egui::Context) -> Updater {
fn save_and_update_saves_first_and_then_installs() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
click_save(&mut u, &mut screen);
assert!(u.take_save_request(), "the click asks the app to save");
assert!(!u.take_save_request(), "once");
@@ -681,7 +693,7 @@ fn save_and_update_saves_first_and_then_installs() {
fn a_note_from_an_earlier_click_goes_when_the_save_starts() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
u.request_install(false);
assert!(prompt_message(&u).starts_with("Save or close"));
click_save(&mut u, &mut screen);
@@ -693,7 +705,7 @@ fn a_note_from_an_earlier_click_goes_when_the_save_starts() {
fn a_failed_save_says_why_and_calls_the_install_off() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
click_save(&mut u, &mut screen);
u.save_stopped(Some("disk full".into()));
assert!(!saving(&u));
@@ -709,7 +721,7 @@ fn a_failed_save_says_why_and_calls_the_install_off() {
fn a_save_that_leaves_work_unsaved_goes_back_to_the_note() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
click_save(&mut u, &mut screen);
assert!(u.take_save_request());
u.save_stopped(None);
@@ -725,7 +737,7 @@ fn a_save_that_leaves_work_unsaved_goes_back_to_the_note() {
fn work_that_can_no_longer_be_saved_stops_the_saving() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
click_save(&mut u, &mut screen);
screen.pass(&mut u, false, false);
assert!(!saving(&u));
@@ -736,7 +748,7 @@ fn work_that_can_no_longer_be_saved_stops_the_saving() {
#[trial]
fn a_late_save_stopped_changes_nothing() {
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
u.save_stopped(Some("disk full".into()));
assert_eq!(prompt_message(&u), "");
}
@@ -746,13 +758,13 @@ fn a_late_save_stopped_changes_nothing() {
fn dismissing_during_the_save_forgets_the_install() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
click_save(&mut u, &mut screen);
screen.fixture.key(egui::Key::Escape, egui::Modifiers::NONE);
screen.pass(&mut u, false, true);
assert!(!u.prompt_open());
assert!(!u.take_save_request());
u.offer(newer());
offer_now(&mut u);
self_updating(&mut u);
screen.pass(&mut u, true, false);
assert!(u.prompt.is_some() && u.install.is_none());
@@ -764,9 +776,9 @@ fn dismissing_during_the_save_forgets_the_install() {
fn a_new_offer_during_the_save_installs_nothing() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
click_save(&mut u, &mut screen);
u.offer(newer());
offer_now(&mut u);
self_updating(&mut u);
screen.pass(&mut u, true, false);
assert!(u.prompt.is_some() && u.install.is_none());
@@ -779,7 +791,7 @@ fn a_new_offer_during_the_save_installs_nothing() {
fn the_button_needs_both_unsaved_work_and_an_app_that_can_save() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
u.offer(newer());
offer_now(&mut u);
self_updating(&mut u);
screen.pass(&mut u, false, true);
assert!(screen.shows("Save and Update"), "unsaved work the app can save");
@@ -846,3 +858,186 @@ fn save_and_update_after_a_canceled_close_closes_once_the_work_is_saved() {
assert_eq!(screen.pass(&mut u, true, false), Action::None);
assert!(u.install.is_none());
}
/// A release the app offers itself is inspected on a thread of its own, as one a check finds
/// is: `offer` and a pass that runs while reading the installed files is stalled return at
/// once, and the prompt opens with the thread's answer at the pass after it answers.
#[trial]
fn a_stalled_offer_inspection_does_not_block_a_frame() {
let ctx = egui::Context::default();
let (seen_tx, seen) = channel();
let (resume, resumed) = channel::<()>();
let resumed = Mutex::new(resumed);
let calls = Arc::new(Mutex::new(0_u32));
let probe_calls = Arc::clone(&calls);
let mut u = updater(Ok(None)).with_probe(Arc::new(move |_, _| {
*probe_calls.lock().unwrap_or_else(PoisonError::into_inner) += 1;
let _ = seen_tx.send(());
// Stalled until the test lets it go, like a read on storage that does not answer.
let _ = resumed.lock().unwrap_or_else(PoisonError::into_inner).recv();
true
}));
u.offer(newer());
assert!(u.prompt.is_none(), "offer returns before the install is inspected");
assert!(seen.recv().is_ok(), "the offer's thread inspects the install");
u.tick(&ctx);
assert!(u.prompt.is_none(), "no prompt while the inspection is stalled");
assert!(u.offered.is_some(), "the offer is still being inspected");
assert!(resume.send(()).is_ok());
settle_offer(&mut u);
assert!(u.prompt.as_ref().is_some_and(|p| p.installs_itself), "the prompt offers Update and Restart");
assert_eq!(u.status(), &Status::Idle);
assert_eq!(*calls.lock().unwrap_or_else(PoisonError::into_inner), 1, "the pass did not inspect the install again");
}
/// Offers made while a slow inspection runs start no thread of their own: the newest waits for
/// it, is inspected next, and its prompt opens in place of the earlier ones.
#[trial]
fn offers_during_a_stalled_inspection_wait_for_it() {
let (seen_tx, seen) = channel();
let (resume, resumed) = channel::<()>();
let resumed = Mutex::new(resumed);
let inspected = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&inspected);
let mut u = updater(Ok(None)).with_probe(Arc::new(move |_: &'static App, release: &Release| {
log.lock().unwrap_or_else(PoisonError::into_inner).push(release.tag.clone());
let _ = seen_tx.send(());
let _ = resumed.lock().unwrap_or_else(PoisonError::into_inner).recv();
true
}));
let tagged = |tag: &str| Release { tag: tag.into(), ..newer() };
u.offer(tagged("v9.0.0"));
assert!(seen.recv().is_ok(), "the first offer is being inspected");
u.offer(tagged("v9.0.1"));
u.offer(tagged("v9.0.2"));
// One go-ahead per offer, so that a thread started for each would not stall the test.
for _ in 0..3 {
assert!(resume.send(()).is_ok());
}
settle_offer(&mut u);
let inspected = inspected.lock().unwrap_or_else(PoisonError::into_inner).clone();
assert_eq!(inspected, ["v9.0.0", "v9.0.2"], "one inspection at a time, and only the newest offer waits");
assert_eq!(u.prompt.as_ref().map(|p| p.release.tag.as_str()), Some("v9.0.2"));
}
/// A check at start that finds the release while the app's own offer is still inspected leaves
/// the prompt to the offer, which says why the last update failed.
#[trial]
fn a_check_answering_during_an_offer_leaves_the_prompt_to_the_offer() {
let ctx = egui::Context::default();
let (_dir, paths, mut u) = with_records("0.1.0");
self_update::record_failure(&paths, "disk full");
u.offer(newer());
start_answered(&mut u, &ctx, Ok(Some(newer())));
settle_offer(&mut u);
assert_eq!(u.status(), &Status::Idle, "the prompt carries the reason");
assert_eq!(prompt_message(&u), "The update could not be installed: disk full");
}
/// A requested check that answers while an offer is inspected keeps its answer when the
/// offer's prompt opens.
#[trial]
fn an_offer_opening_after_a_requested_check_keeps_its_answer() {
let ctx = egui::Context::default();
let mut u = updater(Ok(None));
u.check_now();
u.offer(newer());
u.settle_for_tests(&ctx);
assert_eq!(u.status(), &Status::UpToDate);
settle_offer(&mut u);
assert!(u.prompt_open());
assert_eq!(u.status(), &Status::UpToDate, "the offer's prompt does not close the check's result");
}
/// An installation that starts while an offer is inspected keeps the offer's prompt from
/// opening over it.
#[trial]
fn an_offer_answering_during_an_install_opens_no_prompt() {
let mut u = updater(Ok(None));
u.offer(newer());
let (_tx, rx) = channel();
u.install = Some((rx, newer()));
settle_offer(&mut u);
assert!(!u.prompt_open());
}
/// An installation that fails while an offer made before it is still inspected keeps the
/// prompt that says why: the offer's answer, and an offer waiting for it, open nothing.
#[trial]
fn an_offer_answering_after_a_failed_install_keeps_the_failure() {
let ctx = egui::Context::default();
let (seen_tx, seen) = channel();
let (resume, resumed) = channel::<()>();
let resumed = Mutex::new(resumed);
let mut u = updater(Ok(None)).with_probe(Arc::new(move |_: &'static App, _: &Release| {
let _ = seen_tx.send(());
let _ = resumed.lock().unwrap_or_else(PoisonError::into_inner).recv();
true
}));
u.offer(newer());
assert!(seen.recv().is_ok(), "the offer is being inspected");
u.offer(Release { tag: "v9.0.2".into(), ..newer() });
let (tx, rx) = channel();
u.install = Some((rx, newer()));
assert!(tx.send(Err("disk full".into())).is_ok());
u.tick(&ctx);
assert_eq!(prompt_message(&u), "disk full");
for _ in 0..2 {
assert!(resume.send(()).is_ok());
}
settle_offer(&mut u);
assert_eq!(prompt_message(&u), "disk full", "the failure's prompt stays open");
offer_now(&mut u);
assert_eq!(prompt_message(&u), "", "a later offer opens its own prompt");
}
/// The prompt for an earlier release cannot install it while a newer offer is inspected.
#[trial]
fn a_new_offer_closes_the_prompt_for_the_earlier_release() {
let mut u = updater(Ok(None));
offer_now(&mut u);
self_updating(&mut u);
u.offer(Release { tag: "v9.0.2".into(), ..newer() });
u.request_install(true);
assert!(!u.prompt_open(), "nothing is left to click for the earlier release");
assert!(u.install.is_none());
settle_offer(&mut u);
assert_eq!(u.prompt.as_ref().map(|p| p.release.tag.as_str()), Some("v9.0.2"));
}
/// A save that ends while a newer offer is still inspected installs nothing either: the save
/// was asked for the earlier release.
#[trial]
fn a_save_ending_while_a_new_offer_is_inspected_installs_nothing() {
let mut screen = Screen::new();
let mut u = updater(Ok(None));
offer_now(&mut u);
click_save(&mut u, &mut screen);
assert!(u.take_save_request());
u.offer(newer());
assert!(!u.prompt_open(), "the earlier release's prompt closes while the new one is inspected");
screen.pass(&mut u, true, false);
assert!(u.install.is_none());
settle_offer(&mut u);
assert!(u.prompt.as_ref().is_some_and(|p| !p.saving));
assert_eq!(prompt_message(&u), "", "{}", prompt_message(&u));
assert!(u.install.is_none());
}
/// Later on a finished install drops the close it asked for: saving the work afterwards does
/// not close the app. The update stays ready, and Restart to Update asks for the close again.
#[trial]
fn later_on_a_finished_install_does_not_close_the_app_after_a_save() {
let ctx = egui::Context::default();
let mut screen = Screen::new();
let mut u = installed(&ctx);
assert_eq!(screen.pass(&mut u, false, false), Action::None, "unsaved work holds the close back");
screen.fixture.key(egui::Key::Escape, egui::Modifiers::NONE);
assert_eq!(screen.pass(&mut u, false, false), Action::None);
assert!(!u.prompt_open());
assert_eq!(screen.pass(&mut u, true, false), Action::None, "the work is saved, and the user chose Later");
assert!(u.restart.is_some(), "the update still waits for the exit");
u.restart_to_update();
assert_eq!(screen.pass(&mut u, true, false), Action::Close);
}