"""Distributed per-document lock — prevents two workers from concurrently processing the same document's ingestion stages (e.g. a retried/resumed background job picked up twice). TTL-based so a crashed worker's stale lock is reclaimable rather than permanently blocking reprocessing. """ import logging import socket import uuid from sqlalchemy import text as sql_text from sqlalchemy.ext.asyncio import AsyncSession from app.config import get_settings logger = logging.getLogger(__name__) def _worker_id() -> str: return f"{socket.gethostname()}:{uuid.uuid4().hex[:8]}" class DocumentLockError(RuntimeError): """Raised when a document is already locked by another worker.""" class DocumentLock: def __init__(self, document_id: str, *, ttl_seconds: int | None = None) -> None: self.document_id = document_id self.worker_id = _worker_id() self.ttl_seconds = ttl_seconds or get_settings().GRAPH_DOCUMENT_LOCK_TTL_SECONDS async def acquire(self, session: AsyncSession) -> None: """Atomically claim the lock if unlocked or expired. Raises DocumentLockError if another worker currently holds a live lock.""" result = await session.execute( sql_text(f""" INSERT INTO document_locks (document_id, locked_by, locked_at, expires_at) VALUES (CAST(:doc AS uuid), :who, NOW(), NOW() + INTERVAL '{self.ttl_seconds} seconds') ON CONFLICT (document_id) DO UPDATE SET locked_by = EXCLUDED.locked_by, locked_at = EXCLUDED.locked_at, expires_at = EXCLUDED.expires_at WHERE document_locks.expires_at < NOW() RETURNING locked_by """), {"doc": self.document_id, "who": self.worker_id}, ) row = result.fetchone() await session.commit() if row is None or row.locked_by != self.worker_id: raise DocumentLockError(f"Document {self.document_id} is locked by another worker") async def refresh(self, session: AsyncSession) -> None: await session.execute( sql_text(f""" UPDATE document_locks SET expires_at = NOW() + INTERVAL '{self.ttl_seconds} seconds' WHERE document_id = CAST(:doc AS uuid) AND locked_by = :who """), {"doc": self.document_id, "who": self.worker_id}, ) await session.commit() async def release(self, session: AsyncSession) -> None: # Defensive rollback: if the caller's transaction was left aborted by a # mid-run DB error, the DELETE below would otherwise fail and the lock # would leak until its TTL expires. Rolling back first clears that state # (any pending work is already irrelevant — we're releasing the lock). try: await session.rollback() except Exception: pass try: await session.execute( sql_text("DELETE FROM document_locks WHERE document_id = CAST(:doc AS uuid) AND locked_by = :who"), {"doc": self.document_id, "who": self.worker_id}, ) await session.commit() except Exception: logger.warning("Failed to release document lock for %s (will expire via TTL)", self.document_id)