FileLock - libvcs._internal.file_lock¶

Typed, asyncio-friendly file locking based on filelock patterns.

Overview¶

This module provides portable file-based locking using the SoftFileLock pattern (os.O_CREAT | os.O_EXCL) for atomic lock acquisition. It supports both synchronous and asynchronous contexts.

Key Features¶

  • Atomic acquisition: Uses os.O_CREAT | os.O_EXCL for race-free lock creation

  • Reentrant locking: Same thread can acquire lock multiple times

  • Stale lock detection: Auto-removes locks older than configurable timeout (default 5min)

  • Async support: AsyncFileLock with asyncio.sleep polling

  • Two-file pattern: Lock file (temporary) + marker file (permanent)

  • PID tracking: Writes PID to lock file for debugging

Quick Start¶

Synchronous Usage¶

from libvcs._internal.file_lock import FileLock

# Context manager (recommended)
with FileLock("/tmp/my.lock"):
    # Critical section - only one process at a time
    pass

# Explicit acquire/release
lock = FileLock("/tmp/my.lock")
lock.acquire()
try:
    # Critical section
    pass
finally:
    lock.release()

Asynchronous Usage¶

import asyncio
from libvcs._internal.file_lock import AsyncFileLock


async def main():
    async with AsyncFileLock("/tmp/my.lock"):
        # Async critical section
        pass


asyncio.run(main())

Atomic Initialization¶

The atomic_init() function implements the two-file pattern for coordinating one-time initialization across multiple processes:

from libvcs._internal.file_lock import atomic_init


def expensive_init():
    # One-time setup (e.g., clone repo, build cache)
    pass


# First call does initialization, subsequent calls skip
did_init = atomic_init("/path/to/resource", expensive_init)

API Reference¶

Typed, asyncio-friendly file locking based on filelock patterns.

This module provides atomic file-based locking with support for both synchronous and asynchronous contexts. It uses the SoftFileLock pattern (os.O_CREAT | os.O_EXCL) for portable, atomic lock acquisition.

Note

This is an internal API not covered by versioning policy.

  1. Atomic acquisition: Uses os.O_CREAT | os.O_EXCL for race-free lock creation

  2. Reentrant locking: Same thread can acquire lock multiple times

  3. Stale lock detection: Auto-removes locks older than configurable timeout

  4. Async support: AsyncFileLock wraps sync lock with asyncio.sleep

  5. PID tracking: Writes PID to lock file for debugging

  6. Two-file pattern: Lock file (temporary) + marker file (permanent)

Examples

Basic synchronous usage:

>>> import tempfile
>>> import pathlib
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     lock_path = pathlib.Path(tmpdir) / "my.lock"
...     lock = FileLock(lock_path)
...     with lock:
...         # Critical section - only one process at a time
...         pass
...     lock.is_locked
False

Async usage:

>>> async def example():
...     import tempfile
...     import pathlib
...     with tempfile.TemporaryDirectory() as tmpdir:
...         lock_path = pathlib.Path(tmpdir) / "my.lock"
...         async with AsyncFileLock(lock_path):
...             # Async critical section
...             pass
...         return "done"
>>> asyncio.run(example())
'done'

Two-file atomic initialization pattern:

>>> def do_expensive_init():
...     pass  # Expensive one-time setup
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     path = pathlib.Path(tmpdir) / "resource"
...     path.mkdir()
...     result = atomic_init(path, do_expensive_init)
...     result  # True if we did init, False if another process did
True

See also

-, -

class libvcs._internal.file_lock.AcquireReturnProxy
¶
class libvcs._internal.file_lock.AcquireReturnProxy
¶

Bases: object

Context manager proxy returned by FileLock.acquire().

This proxy allows the acquire/release pattern to be used with context managers while still supporting explicit acquire() calls.

Parameters:

lock (FileLock) – The lock instance this proxy wraps.

Examples

>>> import tempfile
>>> import pathlib
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     lock_path = pathlib.Path(tmpdir) / "my.lock"
...     lock = FileLock(lock_path)
...     with lock.acquire():  # Returns AcquireReturnProxy
...         pass  # Lock is held
...     lock.is_locked
False
class libvcs._internal.file_lock.AsyncAcquireReturnProxy
¶
class libvcs._internal.file_lock.AsyncAcquireReturnProxy
¶

Bases: object

Async context manager proxy returned by AsyncFileLock.acquire().

Parameters:

lock (AsyncFileLock) – The async lock instance this proxy wraps.

Examples

>>> async def example():
...     import tempfile
...     import pathlib
...     with tempfile.TemporaryDirectory() as tmpdir:
...         lock_path = pathlib.Path(tmpdir) / "my.lock"
...         lock = AsyncFileLock(lock_path)
...         proxy = await lock.acquire()
...         async with proxy:
...             pass  # Lock is held
...         return lock.is_locked
>>> asyncio.run(example())
False
class libvcs._internal.file_lock.AsyncFileLock
¶
class libvcs._internal.file_lock.AsyncFileLock
¶

Bases: object

Async file lock wrapping FileLock with async polling.

This class provides an async interface to the underlying FileLock, using asyncio.sleep instead of blocking time.sleep during acquisition polling. This allows other coroutines to run while waiting for the lock.

Parameters:
  • lock_file (str or PathLike) – Path to the lock file. Parent directory must exist.

  • timeout (float, default=-1.0) – Maximum time to wait for lock acquisition in seconds. Use -1 for infinite wait, 0 for non-blocking.

  • poll_interval (float, default=0.05) – Time between acquisition attempts in seconds.

  • stale_timeout (float, default=300.0) – Locks older than this (in seconds) are considered stale.

  • mode (int, default=0o644) – File permission mode for the lock file.

Examples

Async context manager:

>>> async def example():
...     import tempfile
...     import pathlib
...     with tempfile.TemporaryDirectory() as tmpdir:
...         lock_path = pathlib.Path(tmpdir) / "my.lock"
...         async with AsyncFileLock(lock_path) as lock:
...             return lock.is_locked
>>> asyncio.run(example())
True

Explicit acquire/release:

>>> async def example2():
...     import tempfile
...     import pathlib
...     with tempfile.TemporaryDirectory() as tmpdir:
...         lock_path = pathlib.Path(tmpdir) / "my.lock"
...         lock = AsyncFileLock(lock_path)
...         await lock.acquire()
...         try:
...             return lock.is_locked
...         finally:
...             await lock.release()
>>> asyncio.run(example2())
True

See also

FileLock

Synchronous version.

class libvcs._internal.file_lock.FileLock
¶
class libvcs._internal.file_lock.FileLock
¶

Bases: ContextDecorator

Portable file-based lock using atomic file creation.

This lock uses the SoftFileLock pattern where lock acquisition is achieved through atomic file creation with os.O_CREAT | os.O_EXCL. This is portable across platforms and doesn’t require OS-level locking.

The lock is reentrant: the same thread can acquire it multiple times, and must release it the same number of times.

Parameters:
  • lock_file (str or PathLike) – Path to the lock file. Parent directory must exist.

  • timeout (float, default=-1.0) – Maximum time to wait for lock acquisition in seconds. Use -1 for infinite wait, 0 for non-blocking.

  • poll_interval (float, default=0.05) – Time between acquisition attempts in seconds.

  • stale_timeout (float, default=300.0) – Locks older than this (in seconds) are considered stale and may be removed automatically. Default is 5 minutes.

  • mode (int, default=0o644) – File permission mode for the lock file.

Examples

Context manager usage:

>>> import tempfile
>>> import pathlib
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     lock_path = pathlib.Path(tmpdir) / "my.lock"
...     with FileLock(lock_path):
...         # Critical section
...         pass

Explicit acquire/release:

>>> with tempfile.TemporaryDirectory() as tmpdir:
...     lock_path = pathlib.Path(tmpdir) / "my.lock"
...     lock = FileLock(lock_path)
...     lock.acquire()
...     try:
...         pass  # Critical section
...     finally:
...         lock.release()
<...AcquireReturnProxy object at ...>

Non-blocking try-acquire:

>>> with tempfile.TemporaryDirectory() as tmpdir:
...     lock_path = pathlib.Path(tmpdir) / "my.lock"
...     lock = FileLock(lock_path, timeout=0)
...     try:
...         with lock:
...             pass  # Got the lock
...     except FileLockTimeout:
...         pass  # Lock was held by another process

See also

AsyncFileLock

Async version of this lock.

class libvcs._internal.file_lock.FileLockContext
¶
class libvcs._internal.file_lock.FileLockContext
¶

Bases: object

Internal state container for FileLock.

This dataclass holds all the configuration and runtime state for a file lock. It’s separated from the lock class to allow easier testing and to support potential future features like lock serialization.

Parameters:
  • lock_file (str) – Absolute path to the lock file.

  • timeout (float, default=-1.0) – Timeout for lock acquisition. -1 means wait forever.

  • poll_interval (float, default=0.05) – Interval between acquisition attempts in seconds.

  • stale_timeout (float, default=300.0) – Age in seconds after which a lock is considered stale.

  • mode (int, default=0o644) – File permission mode for the lock file.

  • lock_file_fd (int or None) – File descriptor when lock is held, None otherwise.

  • lock_counter (int, default=0) – Reentrant lock counter (number of times acquired).

Examples

>>> ctx = FileLockContext("/tmp/my.lock")
>>> ctx.is_locked
False
>>> ctx.lock_counter
0
exception libvcs._internal.file_lock.FileLockError
¶
exception[source]
exception[source]
exception libvcs._internal.file_lock.FileLockError
¶

Bases: Exception

Base exception for file lock errors.

All file lock-related exceptions inherit from this class, making it easy to catch any lock-related error with a single except clause.

Examples

>>> try:
...     raise FileLockError("Lock failed")
... except FileLockError as e:
...     str(e)
'Lock failed'
exception libvcs._internal.file_lock.FileLockStale
¶
exception[source]
exception[source]
exception libvcs._internal.file_lock.FileLockStale
¶

Bases: FileLockError

Informational exception for stale lock detection.

This exception is raised when a stale lock is detected but cannot be removed. It’s primarily informational and can be caught to log warnings.

Parameters:
  • lock_file (str) – Path to the stale lock file.

  • age_seconds (float) – Age of the lock file in seconds.

Examples

>>> exc = FileLockStale("/tmp/my.lock", 3600.0)
>>> str(exc)
'Stale lock (3600.0s old): /tmp/my.lock'
exception libvcs._internal.file_lock.FileLockTimeout
¶
exception[source]
exception[source]
exception libvcs._internal.file_lock.FileLockTimeout
¶

Bases: FileLockError, TimeoutError

Raised when lock acquisition times out.

This exception inherits from both FileLockError and TimeoutError, allowing it to be caught by either.

Parameters:
  • lock_file (str) – Path to the lock file that could not be acquired.

  • timeout (float) – Timeout value in seconds that was exceeded.

Examples

>>> exc = FileLockTimeout("/tmp/my.lock", 30.0)
>>> str(exc)
'Timeout (30.0s) waiting for lock: /tmp/my.lock'
>>> exc.lock_file
'/tmp/my.lock'
>>> exc.timeout
30.0
libvcs._internal.file_lock.async_atomic_init(path, init_fn, marker_name='.initialized', timeout=60.0, poll_interval=0.05, stale_timeout=300.0)
¶
async function[source]
async function[source]
libvcs._internal.file_lock.async_atomic_init(path, init_fn, marker_name='.initialized', timeout=60.0, poll_interval=0.05, stale_timeout=300.0)
¶

Atomically initialize a resource asynchronously.

Async version of atomic_init(). Supports both sync and async init_fn callables.

Parameters:
  • path (str or PathLike) – Directory where the marker file will be created.

  • init_fn (callable) – Sync or async function to call for initialization.

  • marker_name (str, default=”.initialized”) – Name of the marker file within path.

  • timeout (float, default=60.0) – Maximum time to wait for another process to finish initialization.

  • poll_interval (float, default=0.05) – Time between lock acquisition attempts.

  • stale_timeout (float, default=300.0) – Time after which an orphaned lock is considered stale.

Returns:

True if this call performed initialization, False otherwise.

Return type:

bool

Raises:

FileLockTimeout – If initialization by another process doesn’t complete within timeout.

Examples

>>> async def example():
...     import tempfile
...     import pathlib
...     async def async_init():
...         await asyncio.sleep(0)  # Simulate async work
...     with tempfile.TemporaryDirectory() as tmpdir:
...         path = pathlib.Path(tmpdir) / "resource"
...         path.mkdir()
...         result = await async_atomic_init(path, async_init)
...         return result
>>> asyncio.run(example())
True

See also

atomic_init

Synchronous version.

libvcs._internal.file_lock.atomic_init(path, init_fn, marker_name='.initialized', timeout=60.0, poll_interval=0.05, stale_timeout=300.0)
¶
function[source]
function[source]
libvcs._internal.file_lock.atomic_init(path, init_fn, marker_name='.initialized', timeout=60.0, poll_interval=0.05, stale_timeout=300.0)
¶

Atomically initialize a resource using the two-file pattern.

This function coordinates one-time initialization across multiple processes using a combination of a lock file and a marker file:

  • Lock file: Temporary file held during initialization, deleted after.

  • Marker file: Permanent file indicating initialization is complete.

This pattern is useful for expensive one-time setup like cloning repositories, building caches, or creating database schemas.

Parameters:
  • path (str or PathLike) – Directory where the marker file will be created.

  • init_fn (callable) – Function to call for initialization. Called only if not already initialized. Must be idempotent in case of partial failure.

  • marker_name (str, default=”.initialized”) – Name of the marker file within path.

  • timeout (float, default=60.0) – Maximum time to wait for another process to finish initialization.

  • poll_interval (float, default=0.05) – Time between lock acquisition attempts.

  • stale_timeout (float, default=300.0) – Time after which an orphaned lock is considered stale.

Returns:

True if this call performed initialization, False if another process did or had already done it.

Return type:

bool

Raises:

FileLockTimeout – If initialization by another process doesn’t complete within timeout.

Examples

>>> import tempfile
>>> import pathlib
>>> def expensive_init():
...     pass  # One-time setup
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     resource_path = pathlib.Path(tmpdir) / "myresource"
...     resource_path.mkdir()
...     # First call does initialization
...     first = atomic_init(resource_path, expensive_init)
...     # Second call sees marker and skips
...     second = atomic_init(resource_path, expensive_init)
...     first, second
(True, False)

With cleanup on partial failure:

>>> def init_with_cleanup():
...     import pathlib
...     import tempfile
...     with tempfile.TemporaryDirectory() as tmpdir:
...         path = pathlib.Path(tmpdir) / "repo"
...         path.mkdir()
...         def do_init():
...             (path / "data.txt").write_text("hello")
...         atomic_init(path, do_init)
...         return (path / "data.txt").exists()
>>> init_with_cleanup()
True

See also

async_atomic_init

Async version of this function.