* wip(render): reconcile completed material and image pipeline source with 0.20 (#5493) Source-only integration reference for staged review, not a merge-ready aggregate. Donor: 0xlillith/solidcraft@aea20b0115. Upstream:858e5995d6. Retain original CPU/material contracts and explicit GPU donor provenance in docs/render-materials-lab.md (#2067, #2191, #2780, #3306). Preserve released format migrations and current navigation/startup/shell behavior. New saved records use pending descriptors. The physical-card descriptor follows the maintainer's material-engineering-cards naming request, with a legacy-lab format-29 regression. Replace raw new panel hosts with shared containers. Repository checks, complete workspace/all-target Clippy, and the independent physical/resource authoring checks pass for this source. The fresh full local CI invocation has reached test compilation and is not yet complete. Do not transfer donor native output or prior test totals to this integration. Generated review screenshots, video, package ZIP and machine logs remain at the immutable personal evidence pin. Uncommitted geometric displacement is backed up separately, not silently included. No kernel/vendor change, direct main write, release or independent contributor-branch rewrite. Co-authored-by: Christian Svensson <blue@cmd.nu> * test(cli): pin the Compact camera-sample admission diagnostic (#5493) The bounded request still refuses 1024x1024x64 samples before host initialization and writes no output. Update only the stale expected diagnostic to the existing Compact budget wording; production limits and code are unchanged. Exact-tree CLI regression suite: 14 passed, 0 failed. The full repository gate has been invoked separately and is not yet complete. * Normalize UI container violation paths across platforms Report repository-relative paths with forward slashes so diagnostics and the existing nested-package regression assertions agree on Windows and Unix. Keep the container detection rules unchanged. Validation: official ui-containers gate and all seven focused xtask tests passed; rustfmt and diff checks passed. Only xtask/dependencies were compiled; no application build or heavy tests. (cherry picked from commit44b58d8e10) * fix(render): preserve camera contracts and correct acceptance regressions (#5493) Preserve Design view.apply semantics with a separate strict Render camera command. Retain existing translations when English-only aliases collide; add material-axis entries and camera-specific pitch labels. Compare complete validated engineering cards and retain job handles before cancellation. Focused and native acceptance is pinned to treef8a423b21f. Full CI has been invoked separately and is not claimed green. Landing follows the render integration policy in #5493. * fix(render): resolve showcase licence and upstream resource hygiene (#5493) Record SychPL's explicit MIT OR Apache-2.0 grant, retaining source/model bytes and the Ubuntu lettering notice. Remove 80 absent attribution rows, personal fork records, dead delivery attributes and three fork/resource-only workflows. Existing xtask assets now performs bounded offline hash checks and rejects orphan render attribution; no parallel draft CI or package installation. Original authoring reproduction remains explicit. Scoped xtask tests, assets, Clippy, formatting and prepared SELENE validation pass; no application or renderer-wide result is inferred. * fix(render): align saved bounds and progressive sample resolution (#5493) Address review r4364211669/r4364211677/r4364211681/r4364211691/r4364211695. Persisted light/frame domains respect the existing 1e9 document bound; related LED/rectangle/direction cases use the same bound. Workstation primary resolve shares the 4096 admission cap and film counters use checked conversions. Exact candidate: 485 CPU render tests, 21 render document tests and strict scoped Clippy pass, including positive boundary round trips and 2048/4096 end-to-end checkpoints. No released format/migration edits, relaxed test limits or full-stack acceptance claim. * wip(render): isolate optional resources and harden sample handling (#5493) Review work in progress: opt-in encoded render library with reproducible runtime catalog exports; native-only robust dependency through the workspace; checked bloom slices; per-sample point-light diagnostics; independent area-light spatial/film keys. Resource-module binaries in both configurations, generation, Cargo production feature graphs and attribution checks pass. Full engine/render regression and combined acceptance are pending: do not merge this donor as a constituent or treat scoped resource proof as runtime acceptance. * fix(gpu): preserve donor allocations through the scope-safety repair (#5722) Port the native-validated #5723 scope-cleanup correction into the experimental donor, retaining its adaptive, volume, aging, photographic and bloom allocations. Same reverse-drain helper and regression cases; the donor combination still needs its own compile/test gate and is not covered retroactively by render-base results. * claim: #1369 * Reject unknown pending concepts after format folding (#1369) * test(render): close bounded sampling and bloom review regressions (#5493) Validate the optional-resource/lighting/dependency donor at its exact tree. Required Vulkan GPU 127/0/3; CPU renderer 487/0; engine Render 72/0; document render 21/0; lean library 7/0; strict scoped Clippy, assets/layers/lists/containers and lean-engine WASM pass. Preserve original failed controller/typing attempts. This is the draft donor/disposition source, not a replacement for constituent render PRs or final main acceptance. * wip(render): preserve stable aging target validation candidate Exact staged source from prior review work on donor3b892eab5e. This is a recovery/review checkpoint, NOT accepted delivery. An actual command-path regression currently fails because the selected executor refuses ordered surface aging. No assertion, capability or admission limit is weakened. Native/UI/full combination acceptance remains pending. Saved/runtime split adds one pending descriptor and retains original file scope; no main/render branch is changed. * test(render): preserve numeric setup intent at the admitted coordinate bound Follow up jyviko review on #5494 without weakening the corrected saved-coordinate contract. The positive clicked fixture uses 1e9 instead of inadmissible 2e9; explicit out-of-range cases still refuse, and the full saved setup round-trips through JSON and the native container. Exact-source Render workspace 95/0 and strict all-target UI Clippy pass. This does not incorporate the separately failing stable-aging candidate or claim full current-render acceptance. * test(render): use the real GPU executor for saved aging Move successful native cold-reopen Check/Start coverage from the CPU-backed protocol fixture into the production GPU executor tests. Verify capture-index changes preserve the stable target and that enabling aging changes both PNG and raw EXR output. Retain explicit, allocation-free refusal coverage for executors without aging support. Production capabilities and admission checks are unchanged. * fix(render): persist stable identities for targeted aging (#5493) Separate saved RenderBodyTarget identities from captured mesh ordinals. Reject legacy ambiguous targets, resolve Check/Start after visibility changes and preserve native reopening, copies and undo. Unsupported executors still refuse; real AMD Vulkan regression completes saved aging after reordered capture. Source tree6b84c8adpasses document 23, engine Render 75, GPU effects 5 and Render UI 95 with no failures; scoped strict Clippy, WASM and repository gates pass. Fresh CLI/native reopen and clean/aged GPU exports pass with identical physical totals and inspected actual images. Whole current-render integration is separate. * fix(render): reconcile combined CPU/GPU contracts on current upstream Unify captured resources/status and CPU-vs-GPU request schemas after the real two-parent integration; remove obsolete duplicate Vulkan selector and retain combined platform-filter regression. Deduplicate only identical or superseded test definitions, retaining the stronger card metadata and reserved-executor assertions. No assertions, admission limits or feature refusals are weakened. All targets of render dependencies, GPU, engine, UI, CLI and native app pass cargo check with raytrace-cpu and bundled-render-library at treec70d00d1. Native executable tests and full current-source acceptance remain pending. This is a private integration rehearsal for subsequent constituent PRs, not an aggregate official render/main merge. * test(render): retain one complete host lifetime regression set Deduplicate byte-identical DropProbe/task-lifetime tests and retain the adapted environment/texture ownership regressions with every assertion and complete memory estimate. Keep the registered-geometry admission regression once; only struct field order differed. Replace a one-element diagnostic loop with its equivalent block, preserving all wrap/width assertions. Test-only integration repair. Formatting and diff checks pass; refreshed executable validation is required. No production behavior, limits, assertions or ignores changed. * fix(doc): recognize the proven format-29 card descriptor alias Normalize only the historical format-29 physical-material-cards spelling, and only when material-engineering-cards is registered. Admission and migration de-duplication use the same identity. Unknown concepts, wrong versions and incapable readers still refuse before mutation. Six controlled-history Rust regressions and actual CLI migration/no-clobber acceptance pass. No version, released migration or CI changes. Refs #5793, #1369, #5493. * test(render): preserve grounding refusal before explicit instance moves Update the two Render binding fixtures for upstream first-occurrence grounding. Verify grounded movement refuses without changing document/history, then explicitly unground through the public command before the intended move. Retain every target, resource, copy and persistence assertion. Refs #5493. --------- Co-authored-by: Christian Svensson <blue@cmd.nu> Co-authored-by: Victor Santos Oliveira <56417388+Vittuu@users.noreply.github.com> Co-authored-by: cfaulkingham <colin.faulkingham@gmail.com>
541 lines
23 KiB
Rust
541 lines
23 KiB
Rust
//! Crash-safe file writes: the new content goes to a temporary file next to the target, is
|
|
//! flushed to disk, and replaces the target in one rename. A crash or power cut at any moment
|
|
//! leaves the old file or the new one, never a torn mix. The previous version can be kept as
|
|
//! `<file>.bak` (itself written the same way).
|
|
|
|
use std::fs::{self, OpenOptions};
|
|
use std::io::Write;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
/// The backup of a file written with `backup: true`.
|
|
pub fn backup_path(path: &Path) -> PathBuf {
|
|
let mut s = path.as_os_str().to_owned();
|
|
s.push(".bak");
|
|
PathBuf::from(s)
|
|
}
|
|
|
|
fn temp_beside(path: &Path, tag: &str) -> PathBuf {
|
|
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "file".into());
|
|
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);
|
|
path.with_file_name(format!(".{name}.{tag}.{}.{nanos}.tmp", std::process::id()))
|
|
}
|
|
|
|
fn write_synced(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
|
let mut f = OpenOptions::new().write(true).create_new(true).open(path)?;
|
|
f.write_all(bytes)?;
|
|
flush(&f)
|
|
}
|
|
|
|
/// Flush a written file to the disk. On Apple systems `sync_all` asks the drive itself to flush
|
|
/// (`F_FULLFSYNC`), which a network share refuses (an SMB share: "Operation not supported", os
|
|
/// error 45), so a save there failed before it replaced anything. The plain `fsync` the share
|
|
/// does offer is used then, as SQLite and git do.
|
|
fn flush(f: &fs::File) -> std::io::Result<()> {
|
|
flush_with(f, fs::File::sync_all)
|
|
}
|
|
|
|
fn flush_with(f: &fs::File, full: impl FnOnce(&fs::File) -> std::io::Result<()>) -> std::io::Result<()> {
|
|
match full(f) {
|
|
#[cfg(target_vendor = "apple")]
|
|
Err(e) if e.kind() == std::io::ErrorKind::Unsupported || e.raw_os_error() == Some(45) => rustix::fs::fsync(f).map_err(std::io::Error::from),
|
|
r => r,
|
|
}
|
|
}
|
|
|
|
/// Flush the directory entry (the rename) to disk where the platform allows it.
|
|
fn sync_dir(path: &Path) {
|
|
#[cfg(unix)]
|
|
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty())
|
|
&& let Ok(d) = fs::File::open(dir)
|
|
{
|
|
let _ = d.sync_all();
|
|
}
|
|
#[cfg(not(unix))]
|
|
let _ = path;
|
|
}
|
|
|
|
/// Steps of a save, so tests can stop one part way (as a crash would).
|
|
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
|
|
enum Step {
|
|
TempWritten,
|
|
BackupWritten,
|
|
#[allow(dead_code)] // stopping after the last step is a whole save (tests name it)
|
|
Replaced,
|
|
}
|
|
|
|
/// Most links followed before a path is called a loop.
|
|
const MAX_LINK_HOPS: usize = 40;
|
|
|
|
/// The file a save has to replace: `path`, or where a symbolic link at `path` (or a chain of
|
|
/// them) leads, so a design linked into a project from a synced folder is saved there and the
|
|
/// link survives. A link whose target is missing resolves to the place the target would be.
|
|
fn resolve_links(path: &Path) -> std::io::Result<PathBuf> {
|
|
let mut at = path.to_path_buf();
|
|
for _ in 0..MAX_LINK_HOPS {
|
|
if !fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink()) {
|
|
return Ok(at);
|
|
}
|
|
let to = fs::read_link(&at)?;
|
|
at = if to.is_absolute() { to } else { at.parent().map(|d| d.join(&to)).unwrap_or(to) };
|
|
}
|
|
Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{}: too many levels of symbolic links", path.display())))
|
|
}
|
|
|
|
/// Give the file that replaces `old` the permissions `old` had (a private `0600` design must not
|
|
/// come back readable by everyone, a group's `0664` must not lose the group's write access).
|
|
fn keep_permissions(old: &Option<fs::Permissions>, new: &Path) {
|
|
if let Some(p) = old {
|
|
let _ = fs::set_permissions(new, p.clone());
|
|
}
|
|
}
|
|
|
|
// Retrying only the already-synced atomic rename avoids rewriting a large image
|
|
// or deleting/truncating its existing target. ACL/read-only/other permanent
|
|
// refusals still fail. No file lock is broken and no security setting is changed.
|
|
fn replace_synced(source: &Path, destination: &Path) -> std::io::Result<()> {
|
|
rename_with_retry(|| fs::rename(source, destination), cfg!(windows), std::thread::sleep)
|
|
}
|
|
|
|
fn rename_with_retry(
|
|
mut rename: impl FnMut() -> std::io::Result<()>,
|
|
windows: bool,
|
|
mut wait: impl FnMut(std::time::Duration),
|
|
) -> std::io::Result<()> {
|
|
// Windows can refuse rename while an independently opened handle withholds
|
|
// FILE_SHARE_DELETE. Access denied may also be permanent, so keep both an
|
|
// attempt bound and the original last error. Requested sleeps total 127 ms;
|
|
// scheduling/OS operation time is not a wall-clock latency guarantee.
|
|
let mut result = rename();
|
|
for milliseconds in [1, 2, 4, 8, 16, 32, 64] {
|
|
if !windows || !result.as_ref().is_err_and(|error| matches!(error.raw_os_error(), Some(5 | 32))) {
|
|
return result;
|
|
}
|
|
wait(std::time::Duration::from_millis(milliseconds));
|
|
result = rename();
|
|
}
|
|
result
|
|
}
|
|
|
|
fn write_steps(path: &Path, bytes: &[u8], backup: bool, stop: Option<Step>) -> std::io::Result<()> {
|
|
let permissions = fs::metadata(path).ok().filter(|m| m.is_file()).map(|m| m.permissions());
|
|
let tmp = temp_beside(path, "new");
|
|
if let Err(e) = write_synced(&tmp, bytes) {
|
|
let _ = fs::remove_file(&tmp);
|
|
return Err(e);
|
|
}
|
|
keep_permissions(&permissions, &tmp);
|
|
if stop == Some(Step::TempWritten) {
|
|
return Ok(());
|
|
}
|
|
if backup && path.is_file() {
|
|
// Copy (not move) the old file, so the target exists at every moment.
|
|
let old = fs::read(path);
|
|
let bak_tmp = temp_beside(path, "bak");
|
|
let r = old
|
|
.and_then(|old| write_synced(&bak_tmp, &old))
|
|
.map(|_| keep_permissions(&permissions, &bak_tmp))
|
|
.and_then(|_| replace_synced(&bak_tmp, &backup_path(path)));
|
|
if let Err(e) = r {
|
|
let _ = fs::remove_file(&bak_tmp);
|
|
let _ = fs::remove_file(&tmp);
|
|
return Err(e);
|
|
}
|
|
}
|
|
if stop == Some(Step::BackupWritten) {
|
|
return Ok(());
|
|
}
|
|
if let Err(e) = replace_synced(&tmp, path) {
|
|
let _ = fs::remove_file(&tmp);
|
|
return Err(e);
|
|
}
|
|
sync_dir(path);
|
|
// Temporary files of saves that crashed part way (a minute old or more) go.
|
|
for t in stale_temps(path) {
|
|
if fs::metadata(&t).and_then(|m| m.modified()).ok().and_then(|m| m.elapsed().ok()).is_some_and(|age| age.as_secs() >= 60) {
|
|
let _ = fs::remove_file(t);
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Write `bytes` to `path` atomically; with `backup`, the file being replaced is kept as
|
|
/// `<path>.bak` first. A symbolic link at `path` is followed (the file it points to is replaced,
|
|
/// the link stays), and the file keeps the permissions it had. The app's own folders (autosave,
|
|
/// crash reports) write through this without a [`crate::vfs::PathScope`]; a command writing a
|
|
/// path it was given calls [`crate::vfs::check`] first, which judges where the link leads.
|
|
pub fn write_atomic(path: &Path, bytes: &[u8], backup: bool) -> std::io::Result<()> {
|
|
// In the browser the host stores files (one write is already atomic there).
|
|
if cfg!(target_arch = "wasm32") {
|
|
let _ = backup;
|
|
return crate::vfs::write(&path.to_string_lossy(), bytes);
|
|
}
|
|
write_steps(&resolve_links(path)?, bytes, backup, None)
|
|
}
|
|
|
|
/// Publish a complete new file without replacing an existing destination, even if another
|
|
/// writer creates it after this call starts. Unsupported filesystems return an error.
|
|
pub fn create_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
|
if cfg!(target_arch = "wasm32") {
|
|
let name = path.to_string_lossy();
|
|
if crate::vfs::exists(&name) {
|
|
return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "destination already exists"));
|
|
}
|
|
return crate::vfs::write(&name, bytes);
|
|
}
|
|
let tmp = temp_beside(path, "create");
|
|
// Only remove a temporary file that this invocation successfully created.
|
|
let mut file = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
|
let result = file.write_all(bytes).and_then(|_| flush(&file));
|
|
drop(file);
|
|
let result = result.and_then(|_| fs::hard_link(&tmp, path));
|
|
let _ = fs::remove_file(&tmp);
|
|
if result.is_ok() {
|
|
sync_dir(path);
|
|
}
|
|
result
|
|
}
|
|
|
|
/// Leftover temporary files of saves that never finished (a crash part way), next to `path`
|
|
/// (next to the file a link at `path` points to, where a save puts them).
|
|
pub fn stale_temps(path: &Path) -> Vec<PathBuf> {
|
|
let resolved = resolve_links(path).unwrap_or_else(|_| path.to_path_buf());
|
|
let path = resolved.as_path();
|
|
let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else { return Vec::new() };
|
|
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
|
let prefix = format!(".{name}.");
|
|
fs::read_dir(dir)
|
|
.into_iter()
|
|
.flatten()
|
|
.flatten()
|
|
.map(|e| e.path())
|
|
.filter(|p| p.file_name().map(|n| n.to_string_lossy().to_string()).is_some_and(|n| n.starts_with(&prefix) && n.ends_with(".tmp")))
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn create_does_not_replace_an_existing_destination() {
|
|
let d = dir("create");
|
|
let p = d.join("render.png");
|
|
create_atomic(&p, b"first complete image").unwrap();
|
|
assert_eq!(create_atomic(&p, b"replacement").unwrap_err().kind(), std::io::ErrorKind::AlreadyExists);
|
|
assert_eq!(fs::read(&p).unwrap(), b"first complete image");
|
|
assert!(stale_temps(&p).is_empty());
|
|
fs::remove_dir_all(d).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn concurrent_creators_publish_exactly_one_whole_file() {
|
|
let d = dir("create-race");
|
|
let p = d.join("render.png");
|
|
let gate = std::sync::Arc::new(std::sync::Barrier::new(2));
|
|
let workers: Vec<_> = [b"first image".as_slice(), b"second image".as_slice()]
|
|
.into_iter()
|
|
.map(|bytes| {
|
|
let gate = gate.clone();
|
|
let p = p.clone();
|
|
std::thread::spawn(move || {
|
|
gate.wait();
|
|
create_atomic(&p, bytes)
|
|
})
|
|
})
|
|
.collect();
|
|
let results: Vec<_> = workers.into_iter().map(|w| w.join().unwrap()).collect();
|
|
assert_eq!(results.iter().filter(|r| r.is_ok()).count(), 1);
|
|
assert_eq!(results.iter().filter_map(|r| r.as_ref().err()).next().unwrap().kind(), std::io::ErrorKind::AlreadyExists);
|
|
let bytes = fs::read(&p).unwrap();
|
|
assert!(bytes == b"first image" || bytes == b"second image");
|
|
assert!(stale_temps(&p).is_empty());
|
|
fs::remove_dir_all(d).unwrap();
|
|
}
|
|
|
|
fn dir(tag: &str) -> PathBuf {
|
|
let d = std::env::temp_dir().join(format!("solidcraft-safe-write-{tag}-{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&d);
|
|
fs::create_dir_all(&d).unwrap();
|
|
d
|
|
}
|
|
|
|
/// A network share (SMB on macOS) refuses the drive flush `sync_all` asks for with "Operation
|
|
/// not supported" (os error 45). The file is then flushed the plain way and the save goes on;
|
|
/// any other failure still fails the save.
|
|
#[test]
|
|
fn a_share_that_refuses_the_full_flush_gets_a_plain_one() {
|
|
let d = dir("flush");
|
|
let p = d.join("a.solidcraft");
|
|
fs::write(&p, b"saved").unwrap();
|
|
let f = fs::File::open(&p).unwrap();
|
|
let refused = |_: &fs::File| Err(std::io::Error::from_raw_os_error(45));
|
|
#[cfg(target_vendor = "apple")]
|
|
flush_with(&f, refused).unwrap();
|
|
#[cfg(not(target_vendor = "apple"))]
|
|
assert!(flush_with(&f, refused).is_err(), "elsewhere sync_all is the plain flush already");
|
|
let unsupported = |_: &fs::File| Err(std::io::Error::from(std::io::ErrorKind::Unsupported));
|
|
assert_eq!(flush_with(&f, unsupported).is_ok(), cfg!(target_vendor = "apple"));
|
|
let broken = |_: &fs::File| Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied));
|
|
assert_eq!(flush_with(&f, broken).unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
|
|
flush_with(&f, |_| Ok(())).unwrap();
|
|
drop(f);
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
|
|
#[test]
|
|
fn replaces_and_keeps_a_backup() {
|
|
let d = dir("bak");
|
|
let p = d.join("a.solidcraft");
|
|
write_atomic(&p, b"one", true).unwrap();
|
|
assert!(!backup_path(&p).exists(), "nothing to back up the first time");
|
|
write_atomic(&p, b"two", true).unwrap();
|
|
assert_eq!(fs::read(&p).unwrap(), b"two");
|
|
assert_eq!(fs::read(backup_path(&p)).unwrap(), b"one");
|
|
write_atomic(&p, b"three", false).unwrap();
|
|
assert_eq!(fs::read(backup_path(&p)).unwrap(), b"one");
|
|
assert!(stale_temps(&p).is_empty());
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
|
|
/// A save stopped after any step leaves the old file whole (or the new one).
|
|
#[test]
|
|
fn a_save_stopped_part_way_keeps_the_old_file() {
|
|
let d = dir("stop");
|
|
let p = d.join("a.solidcraft");
|
|
write_atomic(&p, b"old", true).unwrap();
|
|
for stop in [Step::TempWritten, Step::BackupWritten, Step::Replaced] {
|
|
write_steps(&p, b"new content", true, Some(stop)).unwrap();
|
|
let now = fs::read(&p).unwrap();
|
|
assert!(now == b"old" || now == b"new content", "{stop:?}: {now:?}");
|
|
if stop < Step::Replaced {
|
|
assert_eq!(now, b"old");
|
|
assert!(!stale_temps(&p).is_empty(), "the unfinished save's temporary file is left over");
|
|
for t in stale_temps(&p) {
|
|
fs::remove_file(t).unwrap();
|
|
}
|
|
}
|
|
write_atomic(&p, b"old", false).unwrap();
|
|
}
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
|
|
#[test]
|
|
fn a_failed_write_leaves_the_target() {
|
|
let d = dir("fail");
|
|
let p = d.join("missing-dir").join("a.solidcraft");
|
|
assert!(write_atomic(&p, b"x", true).is_err());
|
|
assert!(!p.exists());
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
mod unix {
|
|
use super::*;
|
|
use std::os::unix::fs::{PermissionsExt, symlink};
|
|
|
|
fn mode(p: &Path) -> u32 {
|
|
fs::metadata(p).unwrap().permissions().mode() & 0o777
|
|
}
|
|
|
|
/// saving through a link replaces the file it points to and leaves the link.
|
|
#[test]
|
|
fn a_save_through_a_link_updates_the_target() {
|
|
let d = dir("link");
|
|
fs::create_dir_all(d.join("cloud")).unwrap();
|
|
fs::create_dir_all(d.join("work")).unwrap();
|
|
let target = d.join("cloud").join("a.solidcraft");
|
|
let link = d.join("work").join("a.solidcraft");
|
|
write_atomic(&target, b"one", false).unwrap();
|
|
symlink(&target, &link).unwrap();
|
|
write_atomic(&link, b"two", true).unwrap();
|
|
assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link");
|
|
assert_eq!(fs::read(&target).unwrap(), b"two");
|
|
assert_eq!(fs::read(&link).unwrap(), b"two");
|
|
assert_eq!(fs::read(backup_path(&target)).unwrap(), b"one", "the backup sits beside the real file");
|
|
assert!(!backup_path(&link).exists());
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
|
|
#[test]
|
|
fn relative_and_chained_links_are_followed() {
|
|
let d = dir("chain");
|
|
fs::create_dir_all(d.join("real")).unwrap();
|
|
fs::create_dir_all(d.join("mid")).unwrap();
|
|
let target = d.join("real").join("a.solidcraft");
|
|
write_atomic(&target, b"one", false).unwrap();
|
|
symlink("../real/a.solidcraft", d.join("mid").join("b")).unwrap();
|
|
symlink("mid/b", d.join("c")).unwrap();
|
|
write_atomic(&d.join("c"), b"two", false).unwrap();
|
|
assert_eq!(fs::read(&target).unwrap(), b"two");
|
|
assert!(fs::symlink_metadata(d.join("c")).unwrap().file_type().is_symlink());
|
|
assert!(fs::symlink_metadata(d.join("mid").join("b")).unwrap().file_type().is_symlink());
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
|
|
#[test]
|
|
fn a_dangling_link_is_filled_in_and_a_loop_is_an_error() {
|
|
let d = dir("dangling");
|
|
let link = d.join("a.solidcraft");
|
|
let target = d.join("later.solidcraft");
|
|
symlink(&target, &link).unwrap();
|
|
write_atomic(&link, b"new", true).unwrap();
|
|
assert_eq!(fs::read(&target).unwrap(), b"new");
|
|
assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
|
|
|
|
let (x, y) = (d.join("x"), d.join("y"));
|
|
symlink(&y, &x).unwrap();
|
|
symlink(&x, &y).unwrap();
|
|
let e = write_atomic(&x, b"loop", true).unwrap_err();
|
|
assert!(e.to_string().contains("symbolic links"), "{e}");
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
|
|
/// a private design stays private, a group's file keeps the group's access, and
|
|
/// the backup carries the same permissions.
|
|
#[test]
|
|
fn a_save_keeps_the_permissions() {
|
|
let d = dir("mode");
|
|
for want in [0o600, 0o640, 0o664, 0o444] {
|
|
let p = d.join(format!("a{want:o}.solidcraft"));
|
|
write_atomic(&p, b"one", false).unwrap();
|
|
fs::set_permissions(&p, fs::Permissions::from_mode(want)).unwrap();
|
|
write_atomic(&p, b"two", true).unwrap();
|
|
assert_eq!(fs::read(&p).unwrap(), b"two");
|
|
assert_eq!(mode(&p), want, "{want:o}");
|
|
assert_eq!(mode(&backup_path(&p)), want, "backup {want:o}");
|
|
let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o644));
|
|
}
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
|
|
#[test]
|
|
fn a_save_through_a_link_keeps_the_targets_permissions() {
|
|
let d = dir("linkmode");
|
|
let target = d.join("a.solidcraft");
|
|
write_atomic(&target, b"one", false).unwrap();
|
|
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).unwrap();
|
|
symlink(&target, d.join("l")).unwrap();
|
|
write_atomic(&d.join("l"), b"two", true).unwrap();
|
|
assert_eq!(mode(&target), 0o600);
|
|
assert_eq!(mode(&backup_path(&target)), 0o600);
|
|
let _ = fs::remove_dir_all(&d);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod rename_retry_tests {
|
|
use super::*;
|
|
use std::cell::Cell;
|
|
#[test]
|
|
fn only_windows_sharing_or_access_errors_retry_with_an_exact_finite_budget() {
|
|
for code in [5, 32] {
|
|
let calls = Cell::new(0);
|
|
let mut waits = Vec::new();
|
|
let result = rename_with_retry(
|
|
|| {
|
|
calls.set(calls.get() + 1);
|
|
if calls.get() < 3 { Err(std::io::Error::from_raw_os_error(code)) } else { Ok(()) }
|
|
},
|
|
true,
|
|
|delay| waits.push(delay.as_millis()),
|
|
);
|
|
assert!(result.is_ok());
|
|
assert_eq!(calls.get(), 3);
|
|
assert_eq!(waits, [1, 2]);
|
|
let calls = Cell::new(0);
|
|
let mut waits = Vec::new();
|
|
let error = rename_with_retry(
|
|
|| {
|
|
calls.set(calls.get() + 1);
|
|
Err(std::io::Error::from_raw_os_error(code))
|
|
},
|
|
true,
|
|
|delay| waits.push(delay.as_millis()),
|
|
)
|
|
.unwrap_err();
|
|
assert_eq!(error.raw_os_error(), Some(code));
|
|
assert_eq!(calls.get(), 8);
|
|
assert_eq!(waits, [1, 2, 4, 8, 16, 32, 64]);
|
|
assert_eq!(waits.iter().sum::<u128>(), 127);
|
|
}
|
|
for (windows, code) in [(false, 5), (false, 32), (true, 2), (true, 3), (true, 87), (true, 183)] {
|
|
let calls = Cell::new(0);
|
|
let error = rename_with_retry(
|
|
|| {
|
|
calls.set(calls.get() + 1);
|
|
Err(std::io::Error::from_raw_os_error(code))
|
|
},
|
|
windows,
|
|
|_| panic!("unexpected retry"),
|
|
)
|
|
.unwrap_err();
|
|
assert_eq!(calls.get(), 1);
|
|
assert_eq!(error.raw_os_error(), Some(code));
|
|
}
|
|
let mut calls = 0;
|
|
rename_with_retry(
|
|
|| {
|
|
calls += 1;
|
|
Ok(())
|
|
},
|
|
true,
|
|
|_| panic!("success must not wait"),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(calls, 1);
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
#[test]
|
|
fn native_windows_rename_preserves_old_bytes_until_a_reader_releases_delete_sharing() {
|
|
use std::os::windows::fs::OpenOptionsExt;
|
|
let directory = std::env::temp_dir().join(format!("solidcraft-rename-reader-release-{}", std::process::id()));
|
|
fs::create_dir(&directory).unwrap();
|
|
let old = directory.join("image.png");
|
|
let pending = directory.join("completed.tmp");
|
|
fs::write(&old, b"old complete image").unwrap();
|
|
write_synced(&pending, b"new complete image").unwrap();
|
|
let mut reader = Some(OpenOptions::new().read(true).share_mode(1).open(&old).unwrap());
|
|
let error = fs::rename(&pending, &old).unwrap_err();
|
|
assert!(matches!(error.raw_os_error(), Some(5 | 32)), "{error}");
|
|
let calls = Cell::new(0);
|
|
rename_with_retry(
|
|
|| {
|
|
calls.set(calls.get() + 1);
|
|
fs::rename(&pending, &old)
|
|
},
|
|
true,
|
|
|delay| {
|
|
assert_eq!(fs::read(&old).unwrap(), b"old complete image");
|
|
drop(reader.take());
|
|
std::thread::sleep(delay);
|
|
},
|
|
)
|
|
.unwrap();
|
|
assert!(calls.get() >= 2 && calls.get() <= 8);
|
|
assert_eq!(fs::read(&old).unwrap(), b"new complete image");
|
|
assert!(!pending.exists());
|
|
fs::remove_dir_all(directory).unwrap();
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
#[test]
|
|
fn persistent_native_lock_is_an_error_without_destroying_or_bypassing_the_target() {
|
|
use std::os::windows::fs::OpenOptionsExt;
|
|
let directory = std::env::temp_dir().join(format!("solidcraft-rename-persistent-reader-{}", std::process::id()));
|
|
fs::create_dir(&directory).unwrap();
|
|
let path = directory.join("image.exr");
|
|
fs::write(&path, b"old whole raw master").unwrap();
|
|
let reader = OpenOptions::new().read(true).share_mode(1).open(&path).unwrap();
|
|
let error = write_atomic(&path, b"new whole raw master", false).unwrap_err();
|
|
assert!(matches!(error.raw_os_error(), Some(5 | 32)), "{error}");
|
|
assert_eq!(fs::read(&path).unwrap(), b"old whole raw master");
|
|
assert!(stale_temps(&path).is_empty());
|
|
drop(reader);
|
|
write_atomic(&path, b"new whole raw master", false).unwrap();
|
|
assert_eq!(fs::read(&path).unwrap(), b"new whole raw master");
|
|
fs::remove_dir_all(directory).unwrap();
|
|
}
|
|
}
|