pdf-shell-w4: net change of 2 commits

- pdf-shell-w4: written by an agent
- pdf-shell-w4: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 03:15:53 -05:00
parent 8a2893d336
commit a0e57a9188
16 changed files with 866 additions and 90 deletions
+4 -1
View File
@@ -11,5 +11,8 @@ description = "Crash-safe atomic file writing and replacement for the Craft suit
[lints]
workspace = true
# Plain fsync where F_FULLFSYNC is refused, and the replaced file's extended attributes (`fs`), with
# explicit size queries (`fgetxattr_query`).
[target.'cfg(target_vendor = "apple")'.dependencies]
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
rustix = { version = "1.1.6", default-features = false, features = ["std", "fs"] }
+192 -15
View File
@@ -34,6 +34,13 @@
//! Existing destinations always stage privately and retain their original Unix mode. Restoring
//! an already-matching mode needs no chmod, including on fixed-mode network filesystems.
//!
//! ### Attributes
//! A replaced file is the same document: its stage gets the file's extended attributes (macOS),
//! its hidden and system attributes (Windows, at creation) and its creation date (macOS,
//! Windows) before it is flushed. An extended attribute that cannot be read or copied whole, or
//! passes a bound, refuses the save and leaves the original as it was. Saving through a symbolic
//! link keeps the link and replaces the file it names, so the attributes kept are that file's.
//!
//! ### Platform Characteristics
//! - **Windows**: Antivirus scanners, search indexers, and backup utilities briefly hold files
//! open with sharing violations. The rename is retried with exponential backoff (`RenameRetry`).
@@ -60,8 +67,10 @@ pub trait AtomicFs {
/// umask/default ACL. Other platforms keep their native creation behavior.
fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result<File>;
/// Create the stage like [`AtomicFs::create_new`], carrying over the attributes of the file it
/// replaces. `keep` is the destination's `symlink_metadata`, so a replaced link keeps its own
/// attributes, not its target's. The default ignores `keep` and calls `create_new`.
/// replaces that can only be given at creation (Windows: hidden and system). `keep` is the
/// `metadata` of the regular file being replaced: a save through a symbolic link keeps the
/// link and replaces the file it names, so `keep` describes that file, never the link. `None`
/// for a new file. The default ignores `keep` and calls `create_new`.
fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result<File> {
let _ = keep;
self.create_new(path, permissions)
@@ -107,8 +116,18 @@ impl AtomicFs for RealFs {
}
fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result<File> {
let _ = (path, permissions, keep);
todo!("SH-C33")
// Given as the file is created, so a hidden file's stage is never visible: Windows has no
// safe call that sets them on an open file afterwards.
#[cfg(windows)]
if let Some(keep) = keep {
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
let mut options = OpenOptions::new();
options.write(true).create_new(true).attributes(keep.file_attributes() & KEPT_ATTRIBUTES);
return options.open(path);
}
#[cfg(not(windows))]
let _ = keep;
self.create_new(path, permissions)
}
fn sync(&self, file: &File) -> io::Result<()> {
@@ -327,12 +346,16 @@ fn replace_with_options(
check_writable(&target).map_err(|e| read_only_error(e, path))?;
}
let tmp = stage(fs, &dir, &name, path, existing.as_ref(), new_permissions, fill)?;
let tmp = stage(fs, &dir, &name, path, existing.as_ref().map(|m| (target.as_path(), m)), new_permissions, fill)?;
if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) {
let _ = fs.remove(&tmp);
return Err(rename_error(e, path, existed));
}
#[cfg(windows)]
if let Some(replaced) = existing.as_ref().filter(|m| m.is_file()) {
restore_kept_attributes(&target, replaced);
}
// The new bytes are in place; a failed directory fsync can't be undone and must not report
// the save as failed, so it is best effort.
@@ -381,31 +404,35 @@ fn adopt_group(fs: &dyn AtomicFs, file: &File, stage_gid: u32, replaced_gid: u32
}
/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions and group of
/// the file it replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when
/// the file it replaces (`replaced`: its resolved path and `metadata`, Unix), keep that file's
/// other attributes ([`keep_attributes`]) and flush it. Permission restoration is skipped when
/// the mode already matches after `fill`; the group bits are dropped when the file cannot be put
/// in the replaced file's group, so they never open the file to a group that was not granted
/// them. A leftover file with the same name is skipped. When any step fails, the temporary file
/// is removed.
/// them. A name something already has (a leftover file, a link, a folder) is skipped, never
/// opened, so nothing planted there receives or redirects the write. When any step fails, the
/// temporary file is removed.
fn stage(
fs: &dyn AtomicFs,
dir: &Path,
name: &str,
path: &Path,
replaced: Option<&std::fs::Metadata>,
replaced: Option<(&Path, &std::fs::Metadata)>,
new_permissions: NewFilePermissions,
fill: impl FnOnce(&mut File) -> io::Result<()>,
) -> io::Result<PathBuf> {
let existed = replaced.is_some();
// Windows files carry only a read-only flag, and a read-only file can't be replaced.
let perms = replaced.filter(|_| cfg!(unix)).map(|m| m.permissions());
let perms = replaced.filter(|_| cfg!(unix)).map(|(_, m)| m.permissions());
// A folder or other non-file at the target has no attributes a stage could carry.
let keep = replaced.map(|(_, m)| m).filter(|m| m.is_file());
// New documents inherit the directory's policy directly: no probe or chmod is needed.
// Existing destinations still stage privately, including when their final mode is shared.
let creation = if existed { NewFilePermissions::Private } else { new_permissions };
for _ in 0..8 {
let tmp = dir.join(temp_name(name));
let mut file = match fs.create_new(&tmp, creation) {
let mut file = match fs.create_new_keeping(&tmp, creation, keep) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) if name_taken(&e, &tmp) => continue,
Err(e) => return Err(write_error(e, path, dir, existed)),
};
let written = fill(&mut file)
@@ -425,7 +452,7 @@ fn stage(
}
// The group bits belong to the replaced file's group, which a new
// inode need not be in (setgid directory, another primary group).
if let Some(replaced) = replaced {
if let Some((_, replaced)) = replaced {
let stage_gid = std::os::unix::fs::MetadataExt::gid(&file.metadata()?);
let replaced_gid = std::os::unix::fs::MetadataExt::gid(replaced);
let perms = adopt_group(fs, &file, stage_gid, replaced_gid, p)?;
@@ -436,6 +463,7 @@ fn stage(
})
.map_err(|e| permissions_error(e, path))
})
.and_then(|()| keep_attributes(&file, replaced.filter(|(_, m)| m.is_file())).map_err(|e| attributes_error(e, path)))
.and_then(|()| fs.sync(&file).map_err(|e| write_error(e, path, dir, existed)));
#[allow(
clippy::drop_non_drop,
@@ -450,6 +478,143 @@ fn stage(
Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display())))
}
/// Whether creating the stage failed because something already has its name: a file, a link
/// (even a dangling one) or a folder. Windows reports a folder there as access denied.
fn name_taken(e: &io::Error, tmp: &Path) -> bool {
match e.kind() {
io::ErrorKind::AlreadyExists => true,
io::ErrorKind::PermissionDenied => cfg!(windows) && std::fs::symlink_metadata(tmp).is_ok(),
_ => false,
}
}
/// The Windows attributes a replaced file passes on to its stage: hidden and system, the two that
/// say who should see the file. A read-only file is never replaced, the archive bit is the
/// system's to set on a changed file, and the others describe how the volume stores it.
#[cfg(windows)]
const KEPT_ATTRIBUTES: u32 = 0x2 | 0x4;
/// A server that hides dot-named files (Samba, NAS) marks the stage hidden and keeps the mark
/// through the rename: the saved file then gets the replaced file's attributes back. Only when the
/// kept bits differ, since restoring the whole attribute word on a local disk would clear the
/// archive bit backup tools read. Best effort: the new bytes are already in place.
#[cfg(windows)]
fn restore_kept_attributes(target: &Path, replaced: &std::fs::Metadata) {
use std::os::windows::fs::MetadataExt;
let saved = std::fs::symlink_metadata(target).map(|m| m.file_attributes() & KEPT_ATTRIBUTES);
if saved.is_ok_and(|bits| bits != replaced.file_attributes() & KEPT_ATTRIBUTES) {
let _ = std::fs::set_permissions(target, replaced.permissions());
}
}
/// Give the stage what the replaced regular file (`replaced`: its resolved path and `metadata`)
/// carries besides its bytes and mode, before the stage is flushed: on macOS its extended
/// attributes (`copy_xattrs`; an attribute that cannot be kept refuses the save), on macOS and
/// Windows its creation date (best effort: a volume that stores none keeps the stage's own). A
/// saved document is the same document. A new file has nothing to keep.
fn keep_attributes(stage: &File, replaced: Option<(&Path, &std::fs::Metadata)>) -> io::Result<()> {
let Some((target, meta)) = replaced else { return Ok(()) };
#[cfg(target_os = "macos")]
copy_xattrs(target, stage)?;
#[cfg(not(target_os = "macos"))]
let _ = target;
#[cfg(any(target_os = "macos", windows))]
if let Ok(created) = meta.created() {
#[cfg(target_os = "macos")]
use std::os::macos::fs::FileTimesExt;
#[cfg(windows)]
use std::os::windows::fs::FileTimesExt;
let _ = stage.set_times(std::fs::FileTimes::new().set_created(created));
}
#[cfg(not(any(target_os = "macos", windows)))]
let _ = (stage, meta);
Ok(())
}
/// The longest list of extended attribute names read from a replaced file.
#[cfg(target_os = "macos")]
const MAX_XATTR_NAMES_BYTES: usize = 64 * 1024;
/// The most extended attributes copied from a replaced file.
#[cfg(target_os = "macos")]
const MAX_XATTRS: usize = 1024;
/// The largest extended attribute value copied (a resource fork can be larger than ordinary ones).
#[cfg(target_os = "macos")]
const MAX_XATTR_VALUE_BYTES: usize = 16 * 1024 * 1024;
/// The most extended attribute bytes copied from one file in all.
#[cfg(target_os = "macos")]
const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024;
/// Copy the extended attributes of the regular file at `target` (Finder tags, the "Open with"
/// binding, quarantine, resource forks) to the stage. The attributes are as untrusted as the
/// bytes, so the reads are bounded; one that cannot be read or written whole, or passes a bound,
/// refuses the save rather than dropping the user's metadata unnoticed. Only a volume without
/// extended attributes (`ENOTSUP`) is skipped. `com.apple.provenance` belongs to macOS, which
/// gives the new file its own. Compression bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`).
#[cfg(target_os = "macos")]
fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> {
use rustix::fs::{Mode, OFlags, XattrFlags, fgetxattr, fgetxattr_query, flistxattr, fsetxattr, open};
use rustix::io::Errno;
// Never read through a link: the target is already resolved, and a link swapped in since
// names another file. NONBLOCK keeps a FIFO put at the name from hanging the open.
let source = match open(target, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, Mode::empty()) {
Ok(fd) => File::from(fd),
Err(Errno::NOENT | Errno::LOOP) => return Ok(()),
Err(e) => return Err(e.into()),
};
if !source.metadata()?.is_file() {
return Ok(());
}
let names_too_long = || io::Error::other("the extended attribute names exceed 64 KiB");
let mut names = vec![0u8; MAX_XATTR_NAMES_BYTES];
let len = match flistxattr(&source, names.as_mut_slice()) {
Ok(len) => len,
Err(Errno::NOTSUP) => return Ok(()),
Err(Errno::RANGE) => return Err(names_too_long()),
Err(e) => return Err(e.into()),
};
let names = names.get(..len).ok_or_else(names_too_long)?;
let mut total = 0usize;
for (index, name) in names.split(|b| *b == 0).filter(|name| !name.is_empty()).enumerate() {
if index >= MAX_XATTRS {
return Err(io::Error::other("more than 1024 extended attributes"));
}
if name == b"com.apple.provenance" {
continue;
}
let name = std::ffi::CString::new(name).map_err(|_| io::Error::other("an extended attribute name is not valid"))?;
// An empty read buffer reads zero bytes in rustix, not the size: query it explicitly.
let size = fgetxattr_query(&source, &name)?;
if size > MAX_XATTR_VALUE_BYTES || size > MAX_XATTR_TOTAL_BYTES.saturating_sub(total) {
return Err(io::Error::other("the extended attributes exceed 16 MiB per value or 64 MiB in total"));
}
let value = read_xattr_value(size, |buffer| Ok(fgetxattr(&source, &name, buffer)?), || Ok(fgetxattr_query(&source, &name)?))?;
fsetxattr(stage, &name, &value, XattrFlags::empty())?;
total = total.saturating_add(value.len());
}
Ok(())
}
/// Read one attribute value of `size` bytes (already within the bounds) with `read`, then ask
/// its size again with `query_size`. A read that does not fill `size`, or a size that changed,
/// is refused: a growing resource fork returns the prefix that fits instead of an error.
#[cfg(target_os = "macos")]
fn read_xattr_value(
size: usize,
read: impl FnOnce(&mut [u8]) -> io::Result<usize>,
query_size: impl FnOnce() -> io::Result<usize>,
) -> io::Result<Vec<u8>> {
let mut value = vec![0u8; size.max(1)];
let len = read(value.as_mut_slice())?;
let after = query_size()?;
if len != size || after != size {
return Err(io::Error::other("an extended attribute changed size while saving"));
}
value.truncate(len);
Ok(value)
}
/// Exclusively creates and writes `path` with normal OS permissions, without replacing existing files.
/// Use [`WriteOptions`] for private data.
pub fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> {
@@ -609,11 +774,18 @@ fn resolve_links(path: &Path) -> io::Result<PathBuf> {
Err(io::Error::new(io::ErrorKind::InvalidInput, format!("cannot save {}: too many levels of symbolic links", path.display())))
}
/// Generates a unique, hidden temporary file name beside `file`.
/// The most bytes of the target's name a temporary name keeps: with the leading `.`, the pid, the
/// counter and `.craft_tmp` the name stays within the 255-byte (Linux, macOS) and 255-unit
/// (Windows) limits however long the target's name is.
const TEMP_STEM_BYTES: usize = 128;
/// Generates a unique, hidden temporary file name beside `file`: `.{file}.{pid}-{n}.craft_tmp`,
/// with `file` cut to its first 128 bytes between characters.
pub fn temp_name(file: &str) -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let stem: String = file.chars().take(64).collect();
let end = file.char_indices().map(|(i, c)| i + c.len_utf8()).take_while(|&end| end <= TEMP_STEM_BYTES).last().unwrap_or(0);
let stem = file.get(..end).unwrap_or_default();
#[cfg(not(target_arch = "wasm32"))]
let pid = std::process::id();
#[cfg(target_arch = "wasm32")]
@@ -645,6 +817,11 @@ fn permissions_error(e: io::Error, path: &Path) -> io::Error {
io::Error::new(e.kind(), msg)
}
fn attributes_error(e: io::Error, path: &Path) -> io::Error {
let msg = format!("cannot save {}: the original's extended attributes cannot be kept ({e}){}", path.display(), unchanged(true));
io::Error::new(e.kind(), msg)
}
fn read_only_error(e: io::Error, path: &Path) -> io::Error {
let kept = unchanged(true);
let msg = match e.kind() {
+335
View File
@@ -241,6 +241,341 @@ fn temp_name_format_is_valid() {
assert!(name.ends_with(".craft_tmp"));
}
/// What a [`Planting`] filesystem puts at a stage name just before the stage is created there.
#[derive(Clone, Copy, Debug)]
enum Obstacle {
File,
Folder,
/// A link to the file `outside` beside the stage.
#[cfg(unix)]
Link,
/// A link to `missing` beside the stage, which does not exist.
#[cfg(unix)]
DanglingLink,
}
/// The real filesystem, except that the first `obstacles.len()` stage names get an obstacle
/// planted at them first, as someone racing the save would.
struct Planting {
obstacles: Vec<Obstacle>,
planted: std::cell::RefCell<Vec<PathBuf>>,
}
impl Planting {
fn new(obstacles: Vec<Obstacle>) -> Self {
Self { obstacles, planted: Default::default() }
}
fn plant(&self, at: &Path) -> io::Result<()> {
let next = self.planted.borrow().len();
let Some(&obstacle) = self.obstacles.get(next) else { return Ok(()) };
match obstacle {
Obstacle::File => std::fs::write(at, b"PLANTED")?,
Obstacle::Folder => std::fs::create_dir(at)?,
#[cfg(unix)]
Obstacle::Link => std::os::unix::fs::symlink(at.with_file_name("outside"), at)?,
#[cfg(unix)]
Obstacle::DanglingLink => std::os::unix::fs::symlink(at.with_file_name("missing"), at)?,
}
self.planted.borrow_mut().push(at.to_path_buf());
Ok(())
}
}
impl AtomicFs for Planting {
fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result<File> {
self.plant(path)?;
RealFs.create_new(path, permissions)
}
fn sync(&self, file: &File) -> io::Result<()> {
RealFs.sync(file)
}
fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
RealFs.rename(from, to)
}
fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> {
RealFs.hard_link(from, to)
}
fn remove(&self, path: &Path) -> io::Result<()> {
RealFs.remove(path)
}
fn sync_dir(&self, dir: &Path) -> io::Result<()> {
RealFs.sync_dir(dir)
}
fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> {
RealFs.set_permissions(file, perms)
}
#[cfg(unix)]
fn set_group(&self, file: &File, gid: u32) -> io::Result<()> {
RealFs.set_group(file, gid)
}
}
/// A stage name something already has (a file, a folder, a link, a dangling link) is skipped,
/// never opened: writing through it would put the user's document where the planter chose. With
/// every name taken the save fails and the original is kept.
#[test]
fn a_name_taken_at_the_stage_is_skipped_and_never_written_through() {
let d = TempDir::new("planted");
let p = d.0.join("doc.craft");
let outside = d.0.join("outside");
std::fs::write(&p, ORIGINAL).unwrap();
std::fs::write(&outside, b"OUTSIDE").unwrap();
#[cfg(unix)]
let obstacles = vec![Obstacle::File, Obstacle::Folder, Obstacle::Link, Obstacle::DanglingLink];
#[cfg(not(unix))]
let obstacles = vec![Obstacle::File, Obstacle::Folder];
let fs = Planting::new(obstacles.clone());
atomic_write_custom(&fs, NO_RETRY, &p, b"new").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"new");
let planted = fs.planted.into_inner();
assert_eq!(planted.len(), obstacles.len(), "every obstacle was met");
for (at, obstacle) in planted.iter().zip(&obstacles) {
let meta = std::fs::symlink_metadata(at).unwrap();
match obstacle {
Obstacle::File => assert_eq!(std::fs::read(at).unwrap(), b"PLANTED", "the planted file is not written"),
Obstacle::Folder => assert!(meta.is_dir() && std::fs::read_dir(at).unwrap().next().is_none(), "the folder is left empty"),
#[cfg(unix)]
Obstacle::Link | Obstacle::DanglingLink => assert!(meta.file_type().is_symlink(), "the link is left as a link"),
}
}
assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE", "nothing was written through a link");
assert!(!outside.with_file_name("missing").exists(), "a dangling link's file was not created");
for at in &planted {
let _ = std::fs::remove_file(at).or_else(|_| std::fs::remove_dir(at));
}
assert_no_temp(&d.0);
// Every name taken: the save is refused and the original kept.
let fs = Planting::new(vec![Obstacle::File; 64]);
let e = atomic_write_custom(&fs, NO_RETRY, &p, b"newer").unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{e}");
assert_eq!(std::fs::read(&p).unwrap(), b"new");
for at in fs.planted.into_inner() {
assert_eq!(std::fs::read(&at).unwrap(), b"PLANTED");
let _ = std::fs::remove_file(at);
}
assert_no_temp(&d.0);
}
/// A name near the 255-byte limit, in four-byte characters, still stages: the temporary name
/// keeps at most 128 bytes of it, cut between characters, and only the target is left.
#[test]
fn a_long_name_stages_and_leaves_only_the_target() {
let d = TempDir::new("long-name");
// 2 + 61 × 4 + 4 = 250 bytes, 67 characters: the first 64 characters alone are 247 bytes.
let name = format!("ab{}.pdf", "\u{1F600}".repeat(61));
assert_eq!(name.len(), 250);
let p = d.0.join(&name);
atomic_write(&p, b"first").unwrap();
atomic_write(&p, b"second").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"second");
let left: Vec<_> = std::fs::read_dir(&d.0).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(left, [std::ffi::OsString::from(&name)], "only the target is left");
let staged = temp_name(&name);
assert!(staged.len() <= 255, "{} bytes", staged.len());
assert!(staged.starts_with(&format!(".ab{}.", "\u{1F600}".repeat(31))), "128 bytes of the name, cut between characters: {staged}");
}
/// Reads the extended attribute `name` of `path`, following no further than the path itself.
#[cfg(target_os = "macos")]
fn xattr(path: &Path, name: &str) -> Option<Vec<u8>> {
let size = rustix::fs::getxattr_query(path, name).ok()?;
let mut value = vec![0u8; size.max(1)];
let len = rustix::fs::getxattr(path, name, &mut value[..]).ok()?;
value.truncate(len);
Some(value)
}
/// A save keeps the replaced file's extended attributes (Finder tags, the "Open with" binding,
/// quarantine, binary, empty and resource-fork values), save after save, including one another
/// process sets while the stage is written. Through a symbolic link the link stays and the file it
/// names keeps them. A link swapped in at the target while staging is never read through: its
/// file's attributes stay its own. (`com.apple.provenance` cannot be set by a test; a file that
/// has it saves only because the copy skips it, as macOS refuses writing it.)
#[cfg(target_os = "macos")]
#[test]
fn attributes_set_while_staging_are_kept() {
use rustix::fs::{XattrFlags, setxattr};
let d = TempDir::new("xattrs");
let target = d.0.join("doc.pdf");
std::fs::write(&target, ORIGINAL).unwrap();
let attributes: &[(&str, &[u8])] = &[
("com.apple.metadata:_kMDItemUserTags", b"<plist version=\"1.0\"><array><string>Craft\n6</string></array></plist>"),
("com.apple.LaunchServices.OpenWith", b"bplist00\xd1\x01\x02Wversion\x10\x00"),
("com.apple.quarantine", b"0081;5e0d1d05;Craft;"),
("com.craft.test.binary", b"\0\xff\x80original\0"),
("com.craft.test.empty", b""),
("com.apple.ResourceFork", b"\0\xfffork"),
];
for (name, value) in attributes {
setxattr(&target, *name, value, XattrFlags::empty()).unwrap();
}
// What the system stored (quarantine may be normalised): the saved file must hold the same.
let stored: Vec<_> = attributes.iter().map(|(name, _)| (*name, xattr(&target, name).unwrap())).collect();
for save in 0..2 {
atomic_write_with(&target, |f| {
// Another process tags the original while the new bytes are written.
setxattr(&target, "com.craft.test.late", format!("late {save}").as_bytes(), XattrFlags::empty())?;
f.write_all(b"new")
})
.unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"new");
for (name, value) in &stored {
assert_eq!(xattr(&target, name).as_ref(), Some(value), "save {save} keeps {name}");
}
assert_eq!(xattr(&target, "com.craft.test.late"), Some(format!("late {save}").into_bytes()), "set while staging");
assert_no_temp(&d.0);
}
// Through a link: the link stays, the file it names is replaced and keeps its attributes.
let link = d.0.join("link.pdf");
std::os::unix::fs::symlink(&target, &link).unwrap();
atomic_write(&link, b"through the link").unwrap();
assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link");
assert_eq!(std::fs::read(&target).unwrap(), b"through the link");
for (name, value) in &stored {
assert_eq!(xattr(&target, name).as_ref(), Some(value), "the linked file keeps {name}");
}
// A link put at the target while staging names another file: nothing is read through it.
let outside = d.0.join("outside.pdf");
std::fs::write(&outside, b"OUTSIDE").unwrap();
setxattr(&outside, "com.craft.test.private", b"private", XattrFlags::empty()).unwrap();
atomic_write_with(&target, |f| {
std::fs::remove_file(&target)?;
std::os::unix::fs::symlink(&outside, &target)?;
f.write_all(b"swapped")
})
.unwrap();
assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE");
assert_eq!(xattr(&outside, "com.craft.test.private"), Some(b"private".to_vec()));
assert!(!std::fs::symlink_metadata(&target).unwrap().file_type().is_symlink());
assert_eq!(xattr(&target, "com.craft.test.private"), None, "the swapped-in link's file lent nothing");
assert_no_temp(&d.0);
}
/// An attribute past the 16 MiB value bound refuses the save instead of dropping it: the target
/// keeps its bytes and its attribute, and no stage is left.
#[cfg(target_os = "macos")]
#[test]
fn oversized_attributes_refuse_the_save_and_keep_the_target() {
use rustix::fs::{XattrFlags, getxattr_query, setxattr};
let d = TempDir::new("xattrs-bound");
let target = d.0.join("doc.pdf");
std::fs::write(&target, ORIGINAL).unwrap();
// Only a resource fork may be this large; the bytes exist only in this temporary file.
let fork = vec![42u8; 16 * 1024 * 1024 + 1];
setxattr(&target, "com.apple.ResourceFork", &fork, XattrFlags::empty()).unwrap();
let e = atomic_write(&target, b"new").unwrap_err();
assert!(e.to_string().contains("extended attributes"), "{e}");
assert_eq!(std::fs::read(&target).unwrap(), ORIGINAL);
assert_eq!(getxattr_query(&target, "com.apple.ResourceFork").unwrap(), fork.len());
assert_no_temp(&d.0);
}
/// A value read must fill the size first queried and keep it in a second query: a growing
/// resource fork returns the prefix that fits instead of an error. Complete values, empty and
/// binary, are kept as read.
#[cfg(target_os = "macos")]
#[test]
fn an_attribute_read_must_fill_its_size_and_keep_it() {
for bytes in [&b""[..], &b"\0\xffB"[..]] {
let value = read_xattr_value(
bytes.len(),
|buffer| {
buffer[..bytes.len()].copy_from_slice(bytes);
Ok(bytes.len())
},
|| Ok(bytes.len()),
)
.unwrap();
assert_eq!(value, bytes);
}
// A short read, a size that grew after the read, a prefix of a grown value.
for (before, read_len, after) in [(3, 2, 3), (3, 3, 4), (0, 1, 1), (3, 2, 2)] {
let e = read_xattr_value(before, |_| Ok(read_len), || Ok(after)).unwrap_err();
assert!(e.to_string().contains("changed size"), "{before} {read_len} {after}: {e}");
}
let e = read_xattr_value(3, |_| Ok(3), || Err(io::Error::new(io::ErrorKind::PermissionDenied, "recheck refused"))).unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
}
/// A saved document is the same document: it keeps its creation date. A new file gets its own.
#[cfg(any(target_os = "macos", windows))]
#[test]
fn a_replaced_files_creation_date_is_kept() {
#[cfg(target_os = "macos")]
use std::os::macos::fs::FileTimesExt;
#[cfg(windows)]
use std::os::windows::fs::FileTimesExt;
let d = TempDir::new("created");
let target = d.0.join("doc.pdf");
std::fs::write(&target, ORIGINAL).unwrap();
// 2020-01-02 03:04:05 UTC.
let then = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_577_934_245);
let file = OpenOptions::new().write(true).open(&target).unwrap();
file.set_times(std::fs::FileTimes::new().set_created(then)).unwrap();
drop(file);
assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the fixture's date is set");
atomic_write(&target, b"new").unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"new");
assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the saved file keeps its creation date");
let fresh = d.0.join("new.pdf");
atomic_write(&fresh, b"new").unwrap();
assert!(std::fs::metadata(&fresh).unwrap().created().unwrap() > then, "a new file has a date of its own");
}
/// A hidden or system file stays hidden or system, and its stage already is while written; a
/// plain file stays plain though the stage's name starts with a dot; a new file gets neither.
/// Through a symbolic link the file it names is the replaced file and keeps its attributes.
#[cfg(windows)]
#[test]
fn hidden_and_system_attributes_are_kept() {
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
const HIDDEN: u32 = 0x2;
const SYSTEM: u32 = 0x4;
let d = TempDir::new("attributes");
let kept = |p: &Path| std::fs::metadata(p).unwrap().file_attributes() & (HIDDEN | SYSTEM);
let plant = |p: &Path, attributes: u32| {
let mut fixture = OpenOptions::new().write(true).create_new(true).attributes(attributes).open(p).unwrap();
fixture.write_all(ORIGINAL).unwrap();
};
for (i, keep) in [0, HIDDEN, SYSTEM, HIDDEN | SYSTEM].into_iter().enumerate() {
let target = d.0.join(format!("doc{i}.pdf"));
plant(&target, keep);
assert_eq!(kept(&target), keep, "the fixture has attributes {keep:#x}");
let mut staged = u32::MAX;
atomic_write_with(&target, |f| {
staged = f.metadata()?.file_attributes() & (HIDDEN | SYSTEM);
f.write_all(b"new")
})
.unwrap();
assert_eq!(staged, keep, "the stage has the target's attributes before it is flushed");
assert_eq!(kept(&target), keep, "the saved file keeps attributes {keep:#x}");
assert_eq!(std::fs::read(&target).unwrap(), b"new");
}
let fresh = d.0.join("new.pdf");
atomic_write(&fresh, b"new").unwrap();
assert_eq!(kept(&fresh), 0, "a new file is neither hidden nor system");
let referent = d.0.join("referent.pdf");
plant(&referent, HIDDEN);
let link = d.0.join("link.pdf");
if let Err(e) = std::os::windows::fs::symlink_file(&referent, &link) {
eprintln!("skipped the link case: creating a symbolic link needs Developer Mode or administrator rights ({e})");
return;
}
atomic_write(&link, b"through the link").unwrap();
assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link");
assert_eq!(std::fs::read(&referent).unwrap(), b"through the link");
assert_eq!(kept(&referent), HIDDEN, "the file the link names stays hidden");
assert_no_temp(&d.0);
}
#[cfg(target_arch = "wasm32")]
#[test]
fn wasm_atomic_write_returns_unsupported() {
+2 -6
View File
@@ -21,7 +21,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use craft_docpath::links::{Candidate, Link, LinkFiles, LinkSearch, LinkStatus, SearchEnd, SearchUpdate};
use craft_host::queue::{Cancel, JobQueue, Priority, QueueOptions, QueueOrder};
use craft_host::queue::{Cancel, JobQueue, Priority, QueueOptions};
use craft_host::{Jobs, Wake};
use craft_platform::watch::FileWatch;
@@ -223,11 +223,7 @@ impl<K: Clone + Send + 'static> SearchRun<K> {
wake: Wake,
) -> Self {
// filmcraft: crates/ui-egui/src/panels/media_dialogs.rs:146 (`link_media` ran `media.search` on the UI thread).
let queue = JobQueue::new(
jobs,
wake.clone(),
QueueOptions { lanes: 1, name: "relink-search", order: QueueOrder::default() }, /* P3(pdf-shell-w4): SH-C32 */
);
let queue = JobQueue::new(jobs, wake.clone(), QueueOptions { lanes: 1, name: "relink-search", ..QueueOptions::default() });
let updates = Arc::new(Mutex::new(Vec::new()));
let cancel = Cancel::new();
let inbox = Arc::clone(&updates);
+2 -2
View File
@@ -8,7 +8,7 @@ use craft_behavior::{ColumnKey, ColumnWidth, DisplayOrder, IconId, ItemSource, S
use craft_docpath::links::{
Candidate, CandidateProblem, Link, LinkFiles, LinkSearch, MatchCriteria, SearchEnd, SearchHit, SearchUpdate, check_candidate, derive_remap, rank,
};
use craft_host::queue::{JobQueue, Priority, QueueOptions, QueueOrder};
use craft_host::queue::{JobQueue, Priority, QueueOptions};
use craft_host::{Host, Jobs, PickId, PickRequest, Wake};
use craft_i18n::Format;
use craft_theme::variant::Tone;
@@ -637,7 +637,7 @@ impl<K: Clone + PartialEq + Send + Sync + 'static> Model<K> {
let checks = JobQueue::new(
Arc::clone(&jobs),
wake.clone(),
QueueOptions { lanes: 1, name: "relink-check", order: QueueOrder::default() }, /* P3(pdf-shell-w4): SH-C32 */
QueueOptions { lanes: 1, name: "relink-check", ..QueueOptions::default() },
);
self.runtime = Some(Runtime { jobs, wake, checks });
}
+30 -14
View File
@@ -16,6 +16,7 @@
//! On wasm32 there are no threads: [`QueueOptions::default_lanes`] is 0 and the owner calls
//! [`JobQueue::run_inline`] once per pass.
use std::cmp::Reverse;
use std::collections::VecDeque;
use std::hash::Hash;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -77,14 +78,17 @@ pub struct QueueOptions {
pub order: QueueOrder,
}
/// Which job runs first among jobs of equal priority: the one that arrived last or first.
/// Which job runs first among jobs of equal priority: the one that arrived last or first. Priority
/// always decides first; the order only breaks ties.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum QueueOrder {
/// The newest job runs first.
/// The newest job runs first: what was asked for last is what the user looks at now (a
/// thumbnail scrolled into view, the latest slider value).
#[default]
NewestFirst,
/// The oldest job runs first.
/// The oldest job runs first: every job is wanted and arrival order is the user's order (files
/// opened one after another).
OldestFirst,
}
@@ -102,7 +106,7 @@ impl QueueOptions {
}
impl Default for QueueOptions {
/// [`default_lanes`](QueueOptions::default_lanes) lanes named `"craft-queue"`.
/// [`default_lanes`](QueueOptions::default_lanes) lanes named `"craft-queue"`, newest first.
fn default() -> Self {
// new: the default every library queue starts from.
Self { lanes: Self::default_lanes(), name: "craft-queue", order: QueueOrder::default() }
@@ -137,7 +141,7 @@ type QueueJob<R> = Box<dyn FnOnce(&Cancel) -> R + Send>;
struct Queued<K, R> {
key: K,
priority: Priority,
/// Submission order: among equal priorities the newest runs first.
/// Submission order: among equal priorities [`QueueOrder`] picks the newest or the oldest.
seq: u64,
job: QueueJob<R>,
}
@@ -170,6 +174,8 @@ struct State<K, R> {
lanes_alive: usize,
seq: u64,
stopped: bool,
/// The tie order of [`best`](Self::best), from the queue's options.
order: QueueOrder,
}
struct Shared<K, R> {
@@ -199,14 +205,15 @@ impl<K, R> State<K, R> {
}
impl<K: Clone + Eq, R> State<K, R> {
/// Index of the best waiting job whose key is not running: highest priority, then newest.
/// Index of the best waiting job whose key is not running: highest priority, then the newest
/// or the oldest as [`QueueOrder`] says.
fn best(&self) -> Option<usize> {
self.queued
.iter()
.enumerate()
.filter(|(_, q)| !self.running.iter().any(|r| r.key == q.key))
.max_by_key(|(_, q)| (q.priority, q.seq))
.map(|(i, _)| i)
let startable = self.queued.iter().enumerate().filter(|(_, q)| !self.running.iter().any(|r| r.key == q.key));
match self.order {
QueueOrder::NewestFirst => startable.max_by_key(|(_, q)| (q.priority, q.seq)),
QueueOrder::OldestFirst => startable.max_by_key(|(_, q)| (q.priority, Reverse(q.seq))),
}
.map(|(i, _)| i)
}
/// Moves the best startable job to `running` and returns it.
@@ -320,7 +327,8 @@ impl<K: Clone + Eq + Send + 'static, R: Send + 'static> Shared<K, R> {
/// replaces a queued job of the same key, so scrolling or a slider drag never builds a backlog.
/// A key runs one job at a time: a key's next job waits until its running one ends (overlapping
/// renders of one picture are mostly thrown away).
/// - **Order.** Highest [`Priority`] first; among equal priorities the newest first.
/// - **Order.** Highest [`Priority`] first; among equal priorities the newest first, or the oldest
/// with [`QueueOrder::OldestFirst`] ([`QueueOptions::order`]).
/// [`reprioritize`](Self::reprioritize) re-ranks the waiting jobs or drops them; dropping a key
/// whose job runs sets its [`Cancel`] and its result is never delivered.
/// - **Lanes.** At most [`QueueOptions::lanes`] jobs run at once, each started through the
@@ -356,7 +364,15 @@ impl<K: Clone + Eq + Hash + Send + 'static, R: Send + 'static> JobQueue<K, R> {
/// after each finished job. No lane starts before the first [`submit`](Self::submit).
pub fn new(jobs: Arc<dyn Jobs>, wake: Wake, options: QueueOptions) -> Self {
// new: lanes are spawned on demand by `submit` and by a lane that ends with work waiting.
let state = State { queued: Vec::new(), running: Vec::new(), finished: VecDeque::new(), lanes_alive: 0, seq: 0, stopped: false };
let state = State {
queued: Vec::new(),
running: Vec::new(),
finished: VecDeque::new(),
lanes_alive: 0,
seq: 0,
stopped: false,
order: options.order,
};
Self { shared: Arc::new(Shared { state: Mutex::new(state), ended: Condvar::new(), jobs, wake, options }) }
}
+44 -4
View File
@@ -15,11 +15,24 @@ fn queue(lanes: usize) -> (JobQueue<&'static str, &'static str>, Arc<ManualJobs>
let wake = Wake::new(move || {
counter.fetch_add(1, Ordering::Relaxed);
});
// P3(pdf-shell-w4): SH-C32
let queue = JobQueue::new(jobs.clone(), wake, QueueOptions { lanes, name: "test", order: QueueOrder::default() });
let queue = JobQueue::new(jobs.clone(), wake, QueueOptions { lanes, name: "test", ..QueueOptions::default() });
(queue, jobs, wakes)
}
/// A queue without lanes in `order`: jobs run one at a time through `run_inline`.
fn inline_queue(order: QueueOrder) -> JobQueue<&'static str, &'static str> {
JobQueue::new(Arc::new(ManualJobs::new()), Wake::new(|| {}), QueueOptions { lanes: 0, name: "test", order })
}
/// Runs the waiting jobs one `run_inline(1)` at a time and returns their results in run order.
fn run_one_by_one(queue: &JobQueue<&'static str, &'static str>) -> Vec<&'static str> {
let mut ran = Vec::new();
while queue.run_inline(1) == 1 {
ran.extend(drain(queue));
}
ran
}
fn drain(queue: &JobQueue<&'static str, &'static str>) -> Vec<&'static str> {
std::iter::from_fn(|| queue.try_recv()).map(|Finished { result, .. }| result).collect()
}
@@ -89,11 +102,10 @@ fn queue_gives_back_a_lane_the_host_dropped() {
}
}
let jobs = Arc::new(Refusing(AtomicUsize::new(0), ManualJobs::new()));
// P3(pdf-shell-w4): SH-C32
let queue = JobQueue::<&'static str, &'static str>::new(
jobs.clone(),
Wake::new(|| {}),
QueueOptions { lanes: 1, name: "test", order: QueueOrder::default() },
QueueOptions { lanes: 1, name: "test", ..QueueOptions::default() },
);
queue.submit("a", Priority::VISIBLE, |_| "a");
jobs.0.store(1, Ordering::Relaxed);
@@ -119,3 +131,31 @@ fn queue_finish_runs_the_waiting_jobs_inline() {
done.sort_unstable();
assert_eq!(done, ["a", "b"], "each job ran once");
}
// Among equal priorities `OldestFirst` runs jobs in arrival order and the default runs the newest first; a tie rule
// flipped or ignored would reorder an app's file opens or its thumbnails.
#[test]
fn a_queue_ordered_oldest_first_runs_equal_priorities_in_arrival_order() {
let oldest = inline_queue(QueueOrder::OldestFirst);
let newest = inline_queue(QueueOrder::default());
for queue in [&oldest, &newest] {
queue.submit("one", Priority::NEAR, |_| "one");
queue.submit("two", Priority::NEAR, |_| "two");
queue.submit("three", Priority::NEAR, |_| "three");
}
assert_eq!(run_one_by_one(&oldest), ["one", "two", "three"]);
assert_eq!(run_one_by_one(&newest), ["three", "two", "one"]);
}
// Priority decides before arrival in both orders: background work submitted first never runs before visible work
// submitted later, nor does newer background work outrank older visible work.
#[test]
fn a_higher_priority_runs_before_a_lower_one_in_either_order() {
for order in [QueueOrder::NewestFirst, QueueOrder::OldestFirst] {
let queue = inline_queue(order);
queue.submit("background", Priority::BACKGROUND, |_| "background");
queue.submit("visible", Priority::VISIBLE, |_| "visible");
queue.submit("near", Priority::NEAR, |_| "near");
assert_eq!(run_one_by_one(&queue), ["visible", "near", "background"], "{order:?}");
}
}
+5
View File
@@ -20,5 +20,10 @@ dispatch2 = { version = "0.3.1", default-features = false, features = ["std"] }
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSResponder"] }
# `web::hold_leave`: the browser's `beforeunload` prompt.
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["Window", "Event", "EventTarget", "BeforeUnloadEvent"] }
[lints]
workspace = true
+36 -2
View File
@@ -1,8 +1,42 @@
//! Holding a browser tab open while work is unsaved.
//!
//! A tab has no close request an app can answer: the browser asks the user itself when the page's
//! `beforeunload` listener calls `prevent_default`. So the hold is the browser's own prompt, fed
//! each frame with whether work is at risk.
use std::cell::{Cell, OnceCell};
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
use web_sys::BeforeUnloadEvent;
thread_local! {
/// What the last [`hold_leave`] said. The listener runs on the page's one thread, outside any
/// frame, so it reads the last value the app gave.
static UNSAVED: Cell<bool> = const { Cell::new(false) };
/// The listener, kept alive for the page's life once the window has it.
static LISTENER: OnceCell<Closure<dyn FnMut(BeforeUnloadEvent)>> = const { OnceCell::new() };
}
/// Keeps one `beforeunload` listener that calls `prevent_default` while the last call said
/// `unsaved`. Call it each frame with whether work is at risk.
///
/// The first call adds the listener; a page without a window (a worker) or one that refuses the
/// listener gets none, and a later call tries again.
pub fn hold_leave(unsaved: bool) {
let _ = unsaved;
todo!("SH-C30")
UNSAVED.with(|cell| cell.set(unsaved));
LISTENER.with(|listener| {
if listener.get().is_some() {
return;
}
let Some(window) = web_sys::window() else { return };
let handler = Closure::<dyn FnMut(BeforeUnloadEvent)>::new(|event: BeforeUnloadEvent| {
if UNSAVED.with(Cell::get) {
event.prevent_default();
}
});
if window.add_event_listener_with_callback("beforeunload", handler.as_ref().unchecked_ref()).is_ok() {
let _ = listener.set(handler);
}
});
}
+4
View File
@@ -27,6 +27,10 @@ web-time = "1.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
dirs = "7"
# `BrowserFiles`: the web build's settings in localStorage.
[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3", features = ["Window", "Storage"] }
[dev-dependencies]
craft-settings = { path = ".", features = ["testing"] }
tempfile = "3"
+41 -11
View File
@@ -16,9 +16,9 @@ pub trait SettingsFiles: Send + Sync {
/// Replaces the file atomically; a new file is owner-only.
fn write(&self, path: &Path, text: &str) -> io::Result<()>;
/// Renames a damaged file aside and returns the new path
/// ([`move_aside`](crate::recovery::move_aside)'s naming).
/// ([`broken_path`](crate::recovery::broken_path)'s naming).
fn move_aside(&self, path: &Path) -> io::Result<PathBuf>;
/// Writes the backup beside `path` ([`write_backup`](crate::recovery::write_backup)'s rules).
/// Writes the backup beside `path`, at [`backup_path`](crate::recovery::backup_path).
fn write_backup(&self, path: &Path, text: &str) -> io::Result<()>;
/// Makes sure the folder exists before the store checks it. Files that have no folders
/// (browser storage) keep the default, which does nothing.
@@ -72,38 +72,68 @@ impl SettingsFiles for DiskFiles {
}
/// Settings kept in the browser's localStorage, keyed by path: the files of a web build.
///
/// Open the store with a [`Location::Dir`](crate::Location::Dir) naming the key root
/// (`config.toml` is stored under `<dir>/config.toml`); a storage the browser refuses or a full
/// quota comes back as an error, which the store reports like a disk's.
#[cfg(target_arch = "wasm32")]
#[derive(Clone, Copy, Debug, Default)]
pub struct BrowserFiles;
#[cfg(target_arch = "wasm32")]
impl BrowserFiles {
/// The page's localStorage; an error where the page has none or the browser blocks it.
fn storage() -> io::Result<web_sys::Storage> {
let window = web_sys::window().ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "no browser window"))?;
window.local_storage().map_err(js_error)?.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "browser storage is unavailable"))
}
/// The storage key of `path`: its text.
fn key(path: &Path) -> io::Result<&str> {
path.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path is not valid text"))
}
}
#[cfg(target_arch = "wasm32")]
impl SettingsFiles for BrowserFiles {
fn read(&self, path: &Path) -> io::Result<Option<String>> {
let _ = path;
todo!("SH-C29")
Self::storage()?.get_item(Self::key(path)?).map_err(js_error)
}
fn write(&self, path: &Path, text: &str) -> io::Result<()> {
let _ = (path, text);
todo!("SH-C29")
Self::storage()?.set_item(Self::key(path)?, text).map_err(js_error)
}
fn move_aside(&self, path: &Path) -> io::Result<PathBuf> {
let _ = path;
todo!("SH-C29")
let storage = Self::storage()?;
let key = Self::key(path)?;
let Some(text) = storage.get_item(key).map_err(js_error)? else {
return Err(io::Error::new(io::ErrorKind::NotFound, "nothing to move aside"));
};
let target = crate::recovery::free_broken_path(path, |target| Ok(storage.get_item(Self::key(target)?).map_err(js_error)?.is_some()))?;
storage.set_item(Self::key(&target)?, &text).map_err(js_error)?;
storage.remove_item(key).map_err(js_error)?;
Ok(target)
}
fn write_backup(&self, path: &Path, text: &str) -> io::Result<()> {
let _ = (path, text);
todo!("SH-C29")
let backup = crate::recovery::backup_path(path);
Self::storage()?.set_item(Self::key(&backup)?, text).map_err(js_error)
}
/// Storage has no folders: any key root accepts items while the page has storage at all.
fn check_writable(&self, dir: &Path) -> io::Result<()> {
let _ = dir;
todo!("SH-C29")
Self::storage().map(drop)
}
}
/// A browser exception as an I/O error, so the store treats it like a disk's.
#[cfg(target_arch = "wasm32")]
fn js_error(e: impl std::fmt::Debug) -> io::Error {
io::Error::other(format!("browser storage: {e:?}"))
}
/// New files are owner-only; on a replace `craft-atomic` keeps the existing file's mode.
#[cfg(all(unix, not(target_arch = "wasm32")))]
fn restrict_permissions(file: &std::fs::File) -> io::Result<()> {
+2 -5
View File
@@ -44,13 +44,10 @@ mod names;
pub mod presets;
pub mod remember;
#[cfg(not(target_arch = "wasm32"))]
pub mod paths;
#[cfg(not(target_arch = "wasm32"))]
pub mod profiles;
#[cfg(not(target_arch = "wasm32"))]
pub mod recovery;
#[cfg(not(target_arch = "wasm32"))]
pub mod store;
#[cfg(all(feature = "testing", not(target_arch = "wasm32")))]
pub mod testing;
@@ -63,11 +60,11 @@ pub use files::DiskFiles;
pub use files::SettingsFiles;
pub use migrate::LegacyFile;
#[cfg(not(target_arch = "wasm32"))]
pub use paths::{Location, Portable, Probe, Resolved, Rule};
pub use paths::Probe;
pub use paths::{Location, Portable, Resolved, Rule};
#[cfg(not(target_arch = "wasm32"))]
pub use profiles::{ProfileError, Profiles};
pub use remember::{Remembered, RememberedSection};
#[cfg(not(target_arch = "wasm32"))]
pub use store::{OpenOptions, SettingsStore, SharedSettings};
pub use toml_edit::DocumentMut;
+45 -6
View File
@@ -5,9 +5,16 @@
//! `<APP>_CONFIG_DIR`, or [`Location::Memory`], means no folder at all: nothing is read or written.
//! A portable folder that cannot be created or written to is skipped in favour of the platform
//! folder, and the reason comes back in [`Resolved::warning`].
//!
//! A web build has no environment, executable folder or platform folder, so it has no rules:
//! its location names the key root in browser storage ([`Location::Dir`]) or nothing
//! ([`Location::Memory`]).
#[cfg(not(target_arch = "wasm32"))]
use std::ffi::OsString;
use std::path::{Path, PathBuf};
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::path::PathBuf;
/// How an application spells portable mode: the marker files that turn it on (any one, contents
/// ignored) and the folder created beside the executable. Comes from [`crate::Settings`], so an
@@ -28,7 +35,8 @@ impl Portable {
/// Where the application wants its settings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Location {
/// Apply the rules in order.
/// Apply the rules in order. Native only: the rules read the process and the disk.
#[cfg(not(target_arch = "wasm32"))]
Auto,
/// Use this folder, no questions asked (a `--config-dir` flag, or a library folder).
Dir(PathBuf),
@@ -88,9 +96,11 @@ impl Resolved {
}
/// Reads an environment variable by name.
#[cfg(not(target_arch = "wasm32"))]
pub type EnvReader = Box<dyn Fn(&str) -> Option<OsString>>;
/// What the rules look at. The defaults read the real process; tests supply their own.
#[cfg(not(target_arch = "wasm32"))]
pub struct Probe {
/// Reads an environment variable.
pub env: EnvReader,
@@ -100,6 +110,7 @@ pub struct Probe {
pub platform_config_dir: Option<PathBuf>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for Probe {
fn default() -> Self {
Self {
@@ -110,6 +121,7 @@ impl Default for Probe {
}
}
#[cfg(not(target_arch = "wasm32"))]
impl std::fmt::Debug for Probe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Probe").field("exe_dir", &self.exe_dir).field("platform_config_dir", &self.platform_config_dir).finish_non_exhaustive()
@@ -123,8 +135,28 @@ pub fn env_var_name(app_id: &str) -> String {
name
}
/// The folder of a location that names it: [`Location::Dir`] and [`Location::Memory`]. `None` for
/// [`Location::Auto`], which the rules decide.
fn given(location: &Location) -> Option<Resolved> {
match location {
Location::Dir(dir) => Some(Resolved::new(Some(dir.clone()), Rule::Override)),
Location::Memory => Some(Resolved::new(None, Rule::Memory)),
#[cfg(not(target_arch = "wasm32"))]
Location::Auto => None,
}
}
/// The folder of a web build's location: the location names it, with no rules to apply.
#[cfg(target_arch = "wasm32")]
pub(crate) fn resolve_web(location: &Location) -> Resolved {
// Without `Location::Auto` every location names its folder; no folder is the answer that
// writes nothing should a later location not.
given(location).unwrap_or_else(|| Resolved::new(None, Rule::Memory))
}
/// Applies the rules for `app_id`, with the app's portable-mode names. The platform folder is
/// named after `app_id`; see [`resolve_named`] to name it differently.
#[cfg(not(target_arch = "wasm32"))]
pub fn resolve(app_id: &str, portable: &Portable, location: &Location, probe: &Probe) -> Resolved {
resolve_named(app_id, app_id, portable, location, probe)
}
@@ -133,6 +165,7 @@ pub fn resolve(app_id: &str, portable: &Portable, location: &Location, probe: &P
/// `folder` instead of the app id, so an app whose existing settings sit in a differently spelled
/// folder (`Photocraft` on macOS and Windows) keeps them. The `<APP>_CONFIG_DIR` variable still
/// comes from `app_id`.
#[cfg(not(target_arch = "wasm32"))]
pub fn resolve_named(app_id: &str, folder: &str, portable: &Portable, location: &Location, probe: &Probe) -> Resolved {
resolve_checked(app_id, folder, portable, location, probe, ensure_writable)
}
@@ -140,11 +173,13 @@ pub fn resolve_named(app_id: &str, folder: &str, portable: &Portable, location:
/// [`resolve_named`] without changing the disk: the portable folder is judged by its permissions (see
/// [`accepts_files`]) instead of creating it and writing a probe, with the same fallback to the platform folder.
/// For [`SettingsStore::read`](crate::SettingsStore::read), which writes nothing.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn resolve_unprobed(app_id: &str, folder: &str, portable: &Portable, location: &Location, probe: &Probe) -> Resolved {
resolve_checked(app_id, folder, portable, location, probe, accepts_files)
}
/// The folder rules, with `writable` deciding whether a portable folder is used.
#[cfg(not(target_arch = "wasm32"))]
fn resolve_checked(
app_id: &str,
folder: &str,
@@ -153,10 +188,8 @@ fn resolve_checked(
probe: &Probe,
writable: impl Fn(&Path) -> std::io::Result<()>,
) -> Resolved {
match location {
Location::Dir(dir) => return Resolved::new(Some(dir.clone()), Rule::Override),
Location::Memory => return Resolved::new(None, Rule::Memory),
Location::Auto => {}
if let Some(resolved) = given(location) {
return resolved;
}
let var = env_var_name(app_id);
if let Some(value) = (probe.env)(&var) {
@@ -191,6 +224,7 @@ fn resolve_checked(
}
/// Creates `dir` and proves a file can be written in it: a folder can exist and still be read-only.
#[cfg(not(target_arch = "wasm32"))]
fn ensure_writable(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
crate::recovery::check_writable(dir)
@@ -198,6 +232,7 @@ fn ensure_writable(dir: &Path) -> std::io::Result<()> {
/// Whether `dir`, or for a folder that doesn't exist yet its nearest existing ancestor (where
/// [`ensure_writable`] would create it), is a folder with write permission. Reads metadata only.
#[cfg(not(target_arch = "wasm32"))]
fn accepts_files(dir: &Path) -> std::io::Result<()> {
let existing = dir.ancestors().find(|ancestor| ancestor.exists()).unwrap_or(dir);
let meta = std::fs::metadata(existing)?;
@@ -214,11 +249,13 @@ fn accepts_files(dir: &Path) -> std::io::Result<()> {
///
/// On macOS the executable sits in `X.app/Contents/MacOS`; the marker is looked for next to the
/// `.app` bundle, because writing inside a signed bundle breaks its signature.
#[cfg(not(target_arch = "wasm32"))]
fn portable_dir(exe_dir: &Path, portable: &Portable) -> Option<(PathBuf, PathBuf)> {
let base = bundle_parent(exe_dir).unwrap_or(exe_dir);
portable.markers.iter().map(|m| base.join(m)).find(|m| m.is_file()).map(|marker| (marker, base.join(portable.dir)))
}
#[cfg(not(target_arch = "wasm32"))]
fn bundle_parent(exe_dir: &Path) -> Option<&Path> {
if !cfg!(target_os = "macos") || exe_dir.file_name()? != "MacOS" {
return None;
@@ -235,11 +272,13 @@ fn bundle_parent(exe_dir: &Path) -> Option<&Path> {
}
/// The platform cache folder for `app_id` (`%LOCALAPPDATA%` on Windows, so it does not roam).
#[cfg(not(target_arch = "wasm32"))]
pub fn cache_dir(app_id: &str) -> Option<PathBuf> {
dirs::cache_dir().map(|d| d.join(app_id))
}
/// The platform data folder for `app_id`, for recovery files and other non-settings state.
#[cfg(not(target_arch = "wasm32"))]
pub fn data_dir(app_id: &str) -> Option<PathBuf> {
dirs::data_local_dir().map(|d| d.join(app_id))
}
+35 -16
View File
@@ -1,30 +1,47 @@
//! Keeping damaged and previous files around.
//!
//! The names ([`broken_path`], [`backup_path`]) are the same for every
//! [`SettingsFiles`](crate::SettingsFiles); the file operations here are the disk's.
use std::io;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// Renames a damaged `config.toml` to `config.broken-<unix-ts>.toml` beside it and returns the
/// new path. Never overwrites: a name that exists gets a `-<n>` suffix.
pub fn move_aside(path: &Path) -> io::Result<PathBuf> {
// `std::time::SystemTime::now` panics on wasm32-unknown-unknown; `web_time` is std's on native.
use web_time::{SystemTime, UNIX_EPOCH};
/// How many `-<n>` suffixes a broken copy may try before the move aside gives up.
const MAX_BROKEN_COPIES: u32 = 1000;
/// The `n`th name for a damaged `config.toml` set aside at unix time `ts`, beside it:
/// `config.broken-<ts>.toml`, then `config.broken-<ts>-<n>.toml`.
pub fn broken_path(path: &Path, ts: u64, n: u32) -> PathBuf {
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("config");
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("toml");
let dir = path.parent().unwrap_or_else(|| Path::new("."));
let name = if n == 0 { format!("{stem}.broken-{ts}.{ext}") } else { format!("{stem}.broken-{ts}-{n}.{ext}") };
dir.join(name)
}
/// The first [`broken_path`] for `path` now that `taken` says is free. Never overwrites: after
/// [`MAX_BROKEN_COPIES`] taken names it fails.
pub(crate) fn free_broken_path(path: &Path, mut taken: impl FnMut(&Path) -> io::Result<bool>) -> io::Result<PathBuf> {
let ts = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let mut n = 0u32;
loop {
let name = if n == 0 { format!("{stem}.broken-{ts}.{ext}") } else { format!("{stem}.broken-{ts}-{n}.{ext}") };
let target = dir.join(name);
if target.exists() {
n = n.saturating_add(1);
if n > 1000 {
return Err(io::Error::new(io::ErrorKind::AlreadyExists, "too many broken copies"));
}
continue;
for n in 0..=MAX_BROKEN_COPIES {
let target = broken_path(path, ts, n);
if !taken(&target)? {
return Ok(target);
}
std::fs::rename(path, &target)?;
return Ok(target);
}
Err(io::Error::new(io::ErrorKind::AlreadyExists, "too many broken copies"))
}
/// Renames a damaged `config.toml` to `config.broken-<unix-ts>.toml` beside it and returns the
/// new path. Never overwrites: a name that exists gets a `-<n>` suffix.
#[cfg(not(target_arch = "wasm32"))]
pub fn move_aside(path: &Path) -> io::Result<PathBuf> {
let target = free_broken_path(path, |target| Ok(target.exists()))?;
std::fs::rename(path, &target)?;
Ok(target)
}
/// The backup path for a config file: `config.toml` → `config.toml.bak`.
@@ -40,6 +57,7 @@ pub fn backup_path(path: &Path) -> PathBuf {
/// previous backup. On Unix the backup always gets the same mode and group as `path` (`0600`
/// when there is none), so it is never readable by more people than the settings themselves;
/// when it cannot be put in the config's group, it keeps the owner bits only.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_backup(path: &Path, text: &str) -> io::Result<()> {
let backup = backup_path(path);
#[cfg(unix)]
@@ -69,6 +87,7 @@ pub fn write_backup(path: &Path, text: &str) -> io::Result<()> {
}
/// Checks that `dir` accepts a new file by creating and removing a probe.
#[cfg(not(target_arch = "wasm32"))]
pub fn check_writable(dir: &Path) -> io::Result<()> {
let probe = dir.join(format!(".craft-settings-probe-{}", std::process::id()));
std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
+51 -8
View File
@@ -10,9 +10,15 @@ use web_time::Instant;
use crate::Settings;
use crate::document::{self, merge_changes, merge_into, set_schema_version};
use crate::error::{LoadReport, ReadOnlyReason, SaveStatus, SettingsError, Source, TickResult};
use crate::files::{DiskFiles, SettingsFiles};
use crate::files::SettingsFiles;
#[cfg(target_arch = "wasm32")]
use crate::files::BrowserFiles;
#[cfg(not(target_arch = "wasm32"))]
use crate::files::DiskFiles;
use crate::migrate::{self, LegacyFile, Upgrade};
use crate::paths::{self, Location, Portable, Probe};
use crate::paths::{self, Location};
#[cfg(not(target_arch = "wasm32"))]
use crate::paths::{Portable, Probe};
mod sections;
@@ -48,16 +54,27 @@ pub struct OpenOptions<T> {
/// Quiet period after a change before saving.
pub debounce: Duration,
/// What the folder rules look at.
#[cfg(not(target_arch = "wasm32"))]
pub probe: Probe,
/// How the files are read and written ([`DiskFiles`] by default). The store reads and writes
/// `config.toml`, its backup and the damaged-file rename only through it.
/// How the files are read and written (by default `DiskFiles`, on the web `BrowserFiles`).
/// The store reads and writes `config.toml`, its backup and the damaged-file rename only
/// through it.
pub files: Arc<dyn SettingsFiles>,
}
impl<T> Default for OpenOptions<T> {
/// Native: [`Location::Auto`] on the disk.
#[cfg(not(target_arch = "wasm32"))]
fn default() -> Self {
Self { location: Location::Auto, legacy: Vec::new(), debounce: DEFAULT_DEBOUNCE, probe: Probe::default(), files: Arc::new(DiskFiles) }
}
/// Web: browser storage, in memory until the app names its key root with [`Location::Dir`]
/// (there are no folder rules to find one).
#[cfg(target_arch = "wasm32")]
fn default() -> Self {
Self { location: Location::Memory, legacy: Vec::new(), debounce: DEFAULT_DEBOUNCE, files: Arc::new(BrowserFiles) }
}
}
impl<T> OpenOptions<T> {
@@ -79,6 +96,7 @@ impl<T> OpenOptions<T> {
}
/// What the folder rules look at.
#[cfg(not(target_arch = "wasm32"))]
pub fn probe(mut self, probe: Probe) -> Self {
self.probe = probe;
self
@@ -144,8 +162,7 @@ impl<T: Settings> SettingsStore<T> {
/// Opens the store with full options.
pub fn open_with(options: OpenOptions<T>) -> (Self, LoadReport) {
let portable = Portable { markers: T::PORTABLE_MARKERS, dir: T::PORTABLE_DIR };
let resolved = paths::resolve_named(T::APP_ID, T::FOLDER_NAME, &portable, &options.location, &options.probe);
let resolved = resolve(&options, Probing::Write);
let (mut store, mut report) = Self::unloaded(resolved, options.files, options.debounce);
let (Some(dir), Some(path)) = (store.dir.clone(), store.path.clone()) else {
@@ -172,8 +189,7 @@ impl<T: Settings> SettingsStore<T> {
/// damaged `config.toml` reads as defaults and stays where it is, and with no `config.toml` the legacy files are
/// imported in memory only.
pub fn read(options: &OpenOptions<T>) -> (T, LoadReport) {
let portable = Portable { markers: T::PORTABLE_MARKERS, dir: T::PORTABLE_DIR };
let resolved = paths::resolve_unprobed(T::APP_ID, T::FOLDER_NAME, &portable, &options.location, &options.probe);
let resolved = resolve(options, Probing::ReadOnly);
let (mut store, mut report) = Self::unloaded(resolved, options.files.clone(), options.debounce);
if let Some(path) = store.path.clone() {
store.load(&path, &options.legacy, Damaged::Leave, &mut report);
@@ -503,6 +519,33 @@ impl<T: Settings> SettingsStore<T> {
}
}
/// How the folder rules may judge a portable folder.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Probing {
/// Create it and write a probe (an opened store).
Write,
/// Judge it by its permissions, changing nothing (a read).
ReadOnly,
}
/// The folder `options` asks for: by the folder rules on native, as named on the web.
#[cfg(not(target_arch = "wasm32"))]
fn resolve<T: Settings>(options: &OpenOptions<T>, probing: Probing) -> paths::Resolved {
let portable = Portable { markers: T::PORTABLE_MARKERS, dir: T::PORTABLE_DIR };
match probing {
Probing::Write => paths::resolve_named(T::APP_ID, T::FOLDER_NAME, &portable, &options.location, &options.probe),
Probing::ReadOnly => paths::resolve_unprobed(T::APP_ID, T::FOLDER_NAME, &portable, &options.location, &options.probe),
}
}
/// The folder `options` asks for: by the folder rules on native, as named on the web.
#[cfg(target_arch = "wasm32")]
fn resolve<T: Settings>(options: &OpenOptions<T>, probing: Probing) -> paths::Resolved {
// Nothing on the web is probed: the location names the key root.
let _ = probing;
paths::resolve_web(&options.location)
}
/// What a store with no file holds as its base: the defaults, so only a change from them counts
/// as this store's change when another instance creates the file first.
fn default_document<T: Settings>() -> DocumentMut {
+38
View File
@@ -59,5 +59,43 @@
"text.muted": "#d4d4d4",
"text.normal": "#eeeeee",
"text.on_accent": "#ffffff"
},
"apps": {
"pdfcraft": {
"light": {
"accent.soft": "#e3ecfd",
"accent.solid": "#1b63e0",
"accent.text": "#1755c4",
"line.border": "#dadade",
"line.divider": "#e8e8eb",
"state.hover": "#f0f0f3",
"state.pressed": "#e4e4e9",
"state.selected": "#e6eefd",
"surface.background": "#e9e9eb",
"surface.canvas": "#f1f1f3",
"surface.chrome": "#ffffff",
"surface.panel": "#ffffff",
"surface.raised": "#ffffff",
"surface.sunken": "#ffffff",
"text.faint": "#6b6b73",
"text.muted": "#5e5e66",
"text.normal": "#222226"
},
"dark": {
"accent.solid": "#4b8bf5",
"accent.text": "#8cb6fa",
"line.border": "#3c3c43",
"line.divider": "#333339",
"surface.background": "#1b1b1e",
"surface.canvas": "#19191c",
"surface.chrome": "#26262a",
"surface.panel": "#26262a",
"surface.raised": "#2e2e33",
"surface.sunken": "#1e1e22",
"text.faint": "#97979e",
"text.muted": "#aeaeb6",
"text.normal": "#ececef"
}
}
}
}