mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
Merge fix/separate-app-data: keep app data apart from installed packages (#13)
App data lives in $XDG_DATA_HOME/weft/app-data/<id>, private to the user, and is moved from the earlier layout in one no-replace rename; conflicting or cross-filesystem data is never moved or deleted. weft-pack never removes a data directory with a package. Notes stores text exactly, refuses saves edited from a stale revision and writes through a locked, synced staging file.
This commit is contained in:
commit
84930b13d8
17 changed files with 1345 additions and 83 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -8,3 +8,4 @@ __pycache__/
|
||||||
|
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
/tests/components/*/target/
|
/tests/components/*/target/
|
||||||
|
/examples/*/target/
|
||||||
|
|
|
||||||
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -10522,6 +10522,7 @@ name = "weft-ipc-types"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
|
"rustix 1.1.4",
|
||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web
|
||||||
|
|
||||||
**Runtime** — `weft-runtime` runs WASI Component Model binaries under Wasmtime 30 (`--features wasmtime-runtime`). Provides `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard` host imports. Preopens filesystem paths according to declared capabilities.
|
**Runtime** — `weft-runtime` runs WASI Component Model binaries under Wasmtime 30 (`--features wasmtime-runtime`). Provides `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard` host imports. Preopens filesystem paths according to declared capabilities.
|
||||||
|
|
||||||
**Package management** — `weft-pack` handles check, sign, verify, install, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time.
|
**Package management** — `weft-pack` handles check, sign, verify, install, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time. App data is stored apart from packages and survives uninstall.
|
||||||
|
|
||||||
**File portal** — `weft-file-portal` is a per-session file proxy with a path allowlist and `..` blocking.
|
**File portal** — `weft-file-portal` is a per-session file proxy with a path allowlist and `..` blocking.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,8 @@ pub(crate) struct SessionGrants {
|
||||||
|
|
||||||
/// Why a launch is refused, with the error code reported to the client:
|
/// Why a launch is refused, with the error code reported to the client:
|
||||||
/// 400 for a malformed app ID, 404 for a package that is not installed, 403
|
/// 400 for a malformed app ID, 404 for a package that is not installed, 403
|
||||||
/// for a package this host will not run as declared and 500 for a host
|
/// for a package this host will not run as declared, 409 for app data the
|
||||||
/// fault.
|
/// user must reconcile and 500 for a host fault.
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub(crate) struct Refusal {
|
pub(crate) struct Refusal {
|
||||||
pub code: u32,
|
pub code: u32,
|
||||||
|
|
@ -56,8 +56,11 @@ impl Refusal {
|
||||||
|
|
||||||
/// Where the host resources behind filesystem capabilities live.
|
/// Where the host resources behind filesystem capabilities live.
|
||||||
pub(crate) struct HostDirs {
|
pub(crate) struct HostDirs {
|
||||||
/// Root under which each app's private data directory is created.
|
/// The user's data home (`$XDG_DATA_HOME`); app data lives under it in
|
||||||
pub app_data_root: PathBuf,
|
/// `weft/app-data/<id>`, apart from installed packages.
|
||||||
|
pub data_home: PathBuf,
|
||||||
|
/// The home directory, under which earlier versions kept app data.
|
||||||
|
pub home: PathBuf,
|
||||||
/// The user's documents directory, if the platform configures one.
|
/// The user's documents directory, if the platform configures one.
|
||||||
pub documents: Option<PathBuf>,
|
pub documents: Option<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
@ -73,9 +76,13 @@ impl HostDirs {
|
||||||
.map(PathBuf::from)
|
.map(PathBuf::from)
|
||||||
.filter(|dir| dir.is_absolute())
|
.filter(|dir| dir.is_absolute())
|
||||||
.unwrap_or_else(|| home.join(".config"));
|
.unwrap_or_else(|| home.join(".config"));
|
||||||
|
let data_home = weft_ipc_types::package::data_home().ok_or_else(|| {
|
||||||
|
Refusal::new(500, "no data home: XDG_DATA_HOME and HOME are unusable")
|
||||||
|
})?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
app_data_root: home.join(".local/share/weft/apps"),
|
data_home,
|
||||||
documents: documents_dir(&home, &config),
|
documents: documents_dir(&home, &config),
|
||||||
|
home,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -139,7 +146,7 @@ pub(crate) fn derive(
|
||||||
for capability in capabilities {
|
for capability in capabilities {
|
||||||
match (&capability, &host) {
|
match (&capability, &host) {
|
||||||
(Capability::AppData(access), Some(host)) => {
|
(Capability::AppData(access), Some(host)) => {
|
||||||
let dir = host.app_data_root.join(app_id).join("data");
|
let dir = weft_ipc_types::package::app_data_dir(&host.data_home, app_id);
|
||||||
grant_dir(&mut grants, dir, "/data", *access)?;
|
grant_dir(&mut grants, dir, "/data", *access)?;
|
||||||
}
|
}
|
||||||
(Capability::Documents(access), Some(host)) => {
|
(Capability::Documents(access), Some(host)) => {
|
||||||
|
|
@ -158,16 +165,49 @@ pub(crate) fn derive(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for dir in &grants.dirs {
|
if let (Some(dir), Some(host)) = (grants.dirs.iter().find(|d| d.guest == "/data"), &host) {
|
||||||
if dir.guest == "/data" {
|
prepare_app_data(app_id, &dir.host, host)?;
|
||||||
std::fs::create_dir_all(&dir.host).map_err(|e| {
|
|
||||||
Refusal::new(500, format!("cannot create {}: {e}", dir.host.display()))
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Ok(grants)
|
Ok(grants)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates the app's data directory, first moving data an earlier version
|
||||||
|
/// kept inside the user package store, and makes it private. A conflict
|
||||||
|
/// between the two locations refuses the launch (409) and leaves both
|
||||||
|
/// untouched.
|
||||||
|
fn prepare_app_data(app_id: &str, dir: &Path, host: &HostDirs) -> Result<(), Refusal> {
|
||||||
|
use weft_ipc_types::package::{
|
||||||
|
Migration, MigrationError, legacy_app_data_dir, migrate_app_data,
|
||||||
|
};
|
||||||
|
let legacy = legacy_app_data_dir(&host.home, app_id);
|
||||||
|
match migrate_app_data(&legacy, dir) {
|
||||||
|
Ok(Migration::Moved) => {
|
||||||
|
tracing::info!(%app_id, from = %legacy.display(), to = %dir.display(), "app data moved");
|
||||||
|
}
|
||||||
|
Ok(Migration::NotNeeded) => {}
|
||||||
|
Err(e @ MigrationError::Conflict { .. }) => return Err(Refusal::new(409, e.to_string())),
|
||||||
|
Err(MigrationError::Io(e)) => {
|
||||||
|
return Err(Refusal::new(
|
||||||
|
500,
|
||||||
|
format!(
|
||||||
|
"cannot move app data from {} to {}: {e}",
|
||||||
|
legacy.display(),
|
||||||
|
dir.display()
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(e) => return Err(Refusal::new(500, e.to_string())),
|
||||||
|
}
|
||||||
|
let mut builder = std::fs::DirBuilder::new();
|
||||||
|
builder.recursive(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||||
|
builder
|
||||||
|
.create(dir)
|
||||||
|
.and_then(|()| weft_ipc_types::package::make_private(dir))
|
||||||
|
.map_err(|e| Refusal::new(500, format!("cannot prepare {}: {e}", dir.display())))
|
||||||
|
}
|
||||||
|
|
||||||
/// Adds a directory grant; declaring both modes for one directory grants the
|
/// Adds a directory grant; declaring both modes for one directory grants the
|
||||||
/// wider one. The host path must survive the `--preopen HOST::GUEST::MODE`
|
/// wider one. The host path must survive the `--preopen HOST::GUEST::MODE`
|
||||||
/// encoding unchanged: it must be UTF-8 and must not contain `::`.
|
/// encoding unchanged: it must be UTF-8 and must not contain `::`.
|
||||||
|
|
@ -237,7 +277,8 @@ mod tests {
|
||||||
let root = root.to_path_buf();
|
let root = root.to_path_buf();
|
||||||
move || {
|
move || {
|
||||||
Ok(HostDirs {
|
Ok(HostDirs {
|
||||||
app_data_root: root.join("apps"),
|
data_home: root.join("share"),
|
||||||
|
home: root.join("home"),
|
||||||
documents,
|
documents,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -276,7 +317,7 @@ mod tests {
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(read.dirs[0].access, Access::Read);
|
assert_eq!(read.dirs[0].access, Access::Read);
|
||||||
assert!(read.dirs[0].preopen_arg().ends_with("::/data::ro"));
|
assert!(read.dirs[0].preopen_arg().ends_with("::/data::ro"));
|
||||||
assert!(root.join("apps/org.example.app/data").is_dir());
|
assert!(root.join("share/weft/app-data/org.example.app").is_dir());
|
||||||
|
|
||||||
let both = derive(
|
let both = derive(
|
||||||
"org.example.app",
|
"org.example.app",
|
||||||
|
|
@ -320,7 +361,7 @@ mod tests {
|
||||||
derive("org.example.app", &caps(declared), host(&root, None)).unwrap_err();
|
derive("org.example.app", &caps(declared), host(&root, None)).unwrap_err();
|
||||||
assert_eq!(refusal.code, 403, "{declared:?}");
|
assert_eq!(refusal.code, 403, "{declared:?}");
|
||||||
}
|
}
|
||||||
assert!(!root.join("apps").exists());
|
assert!(!root.join("share").exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -378,4 +419,71 @@ mod tests {
|
||||||
assert_eq!(grants.dirs[0].guest, "/xdg/documents");
|
assert_eq!(grants.dirs[0].guest, "/xdg/documents");
|
||||||
assert_eq!(grants.dirs[0].access, Access::ReadWrite);
|
assert_eq!(grants.dirs[0].access, Access::ReadWrite);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn earlier_app_data_is_moved_on_launch() {
|
||||||
|
let root = temp("migrate");
|
||||||
|
let legacy = root.join("home/.local/share/weft/apps/org.example.app/data");
|
||||||
|
std::fs::create_dir_all(&legacy).unwrap();
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
std::fs::set_permissions(&legacy, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::write(legacy.join("notes.txt"), "kept").unwrap();
|
||||||
|
let grants = derive(
|
||||||
|
"org.example.app",
|
||||||
|
&caps(&["fs:rw:app-data"]),
|
||||||
|
host(&root, None),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let data = root.join("share/weft/app-data/org.example.app");
|
||||||
|
assert_eq!(grants.dirs[0].host, data);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(data.join("notes.txt")).unwrap(),
|
||||||
|
"kept"
|
||||||
|
);
|
||||||
|
assert!(!legacy.exists());
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let mode = std::fs::metadata(&data).unwrap().permissions().mode();
|
||||||
|
assert_eq!(mode & 0o777, 0o700);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn conflicting_app_data_refuses_the_launch() {
|
||||||
|
let root = temp("conflict");
|
||||||
|
let legacy = root.join("home/.local/share/weft/apps/org.example.app/data");
|
||||||
|
let data = root.join("share/weft/app-data/org.example.app");
|
||||||
|
std::fs::create_dir_all(&legacy).unwrap();
|
||||||
|
std::fs::create_dir_all(&data).unwrap();
|
||||||
|
let refusal = derive(
|
||||||
|
"org.example.app",
|
||||||
|
&caps(&["fs:read:app-data"]),
|
||||||
|
host(&root, None),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(refusal.code, 409);
|
||||||
|
assert!(legacy.is_dir() && data.is_dir());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn app_data_is_private() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let root = temp("private");
|
||||||
|
derive(
|
||||||
|
"org.example.app",
|
||||||
|
&caps(&["fs:rw:app-data"]),
|
||||||
|
host(&root, None),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mode = std::fs::metadata(root.join("share/weft/app-data/org.example.app"))
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode();
|
||||||
|
assert_eq!(mode & 0o777, 0o700);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,3 +14,6 @@ rmp-serde = "1"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
|
rustix = { version = "1", features = ["fs"] }
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,7 @@
|
||||||
//! Package identity rules shared by the packaging tool and the supervisor.
|
//! Package identity and storage rules shared by the packaging tool and the
|
||||||
|
//! supervisor.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
/// Whether `id` is a valid application ID: at least three dot-separated
|
/// Whether `id` is a valid application ID: at least three dot-separated
|
||||||
/// segments, each starting with a lowercase ASCII letter and containing only
|
/// segments, each starting with a lowercase ASCII letter and containing only
|
||||||
|
|
@ -14,6 +17,166 @@ pub fn is_valid_app_id(id: &str) -> bool {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The user's data home: `$XDG_DATA_HOME` when it is an absolute path,
|
||||||
|
/// otherwise `$HOME/.local/share`.
|
||||||
|
pub fn data_home() -> Option<PathBuf> {
|
||||||
|
std::env::var_os("XDG_DATA_HOME")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|dir| dir.is_absolute())
|
||||||
|
.or_else(|| {
|
||||||
|
std::env::var_os("HOME")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|home| home.is_absolute())
|
||||||
|
.map(|home| home.join(".local/share"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The private data directory of an application, independent of where or
|
||||||
|
/// whether its package is installed.
|
||||||
|
pub fn app_data_dir(data_home: &Path, app_id: &str) -> PathBuf {
|
||||||
|
data_home.join("weft/app-data").join(app_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where earlier versions kept application data: inside the user package
|
||||||
|
/// store, under the installed package directory.
|
||||||
|
pub fn legacy_app_data_dir(home: &Path, app_id: &str) -> PathBuf {
|
||||||
|
home.join(".local/share/weft/apps")
|
||||||
|
.join(app_id)
|
||||||
|
.join("data")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The result of moving data from the earlier layout.
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum Migration {
|
||||||
|
/// No data in the earlier layout.
|
||||||
|
NotNeeded,
|
||||||
|
/// The directory was moved to the new location.
|
||||||
|
Moved,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why data in the earlier layout could not be moved. Nothing was changed.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum MigrationError {
|
||||||
|
/// Data exists in both locations; either may hold the user's latest
|
||||||
|
/// data, so the user has to choose.
|
||||||
|
Conflict {
|
||||||
|
legacy: PathBuf,
|
||||||
|
target: PathBuf,
|
||||||
|
},
|
||||||
|
/// The two locations are on different filesystems, so the data cannot
|
||||||
|
/// be moved in one step.
|
||||||
|
CrossDevice {
|
||||||
|
legacy: PathBuf,
|
||||||
|
target: PathBuf,
|
||||||
|
},
|
||||||
|
/// The earlier location is not a plain directory.
|
||||||
|
NotADirectory(PathBuf),
|
||||||
|
Io(std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for MigrationError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Conflict { legacy, target } => write!(
|
||||||
|
f,
|
||||||
|
"app data exists both in {} and in {}; keep one of them and remove the other",
|
||||||
|
legacy.display(),
|
||||||
|
target.display()
|
||||||
|
),
|
||||||
|
Self::CrossDevice { legacy, target } => write!(
|
||||||
|
f,
|
||||||
|
"app data in {} cannot be moved to {} on another filesystem; move it there by hand",
|
||||||
|
legacy.display(),
|
||||||
|
target.display()
|
||||||
|
),
|
||||||
|
Self::NotADirectory(path) => write!(
|
||||||
|
f,
|
||||||
|
"{} is not a plain directory; move it aside to continue",
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
|
Self::Io(e) => e.fmt(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for MigrationError {}
|
||||||
|
|
||||||
|
/// Moves `legacy` to `target` if `legacy` is a directory, in one rename so
|
||||||
|
/// the data is never partly in both places, and then removes the earlier
|
||||||
|
/// package directory if that leaves it empty. Refuses, changing nothing,
|
||||||
|
/// when `target` already exists (even empty), when `legacy` is a symbolic
|
||||||
|
/// link or not a directory, and when the rename would cross filesystems.
|
||||||
|
pub fn migrate_app_data(legacy: &Path, target: &Path) -> Result<Migration, MigrationError> {
|
||||||
|
let conflict = || MigrationError::Conflict {
|
||||||
|
legacy: legacy.to_path_buf(),
|
||||||
|
target: target.to_path_buf(),
|
||||||
|
};
|
||||||
|
let metadata = match std::fs::symlink_metadata(legacy) {
|
||||||
|
Ok(metadata) => metadata,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Migration::NotNeeded),
|
||||||
|
Err(e) => return Err(MigrationError::Io(e)),
|
||||||
|
};
|
||||||
|
if !metadata.is_dir() {
|
||||||
|
return Err(MigrationError::NotADirectory(legacy.to_path_buf()));
|
||||||
|
}
|
||||||
|
if std::fs::symlink_metadata(target).is_ok() {
|
||||||
|
return Err(conflict());
|
||||||
|
}
|
||||||
|
if let Some(parent) = target.parent() {
|
||||||
|
std::fs::create_dir_all(parent).map_err(MigrationError::Io)?;
|
||||||
|
}
|
||||||
|
match rename_no_replace(legacy, target) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Err(conflict()),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
|
||||||
|
return Err(MigrationError::CrossDevice {
|
||||||
|
legacy: legacy.to_path_buf(),
|
||||||
|
target: target.to_path_buf(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(e) => return Err(MigrationError::Io(e)),
|
||||||
|
}
|
||||||
|
if let Some(package_dir) = legacy.parent() {
|
||||||
|
// Fails, harmlessly, unless the directory is now empty.
|
||||||
|
let _ = std::fs::remove_dir(package_dir);
|
||||||
|
}
|
||||||
|
Ok(Migration::Moved)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renames `from` to `to`, failing with `AlreadyExists` instead of replacing
|
||||||
|
/// an existing `to`, even one created after the caller checked for it.
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||||
|
use rustix::fs::{CWD, RenameFlags, renameat_with};
|
||||||
|
renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE).map_err(std::io::Error::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||||
|
if std::fs::symlink_metadata(to).is_ok() {
|
||||||
|
return Err(std::io::ErrorKind::AlreadyExists.into());
|
||||||
|
}
|
||||||
|
std::fs::rename(from, to)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes `dir` accessible only to its owner. A symbolic link is refused
|
||||||
|
/// rather than followed.
|
||||||
|
pub fn make_private(dir: &Path) -> std::io::Result<()> {
|
||||||
|
let metadata = std::fs::symlink_metadata(dir)?;
|
||||||
|
if !metadata.is_dir() {
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"{} is not a plain directory",
|
||||||
|
dir.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
@ -34,4 +197,96 @@ mod tests {
|
||||||
assert!(!is_valid_app_id(bad), "{bad:?}");
|
assert!(!is_valid_app_id(bad), "{bad:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn temp(name: &str) -> PathBuf {
|
||||||
|
let dir = std::env::temp_dir().join(format!("weft_migrate_{name}_{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn data_lives_outside_the_package_store() {
|
||||||
|
let home = Path::new("/home/u");
|
||||||
|
let data = app_data_dir(&home.join(".local/share"), "org.weft.demo");
|
||||||
|
assert_eq!(
|
||||||
|
data,
|
||||||
|
Path::new("/home/u/.local/share/weft/app-data/org.weft.demo")
|
||||||
|
);
|
||||||
|
assert!(!data.starts_with("/home/u/.local/share/weft/apps"));
|
||||||
|
assert_eq!(
|
||||||
|
legacy_app_data_dir(home, "org.weft.demo"),
|
||||||
|
Path::new("/home/u/.local/share/weft/apps/org.weft.demo/data")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn migration_keeps_a_package_directory_with_other_content() {
|
||||||
|
let root = temp("keep-package");
|
||||||
|
let legacy = root.join("apps/org.weft.app/data");
|
||||||
|
std::fs::create_dir_all(&legacy).unwrap();
|
||||||
|
std::fs::write(root.join("apps/org.weft.app/wapp.toml"), "").unwrap();
|
||||||
|
migrate_app_data(&legacy, &root.join("new")).unwrap();
|
||||||
|
assert!(root.join("apps/org.weft.app/wapp.toml").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn migration_moves_data_intact() {
|
||||||
|
let root = temp("move");
|
||||||
|
let legacy = root.join("apps/org.weft.notes/data");
|
||||||
|
std::fs::create_dir_all(legacy.join("sub")).unwrap();
|
||||||
|
std::fs::write(legacy.join("notes.txt"), "line one\nline \\two").unwrap();
|
||||||
|
std::fs::write(legacy.join("sub/x"), [0u8, 255, 10]).unwrap();
|
||||||
|
let target = root.join("app-data/org.weft.notes");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
migrate_app_data(&legacy, &target).unwrap(),
|
||||||
|
Migration::Moved
|
||||||
|
);
|
||||||
|
assert!(!legacy.exists());
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(target.join("notes.txt")).unwrap(),
|
||||||
|
"line one\nline \\two"
|
||||||
|
);
|
||||||
|
assert_eq!(std::fs::read(target.join("sub/x")).unwrap(), [0u8, 255, 10]);
|
||||||
|
assert_eq!(
|
||||||
|
migrate_app_data(&legacy, &target).unwrap(),
|
||||||
|
Migration::NotNeeded
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn migration_refuses_conflicts_and_leaves_both() {
|
||||||
|
let root = temp("conflict");
|
||||||
|
let legacy = root.join("old");
|
||||||
|
let target = root.join("new");
|
||||||
|
std::fs::create_dir_all(&legacy).unwrap();
|
||||||
|
std::fs::create_dir_all(&target).unwrap();
|
||||||
|
std::fs::write(legacy.join("a"), "old").unwrap();
|
||||||
|
std::fs::write(target.join("a"), "new").unwrap();
|
||||||
|
let err = migrate_app_data(&legacy, &target).unwrap_err();
|
||||||
|
assert!(matches!(err, MigrationError::Conflict { .. }));
|
||||||
|
// An empty target is a conflict too: it may be in use.
|
||||||
|
std::fs::remove_file(target.join("a")).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
migrate_app_data(&legacy, &target),
|
||||||
|
Err(MigrationError::Conflict { .. })
|
||||||
|
));
|
||||||
|
std::fs::write(target.join("a"), "new").unwrap();
|
||||||
|
assert_eq!(std::fs::read_to_string(legacy.join("a")).unwrap(), "old");
|
||||||
|
assert_eq!(std::fs::read_to_string(target.join("a")).unwrap(), "new");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn migration_refuses_a_linked_legacy_directory() {
|
||||||
|
let root = temp("link");
|
||||||
|
std::fs::create_dir_all(root.join("elsewhere")).unwrap();
|
||||||
|
std::os::unix::fs::symlink(root.join("elsewhere"), root.join("old")).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
migrate_app_data(&root.join("old"), &root.join("new")),
|
||||||
|
Err(MigrationError::NotADirectory(_))
|
||||||
|
));
|
||||||
|
assert!(!root.join("new").exists());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -154,6 +154,12 @@ fn check_package(dir: &Path) -> anyhow::Result<String> {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Earlier versions kept app data in `<package>/data`; the name stays
|
||||||
|
// reserved so package content is never mistaken for user data.
|
||||||
|
if std::fs::symlink_metadata(dir.join("data")).is_ok() {
|
||||||
|
errors.push("a top-level 'data' entry is reserved and cannot be part of a package".into());
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(ref m) = manifest {
|
if let Some(ref m) = manifest {
|
||||||
if !weft_ipc_types::package::is_valid_app_id(&m.package.id) {
|
if !weft_ipc_types::package::is_valid_app_id(&m.package.id) {
|
||||||
errors.push(format!(
|
errors.push(format!(
|
||||||
|
|
@ -292,6 +298,15 @@ fn install_package_to(path: &Path, store_root: &Path) -> anyhow::Result<()> {
|
||||||
let manifest = load_manifest(dir)?;
|
let manifest = load_manifest(dir)?;
|
||||||
let app_id = &manifest.package.id;
|
let app_id = &manifest.package.id;
|
||||||
let dest = store_root.join(app_id);
|
let dest = store_root.join(app_id);
|
||||||
|
// An earlier weft-appd could leave only app data, or an empty directory,
|
||||||
|
// where the package now goes; move the data to its own location so it
|
||||||
|
// neither blocks nor joins the package.
|
||||||
|
if dest.is_dir() && only_holds_app_data(&dest)? {
|
||||||
|
if std::fs::symlink_metadata(dest.join("data")).is_ok() && is_user_store(store_root) {
|
||||||
|
move_app_data_out(app_id, &dest)?;
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_dir(&dest);
|
||||||
|
}
|
||||||
if dest.exists() {
|
if dest.exists() {
|
||||||
anyhow::bail!(
|
anyhow::bail!(
|
||||||
"package '{}' is already installed at {}; remove it first",
|
"package '{}' is already installed at {}; remove it first",
|
||||||
|
|
@ -322,11 +337,89 @@ fn uninstall_package_from(app_id: &str, store_root: &Path) -> anyhow::Result<()>
|
||||||
target.display()
|
target.display()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
std::fs::remove_dir_all(&target).with_context(|| format!("remove {}", target.display()))?;
|
// A `data` directory is never removed with the package: packages cannot
|
||||||
|
// ship one, so it holds app data from an earlier version. It is moved to
|
||||||
|
// the app data directory when this is the user store and the package
|
||||||
|
// declares app data (or its manifest cannot be read); otherwise uninstall
|
||||||
|
// stops and leaves everything in place.
|
||||||
|
if std::fs::symlink_metadata(target.join("data")).is_ok() {
|
||||||
|
let may_hold_app_data = load_manifest(&target).map_or(true, |m| declares_app_data(&m));
|
||||||
|
if !(may_hold_app_data && is_user_store(store_root)) {
|
||||||
|
anyhow::bail!(
|
||||||
|
"{} contains a 'data' directory that may hold app data; move it aside before \
|
||||||
|
uninstalling",
|
||||||
|
target.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
move_app_data_out(app_id, &target)?;
|
||||||
|
}
|
||||||
|
// Moving the data removes a package directory it leaves empty.
|
||||||
|
match std::fs::remove_dir_all(&target) {
|
||||||
|
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
|
||||||
|
return Err(e).with_context(|| format!("remove {}", target.display()));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
println!("uninstalled {}", app_id);
|
println!("uninstalled {}", app_id);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a package directory is empty or contains nothing but `data`.
|
||||||
|
fn only_holds_app_data(package_dir: &Path) -> anyhow::Result<bool> {
|
||||||
|
let entries = std::fs::read_dir(package_dir)
|
||||||
|
.with_context(|| format!("read {}", package_dir.display()))?
|
||||||
|
.map(|entry| entry.map(|e| e.file_name()))
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
Ok(entries.is_empty() || entries == ["data"])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the manifest declares an app-data capability; only such apps
|
||||||
|
/// had data kept in the package directory.
|
||||||
|
fn declares_app_data(manifest: &Manifest) -> bool {
|
||||||
|
use weft_ipc_types::capability::Capability;
|
||||||
|
manifest
|
||||||
|
.package
|
||||||
|
.capabilities
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.any(|c| matches!(c.parse(), Ok(Capability::AppData(_))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `store_root` is the user package store, where earlier versions of
|
||||||
|
/// weft-appd kept app data, however the path is spelled.
|
||||||
|
fn is_user_store(store_root: &Path) -> bool {
|
||||||
|
let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let user_store = home.join(".local/share/weft/apps");
|
||||||
|
match (
|
||||||
|
std::fs::canonicalize(store_root),
|
||||||
|
std::fs::canonicalize(user_store),
|
||||||
|
) {
|
||||||
|
(Ok(a), Ok(b)) => a == b,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves app data that an earlier weft-appd kept in `<package_dir>/data` in
|
||||||
|
/// the user store to the app's data directory, which package operations
|
||||||
|
/// never remove. Fails, changing nothing, if the data cannot be moved.
|
||||||
|
fn move_app_data_out(app_id: &str, package_dir: &Path) -> anyhow::Result<()> {
|
||||||
|
use weft_ipc_types::package::{
|
||||||
|
Migration, app_data_dir, data_home, make_private, migrate_app_data,
|
||||||
|
};
|
||||||
|
let legacy = package_dir.join("data");
|
||||||
|
let data_home = data_home().context("cannot locate the data home to keep app data")?;
|
||||||
|
let target = app_data_dir(&data_home, app_id);
|
||||||
|
if migrate_app_data(&legacy, &target).with_context(|| format!("keep app data of {app_id}"))?
|
||||||
|
== Migration::Moved
|
||||||
|
{
|
||||||
|
make_private(&target).with_context(|| format!("restrict {}", target.display()))?;
|
||||||
|
println!("app data kept at {}", target.display());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn list_installed_roots() -> Vec<PathBuf> {
|
fn list_installed_roots() -> Vec<PathBuf> {
|
||||||
if let Ok(explicit) = std::env::var("WEFT_APP_STORE") {
|
if let Ok(explicit) = std::env::var("WEFT_APP_STORE") {
|
||||||
return vec![PathBuf::from(explicit)];
|
return vec![PathBuf::from(explicit)];
|
||||||
|
|
@ -593,6 +686,199 @@ fn verify_package(dir: &Path, pub_key_file: &Path) -> anyhow::Result<bool> {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
/// Serialises the tests that change the process environment; the test
|
||||||
|
/// harness runs tests on parallel threads that share it.
|
||||||
|
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||||
|
|
||||||
|
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||||
|
ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A minimal valid package for `app_id` in `src` declaring `capabilities`.
|
||||||
|
fn write_package(src: &Path, app_id: &str, capabilities: &str) {
|
||||||
|
std::fs::create_dir_all(src.join("ui")).unwrap();
|
||||||
|
std::fs::write(src.join("app.wasm"), b"\0asm").unwrap();
|
||||||
|
std::fs::write(src.join("ui/index.html"), b"").unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
src.join("wapp.toml"),
|
||||||
|
format!(
|
||||||
|
"[package]\nid = \"{app_id}\"\nname = \"D\"\nversion = \"1.0.0\"\n\
|
||||||
|
capabilities = [{capabilities}]\n\n\
|
||||||
|
[runtime]\nmodule = \"app.wasm\"\n\n[ui]\nentry = \"ui/index.html\"\n"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `f` with HOME set to `home` and XDG_DATA_HOME to `home/share`.
|
||||||
|
fn with_home<T>(home: &Path, f: impl FnOnce() -> T) -> T {
|
||||||
|
let _env = env_lock();
|
||||||
|
let prior: Vec<_> = ["HOME", "XDG_DATA_HOME"]
|
||||||
|
.iter()
|
||||||
|
.map(|k| (*k, std::env::var_os(k)))
|
||||||
|
.collect();
|
||||||
|
// SAFETY: env_lock serialises every test that touches the environment.
|
||||||
|
unsafe {
|
||||||
|
std::env::set_var("HOME", home);
|
||||||
|
std::env::set_var("XDG_DATA_HOME", home.join("share"));
|
||||||
|
}
|
||||||
|
let result = f();
|
||||||
|
for (key, value) in prior {
|
||||||
|
unsafe {
|
||||||
|
match value {
|
||||||
|
Some(v) => std::env::set_var(key, v),
|
||||||
|
None => std::env::remove_var(key),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn temp_root(name: &str) -> PathBuf {
|
||||||
|
let root = std::env::temp_dir().join(format!("weft_pack_{name}_{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
root
|
||||||
|
}
|
||||||
|
|
||||||
|
const APP_DATA: &str = "\"fs:rw:app-data\"";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn uninstall_keeps_app_data_from_the_user_store() {
|
||||||
|
let home = temp_root("keep");
|
||||||
|
let app_id = "com.example.keep";
|
||||||
|
write_package(&home.join("src"), app_id, APP_DATA);
|
||||||
|
let store = home.join(".local/share/weft/apps");
|
||||||
|
install_package_to(&home.join("src"), &store).unwrap();
|
||||||
|
let legacy = store.join(app_id).join("data");
|
||||||
|
std::fs::create_dir_all(&legacy).unwrap();
|
||||||
|
std::fs::write(legacy.join("notes.txt"), "first\nsecond").unwrap();
|
||||||
|
|
||||||
|
with_home(&home, || uninstall_package_from(app_id, &store)).unwrap();
|
||||||
|
assert!(!store.join(app_id).exists());
|
||||||
|
let kept = weft_ipc_types::package::app_data_dir(&home.join("share"), app_id);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(kept.join("notes.txt")).unwrap(),
|
||||||
|
"first\nsecond"
|
||||||
|
);
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let mode = std::fs::metadata(&kept).unwrap().permissions().mode();
|
||||||
|
assert_eq!(mode & 0o777, 0o700);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A second copy cannot be merged: uninstall refuses and removes nothing.
|
||||||
|
install_package_to(&home.join("src"), &store).unwrap();
|
||||||
|
std::fs::create_dir_all(&legacy).unwrap();
|
||||||
|
assert!(with_home(&home, || uninstall_package_from(app_id, &store)).is_err());
|
||||||
|
assert!(legacy.is_dir() && kept.is_dir());
|
||||||
|
let _ = std::fs::remove_dir_all(&home);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn data_that_is_not_moved_is_never_removed() {
|
||||||
|
let home = temp_root("refuse");
|
||||||
|
let app_id = "com.example.refuse";
|
||||||
|
// No app-data capability: the data directory is left and uninstall stops.
|
||||||
|
write_package(&home.join("src"), app_id, "");
|
||||||
|
let store = home.join(".local/share/weft/apps");
|
||||||
|
install_package_to(&home.join("src"), &store).unwrap();
|
||||||
|
std::fs::create_dir_all(store.join(app_id).join("data")).unwrap();
|
||||||
|
std::fs::write(store.join(app_id).join("data/x"), "x").unwrap();
|
||||||
|
assert!(with_home(&home, || uninstall_package_from(app_id, &store)).is_err());
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(store.join(app_id).join("data/x")).unwrap(),
|
||||||
|
"x"
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(store.join(app_id)).unwrap();
|
||||||
|
|
||||||
|
// Another store: earlier versions never kept data there, so it stops too.
|
||||||
|
write_package(&home.join("src2"), app_id, APP_DATA);
|
||||||
|
let other = home.join("other-store");
|
||||||
|
install_package_to(&home.join("src2"), &other).unwrap();
|
||||||
|
std::fs::create_dir_all(other.join(app_id).join("data")).unwrap();
|
||||||
|
assert!(with_home(&home, || uninstall_package_from(app_id, &other)).is_err());
|
||||||
|
assert!(other.join(app_id).join("data").is_dir());
|
||||||
|
assert!(!home.join("share").exists());
|
||||||
|
let _ = std::fs::remove_dir_all(&home);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn data_left_without_a_manifest_is_moved_not_deleted() {
|
||||||
|
let home = temp_root("orphan");
|
||||||
|
let app_id = "org.weft.demo.notes";
|
||||||
|
let store = home.join(".local/share/weft/apps");
|
||||||
|
std::fs::create_dir_all(store.join(app_id).join("data")).unwrap();
|
||||||
|
std::fs::write(store.join(app_id).join("data/notes.txt"), "kept").unwrap();
|
||||||
|
// The store reached through another spelling of the same path.
|
||||||
|
let spelled = home.join(".local/share/weft/../weft/apps");
|
||||||
|
with_home(&home, || uninstall_package_from(app_id, &spelled)).unwrap();
|
||||||
|
let kept = weft_ipc_types::package::app_data_dir(&home.join("share"), app_id);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(kept.join("notes.txt")).unwrap(),
|
||||||
|
"kept"
|
||||||
|
);
|
||||||
|
assert!(!store.join(app_id).exists());
|
||||||
|
let _ = std::fs::remove_dir_all(&home);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_linked_home_still_finds_the_user_store() {
|
||||||
|
let root = temp_root("linked");
|
||||||
|
let real = root.join("var-home");
|
||||||
|
let app_id = "org.weft.demo.notes";
|
||||||
|
std::fs::create_dir_all(
|
||||||
|
real.join(".local/share/weft/apps")
|
||||||
|
.join(app_id)
|
||||||
|
.join("data"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::os::unix::fs::symlink(&real, root.join("home")).unwrap();
|
||||||
|
let store = real.join(".local/share/weft/apps");
|
||||||
|
with_home(&root.join("home"), || {
|
||||||
|
uninstall_package_from(app_id, &store)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert!(weft_ipc_types::package::app_data_dir(&root.join("home/share"), app_id).is_dir());
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn packages_cannot_ship_a_top_level_data_entry() {
|
||||||
|
let root = temp_root("ships-data");
|
||||||
|
let src = root.join("src");
|
||||||
|
write_package(&src, "com.example.ships", "");
|
||||||
|
std::fs::create_dir_all(src.join("data")).unwrap();
|
||||||
|
std::fs::write(src.join("data/asset.json"), "{}").unwrap();
|
||||||
|
let err = check_package(&src).unwrap_err().to_string();
|
||||||
|
assert!(err.contains("'data'"), "{err}");
|
||||||
|
assert!(install_package_to(&src, &root.join("store")).is_err());
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn install_moves_leftover_app_data_out_of_the_way() {
|
||||||
|
let home = temp_root("leftover");
|
||||||
|
let app_id = "com.example.leftover";
|
||||||
|
write_package(&home.join("src"), app_id, APP_DATA);
|
||||||
|
let store = home.join(".local/share/weft/apps");
|
||||||
|
std::fs::create_dir_all(store.join(app_id).join("data")).unwrap();
|
||||||
|
std::fs::write(store.join(app_id).join("data/x"), "x").unwrap();
|
||||||
|
|
||||||
|
with_home(&home, || install_package_to(&home.join("src"), &store)).unwrap();
|
||||||
|
assert!(store.join(app_id).join("wapp.toml").exists());
|
||||||
|
assert!(!store.join(app_id).join("data").exists());
|
||||||
|
let kept = weft_ipc_types::package::app_data_dir(&home.join("share"), app_id);
|
||||||
|
assert_eq!(std::fs::read_to_string(kept.join("x")).unwrap(), "x");
|
||||||
|
|
||||||
|
// An empty directory left behind does not block installation either.
|
||||||
|
with_home(&home, || uninstall_package_from(app_id, &store)).unwrap();
|
||||||
|
std::fs::create_dir_all(store.join(app_id)).unwrap();
|
||||||
|
with_home(&home, || install_package_to(&home.join("src"), &store)).unwrap();
|
||||||
|
let _ = std::fs::remove_dir_all(&home);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn app_id_valid() {
|
fn app_id_valid() {
|
||||||
assert!(weft_ipc_types::package::is_valid_app_id(
|
assert!(weft_ipc_types::package::is_valid_app_id(
|
||||||
|
|
@ -971,6 +1257,7 @@ entry = "ui/index.html"
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn list_installed_roots_uses_weft_app_store_when_set() {
|
fn list_installed_roots_uses_weft_app_store_when_set() {
|
||||||
|
let _env = env_lock();
|
||||||
let prior = std::env::var("WEFT_APP_STORE").ok();
|
let prior = std::env::var("WEFT_APP_STORE").ok();
|
||||||
unsafe { std::env::set_var("WEFT_APP_STORE", "/custom/store") };
|
unsafe { std::env::set_var("WEFT_APP_STORE", "/custom/store") };
|
||||||
let roots = list_installed_roots();
|
let roots = list_installed_roots();
|
||||||
|
|
@ -985,6 +1272,7 @@ entry = "ui/index.html"
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn list_installed_roots_includes_system_path() {
|
fn list_installed_roots_includes_system_path() {
|
||||||
|
let _env = env_lock();
|
||||||
let prior = std::env::var("WEFT_APP_STORE").ok();
|
let prior = std::env::var("WEFT_APP_STORE").ok();
|
||||||
unsafe { std::env::remove_var("WEFT_APP_STORE") };
|
unsafe { std::env::remove_var("WEFT_APP_STORE") };
|
||||||
let roots = list_installed_roots();
|
let roots = list_installed_roots();
|
||||||
|
|
|
||||||
|
|
@ -71,7 +71,7 @@ Every WebSocket connection must complete the upgrade and send `HELLO` as its fir
|
||||||
|
|
||||||
Capabilities are declared in `wapp.toml` under `[package] capabilities`. One vocabulary (`weft_ipc_types::capability`) is used by `weft-pack check`, which rejects unknown strings, by `weft-appd`, which derives the session's effective grants, and by `weft-runtime`, which enforces them.
|
Capabilities are declared in `wapp.toml` under `[package] capabilities`. One vocabulary (`weft_ipc_types::capability`) is used by `weft-pack check`, which rejects unknown strings, by `weft-appd`, which derives the session's effective grants, and by `weft-runtime`, which enforces them.
|
||||||
|
|
||||||
`weft-appd` derives grants once, before a session exists. `LAUNCH_APP` is answered with an error and nothing starts when the app ID is malformed (code 400), the package is not installed (404), a declared capability is unknown, unsupported on this host or cannot be satisfied (403), or the host cannot provide the resources (500, for example without `HOME`). All capabilities are checked before the app's data directory is created. Without `WEFT_RUNTIME_BIN`, appd starts no processes and derives no grants. The runtime does not read the manifest; it receives the grants as arguments:
|
`weft-appd` derives grants once, before a session exists. `LAUNCH_APP` is answered with an error and nothing starts when the app ID is malformed (code 400), the package is not installed (404), a declared capability is unknown, unsupported on this host or cannot be satisfied (403), app data exists in both the current and the earlier location (409), or the host cannot provide the resources (500, for example without `HOME`). All capabilities are checked before the app's data directory is created. Without `WEFT_RUNTIME_BIN`, appd starts no processes and derives no grants. The runtime does not read the manifest; it receives the grants as arguments:
|
||||||
|
|
||||||
- `--preopen HOST::GUEST::ro|rw` for each directory, with the access mode the capability names;
|
- `--preopen HOST::GUEST::ro|rw` for each directory, with the access mode the capability names;
|
||||||
- `--grant <capability>` for each host-import capability.
|
- `--grant <capability>` for each host-import capability.
|
||||||
|
|
@ -80,7 +80,7 @@ Each capability-controlled host import (fetch, notifications, clipboard) checks
|
||||||
|
|
||||||
| Capability | Effect |
|
| Capability | Effect |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `fs:read:app-data` / `fs:rw:app-data` | Preopen `~/.local/share/weft/apps/<id>/data` as `/data`, read-only or read-write |
|
| `fs:read:app-data` / `fs:rw:app-data` | Preopen the app's data directory (see *App data*) as `/data`, read-only or read-write |
|
||||||
| `fs:read:xdg-documents` / `fs:rw:xdg-documents` | Preopen the documents directory from the XDG user-dirs configuration (`XDG_DOCUMENTS_DIR`) as `/xdg/documents`; the launch fails when none is configured |
|
| `fs:read:xdg-documents` / `fs:rw:xdg-documents` | Preopen the documents directory from the XDG user-dirs configuration (`XDG_DOCUMENTS_DIR`) as `/xdg/documents`; the launch fails when none is configured |
|
||||||
| `net:fetch:<host>` | `weft:app/fetch` to that exact host (a lowercase DNS name or dotted IPv4 address) over HTTP or HTTPS, on any port |
|
| `net:fetch:<host>` | `weft:app/fetch` to that exact host (a lowercase DNS name or dotted IPv4 address) over HTTP or HTTPS, on any port |
|
||||||
| `net:fetch:*` | `weft:app/fetch` to any host |
|
| `net:fetch:*` | `weft:app/fetch` to any host |
|
||||||
|
|
@ -110,6 +110,17 @@ Package store roots (in priority order):
|
||||||
2. `~/.local/share/weft/apps/`
|
2. `~/.local/share/weft/apps/`
|
||||||
3. `/usr/share/weft/apps/`
|
3. `/usr/share/weft/apps/`
|
||||||
|
|
||||||
|
## App data
|
||||||
|
|
||||||
|
Each app's private data lives in `$XDG_DATA_HOME/weft/app-data/<id>` (`~/.local/share/weft/app-data/<id>` by default), apart from installed packages. Installing, updating or uninstalling a package never removes it. `weft-appd` creates the directory when a session with an app-data capability starts and makes it accessible only to the user (mode 0700); a symbolic link in its place is refused rather than followed. `weft-appd` and `weft-pack` must run with the same `HOME` and `XDG_DATA_HOME` to agree on this location; the systemd unit allows `weft-appd` to write under `~/.local/share/weft`.
|
||||||
|
|
||||||
|
Earlier versions kept app data inside the user package store, in `~/.local/share/weft/apps/<id>/data`, for apps declaring an app-data capability. That directory is moved to the new location in a single rename, which never replaces an existing directory:
|
||||||
|
|
||||||
|
- by `weft-appd`, on the first launch with an app-data capability;
|
||||||
|
- by `weft-pack uninstall` and `weft-pack install`, before they touch a package directory in the user store (however its path is spelled). `uninstall` moves it when the package declares an app-data capability or its manifest cannot be read, and otherwise stops without removing anything; a `data` directory is never deleted with a package.
|
||||||
|
|
||||||
|
A package directory left empty by the move is removed. Nothing is moved, and `weft-pack` stops or the launch is refused, when the new location already exists, even empty (error 409), when the old one is not a plain directory, or when the two are on different filesystems (error 500); the message names both locations so the user can keep one copy and remove the other. The system UI shows such refusals. Packages cannot contain a top-level `data` entry, so package content is never taken for app data. `tests/frame/check_app_data.py` checks that existing Notes data arrives byte for byte, that the Notes session then reads and saves it, and that a conflict is refused.
|
||||||
|
|
||||||
## Environment Variables
|
## Environment Variables
|
||||||
|
|
||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
|
|
|
||||||
|
|
@ -77,15 +77,33 @@ page reacts to clicks on either side of a boundary and to the `a` and
|
||||||
python3 tests/frame/check_input.py
|
python3 tests/frame/check_input.py
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The application checks run `weft-appd` with `weft-runtime` (built with
|
||||||
|
`wasmtime-runtime`) and `weft-app-shell` (built with `servo-embed`) on the
|
||||||
|
same nested desktop and drive the demo apps with real keyboard input:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 tests/frame/check_counter.py # Counter round trip through the session bridge
|
||||||
|
python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves
|
||||||
|
python3 tests/frame/check_app_data.py # Notes data from the earlier layout is moved and kept
|
||||||
|
```
|
||||||
|
|
||||||
## Demo apps (wasm32-wasip2)
|
## Demo apps (wasm32-wasip2)
|
||||||
|
|
||||||
Each demo is a standalone crate in `examples/`. Pre-built `app.wasm` binaries are committed. To rebuild:
|
Each demo is a standalone crate in `examples/`. Pre-built `app.wasm` binaries are committed; they are reproducible with the toolchain pinned in `rust-toolchain.toml`. To rebuild:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
rustup target add wasm32-wasip2
|
rustup target add wasm32-wasip2
|
||||||
cd examples/org.weft.demo.counter
|
cd examples/org.weft.demo.counter
|
||||||
cargo build --release
|
cargo build --release
|
||||||
# output: target/wasm32-wasip2/release/app.wasm
|
# output: target/wasm32-wasip2/release/app.wasm
|
||||||
|
cp target/wasm32-wasip2/release/app.wasm app.wasm
|
||||||
|
rm -rf target
|
||||||
|
```
|
||||||
|
|
||||||
|
The signature covers every file in the package directory, so remove the crate's `target` directory before signing it again. The demo packages are signed with the test key in `examples/keys`, which is a fixture, not a signing authority:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
weft-pack sign examples/org.weft.demo.notes --key examples/keys/weft-sign.key
|
||||||
```
|
```
|
||||||
|
|
||||||
## weft-runtime with Wasmtime
|
## weft-runtime with Wasmtime
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -1 +1 @@
|
||||||
e781544104eee4538e17f953ea3223903e2b2a46a78705cd1ffa8d6946a62d0385c76eab2cc1c2533eecbeff7600e76a4205abc66915be8851fe2e71316ebc0d
|
e8c10750b142b9df4405fd33ea0c060e63d44b5293e7f9ffa5b076989146b05e81f716e9b92aaeeb139ce1dc9b13ed26f356385d6a61a19c7f3dcaf6e95d2d03
|
||||||
|
|
@ -7,31 +7,195 @@ wit_bindgen::generate!({
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
use serde_json::{Value, json};
|
||||||
use weft::app::{ipc, notify};
|
use weft::app::{ipc, notify};
|
||||||
|
|
||||||
const NOTES_PATH: &str = "/data/notes.txt";
|
const NOTES_PATH: &str = "/data/notes.txt";
|
||||||
|
/// Held while a save checks the revision and replaces the file, so saves
|
||||||
|
/// from two Notes windows cannot interleave.
|
||||||
|
const LOCK_PATH: &str = "/data/.notes.lock";
|
||||||
|
/// A lock older than this was left by a session that ended mid-save.
|
||||||
|
const STALE_LOCK: std::time::Duration = std::time::Duration::from_secs(10);
|
||||||
|
/// Largest note accepted, in bytes; the page also keeps each request under
|
||||||
|
/// the 64 KiB app message limit.
|
||||||
|
const MAX_NOTES: usize = 60 * 1024;
|
||||||
|
|
||||||
fn load_notes() -> String {
|
/// A revision names the exact stored bytes. A save must name the revision
|
||||||
std::fs::read_to_string(NOTES_PATH).unwrap_or_default()
|
/// it was edited from, so a save based on stale content is refused instead
|
||||||
|
/// of silently replacing changes made in another window.
|
||||||
|
fn revision(bytes: &[u8]) -> String {
|
||||||
|
// FNV-1a, 64-bit.
|
||||||
|
let hash = bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| {
|
||||||
|
(h ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)
|
||||||
|
});
|
||||||
|
format!("{hash:016x}")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save_notes(text: &str) -> Result<(), String> {
|
fn stored() -> Result<Vec<u8>, String> {
|
||||||
std::fs::write(NOTES_PATH, text).map_err(|e| e.to_string())
|
match std::fs::read(NOTES_PATH) {
|
||||||
|
Ok(bytes) => Ok(bytes),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
|
||||||
|
Err(e) => Err(format!("cannot read notes: {e}")),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn json_text(text: &str) -> String {
|
fn load() -> Value {
|
||||||
let escaped = text
|
let bytes = match stored() {
|
||||||
.replace('\\', "\\\\")
|
Ok(bytes) => bytes,
|
||||||
.replace('"', "\\\"")
|
Err(message) => return json!({ "op": "error", "message": message }),
|
||||||
.replace('\n', "\\n")
|
};
|
||||||
.replace('\r', "\\r")
|
match String::from_utf8(bytes) {
|
||||||
.replace('\t', "\\t");
|
Ok(text) => json!({ "op": "loaded", "rev": revision(text.as_bytes()), "text": text }),
|
||||||
format!("{{\"text\":\"{escaped}\"}}")
|
Err(_) => json!({ "op": "error", "message": "stored notes are not valid UTF-8" }),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn json_error(msg: &str) -> String {
|
/// A value unique to this process and moment, for lock ownership and
|
||||||
let escaped = msg.replace('"', "\\\"");
|
/// staging file names.
|
||||||
format!("{{\"error\":\"{escaped}\"}}")
|
fn unique() -> String {
|
||||||
|
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
let nanos = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_nanos())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
format!("{nanos}-{n}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exclusive access to the notes file for one save. The lock file holds an
|
||||||
|
/// owner token, so a save only ever removes its own lock.
|
||||||
|
struct SaveLock {
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SaveLock {
|
||||||
|
fn acquire() -> Result<Self, String> {
|
||||||
|
use std::io::Write;
|
||||||
|
let token = unique();
|
||||||
|
for _ in 0..50 {
|
||||||
|
match std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(LOCK_PATH)
|
||||||
|
{
|
||||||
|
Ok(mut file) => {
|
||||||
|
if let Err(e) = file.write_all(token.as_bytes()) {
|
||||||
|
let _ = std::fs::remove_file(LOCK_PATH);
|
||||||
|
return Err(format!("cannot lock notes: {e}"));
|
||||||
|
}
|
||||||
|
return Ok(SaveLock { token });
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||||
|
// A lock older than STALE_LOCK was left by an ended session
|
||||||
|
// (wasmtime-wasi reports modification times, so an unknown
|
||||||
|
// age does not occur in practice). Renaming it away is
|
||||||
|
// atomic, so only one save can take it over. Two saves that
|
||||||
|
// both see it stale within the same instant could still
|
||||||
|
// both proceed; that needs an abandoned lock and two
|
||||||
|
// windows saving at once.
|
||||||
|
let stale = std::fs::metadata(LOCK_PATH)
|
||||||
|
.and_then(|m| m.modified())
|
||||||
|
.map(|t| t.elapsed().is_ok_and(|age| age > STALE_LOCK))
|
||||||
|
.unwrap_or(true);
|
||||||
|
let taken = format!("/data/.notes.lock.{token}.stale");
|
||||||
|
if stale && std::fs::rename(LOCK_PATH, &taken).is_ok() {
|
||||||
|
let _ = std::fs::remove_file(&taken);
|
||||||
|
} else {
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => return Err(format!("cannot lock notes: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err("notes are being saved by another window; try again".to_owned())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for SaveLock {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if std::fs::read_to_string(LOCK_PATH).is_ok_and(|t| t == self.token) {
|
||||||
|
let _ = std::fs::remove_file(LOCK_PATH);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes staging files left by saves that ended before their rename, and
|
||||||
|
/// stale locks whose removal failed. Only
|
||||||
|
/// called with the lock held, when no other save is in progress.
|
||||||
|
fn remove_abandoned_staging() {
|
||||||
|
let Ok(entries) = std::fs::read_dir("/data") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let name = entry.file_name();
|
||||||
|
let name = name.to_string_lossy();
|
||||||
|
let abandoned = (name.starts_with(".notes.txt.") && name.ends_with(".saving"))
|
||||||
|
|| (name.starts_with(".notes.lock.") && name.ends_with(".stale"));
|
||||||
|
if abandoned {
|
||||||
|
let _ = std::fs::remove_file(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes `text` to a staging file unique to this save, syncs it and renames
|
||||||
|
/// it over the notes, so the stored notes are always either the previous or
|
||||||
|
/// the new text in full.
|
||||||
|
fn replace_notes(text: &str) -> std::io::Result<()> {
|
||||||
|
use std::io::Write;
|
||||||
|
let staging = format!("/data/.notes.txt.{}.saving", unique());
|
||||||
|
let mut file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(&staging)?;
|
||||||
|
let written = file
|
||||||
|
.write_all(text.as_bytes())
|
||||||
|
.and_then(|()| file.sync_all())
|
||||||
|
.and_then(|()| std::fs::rename(&staging, NOTES_PATH));
|
||||||
|
if written.is_err() {
|
||||||
|
let _ = std::fs::remove_file(&staging);
|
||||||
|
}
|
||||||
|
written
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(seq: &Value, base: &str, text: &str) -> Value {
|
||||||
|
let error = |conflict: bool, message: String| json!({ "op": "error", "seq": seq, "conflict": conflict, "message": message });
|
||||||
|
if text.len() > MAX_NOTES {
|
||||||
|
return error(false, format!("notes are limited to {MAX_NOTES} bytes"));
|
||||||
|
}
|
||||||
|
let _lock = match SaveLock::acquire() {
|
||||||
|
Ok(lock) => lock,
|
||||||
|
Err(message) => return error(false, message),
|
||||||
|
};
|
||||||
|
remove_abandoned_staging();
|
||||||
|
let current = match stored() {
|
||||||
|
Ok(bytes) => revision(&bytes),
|
||||||
|
Err(message) => return error(false, message),
|
||||||
|
};
|
||||||
|
if current != base {
|
||||||
|
return error(true, "the notes were changed elsewhere".to_owned());
|
||||||
|
}
|
||||||
|
match replace_notes(text) {
|
||||||
|
Ok(()) => json!({ "op": "saved", "seq": seq, "rev": revision(text.as_bytes()) }),
|
||||||
|
Err(e) => error(false, format!("cannot save notes: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every request gets a reply, so the page never waits on one that was not
|
||||||
|
/// understood.
|
||||||
|
fn handle(raw: &str) -> Value {
|
||||||
|
let Ok(request) = serde_json::from_str::<Value>(raw) else {
|
||||||
|
return json!({ "op": "error", "message": "request is not valid JSON" });
|
||||||
|
};
|
||||||
|
let seq = request.get("seq").cloned().unwrap_or(Value::Null);
|
||||||
|
let field = |name: &str| request.get(name).and_then(Value::as_str);
|
||||||
|
match field("op") {
|
||||||
|
Some("load") => load(),
|
||||||
|
Some("save") => match (field("base"), field("text")) {
|
||||||
|
(Some(base), Some(text)) => save(&seq, base, text),
|
||||||
|
_ => json!({ "op": "error", "seq": seq, "message": "malformed save request" }),
|
||||||
|
},
|
||||||
|
_ => json!({ "op": "error", "seq": seq, "message": "unknown request" }),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|
@ -39,19 +203,7 @@ fn main() {
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
if let Some(raw) = ipc::recv() {
|
if let Some(raw) = ipc::recv() {
|
||||||
let raw = raw.trim().to_owned();
|
let _ = ipc::send(&handle(&raw).to_string());
|
||||||
let reply = if raw == "load" {
|
|
||||||
json_text(&load_notes())
|
|
||||||
} else if let Some(rest) = raw.strip_prefix("save:") {
|
|
||||||
let text = rest.replace("\\n", "\n");
|
|
||||||
match save_notes(&text) {
|
|
||||||
Ok(()) => json_text(&text),
|
|
||||||
Err(e) => json_error(&e),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let _ = ipc::send(&reply);
|
|
||||||
} else {
|
} else {
|
||||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -103,60 +103,144 @@
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
|
// The component stores the text exactly as typed. Messages are JSON; each
|
||||||
|
// save names the revision it was edited from and is acknowledged by its
|
||||||
|
// sequence number, so a reply never replaces text typed after it was sent.
|
||||||
|
// The editor is read-only until it holds the stored text, so nothing typed
|
||||||
|
// before a load completes can be saved over notes the user never saw.
|
||||||
|
var MAX_MESSAGE = 65536; // weft-appd's limit for one app message, in bytes
|
||||||
|
var REPLY_TIMEOUT = 10000;
|
||||||
var editor = document.getElementById('editor');
|
var editor = document.getElementById('editor');
|
||||||
var statusEl = document.getElementById('status');
|
var statusEl = document.getElementById('status');
|
||||||
var charEl = document.getElementById('charcount');
|
var charEl = document.getElementById('charcount');
|
||||||
|
var saveButton = document.getElementById('save');
|
||||||
var saved = '';
|
var saved = '';
|
||||||
|
var rev = null;
|
||||||
|
var seq = 0;
|
||||||
|
var pending = null;
|
||||||
|
var lastSent = null;
|
||||||
|
var loading = null; // timer of the outstanding load, if any
|
||||||
|
var encoder = new TextEncoder();
|
||||||
|
|
||||||
function setStatus(msg) { statusEl.textContent = msg; }
|
function setStatus(msg) { statusEl.textContent = msg; }
|
||||||
|
function countChars() { charEl.textContent = editor.value.length + ' chars'; }
|
||||||
|
function send(message) { window.weftIpc.send(JSON.stringify(message)); }
|
||||||
|
function setLoaded(loaded) {
|
||||||
|
editor.readOnly = !loaded;
|
||||||
|
saveButton.disabled = !loaded || pending !== null;
|
||||||
|
}
|
||||||
|
|
||||||
editor.addEventListener('input', function () {
|
editor.addEventListener('input', countChars);
|
||||||
charEl.textContent = editor.value.length + ' chars';
|
|
||||||
});
|
|
||||||
|
|
||||||
document.getElementById('save').addEventListener('click', function () {
|
function finishSave() {
|
||||||
if (!window.weftIpc) return;
|
if (pending) clearTimeout(pending.timer);
|
||||||
var text = editor.value.replace(/\n/g, '\\n');
|
pending = null;
|
||||||
window.weftIpc.send('save:' + text);
|
setLoaded(rev !== null);
|
||||||
|
}
|
||||||
|
|
||||||
|
saveButton.addEventListener('click', function () {
|
||||||
|
if (!window.weftIpc || pending) return;
|
||||||
|
if (rev === null) {
|
||||||
|
setStatus('the notes have not loaded; use Discard to reload them');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var request = { op: 'save', seq: seq + 1, base: rev, text: editor.value };
|
||||||
|
try {
|
||||||
|
encodeURIComponent(request.text);
|
||||||
|
} catch (_) {
|
||||||
|
setStatus('not saved: the text contains characters that cannot be stored');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (encoder.encode(JSON.stringify(request)).length > MAX_MESSAGE) {
|
||||||
|
setStatus('not saved: the notes are too long');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
seq += 1;
|
||||||
|
lastSent = { seq: seq, text: request.text };
|
||||||
|
pending = {
|
||||||
|
seq: seq,
|
||||||
|
text: request.text,
|
||||||
|
timer: setTimeout(function () {
|
||||||
|
finishSave();
|
||||||
|
setStatus('not saved: no reply; try again');
|
||||||
|
}, REPLY_TIMEOUT),
|
||||||
|
};
|
||||||
|
setLoaded(true);
|
||||||
|
send(request);
|
||||||
setStatus('saving…');
|
setStatus('saving…');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Loads the stored notes into a read-only editor. Only one load is
|
||||||
|
// outstanding at a time; a failed or unanswered load can be retried with
|
||||||
|
// Discard.
|
||||||
|
function load(status) {
|
||||||
|
rev = null;
|
||||||
|
lastSent = null;
|
||||||
|
setLoaded(false);
|
||||||
|
loading = setTimeout(function () {
|
||||||
|
loading = null;
|
||||||
|
setStatus('the notes did not load; use Discard to retry');
|
||||||
|
}, REPLY_TIMEOUT);
|
||||||
|
send({ op: 'load' });
|
||||||
|
setStatus(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
function finishLoad() {
|
||||||
|
clearTimeout(loading);
|
||||||
|
loading = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Discard reloads the stored notes, replacing unsaved edits.
|
||||||
document.getElementById('discard').addEventListener('click', function () {
|
document.getElementById('discard').addEventListener('click', function () {
|
||||||
|
if (!window.weftIpc || pending || loading) return;
|
||||||
editor.value = saved;
|
editor.value = saved;
|
||||||
charEl.textContent = saved.length + ' chars';
|
countChars();
|
||||||
setStatus('discarded');
|
load('reloading…');
|
||||||
setTimeout(function () { setStatus(''); }, 1500);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.addEventListener('keydown', function (e) {
|
document.addEventListener('keydown', function (e) {
|
||||||
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
document.getElementById('save').click();
|
saveButton.click();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
function setupIpc() {
|
function onMessage(raw) {
|
||||||
if (!window.weftIpc) { setTimeout(setupIpc, 50); return; }
|
var msg;
|
||||||
window.weftIpc.onmessage = function (raw) {
|
try { msg = JSON.parse(raw); } catch (_) { return; }
|
||||||
try {
|
if (msg.op === 'loaded') {
|
||||||
var msg = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
// Only the reply to the outstanding load applies; the editor is
|
||||||
if (typeof msg.error === 'string') {
|
// read-only until it arrives, so it never replaces newer text.
|
||||||
setStatus('error: ' + msg.error);
|
if (!loading) return;
|
||||||
return;
|
finishLoad();
|
||||||
}
|
editor.value = msg.text;
|
||||||
if (typeof msg.text === 'string') {
|
countChars();
|
||||||
var text = msg.text.replace(/\\n/g, '\n');
|
saved = msg.text;
|
||||||
editor.value = text;
|
rev = msg.rev;
|
||||||
saved = text;
|
setLoaded(true);
|
||||||
charEl.textContent = text.length + ' chars';
|
|
||||||
setStatus('');
|
setStatus('');
|
||||||
|
} else if (msg.op === 'saved' && !loading && lastSent && msg.seq === lastSent.seq) {
|
||||||
|
// Also accepts an acknowledgement that arrives after the timeout.
|
||||||
|
saved = lastSent.text;
|
||||||
|
rev = msg.rev;
|
||||||
|
finishSave();
|
||||||
|
setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet');
|
||||||
|
} else if (msg.op === 'error') {
|
||||||
|
if (pending && msg.seq === pending.seq) finishSave();
|
||||||
|
if (loading && msg.seq === undefined) finishLoad();
|
||||||
|
setStatus(msg.conflict
|
||||||
|
? 'not saved: changed in another window. Copy your text, then Discard to reload.'
|
||||||
|
: 'error: ' + msg.message);
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
|
||||||
};
|
|
||||||
setStatus('');
|
|
||||||
window.weftIpc.send('load');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setupIpc() {
|
||||||
|
if (!window.weftIpc) { setTimeout(setupIpc, 50); return; }
|
||||||
|
window.weftIpc.onmessage = onMessage;
|
||||||
|
load('loading…');
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoaded(false);
|
||||||
setupIpc();
|
setupIpc();
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
|
|
@ -336,7 +336,10 @@
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
} else if (msg.type === 'ERROR') {
|
} else if (msg.type === 'ERROR') {
|
||||||
|
// Launch refusals (missing package, capability or data conflict)
|
||||||
|
// must reach the user; the launcher otherwise looks unresponsive.
|
||||||
console.warn('appd error', msg.code, msg.message);
|
console.warn('appd error', msg.code, msg.message);
|
||||||
|
showNotification('Cannot open: ' + msg.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,9 @@ Restart=on-failure
|
||||||
RestartSec=1s
|
RestartSec=1s
|
||||||
ProtectSystem=strict
|
ProtectSystem=strict
|
||||||
PrivateTmp=true
|
PrivateTmp=true
|
||||||
ReadWritePaths=%t
|
# App data and the user package store, where earlier versions kept app data.
|
||||||
|
# %h is the home of the user the unit runs as; run it as the session user.
|
||||||
|
ReadWritePaths=%t -%h/.local/share/weft
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=graphical.target
|
WantedBy=graphical.target
|
||||||
|
|
|
||||||
128
tests/frame/check_app_data.py
Normal file
128
tests/frame/check_app_data.py
Normal file
|
|
@ -0,0 +1,128 @@
|
||||||
|
"""Check that existing Notes data survives the move to the app data store.
|
||||||
|
|
||||||
|
Earlier versions kept app data inside the user package store, at
|
||||||
|
`~/.local/share/weft/apps/<id>/data`. The harness places a notes file there
|
||||||
|
(with a backslash sequence, a newline and non-ASCII text, which must come
|
||||||
|
through byte for byte), runs weft-appd on a nested desktop and launches
|
||||||
|
`org.weft.demo.notes` with the real runtime and app shell. The session must
|
||||||
|
reach APP_READY, the file must then be at
|
||||||
|
`$XDG_DATA_HOME/weft/app-data/org.weft.demo.notes/notes.txt` with identical
|
||||||
|
bytes, the old directory and the emptied package directory must be gone,
|
||||||
|
and the new one private (0700). Typing at the end of the note and pressing
|
||||||
|
Ctrl+S must then store the moved text plus the typed text, which shows that
|
||||||
|
the session reads and writes the moved directory.
|
||||||
|
|
||||||
|
A second launch after placing a different file at the old location must be
|
||||||
|
refused with error 409, leaving both copies untouched.
|
||||||
|
|
||||||
|
Requires Xvfb, xwd, ImageMagick's convert and xdotool.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.dont_write_bytecode = True
|
||||||
|
from check_counter import AppdClient, free_port, read_endpoint # noqa: E402
|
||||||
|
from check_notes import wait_for_file # noqa: E402
|
||||||
|
from session import ROOT, Desktop, SessionError, missing_tools # noqa: E402
|
||||||
|
|
||||||
|
APP_ID = "org.weft.demo.notes"
|
||||||
|
NOTES = "first line\nliteral \\n stays\ncafé ☃\n".encode()
|
||||||
|
|
||||||
|
|
||||||
|
def run(args, desktop, home, xdotool):
|
||||||
|
legacy = home / ".local/share/weft/apps" / APP_ID / "data"
|
||||||
|
legacy.mkdir(parents=True)
|
||||||
|
(legacy / "notes.txt").write_bytes(NOTES)
|
||||||
|
data_home = home / "data-home"
|
||||||
|
target = data_home / "weft/app-data" / APP_ID
|
||||||
|
|
||||||
|
t = Path(args.target)
|
||||||
|
desktop.launch_client("appd", [t / "weft-appd"], {
|
||||||
|
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||||
|
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||||
|
"WEFT_APP_STORE": str(args.store),
|
||||||
|
"WEFT_DISABLE_CGROUP": "1",
|
||||||
|
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||||
|
"HOME": str(home),
|
||||||
|
"XDG_DATA_HOME": str(data_home),
|
||||||
|
})
|
||||||
|
port, token = read_endpoint(desktop.runtime, 30)
|
||||||
|
appd = AppdClient(port, token)
|
||||||
|
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||||
|
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 120)
|
||||||
|
if reply.get("type") != "APP_READY":
|
||||||
|
raise AssertionError(f"Notes did not start: {reply}")
|
||||||
|
if not (target / "notes.txt").is_file() or (target / "notes.txt").read_bytes() != NOTES:
|
||||||
|
raise AssertionError("notes did not arrive unchanged")
|
||||||
|
if legacy.parent.exists():
|
||||||
|
raise AssertionError(f"{legacy.parent} still exists")
|
||||||
|
if target.stat().st_mode & 0o777 != 0o700:
|
||||||
|
raise AssertionError(f"{target} is not private: {oct(target.stat().st_mode)}")
|
||||||
|
|
||||||
|
def act(*arguments):
|
||||||
|
subprocess.run([xdotool, *arguments], env={"DISPLAY": desktop.display},
|
||||||
|
check=True, timeout=30)
|
||||||
|
|
||||||
|
time.sleep(2)
|
||||||
|
act("search", "--class", "weft-compositor", "windowfocus", "--sync")
|
||||||
|
act("mousemove", "--sync", "100", "300")
|
||||||
|
act("click", "1")
|
||||||
|
act("key", "ctrl+End")
|
||||||
|
act("type", "--delay", "40", "ok")
|
||||||
|
act("key", "ctrl+s")
|
||||||
|
wait_for_file(target / "notes.txt", NOTES.decode() + "ok")
|
||||||
|
|
||||||
|
appd.send({"type": "TERMINATE_APP", "session_id": reply["session_id"]})
|
||||||
|
legacy.mkdir(parents=True)
|
||||||
|
(legacy / "notes.txt").write_bytes(b"other copy")
|
||||||
|
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||||
|
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 60)
|
||||||
|
if reply.get("type") != "ERROR" or reply.get("code") != 409:
|
||||||
|
raise AssertionError(f"conflicting data was not refused: {reply}")
|
||||||
|
if (legacy / "notes.txt").read_bytes() != b"other copy" or \
|
||||||
|
(target / "notes.txt").read_bytes() != NOTES + b"ok":
|
||||||
|
raise AssertionError("a refused launch changed app data")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__,
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor")
|
||||||
|
parser.add_argument("--target", type=Path, default=ROOT / "target/debug",
|
||||||
|
help="directory with weft-appd, weft-runtime and weft-app-shell")
|
||||||
|
parser.add_argument("--store", type=Path, default=ROOT / "examples",
|
||||||
|
help="app store containing org.weft.demo.notes")
|
||||||
|
parser.add_argument("--output", type=Path, default=ROOT / "target/app-data-check")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
xdotool = shutil.which("xdotool")
|
||||||
|
missing = missing_tools() + ([] if xdotool else ["xdotool"])
|
||||||
|
missing += [str(p) for p in (args.compositor, args.target / "weft-appd",
|
||||||
|
args.target / "weft-runtime",
|
||||||
|
args.target / "weft-app-shell")
|
||||||
|
if not p.is_file()]
|
||||||
|
if missing:
|
||||||
|
print("missing: " + ", ".join(missing), file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
home = Path(tempfile.mkdtemp(prefix="weft-home-"))
|
||||||
|
try:
|
||||||
|
with Desktop(args.compositor, args.output, outputs=["appd.log"]) as desktop:
|
||||||
|
run(args, desktop, home, xdotool)
|
||||||
|
except (AssertionError, SessionError, TimeoutError) as failure:
|
||||||
|
print(f"app data check failed: {failure}", file=sys.stderr)
|
||||||
|
print(f"logs in {args.output}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(home, ignore_errors=True)
|
||||||
|
print("app data check passed")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
208
tests/frame/check_notes.py
Normal file
208
tests/frame/check_notes.py
Normal file
|
|
@ -0,0 +1,208 @@
|
||||||
|
"""Check that the Notes demo stores exactly what the user types.
|
||||||
|
|
||||||
|
The harness runs weft-appd on a nested desktop with the real runtime and app
|
||||||
|
shell, seeds the Notes data with text containing a literal backslash
|
||||||
|
sequence, quotes, a tab and non-ASCII characters, launches
|
||||||
|
`org.weft.demo.notes` and edits it with real keyboard input:
|
||||||
|
|
||||||
|
1. Typing at the end and pressing Ctrl+S must store the seeded text plus
|
||||||
|
the typed text, byte for byte; a load or save that rewrote `\\n`, quotes
|
||||||
|
or tabs fails.
|
||||||
|
2. Text typed while a save is in flight (the runtime is paused with SIGSTOP
|
||||||
|
between Ctrl+S and the reply) must still be in the editor afterwards: a
|
||||||
|
second Ctrl+S stores it too.
|
||||||
|
3. After the file is changed on disk (as by another Notes window), a save
|
||||||
|
must be refused and the other window's text kept.
|
||||||
|
4. Discard reloads the stored text. Keys typed while that reload is in
|
||||||
|
flight (runtime paused again) must be ignored, so a following save stores
|
||||||
|
the reloaded text plus only what was typed afterwards.
|
||||||
|
5. A load that fails (the stored notes are not valid UTF-8) leaves Discard
|
||||||
|
usable: after the file is repaired, Discard loads it and it can be edited
|
||||||
|
and saved again.
|
||||||
|
|
||||||
|
Requires Xvfb, xwd, ImageMagick's convert and xdotool.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.dont_write_bytecode = True
|
||||||
|
from check_counter import AppdClient, free_port, read_endpoint # noqa: E402
|
||||||
|
from session import ROOT, Desktop, SessionError, missing_tools # noqa: E402
|
||||||
|
|
||||||
|
APP_ID = "org.weft.demo.notes"
|
||||||
|
SEED = 'path C:\\new\\table "quoted"\tcaf\u00e9 \u2603'
|
||||||
|
|
||||||
|
|
||||||
|
# The Discard button in the 800x600 Notes window at the desktop's origin.
|
||||||
|
DISCARD = ("663", "68")
|
||||||
|
|
||||||
|
|
||||||
|
def runtime_pid():
|
||||||
|
"""The process ID of the Notes session's weft-runtime."""
|
||||||
|
found = subprocess.run(["pgrep", "-n", "-f", f"weft-runtime {APP_ID}"],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
if found.returncode != 0:
|
||||||
|
raise AssertionError("no weft-runtime process for Notes")
|
||||||
|
return int(found.stdout.split()[0])
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_file(path, expected, timeout=15):
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if path.exists() and path.read_text(encoding="utf-8") == expected:
|
||||||
|
return
|
||||||
|
time.sleep(0.2)
|
||||||
|
actual = path.read_text(encoding="utf-8") if path.exists() else None
|
||||||
|
raise AssertionError(f"stored notes {actual!r}, expected {expected!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def run(args, desktop, home, xdotool):
|
||||||
|
data_home = home / "share"
|
||||||
|
notes = data_home / "weft/app-data" / APP_ID / "notes.txt"
|
||||||
|
notes.parent.mkdir(parents=True)
|
||||||
|
notes.write_text(SEED, encoding="utf-8")
|
||||||
|
|
||||||
|
t = Path(args.target)
|
||||||
|
desktop.launch_client("appd", [t / "weft-appd"], {
|
||||||
|
"WEFT_RUNTIME_BIN": str(t / "weft-runtime"),
|
||||||
|
"WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"),
|
||||||
|
"WEFT_APP_STORE": str(args.store),
|
||||||
|
"WEFT_DISABLE_CGROUP": "1",
|
||||||
|
"WEFT_APPD_WS_PORT": str(free_port()),
|
||||||
|
"HOME": str(home),
|
||||||
|
"XDG_DATA_HOME": str(data_home),
|
||||||
|
})
|
||||||
|
port, token = read_endpoint(desktop.runtime, 30)
|
||||||
|
appd = AppdClient(port, token)
|
||||||
|
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||||
|
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 120)
|
||||||
|
if reply.get("type") != "APP_READY":
|
||||||
|
raise AssertionError(f"Notes did not start: {reply}")
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
def act(*arguments):
|
||||||
|
subprocess.run([xdotool, *arguments], env={"DISPLAY": desktop.display},
|
||||||
|
check=True, timeout=30)
|
||||||
|
|
||||||
|
act("search", "--class", "weft-compositor", "windowfocus", "--sync")
|
||||||
|
# The editor fills the window below the header.
|
||||||
|
act("mousemove", "--sync", "100", "300")
|
||||||
|
act("click", "1")
|
||||||
|
act("key", "ctrl+End")
|
||||||
|
|
||||||
|
runtime = runtime_pid()
|
||||||
|
|
||||||
|
act("type", "--delay", "40", ' +\\t "x"')
|
||||||
|
expected = SEED + ' +\\t "x"'
|
||||||
|
os.kill(runtime, signal.SIGSTOP)
|
||||||
|
try:
|
||||||
|
act("key", "ctrl+s")
|
||||||
|
act("type", "--delay", "40", " more")
|
||||||
|
time.sleep(2)
|
||||||
|
finally:
|
||||||
|
os.kill(runtime, signal.SIGCONT)
|
||||||
|
wait_for_file(notes, expected)
|
||||||
|
time.sleep(1)
|
||||||
|
act("key", "ctrl+s")
|
||||||
|
expected += " more"
|
||||||
|
wait_for_file(notes, expected)
|
||||||
|
|
||||||
|
other = "written by another window"
|
||||||
|
notes.write_text(other, encoding="utf-8")
|
||||||
|
act("type", "--delay", "40", " lost?")
|
||||||
|
act("key", "ctrl+s")
|
||||||
|
time.sleep(3)
|
||||||
|
if notes.read_text(encoding="utf-8") != other:
|
||||||
|
raise AssertionError("a save replaced notes changed elsewhere")
|
||||||
|
|
||||||
|
os.kill(runtime, signal.SIGSTOP)
|
||||||
|
try:
|
||||||
|
act("mousemove", "--sync", *DISCARD)
|
||||||
|
act("click", "1")
|
||||||
|
act("mousemove", "--sync", "100", "300")
|
||||||
|
act("click", "1")
|
||||||
|
act("type", "--delay", "40", "zz")
|
||||||
|
# Let the page handle the keys while the reload is still unanswered.
|
||||||
|
time.sleep(2)
|
||||||
|
finally:
|
||||||
|
os.kill(runtime, signal.SIGCONT)
|
||||||
|
time.sleep(2)
|
||||||
|
act("key", "ctrl+End")
|
||||||
|
act("type", "--delay", "40", "!")
|
||||||
|
act("key", "ctrl+s")
|
||||||
|
wait_for_file(notes, other + "!")
|
||||||
|
notes.write_bytes(b"\xff not text")
|
||||||
|
act("mousemove", "--sync", *DISCARD)
|
||||||
|
act("click", "1")
|
||||||
|
time.sleep(2)
|
||||||
|
# The editor stays read-only and nothing can be saved over the file.
|
||||||
|
act("mousemove", "--sync", "100", "300")
|
||||||
|
act("click", "1")
|
||||||
|
act("type", "--delay", "40", "x")
|
||||||
|
act("key", "ctrl+s")
|
||||||
|
time.sleep(2)
|
||||||
|
if notes.read_bytes() != b"\xff not text":
|
||||||
|
raise AssertionError("a failed load changed the stored notes")
|
||||||
|
act("mousemove", "--sync", *DISCARD)
|
||||||
|
notes.write_text("repaired", encoding="utf-8")
|
||||||
|
act("click", "1")
|
||||||
|
time.sleep(2)
|
||||||
|
act("mousemove", "--sync", "100", "300")
|
||||||
|
act("click", "1")
|
||||||
|
act("key", "ctrl+End")
|
||||||
|
act("type", "--delay", "40", "?")
|
||||||
|
act("key", "ctrl+s")
|
||||||
|
wait_for_file(notes, "repaired?")
|
||||||
|
|
||||||
|
leftovers = [p.name for p in notes.parent.iterdir() if p.name != "notes.txt"]
|
||||||
|
if leftovers:
|
||||||
|
raise AssertionError(f"files left beside the notes: {leftovers}")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__,
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor")
|
||||||
|
parser.add_argument("--target", type=Path, default=ROOT / "target/debug",
|
||||||
|
help="directory with weft-appd, weft-runtime and weft-app-shell")
|
||||||
|
parser.add_argument("--store", type=Path, default=ROOT / "examples",
|
||||||
|
help="app store containing org.weft.demo.notes")
|
||||||
|
parser.add_argument("--output", type=Path, default=ROOT / "target/notes-check")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
xdotool = shutil.which("xdotool")
|
||||||
|
missing = missing_tools() + ([] if xdotool else ["xdotool"])
|
||||||
|
missing += [str(p) for p in (args.compositor, args.target / "weft-appd",
|
||||||
|
args.target / "weft-runtime", args.target / "weft-app-shell")
|
||||||
|
if not p.is_file()]
|
||||||
|
if missing:
|
||||||
|
print("missing: " + ", ".join(missing), file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
home = Path(tempfile.mkdtemp(prefix="weft-home-"))
|
||||||
|
try:
|
||||||
|
with Desktop(args.compositor, args.output, outputs=["appd.log", "notes.ppm"]) as desktop:
|
||||||
|
try:
|
||||||
|
run(args, desktop, home, xdotool)
|
||||||
|
except AssertionError:
|
||||||
|
(args.output / "notes.ppm").write_bytes(desktop.capture())
|
||||||
|
raise
|
||||||
|
except (AssertionError, SessionError, TimeoutError) as failure:
|
||||||
|
print(f"notes check failed: {failure}", file=sys.stderr)
|
||||||
|
print(f"logs and capture in {args.output}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(home, ignore_errors=True)
|
||||||
|
print("notes check passed")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Loading…
Reference in a new issue