Files
claude-config/bin/loop_state/session_lock.py
T

67 lines
2.2 KiB
Python

"""The lock by which loop-inbox tells whether a loop-claude still runs.
A loop holds <session>.lock for its whole run (running_loops.py), with flock, which the kernel frees however the loop
ends, killed included. The 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 text_files.file_writes import make_private
def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.lock"
@contextlib.contextmanager
def held(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 takes the lock for a moment through ended, on each session whose files are still on disk, so a loop may find it held."""
path = lock_file(folder, session)
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 ended(folder: pathlib.Path, pattern: str) -> typing.Iterator[str]:
"""Each session with a file in folder that matches pattern, such as "*.json", and whose lock no loop holds. It yields each while holding that lock, so a loop that starts meanwhile keeps its files."""
try:
sessions = {path.stem for path in folder.glob(pattern)}
except OSError:
return
for session in sessions:
with held(folder, session) as unlocked:
if not unlocked:
yield session
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."""
try:
with open(lock_file(folder, session)) as handle:
fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB)
except BlockingIOError:
return True
except OSError:
return False
return False