mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
Merge main into feat/scripts-xmp-objects
XMP updates flush their destination folders on Unix. The host records completed writes and refreshes open readers before reporting a folder flush error. XMPFile retains its pending packet for retry.
This commit is contained in:
@@ -1940,6 +1940,8 @@ fn xmp_open(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
/// the rules for writing. The packet goes to a temporary file in the same folder that then takes the
|
||||
/// file's name, when the run may write there; otherwise to the file itself, unless `safely`, which
|
||||
/// fails and leaves the file as it is. Open objects of the file hold the new bytes.
|
||||
/// On Unix, the destination folder is flushed after writing. A folder flush failure returns an
|
||||
/// error after the written path is recorded and open readers receive the replacement packet.
|
||||
fn xmp_write(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
let path = arg_text(a, 0);
|
||||
let packet = arg_text(a, 1).into_bytes();
|
||||
@@ -2052,6 +2054,14 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
file.dirty = false;
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
let r = r.and_then(|()| {
|
||||
#[cfg(test)]
|
||||
if XMP_DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
|
||||
return Err(std::io::Error::other("directory flush failed"));
|
||||
}
|
||||
vectorcraft_format::sync_parent(&target)
|
||||
});
|
||||
Ok(done(r.map_err(|_| WRITE_FAILED)))
|
||||
}
|
||||
|
||||
@@ -2686,6 +2696,8 @@ thread_local! {
|
||||
pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: while set, `xmpWrite` fails after its checks and before it writes.
|
||||
pub(crate) static XMP_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
#[cfg(unix)]
|
||||
pub(crate) static XMP_DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: the permission bits of the last temporary file `xmpWrite` made, before it wrote to it.
|
||||
#[cfg(unix)]
|
||||
pub(crate) static XMP_TEMP_MODE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
|
||||
|
||||
@@ -601,6 +601,45 @@ fn a_failed_write_keeps_the_packet_for_a_later_close() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_directory_flush_failure_keeps_the_written_packet_and_allows_retry() {
|
||||
struct Reset;
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
}
|
||||
}
|
||||
let _reset = Reset;
|
||||
let base = folder("directory-flush");
|
||||
let mut session = with_data(&base);
|
||||
let dir = logged(&mut session, &base, "vc.log(Folder.userData.fsName);");
|
||||
let path = PathBuf::from(dir[0].as_str().unwrap()).join("packet.xmp");
|
||||
write(&path, format!("\u{FEFF}{PACKET}").as_bytes());
|
||||
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
start_framed(
|
||||
&mut session,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var p = {:?}, reader = new File(p); reader.open('r'); reader.read(7);\n\
|
||||
var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var meta = kept.getXMP(); meta.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(meta);\n\
|
||||
var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\
|
||||
out.push(reader.tell() === 0, reader.read().indexOf('changed') >= 0); reader.close();\n\
|
||||
File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out);",
|
||||
path.to_string_lossy()
|
||||
),
|
||||
);
|
||||
let paused = pump_to_picker(&mut session);
|
||||
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
assert!(paused.is_none(), "the run waits before retrying: {paused:?}");
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"), "the replacement already wrote the packet");
|
||||
assert!(session.script_pick(crate::script::files::PickAnswer::Deny));
|
||||
let report = pump_to_picker(&mut session).unwrap().unwrap();
|
||||
assert_eq!(report["log"][0], json!(["Script file could not be written", "changed", true, true, "closed"]));
|
||||
assert_eq!(report["written"], json!([path.to_string_lossy()]), "the written replacement is reported once");
|
||||
}
|
||||
|
||||
/// An `XMPFile` from an earlier run of a named engine is closed.
|
||||
#[test]
|
||||
fn an_xmp_file_from_an_earlier_run_is_closed() {
|
||||
|
||||
+121
-14
@@ -1,5 +1,7 @@
|
||||
//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed
|
||||
//! or interrupted write never leaves a damaged file behind (the old one stays as it was).
|
||||
//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination.
|
||||
//! A failure while writing or flushing the temporary file leaves the original file unchanged.
|
||||
//! On Unix, saves also flush the destination directory after the complete file is written.
|
||||
//! An error at that step reports that the file was written.
|
||||
//! [`write_new_with`] creates a file the same way without ever replacing one.
|
||||
//!
|
||||
//! Where a folder refuses the temporary file or the rename (some network shares, a file another
|
||||
@@ -22,11 +24,29 @@ use std::io::{self, Write as _};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Whether the returned write error refuses this location. Recovery errors must still be shown:
|
||||
/// their message names copies the user may need, even when their kind is PermissionDenied.
|
||||
/// Reports whether a write error identifies a read-only location.
|
||||
/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied.
|
||||
pub fn read_only_location(error: &io::Error) -> bool {
|
||||
matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied)
|
||||
&& !error.get_ref().is_some_and(|e| e.is::<RecoveryError>())
|
||||
&& !error.get_ref().is_some_and(|e| e.is::<RecoveryError>() || e.is::<WrittenError>())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WrittenError {
|
||||
path: PathBuf,
|
||||
error: io::Error,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for WrittenError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for WrittenError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
Some(&self.error)
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks the existing recovery message without changing its text or the returned error kind.
|
||||
@@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
write_atomic_with(path, |f| f.write_all(bytes))
|
||||
}
|
||||
|
||||
/// Write `path` atomically with `fill`, which writes the content into the temporary file. When
|
||||
/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the
|
||||
/// temporary file is removed and `path` is left untouched. When the
|
||||
/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see
|
||||
/// the module docs).
|
||||
/// This function writes `path` atomically with `fill`, which writes content into a temporary file.
|
||||
/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged.
|
||||
/// Cleanup attempts to remove the temporary file and ignores removal errors.
|
||||
/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs).
|
||||
pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
|
||||
// Replacing a file: its staging copy starts owner-only, so a private document is never readable
|
||||
// beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode.
|
||||
@@ -97,7 +116,7 @@ fn write_atomic_stepping(
|
||||
// Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none
|
||||
// to keep.
|
||||
let _ = keep_permissions(&target, &tmp);
|
||||
let Err(e) = rename(&tmp, &target) else { return Ok(()) };
|
||||
let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) };
|
||||
e
|
||||
}
|
||||
};
|
||||
@@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
|
||||
if let Some(old) = old {
|
||||
let _ = std::fs::remove_file(old);
|
||||
}
|
||||
Ok(())
|
||||
sync_written_parent(target)
|
||||
}
|
||||
(Err(e), Some(old)) => Err(io::Error::new(
|
||||
e.kind(),
|
||||
@@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result<File> {
|
||||
/// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was
|
||||
/// taken meanwhile). The file appears whole or not at all. Where hard links fail for another
|
||||
/// reason, `path` is created with `create_new` and the content copied in; a failed copy removes
|
||||
/// it. The temporary file is always removed.
|
||||
/// it. Cleanup attempts to remove the temporary file and ignores removal errors.
|
||||
pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
|
||||
write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path))
|
||||
}
|
||||
@@ -189,7 +208,31 @@ fn write_new_linking(
|
||||
});
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
placed
|
||||
placed.and_then(|()| sync_written_parent(path))
|
||||
}
|
||||
|
||||
fn sync_written_parent(path: &Path) -> io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error }))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = path;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// This function flushes the directory containing `path` with `fsync`.
|
||||
/// It returns errors from opening or flushing the directory.
|
||||
#[cfg(unix)]
|
||||
pub fn sync_parent(path: &Path) -> io::Result<()> {
|
||||
#[cfg(test)]
|
||||
if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
|
||||
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed"));
|
||||
}
|
||||
let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
|
||||
rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from)
|
||||
}
|
||||
|
||||
/// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has
|
||||
@@ -272,6 +315,8 @@ const ENOTTY: i32 = 25;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
#[cfg(unix)]
|
||||
static DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: every full flush on this thread fails as on an SMB share mounted by macOS.
|
||||
static REFUSE_FULL_SYNC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: the plain `fsync` fallback fails too, with this OS error.
|
||||
@@ -474,6 +519,68 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_directory_sync_failure_reports_the_completed_replacement() {
|
||||
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace");
|
||||
let path = directory.join("doc.vectorcraft");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
let result = write_atomic(&path, b"new");
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
assert!(result.is_err(), "a failed directory flush was reported as success");
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert!(error.to_string().contains("The file was written to"), "{error}");
|
||||
assert!(!read_only_location(&error), "the file was already replaced: {error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
assert!(leftovers(&directory, "doc.vectorcraft").is_empty());
|
||||
write_atomic(&path, b"retried").unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"retried");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_directory_sync_failure_preserves_the_completed_new_file() {
|
||||
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create");
|
||||
let path = directory.join("doc.vectorcraft");
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
let result = write_new_with(&path, |file| file.write_all(b"created"));
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
assert!(result.is_err(), "a failed directory flush was reported as success");
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert!(error.to_string().contains("The file was written to"), "{error}");
|
||||
assert!(!read_only_location(&error), "the file was already created: {error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"created");
|
||||
assert!(leftovers(&directory, "doc.vectorcraft").is_empty());
|
||||
let result = write_new_with(&path, |file| file.write_all(b"replacement"));
|
||||
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"created");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_directory_sync_failure_is_reported_after_copy_fallbacks() {
|
||||
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy");
|
||||
let path = directory.join("doc.vectorcraft");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied());
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
let error = replaced.unwrap_err();
|
||||
assert!(!read_only_location(&error), "the file was already replaced: {error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
let new_path = directory.join("new.vectorcraft");
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied());
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
let error = created.unwrap_err();
|
||||
assert!(!read_only_location(&error), "the file was already created: {error}");
|
||||
assert_eq!(std::fs::read(&new_path).unwrap(), b"created");
|
||||
assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2);
|
||||
}
|
||||
|
||||
/// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the
|
||||
/// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before,
|
||||
/// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain
|
||||
|
||||
@@ -55,6 +55,8 @@ use serde::{Deserializer, Serialize};
|
||||
use vectorcraft_brush::stored_art::StoredArt;
|
||||
use vectorcraft_doc::{Document, ImageBlob};
|
||||
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
pub use atomic::sync_parent;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
use craft_gzip::Gz;
|
||||
|
||||
+9
-3
@@ -1393,9 +1393,12 @@ Each coordinate goes to the nearest step of its stored binary value, and a value
|
||||
zero (`0.125` at 2 places is `0.13`); `1.005` is stored as slightly less than that and is written as `1.0`. Each anchor is rounded on
|
||||
its own, so a closed path stays closed and a shape smaller than one step keeps its anchors on one point. Opening the
|
||||
file and saving it again does not bring back the dropped digits. The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores
|
||||
`precision`. A save writes
|
||||
a temporary file and renames it over the old one, so a failed save never damages the file; only the images the
|
||||
document uses are written, and document keys written by a newer version are kept.
|
||||
`precision`. A save first writes and flushes a temporary file, then renames it over the destination or copies the complete
|
||||
content into the destination. The copy path keeps a flushed copy of any existing content before overwriting it.
|
||||
A failure during that copy reports the locations of the new content and any saved original.
|
||||
Only the images the document uses are written, and document keys written by a newer version are kept.
|
||||
On Unix, a save flushes the destination directory after writing or replacing the file. If that flush fails,
|
||||
the save reports an error stating that the file was written.
|
||||
An uncompressed file is indented JSON when the document has at most 2,000 layers and objects and the indented
|
||||
document, as the chosen version writes it, is at most 1 MiB; otherwise the file is compact JSON.
|
||||
|
||||
@@ -3421,6 +3424,9 @@ rules for these objects:
|
||||
After a successful update, an open `File` reader with a UTF-8 byte order mark or UTF-16 encoding
|
||||
restarts in UTF-8 at the beginning of the replacement packet. A UTF-8 reader without a byte order mark keeps its position,
|
||||
limited to the replacement packet's length.
|
||||
- On Unix, `closeFile()` flushes the destination folder after writing the packet. If that flush fails,
|
||||
it throws `Script file could not be written`, and the file already contains the replacement packet.
|
||||
Open readers use that packet, `written` names the file, and the `XMPFile` keeps its pending packet for retry.
|
||||
- Registered namespace storage and expanded XML values count toward the script's heap limit.
|
||||
`canPutXMP` checks string packets without retaining their expanded XML values.
|
||||
- A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity,
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user