Expand description
Write a file without ever leaving it half-written.
A truncating write is two operations on disk โ the size goes to zero, then the bytes arrive โ
and everything in between is a file a reader can open. For a settings file that means a machine
whose provider.* silently vanished because a crash, a full disk or a kill -9 landed in the
gap; for jobs.toml it means a job list that no longer parses; for state.json it means the
next tick reading a record that is not a record (#408).
The fix is the one rename(2) has always offered: write a sibling and rename over the target.
Rename is atomic on one filesystem, so a reader sees the old file or the new one and never a
mixture, and a process that dies mid-write leaves the old file exactly as it was.
Two details are load-bearing:
- The temporary name is unique per writer, pid and an in-process counter. A fixed
<path>.tmpgives two writers one scratch file โ they interleave inside it and the rename publishes whatever the mixture was. A clock is not a source of uniqueness either: cargo runs tests as threads of one process, and two calls inside one tick get the same name (the lessontempdir_liteandrelease.rsboth learned). - The mode is set on the temporary file, not after the rename. A file that is created
world-readable and tightened later is world-readable in between, and
0600here is not decoration: this writer carriesconfig.toml,.env,MEMORY.md,jobs.tomland the cron state.
sync_all before the rename is what makes the promise survive a power cut rather than only a
killed process. It is the slow part, which is why it is here and not in a loop somewhere.
Functionsยง
- write_
file_ atomically - Write
texttopathatomically,0600.