Source code for s365b.jobs.locks

"""Per-repository locks shared between processes (Postgres advisory locks).

Backups hold a repository's lock *shared*: any number may write at once.
Retention's space reclamation holds it *exclusively*, because it deletes
blobs nothing refers to, and a running backup could be about to reuse one
of them (de-duplication).
"""

from __future__ import annotations

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from sqlalchemy import text

from s365b.db.session import Database

# Arbitrary namespace so these keys do not collide with other advisory locks.
_NAMESPACE = 0x53365B00


[docs] class RepositoryBusyError(Exception): """The repository is locked by another job."""
def _key(repository_id: int) -> int: return (_NAMESPACE << 20) + repository_id @asynccontextmanager
[docs] async def repository_lock( db: Database, repository_id: int, *, exclusive: bool, wait: bool = True ) -> AsyncIterator[None]: """Hold a repository's lock for the duration of the block. Args: db: Database. repository_id: Repository row ID. exclusive: Exclusive (retention) or shared (backups). wait: Wait for the lock; if False, raise when it is taken. Yields: Nothing; the lock is held until the block ends. Raises: RepositoryBusyError: If ``wait`` is False and the lock is taken. """ mode = "" if exclusive else "_shared" async with db.engine.connect() as conn: key = {"k": _key(repository_id)} if wait: await conn.execute(text(f"SELECT pg_advisory_lock{mode}(:k)"), key) elif not ( await conn.execute(text(f"SELECT pg_try_advisory_lock{mode}(:k)"), key) ).scalar_one(): raise RepositoryBusyError(f"repository {repository_id} is in use") # Session-level lock: end the transaction so the connection is not # left "idle in transaction" for the length of a backup. await conn.commit() try: yield finally: await conn.execute(text(f"SELECT pg_advisory_unlock{mode}(:k)"), key) await conn.commit()