|
| 1 | +"""Advisory Lock Service for PostgreSQL.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import hashlib |
| 5 | +import logging |
| 6 | +import struct |
| 7 | +import time |
| 8 | +from contextlib import asynccontextmanager |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +import psycopg |
| 12 | +from psycopg.rows import tuple_row |
| 13 | +from psycopg.sql import SQL, Identifier |
| 14 | + |
| 15 | +from .async_lock import AsyncLock |
| 16 | + |
| 17 | +LOGGER = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class PostgresAsyncLock(AsyncLock): |
| 21 | + """A class to manage distributed advisory locks in PostgreSQL. |
| 22 | +
|
| 23 | + Note: This implementation uses PostgreSQL's advisory locks |
| 24 | + to provide a distributed locking mechanism suitable for clustered environments. |
| 25 | + It is designed to work with PostgreSQL databases and requires a valid connection URI |
| 26 | + that it acquires from the provided storage configuration. |
| 27 | + """ |
| 28 | + |
| 29 | + @classmethod |
| 30 | + async def create(cls, connection_uri: Optional[str] = None): |
| 31 | + """Create a Lock instance with a PostgreSQL connection.""" |
| 32 | + cls.connection_uri = connection_uri |
| 33 | + await cls._create_db_if_not_exists(cls.connection_uri) |
| 34 | + |
| 35 | + @staticmethod |
| 36 | + async def _create_db_if_not_exists(base_uri: str, dbname="lock_db"): |
| 37 | + async with await psycopg.AsyncConnection.connect( |
| 38 | + base_uri, autocommit=True |
| 39 | + ) as conn: |
| 40 | + async with conn.cursor(row_factory=tuple_row) as cur: |
| 41 | + await cur.execute( |
| 42 | + "SELECT 1 FROM pg_database WHERE datname = %s", (dbname,) |
| 43 | + ) |
| 44 | + exists = await cur.fetchone() |
| 45 | + |
| 46 | + if not exists: |
| 47 | + LOGGER.info(f"Creating database '{dbname}'...") |
| 48 | + await cur.execute( |
| 49 | + SQL("CREATE DATABASE {}").format(Identifier(dbname)) |
| 50 | + ) |
| 51 | + else: |
| 52 | + LOGGER.debug(f"Database '{dbname}' already exists.") |
| 53 | + |
| 54 | + def _make_pg_lock_key(self, value) -> int: |
| 55 | + h = hashlib.sha256(str(value).encode()).digest() |
| 56 | + return struct.unpack("q", h[:8])[0] # signed 64-bit int |
| 57 | + |
| 58 | + @asynccontextmanager |
| 59 | + async def lock(self, lock_key: str, timeout: int = 10): |
| 60 | + """Acquires a PostgreSQL advisory lock for the given key. |
| 61 | +
|
| 62 | + Times out after `timeout` seconds if the lock isn't available. |
| 63 | + """ |
| 64 | + lock_key = self._make_pg_lock_key(lock_key) |
| 65 | + async with await psycopg.AsyncConnection.connect( |
| 66 | + self.connection_uri, autocommit=True |
| 67 | + ) as conn: |
| 68 | + async with conn.cursor() as cur: |
| 69 | + start = time.time() |
| 70 | + acquired = False |
| 71 | + |
| 72 | + while time.time() - start < timeout: |
| 73 | + await cur.execute("SELECT pg_try_advisory_lock(%s);", (lock_key,)) |
| 74 | + acquired = (await cur.fetchone())[0] |
| 75 | + |
| 76 | + if acquired: |
| 77 | + LOGGER.debug(f"[LOCK ACQUIRED] Key: {lock_key}") |
| 78 | + break |
| 79 | + |
| 80 | + await asyncio.sleep(1) |
| 81 | + |
| 82 | + if not acquired: |
| 83 | + raise TimeoutError( |
| 84 | + f"Could not acquire advisory lock {lock_key} within {timeout} seconds." |
| 85 | + ) |
| 86 | + |
| 87 | + try: |
| 88 | + yield |
| 89 | + finally: |
| 90 | + await cur.execute("SELECT pg_advisory_unlock(%s);", (lock_key,)) |
| 91 | + LOGGER.debug(f"[LOCK RELEASED] Key: {lock_key}") |
0 commit comments