"""The locks by which loop-inbox tells that a loop-claude still runs. A loop holds .lock while loop-inbox lists the session's question, and .running.lock for its whole run (running_loops.py). Each is held with flock, which the kernel frees however the loop ends, killed included. A lock file stays once the loop ends: docs/decisions.md → `loop-inbox: …` says why. """ import contextlib import fcntl import pathlib import typing from failure import Failure from file_writes import make_private def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path: return folder / f"{session}.lock" @contextlib.contextmanager def locked(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None]: """Holds the session's lock while the with block runs, or yields a Failure where it cannot. loop-inbox's drop_ended takes the lock for a moment on each ask still on disk, so a loop may find it held.""" with held(folder, lock_file(folder, session)) as unlocked: yield unlocked @contextlib.contextmanager def held(folder: pathlib.Path, path: pathlib.Path) -> typing.Iterator[Failure | None]: """Holds the lock at path, a file in folder, while the with block runs, or yields a Failure where it cannot.""" try: make_private(folder) except OSError as failure: yield Failure(f"cannot make {folder}: {failure.strerror}") return try: handle = open(path, "a") except OSError as failure: yield Failure(f"cannot open {path}: {failure.strerror}") return with handle: try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: yield Failure(f"another process holds {path}") return except OSError as failure: yield Failure(f"cannot lock {path}: {failure.strerror}") return yield None def running(folder: pathlib.Path, session: str) -> bool: """Whether a loop holds the session's lock; False also where the lock file cannot be opened or locked.""" return taken(lock_file(folder, session)) def taken(path: pathlib.Path) -> bool: """Whether a process holds the lock at path; False also where it cannot be opened or locked.""" try: with open(path) as handle: fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB) except BlockingIOError: return True except OSError: return False return False