Expand description
Atomic file-write helper for sqry’s on-disk persistence paths.
§Overview
atomic_write_bytes implements the canonical “write to tempfile in the
same directory, then rename” pattern. This gives callers a best-effort
atomic replace on any POSIX-compliant filesystem: readers either see the
old content or the new content, never a partial write.
§Protocol
- Reject if
target_pathitself is an existing symlink — we refuse to follow or replace symlinks silently. - Reject if
target_path’s parent directory resolves to a symlink (canonicalize + re-stat check) — avoids TOCTOU races. - Create a named tempfile inside the same directory as the target.
Same-directory placement is critical:
rename(2)is only guaranteed atomic within a single filesystem/device boundary. - Write all bytes, then
fsyncthe file to flush kernel page-cache to durable storage. - Close the tempfile handle (implicit on drop after
persist). rename(temp, target)— atomic on POSIX.- On Unix only: open the parent directory and call
fsyncon its file descriptor to flush the directory entry pointing at the new inode. This step ensures the rename itself survives a crash/power-loss event. On Windows and other non-Unix targets, the parent-directory fsync is a no-op (Windows rename semantics differ; the OS provides sufficient durability guarantees for the scenarios sqry targets on that platform).
§Error semantics
On any error the tempfile is removed before returning. The target path is never modified unless the rename succeeds.
Functions§
- atomic_
write_ bytes - Write
bytestotarget_pathatomically.