Skip to main content

atomic_files

First-writer-wins file creation.

For files that define an identity and must therefore be created exactly once -- the compute's key pair and installation id (ADR 0011). Two processes starting together on an empty directory each generate a candidate; whichever creates the file first wins, and the other discards its candidate and loads the file. Neither needs to know the other exists.

Module​

Functions​

create_exclusively​

def create_exclusively(path: Path, data: bytes, *, mode: int = 384) ‑> bool:

Create path holding data, but only if it does not already exist.

data is written in full to a private temporary file first, which is then linked into path. The link is atomic against every other process doing the same thing, so exactly one caller can ever succeed for a given path -- and, unlike creating path itself with O_EXCL, a loser can never observe path after it exists but before the winner's write has landed.

Arguments

  • path: The file to create. Parent directories are created as needed.
  • data: The bytes to write into the new file.
  • mode: Permission bits for the new file. Defaults to owner-only, the right default for key material.

Returns True if this call created the file. False if it already existed, in which case nothing was written and data should be discarded in favour of the file's contents.