|
| 1 | +"""Distributed-lock abstraction for process-wide singleton tasks. |
| 2 | +
|
| 3 | +The current provider uses PostgreSQL advisory locks. Business callers use |
| 4 | +``SingleWorkerGuard``, which delegates lock operations to ``DistributedLock``. |
| 5 | +""" |
| 6 | + |
| 7 | +import hashlib |
| 8 | +from collections.abc import Callable |
| 9 | +from enum import Enum, auto |
| 10 | +from functools import wraps |
| 11 | +from threading import Lock |
| 12 | +from typing import ClassVar, Self |
| 13 | + |
| 14 | +from sqlalchemy import func, select |
| 15 | +from sqlalchemy.engine import Connection |
| 16 | +from sqlalchemy.exc import SQLAlchemyError |
| 17 | + |
| 18 | +from common.core.db import engine |
| 19 | +from common.utils.utils import SQLBotLogUtil |
| 20 | + |
| 21 | + |
| 22 | +class LockStatus(Enum): |
| 23 | + """Process-local state of the single-worker lock acquisition attempt.""" |
| 24 | + |
| 25 | + NOT_ATTEMPTED = auto() |
| 26 | + ACQUIRED = auto() |
| 27 | + NOT_ACQUIRED = auto() |
| 28 | + |
| 29 | + |
| 30 | +class DistributedLock: |
| 31 | + """A lock held by this process until ``release`` or process shutdown.""" |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + advisory_key: int, |
| 36 | + connection: Connection, |
| 37 | + ) -> None: |
| 38 | + self._connection = connection |
| 39 | + self._advisory_key = advisory_key |
| 40 | + |
| 41 | + @staticmethod |
| 42 | + def _postgres_advisory_key(key: str) -> int: |
| 43 | + """Convert a readable lock key into PostgreSQL's signed 64-bit key.""" |
| 44 | + digest = hashlib.sha256(key.encode("utf-8")).digest() |
| 45 | + return int.from_bytes(digest[:8], byteorder="big", signed=True) |
| 46 | + |
| 47 | + @classmethod |
| 48 | + def try_acquire(cls, key: str) -> Self | None: |
| 49 | + """Try to acquire a named distributed lock without waiting.""" |
| 50 | + advisory_key = cls._postgres_advisory_key(key) |
| 51 | + connection: Connection | None = None |
| 52 | + try: |
| 53 | + connection = engine.connect() |
| 54 | + acquired = connection.execute( |
| 55 | + select(func.pg_try_advisory_lock(advisory_key)) |
| 56 | + ).scalar_one() |
| 57 | + # End the implicit transaction; the session-level lock remains held. |
| 58 | + connection.commit() |
| 59 | + except SQLAlchemyError: |
| 60 | + SQLBotLogUtil.exception("Failed to acquire distributed lock: %s", key) |
| 61 | + if connection is not None: |
| 62 | + connection.close() |
| 63 | + return None |
| 64 | + |
| 65 | + if not acquired: |
| 66 | + connection.close() |
| 67 | + return None |
| 68 | + |
| 69 | + return cls(advisory_key, connection) |
| 70 | + |
| 71 | + def release(self) -> None: |
| 72 | + """Release the lock and return its dedicated connection to the pool.""" |
| 73 | + if self._connection.closed: |
| 74 | + return |
| 75 | + |
| 76 | + try: |
| 77 | + self._connection.execute( |
| 78 | + select(func.pg_advisory_unlock(self._advisory_key)) |
| 79 | + ) |
| 80 | + self._connection.commit() |
| 81 | + finally: |
| 82 | + self._connection.close() |
| 83 | + |
| 84 | + |
| 85 | +class SingleWorkerGuard: |
| 86 | + """Run startup tasks in only one worker process.""" |
| 87 | + |
| 88 | + _LOCK_KEY = "sqlbot:startup:embedding" |
| 89 | + _lock_status: ClassVar[LockStatus] = LockStatus.NOT_ATTEMPTED |
| 90 | + # Keep the acquired lock and its dedicated connection alive. |
| 91 | + _acquired_lock: ClassVar[DistributedLock | None] = None |
| 92 | + _state_mutex = Lock() |
| 93 | + |
| 94 | + @classmethod |
| 95 | + def _has_acquired_lock(cls) -> bool: |
| 96 | + with cls._state_mutex: |
| 97 | + if cls._lock_status is LockStatus.NOT_ATTEMPTED: |
| 98 | + lock = DistributedLock.try_acquire(cls._LOCK_KEY) |
| 99 | + if lock is None: |
| 100 | + cls._lock_status = LockStatus.NOT_ACQUIRED |
| 101 | + SQLBotLogUtil.info( |
| 102 | + "Current process FAILED to acquire the single-worker lock" |
| 103 | + ) |
| 104 | + else: |
| 105 | + cls._acquired_lock = lock |
| 106 | + cls._lock_status = LockStatus.ACQUIRED |
| 107 | + SQLBotLogUtil.info( |
| 108 | + "Current process acquired the single-worker lock" |
| 109 | + ) |
| 110 | + return cls._lock_status is LockStatus.ACQUIRED |
| 111 | + |
| 112 | + @classmethod |
| 113 | + def once(cls, func: Callable[[], None]) -> Callable[[], None]: |
| 114 | + """Run the decorated startup task in only one worker.""" |
| 115 | + |
| 116 | + @wraps(func) |
| 117 | + def wrapper() -> None: |
| 118 | + if not cls._has_acquired_lock(): |
| 119 | + return |
| 120 | + func() |
| 121 | + |
| 122 | + return wrapper |
| 123 | + |
| 124 | + @classmethod |
| 125 | + def release(cls) -> None: |
| 126 | + """Release the single-worker lock and reset this process's state.""" |
| 127 | + with cls._state_mutex: |
| 128 | + try: |
| 129 | + if cls._acquired_lock is not None: |
| 130 | + cls._acquired_lock.release() |
| 131 | + finally: |
| 132 | + cls._acquired_lock = None |
| 133 | + cls._lock_status = LockStatus.NOT_ATTEMPTED |
0 commit comments