locking.py
1"""Exclusive local-file locks shared by workspace and artifact owners.23Callers own the open binary stream and its lifetime. Closing it releases the lock,4including after process exit. Lock files must not be replaced while owners are active.5"""67from __future__ import annotations89import errno10import os11import time12from typing import Any, BinaryIO, cast1314# Wait between attempts while blocking on a Windows lock.15RETRY_SECONDS = 0.05161718def _try_windows_lock(stream: BinaryIO) -> bool:19 import msvcrt2021 # CRT locks start at the current offset, unlike flock's whole-file lock.22 stream.seek(0)23 # msvcrt exists only on Windows; mypy checks against this machine's stubs.24 windows = cast(Any, msvcrt)25 try:26 windows.locking(stream.fileno(), windows.LK_NBLCK, 1)27 except OSError as error:28 if error.errno in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):29 return False30 raise31 return True323334def acquire_exclusive(stream: BinaryIO, *, blocking: bool = True) -> bool:35 """Acquire an exclusive lock; return False only for nonblocking contention.3637 Windows locks byte zero, including for an empty file. Blocking acquisition retries38 the nonblocking CRT call, avoiding its fixed ten-attempt blocking limit.39 Permission/open errors and unexpected IO errors propagate to the owner.40 """41 if os.name == 'nt':42 while not _try_windows_lock(stream):43 if not blocking:44 return False45 time.sleep(RETRY_SECONDS)46 return True47 import fcntl4849 try:50 fcntl.flock(stream, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB))51 except BlockingIOError:52 return False53 return True545556def release_exclusive(stream: BinaryIO) -> None:57 """Release a held lock without closing the caller's stream."""58 if os.name == 'nt':59 import msvcrt6061 stream.seek(0)62 # msvcrt exists only on Windows; mypy checks against this machine's stubs.63 windows = cast(Any, msvcrt)64 windows.locking(stream.fileno(), windows.LK_UNLCK, 1)65 else:66 import fcntl6768 fcntl.flock(stream, fcntl.LOCK_UN)