Skip to main content

Module atomic_write

Module atomic_write 

Source
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

  1. Reject if target_path itself is an existing symlink — we refuse to follow or replace symlinks silently.
  2. Reject if target_path’s parent directory resolves to a symlink (canonicalize + re-stat check) — avoids TOCTOU races.
  3. 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.
  4. Write all bytes, then fsync the file to flush kernel page-cache to durable storage.
  5. Close the tempfile handle (implicit on drop after persist).
  6. rename(temp, target) — atomic on POSIX.
  7. On Unix only: open the parent directory and call fsync on 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 bytes to target_path atomically.