Skip to content

Locks

rn_forge.commons.fs.locks

Cross-process serialization and atomic publication on the filesystem.

:class:DirectoryLock is a portable, mkdir-based advisory lock. :func:atomic_symlink replaces a symlink without first leaving the path unlinked.

DirectoryLock(path, *, timeout=30.0, poll_interval=0.05, on_wait=None)

A portable advisory lock backed by mkdir, for cross-process serialization.

mkdir is atomic on every filesystem this runs on; flock is not available everywhere (and behaves inconsistently over network filesystems). Use this when the lock must actually hold across processes on an unknown filesystem, and something with a best-effort flock instead when a failed lock should degrade to an unlocked write rather than raise.

Example::

with DirectoryLock(product_home / ".lock", on_wait=lambda p: print(f"waiting for {p}...")):
    ...

Initialize :class:DirectoryLock.

Parameters:

Name Type Description Default
path str | Path

The lock directory. Must not exist while the lock is held by anyone; created (and removed) by this lock.

required
timeout float

Seconds to wait for the lock before raising.

30.0
poll_interval float

Seconds between acquisition attempts.

0.05
on_wait Callable[[Path], None] | None

Called once, with path, the first time acquisition has to wait — lets a caller print "waiting for lock ..." without this module importing a console.

None

__enter__()

Acquire the lock, waiting up to timeout seconds.

Raises:

Type Description
AppException

The lock could not be acquired within timeout.

__exit__(*exc)

Release the lock, if held.

Atomically create or replace the symlink link, pointing at target.

Writes a temporary symlink (.<name>.tmp-<pid>) next to link and renames it into place with :meth:~pathlib.Path.replace. Never unlinks link first — that would leave a window where the link does not exist at all, which a concurrent reader could observe.

Parameters:

Name Type Description Default
link str | Path

The symlink path to create or replace.

required
target str | Path

The path the symlink should point at. Not resolved — pass a relative path here for a relocatable symlink.

required