db-mutex 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of db-mutex might be problematic. Click here for more details.

@@ -0,0 +1,142 @@
1
+ """MySQL async backend: mirrors sync.py but over asyncmy.
2
+
3
+ NOTE: asyncmy's API tracks PyMySQL's closely (connect kwargs, cursor.execute param
4
+ style, begin/commit/rollback, the ``CLIENT.FOUND_ROWS`` flag, and an
5
+ ``IntegrityError`` with the MySQL errno in ``args[0]``) but wasn't exercised against
6
+ a running MySQL instance while writing this — verify against asyncmy's actual API
7
+ before relying on it, same as any new third-party integration.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import contextlib
14
+ from collections.abc import AsyncIterator
15
+ from typing import Any
16
+
17
+ import asyncmy
18
+ import asyncmy.errors
19
+ from asyncmy.constants import CLIENT
20
+
21
+ from ..._config import MutexConfig
22
+ from ...metrics import MetricsHook
23
+ from .. import _core
24
+ from .._core import AsyncConnectionPool
25
+ from . import _sql
26
+ from ._dsn import parse_mysql_dsn
27
+
28
+ _DUPLICATE_KEY_ERRNO = 1062
29
+
30
+
31
+ class AsyncMutexCore(_core.AsyncCoreBase):
32
+ """Async counterpart to the MySQL ``SyncMutexCore`` — same dsn/pool modes and the
33
+ same locking logic, delegated to the shared ``_core.AsyncCoreBase``.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ config: MutexConfig,
39
+ metrics: MetricsHook | None,
40
+ *,
41
+ dsn: str | None = None,
42
+ pool: AsyncConnectionPool | None = None,
43
+ ) -> None:
44
+ super().__init__(config, metrics, dsn=dsn, pool=pool)
45
+ self._conn: Any | None = None
46
+ self._db_lock = asyncio.Lock()
47
+
48
+ async def _connection(self) -> Any:
49
+ """The dedicated dsn-mode connection, opened lazily. Not used in pool mode."""
50
+ if self._conn is None or self._conn.closed():
51
+ assert self.dsn is not None
52
+ self._conn = await asyncmy.connect(
53
+ **parse_mysql_dsn(self.dsn),
54
+ autocommit=True,
55
+ client_flag=CLIENT.FOUND_ROWS,
56
+ )
57
+ async with self._conn.cursor() as cur:
58
+ await cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
59
+ return self._conn
60
+
61
+ @contextlib.asynccontextmanager
62
+ async def _borrow(self) -> AsyncIterator[Any]:
63
+ if self.pool is not None:
64
+ async with self.pool.connection() as conn:
65
+ yield conn
66
+ else:
67
+ yield await self._connection()
68
+
69
+ async def ensure_schema(self) -> None:
70
+ query = _sql.CREATE_TABLE.format(
71
+ table=_sql.quote_identifier(self.config.table),
72
+ table_uq=_sql.quote_identifier(f"{self.config.table}_uq"),
73
+ table_chk=_sql.quote_identifier(f"{self.config.table}_chk_locked"),
74
+ )
75
+ async with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
76
+ await cur.execute(query)
77
+
78
+ async def close(self) -> None:
79
+ await self.stop_heartbeat()
80
+ async with self._db_lock:
81
+ if self._conn is not None and not self._conn.closed():
82
+ self._conn.close()
83
+
84
+ async def _do_try_acquire(self) -> _core.AcquireOutcome:
85
+ table = _sql.quote_identifier(self.config.table)
86
+ q_select = _sql.SELECT_FOR_ACQUIRE.format(table=table)
87
+ q_delete = _sql.DELETE_ROW.format(table=table)
88
+ q_insert = _sql.INSERT_ROW.format(table=table)
89
+ lock_params = {"lock_name": self.config.lock_name}
90
+ insert_params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
91
+
92
+ async with self._db_lock, self._borrow() as conn:
93
+ await conn.begin()
94
+ try:
95
+ async with conn.cursor() as cur:
96
+ await cur.execute(q_select, lock_params)
97
+ row = await cur.fetchone()
98
+
99
+ if row is None:
100
+ await cur.execute(q_insert, insert_params)
101
+ outcome = _core.AcquireOutcome(acquired=True)
102
+ else:
103
+ holder, seconds_since = row
104
+ if (
105
+ seconds_since is not None
106
+ and seconds_since >= self.config.stale_threshold
107
+ ):
108
+ await cur.execute(q_delete, lock_params)
109
+ await cur.execute(q_insert, insert_params)
110
+ outcome = _core.AcquireOutcome(acquired=True, reclaimed_from=holder)
111
+ else:
112
+ outcome = _core.AcquireOutcome(
113
+ acquired=False, holder=holder, seconds_since=seconds_since
114
+ )
115
+ await conn.commit()
116
+ return outcome
117
+ except asyncmy.errors.IntegrityError as exc:
118
+ await conn.rollback()
119
+ if exc.args and exc.args[0] == _DUPLICATE_KEY_ERRNO:
120
+ # Same race as the sync/Postgres backends: SELECT ... FOR UPDATE
121
+ # can't serialize two contenders racing to INSERT a lock row that
122
+ # doesn't exist yet. The UNIQUE constraint still guarantees
123
+ # exactly one wins; the loser just lost a race, not an error.
124
+ return _core.AcquireOutcome(acquired=False)
125
+ raise
126
+ except Exception:
127
+ await conn.rollback()
128
+ raise
129
+
130
+ async def _do_heartbeat(self) -> bool:
131
+ query = _sql.HEARTBEAT.format(table=_sql.quote_identifier(self.config.table))
132
+ params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
133
+ async with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
134
+ await cur.execute(query, params)
135
+ return bool(cur.rowcount > 0)
136
+
137
+ async def _do_release(self) -> bool:
138
+ query = _sql.RELEASE.format(table=_sql.quote_identifier(self.config.table))
139
+ params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
140
+ async with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
141
+ await cur.execute(query, params)
142
+ return bool(cur.rowcount > 0)
@@ -0,0 +1,149 @@
1
+ """MySQL sync backend: connection handling and acquire/release/heartbeat SQL over
2
+ PyMySQL. See ``backends/mysql/_sql.py`` for the dialect differences from Postgres.
3
+
4
+ Requires MySQL >= 8.0.16 (for enforced CHECK constraints) and the ``db-mutex[mysql]``
5
+ extra (``pymysql``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import threading
12
+ from collections.abc import Iterator
13
+
14
+ import pymysql
15
+ import pymysql.cursors
16
+ from pymysql.constants import CLIENT
17
+
18
+ from ..._config import MutexConfig
19
+ from ...metrics import MetricsHook
20
+ from .. import _core
21
+ from .._core import SyncConnectionPool
22
+ from . import _sql
23
+ from ._dsn import parse_mysql_dsn
24
+
25
+ _DUPLICATE_KEY_ERRNO = 1062
26
+
27
+
28
+ class SyncMutexCore(_core.SyncCoreBase):
29
+ """MySQL counterpart to the Postgres ``SyncMutexCore`` — same dsn/pool modes and
30
+ the same locking logic, delegated to the shared ``_core.SyncCoreBase``.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ config: MutexConfig,
36
+ metrics: MetricsHook | None,
37
+ *,
38
+ dsn: str | None = None,
39
+ pool: SyncConnectionPool | None = None,
40
+ ) -> None:
41
+ super().__init__(config, metrics, dsn=dsn, pool=pool)
42
+ self._conn: pymysql.connections.Connection | None = None
43
+ self._db_lock = threading.Lock()
44
+
45
+ def _connection(self) -> pymysql.connections.Connection:
46
+ """The dedicated dsn-mode connection, opened lazily. Not used in pool mode."""
47
+ if self._conn is None or not self._conn.open:
48
+ assert self.dsn is not None
49
+ self._conn = pymysql.connect(
50
+ **parse_mysql_dsn(self.dsn),
51
+ autocommit=True,
52
+ cursorclass=pymysql.cursors.Cursor,
53
+ # Without this, MySQL's UPDATE rowcount reflects rows *changed*, not
54
+ # rows *matched* — a heartbeat that writes an identical microsecond
55
+ # timestamp twice in a row would then read as "lock not held" even
56
+ # though the row matched. FOUND_ROWS makes rowcount match psycopg's
57
+ # RETURNING-based "was a row matched" semantics exactly.
58
+ client_flag=CLIENT.FOUND_ROWS,
59
+ )
60
+ with self._conn.cursor() as cur:
61
+ # Match Postgres's default READ COMMITTED (MySQL/InnoDB defaults to
62
+ # REPEATABLE READ) so the acquire logic behaves identically across
63
+ # backends rather than relying on isolation-level nuance to still
64
+ # be correct.
65
+ cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
66
+ return self._conn
67
+
68
+ @contextlib.contextmanager
69
+ def _borrow(self) -> Iterator[pymysql.connections.Connection]:
70
+ if self.pool is not None:
71
+ with self.pool.connection() as conn:
72
+ yield conn
73
+ else:
74
+ yield self._connection()
75
+
76
+ def ensure_schema(self) -> None:
77
+ query = _sql.CREATE_TABLE.format(
78
+ table=_sql.quote_identifier(self.config.table),
79
+ table_uq=_sql.quote_identifier(f"{self.config.table}_uq"),
80
+ table_chk=_sql.quote_identifier(f"{self.config.table}_chk_locked"),
81
+ )
82
+ with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
83
+ cur.execute(query)
84
+
85
+ def close(self) -> None:
86
+ self.stop_heartbeat()
87
+ with self._db_lock:
88
+ if self._conn is not None and self._conn.open:
89
+ self._conn.close()
90
+
91
+ def _do_try_acquire(self) -> _core.AcquireOutcome:
92
+ table = _sql.quote_identifier(self.config.table)
93
+ q_select = _sql.SELECT_FOR_ACQUIRE.format(table=table)
94
+ q_delete = _sql.DELETE_ROW.format(table=table)
95
+ q_insert = _sql.INSERT_ROW.format(table=table)
96
+ lock_params = {"lock_name": self.config.lock_name}
97
+ insert_params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
98
+
99
+ with self._db_lock, self._borrow() as conn:
100
+ conn.begin()
101
+ try:
102
+ with conn.cursor() as cur:
103
+ cur.execute(q_select, lock_params)
104
+ row = cur.fetchone()
105
+
106
+ if row is None:
107
+ cur.execute(q_insert, insert_params)
108
+ outcome = _core.AcquireOutcome(acquired=True)
109
+ else:
110
+ holder, seconds_since = row
111
+ if (
112
+ seconds_since is not None
113
+ and seconds_since >= self.config.stale_threshold
114
+ ):
115
+ cur.execute(q_delete, lock_params)
116
+ cur.execute(q_insert, insert_params)
117
+ outcome = _core.AcquireOutcome(acquired=True, reclaimed_from=holder)
118
+ else:
119
+ outcome = _core.AcquireOutcome(
120
+ acquired=False, holder=holder, seconds_since=seconds_since
121
+ )
122
+ conn.commit()
123
+ return outcome
124
+ except pymysql.err.IntegrityError as exc:
125
+ conn.rollback()
126
+ if exc.args and exc.args[0] == _DUPLICATE_KEY_ERRNO:
127
+ # Same race as the Postgres backend: SELECT ... FOR UPDATE can't
128
+ # serialize two contenders racing to INSERT a lock row that
129
+ # doesn't exist yet. The UNIQUE constraint still guarantees
130
+ # exactly one wins; the loser just lost a race, not an error.
131
+ return _core.AcquireOutcome(acquired=False)
132
+ raise
133
+ except Exception:
134
+ conn.rollback()
135
+ raise
136
+
137
+ def _do_heartbeat(self) -> bool:
138
+ query = _sql.HEARTBEAT.format(table=_sql.quote_identifier(self.config.table))
139
+ params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
140
+ with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
141
+ cur.execute(query, params)
142
+ return bool(cur.rowcount > 0)
143
+
144
+ def _do_release(self) -> bool:
145
+ query = _sql.RELEASE.format(table=_sql.quote_identifier(self.config.table))
146
+ params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
147
+ with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
148
+ cur.execute(query, params)
149
+ return bool(cur.rowcount > 0)
File without changes
@@ -0,0 +1,69 @@
1
+ """Raw SQL for the mutex_lock table.
2
+
3
+ Kept in one place so the acquire/steal logic — the one part of this project that has
4
+ to be exactly right — is easy to audit independently of the Python control flow
5
+ around it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ CREATE_TABLE = """
11
+ CREATE TABLE IF NOT EXISTS {table} (
12
+ lock_name VARCHAR(64) NOT NULL,
13
+ locked INT NOT NULL DEFAULT 1,
14
+ instance_id VARCHAR(64) NOT NULL,
15
+ last_heartbeat TIMESTAMPTZ NOT NULL,
16
+ acquired_at TIMESTAMPTZ NOT NULL,
17
+ CONSTRAINT {table_uq} UNIQUE (locked, lock_name),
18
+ CONSTRAINT {table_chk} CHECK (locked = 1)
19
+ )
20
+ """
21
+
22
+ # Acquire is a locate-then-act sequence run inside one explicit transaction (see
23
+ # SyncMutexCore.try_acquire / AsyncMutexCore.try_acquire):
24
+ #
25
+ # 1. SELECT_FOR_ACQUIRE ... FOR UPDATE locks the row (if any) so two concurrent
26
+ # acquirers for the same lock_name serialize on it instead of racing.
27
+ # 2. If no row: INSERT_ROW.
28
+ # 3. If the row is stale (past stale_threshold): DELETE_ROW then INSERT_ROW.
29
+ # 4. Otherwise: no writes; the transaction commits as a no-op.
30
+ #
31
+ # Earlier this was a single statement with a data-modifying DELETE ... CTE feeding an
32
+ # INSERT ... ON CONFLICT. That looked atomic but isn't: sibling CTEs in one statement
33
+ # all execute against the *same* snapshot, so the INSERT's conflict check can't see
34
+ # rows the CTE's DELETE just removed — the delete would apply but the insert would
35
+ # still no-op, silently emptying the table. An explicit transaction with row-level
36
+ # locking avoids that pitfall and, as a bonus, lets us read the previous holder's
37
+ # instance_id directly instead of smuggling it out of a CTE.
38
+ SELECT_FOR_ACQUIRE = """
39
+ SELECT instance_id, EXTRACT(EPOCH FROM (now() - last_heartbeat)) AS seconds_since_heartbeat
40
+ FROM {table}
41
+ WHERE lock_name = %(lock_name)s
42
+ FOR UPDATE
43
+ """
44
+
45
+ DELETE_ROW = """
46
+ DELETE FROM {table}
47
+ WHERE lock_name = %(lock_name)s
48
+ """
49
+
50
+ INSERT_ROW = """
51
+ INSERT INTO {table} (lock_name, locked, instance_id, last_heartbeat, acquired_at)
52
+ VALUES (%(lock_name)s, 1, %(instance_id)s, now(), now())
53
+ """
54
+
55
+ HEARTBEAT = """
56
+ UPDATE {table}
57
+ SET last_heartbeat = now()
58
+ WHERE lock_name = %(lock_name)s AND instance_id = %(instance_id)s
59
+ RETURNING 1
60
+ """
61
+
62
+ # Clean shutdown: delete the row outright so the next instance doesn't wait out the
63
+ # stale_threshold. Scoped to instance_id so a holder that already lost the lock to a
64
+ # stale-reclaim can't accidentally delete the new holder's row.
65
+ RELEASE = """
66
+ DELETE FROM {table}
67
+ WHERE lock_name = %(lock_name)s AND instance_id = %(instance_id)s
68
+ RETURNING 1
69
+ """
@@ -0,0 +1,128 @@
1
+ """Postgres async backend: mirrors sync.py but over psycopg's AsyncConnection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ from collections.abc import AsyncIterator
8
+ from typing import Any
9
+
10
+ import psycopg
11
+ from psycopg import sql
12
+
13
+ from ..._config import MutexConfig
14
+ from ...metrics import MetricsHook
15
+ from .. import _core
16
+ from .._core import AsyncConnectionPool
17
+ from . import _sql
18
+
19
+
20
+ class AsyncMutexCore(_core.AsyncCoreBase):
21
+ """Async counterpart to ``SyncMutexCore``.
22
+
23
+ Either owns one dedicated connection (``dsn`` mode) or borrows short-lived
24
+ connections from a caller-supplied pool (``pool`` mode) — see ``Mutex.__init__``.
25
+ In ``dsn`` mode, a single asyncio task holds the connection and both issues
26
+ heartbeats and serves ad hoc queries (acquire/release); the asyncio.Lock below
27
+ just prevents two coroutines from interleaving queries on that one connection.
28
+ In ``pool`` mode the lock is unnecessary (each borrow gets its own connection)
29
+ but harmless, so the same code path is used for both.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ config: MutexConfig,
35
+ metrics: MetricsHook | None,
36
+ *,
37
+ dsn: str | None = None,
38
+ pool: AsyncConnectionPool | None = None,
39
+ ) -> None:
40
+ super().__init__(config, metrics, dsn=dsn, pool=pool)
41
+ self._conn: psycopg.AsyncConnection[Any] | None = None
42
+ self._db_lock = asyncio.Lock()
43
+
44
+ async def _connection(self) -> psycopg.AsyncConnection[Any]:
45
+ """The dedicated dsn-mode connection, opened lazily. Not used in pool mode."""
46
+ if self._conn is None or self._conn.closed:
47
+ assert self.dsn is not None
48
+ self._conn = await psycopg.AsyncConnection.connect(self.dsn, autocommit=True)
49
+ return self._conn
50
+
51
+ @contextlib.asynccontextmanager
52
+ async def _borrow(self) -> AsyncIterator[psycopg.AsyncConnection[Any]]:
53
+ """Yield a connection to run one operation against.
54
+
55
+ dsn mode: yields the long-lived dedicated connection, unchanged after use.
56
+ pool mode: borrows one from the pool and returns it on exit — db_mutex never
57
+ owns or closes a caller-supplied pool.
58
+ """
59
+ if self.pool is not None:
60
+ async with self.pool.connection() as conn:
61
+ yield conn
62
+ else:
63
+ yield await self._connection()
64
+
65
+ async def ensure_schema(self) -> None:
66
+ query = sql.SQL(_sql.CREATE_TABLE).format(
67
+ table=sql.Identifier(self.config.table),
68
+ table_uq=sql.Identifier(f"{self.config.table}_uq"),
69
+ table_chk=sql.Identifier(f"{self.config.table}_chk_locked"),
70
+ )
71
+ async with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
72
+ await cur.execute(query)
73
+
74
+ async def close(self) -> None:
75
+ """Close the dedicated dsn-mode connection, if one was opened. In pool mode,
76
+ this is a no-op — the pool belongs to the caller.
77
+ """
78
+ await self.stop_heartbeat()
79
+ async with self._db_lock:
80
+ if self._conn is not None and not self._conn.closed:
81
+ await self._conn.close()
82
+
83
+ async def _do_try_acquire(self) -> _core.AcquireOutcome:
84
+ q_select = sql.SQL(_sql.SELECT_FOR_ACQUIRE).format(table=sql.Identifier(self.config.table))
85
+ q_delete = sql.SQL(_sql.DELETE_ROW).format(table=sql.Identifier(self.config.table))
86
+ q_insert = sql.SQL(_sql.INSERT_ROW).format(table=sql.Identifier(self.config.table))
87
+ lock_params = {"lock_name": self.config.lock_name}
88
+ insert_params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
89
+
90
+ async with self._db_lock, self._borrow() as conn:
91
+ try:
92
+ async with conn.transaction(), conn.cursor() as cur:
93
+ await cur.execute(q_select, lock_params)
94
+ row = await cur.fetchone()
95
+
96
+ if row is None:
97
+ await cur.execute(q_insert, insert_params)
98
+ return _core.AcquireOutcome(acquired=True)
99
+
100
+ holder, seconds_since = row
101
+ if seconds_since is not None and seconds_since >= self.config.stale_threshold:
102
+ await cur.execute(q_delete, lock_params)
103
+ await cur.execute(q_insert, insert_params)
104
+ return _core.AcquireOutcome(acquired=True, reclaimed_from=holder)
105
+
106
+ return _core.AcquireOutcome(
107
+ acquired=False, holder=holder, seconds_since=seconds_since
108
+ )
109
+ except psycopg.errors.UniqueViolation:
110
+ # See SyncMutexCore._do_try_acquire: SELECT ... FOR UPDATE can't
111
+ # serialize two contenders racing to INSERT a lock row that doesn't
112
+ # exist yet. The UNIQUE constraint still guarantees exactly one wins;
113
+ # the loser just lost a race, not an error.
114
+ return _core.AcquireOutcome(acquired=False)
115
+
116
+ async def _do_heartbeat(self) -> bool:
117
+ query = sql.SQL(_sql.HEARTBEAT).format(table=sql.Identifier(self.config.table))
118
+ params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
119
+ async with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
120
+ await cur.execute(query, params)
121
+ return await cur.fetchone() is not None
122
+
123
+ async def _do_release(self) -> bool:
124
+ query = sql.SQL(_sql.RELEASE).format(table=sql.Identifier(self.config.table))
125
+ params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
126
+ async with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
127
+ await cur.execute(query, params)
128
+ return await cur.fetchone() is not None
@@ -0,0 +1,137 @@
1
+ """Postgres sync backend: connection handling and acquire/release/heartbeat SQL over
2
+ psycopg 3. The reference backend — this behavior is what the crash-recovery,
3
+ contention, clock-skew, and network-partition tests were written against.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextlib
9
+ import threading
10
+ from collections.abc import Iterator
11
+ from typing import Any
12
+
13
+ import psycopg
14
+ from psycopg import sql
15
+
16
+ from ..._config import MutexConfig
17
+ from ...metrics import MetricsHook
18
+ from .. import _core
19
+ from .._core import SyncConnectionPool
20
+ from . import _sql
21
+
22
+
23
+ class SyncMutexCore(_core.SyncCoreBase):
24
+ """Does the actual SQL work, either over one dedicated connection (``dsn`` mode)
25
+ or by borrowing short-lived connections from a caller-supplied pool (``pool``
26
+ mode) — see ``Mutex.__init__``.
27
+
28
+ A background thread sends heartbeats while the lock is held. In ``dsn`` mode, all
29
+ queries against the single shared connection (from the main thread or the
30
+ heartbeat thread) go through ``_db_lock`` — psycopg connections are not safe for
31
+ concurrent use from multiple threads. In ``pool`` mode the lock is unnecessary
32
+ (each borrow gets its own connection) but harmless, so the same code path is used
33
+ for both to avoid maintaining two.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ config: MutexConfig,
39
+ metrics: MetricsHook | None,
40
+ *,
41
+ dsn: str | None = None,
42
+ pool: SyncConnectionPool | None = None,
43
+ ) -> None:
44
+ super().__init__(config, metrics, dsn=dsn, pool=pool)
45
+ self._conn: psycopg.Connection[Any] | None = None
46
+ self._db_lock = threading.Lock()
47
+
48
+ # -- connection / schema -------------------------------------------------
49
+
50
+ def _connection(self) -> psycopg.Connection[Any]:
51
+ """The dedicated dsn-mode connection, opened lazily. Not used in pool mode."""
52
+ if self._conn is None or self._conn.closed:
53
+ assert self.dsn is not None
54
+ self._conn = psycopg.connect(self.dsn, autocommit=True)
55
+ return self._conn
56
+
57
+ @contextlib.contextmanager
58
+ def _borrow(self) -> Iterator[psycopg.Connection[Any]]:
59
+ """Yield a connection to run one operation against.
60
+
61
+ dsn mode: yields the long-lived dedicated connection, unchanged after use.
62
+ pool mode: borrows one from the pool and returns it on exit — db_mutex never
63
+ owns or closes a caller-supplied pool.
64
+ """
65
+ if self.pool is not None:
66
+ with self.pool.connection() as conn:
67
+ yield conn
68
+ else:
69
+ yield self._connection()
70
+
71
+ def ensure_schema(self) -> None:
72
+ query = sql.SQL(_sql.CREATE_TABLE).format(
73
+ table=sql.Identifier(self.config.table),
74
+ table_uq=sql.Identifier(f"{self.config.table}_uq"),
75
+ table_chk=sql.Identifier(f"{self.config.table}_chk_locked"),
76
+ )
77
+ with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
78
+ cur.execute(query)
79
+
80
+ def close(self) -> None:
81
+ """Close the dedicated dsn-mode connection, if one was opened. In pool mode,
82
+ this is a no-op — the pool belongs to the caller.
83
+ """
84
+ self.stop_heartbeat()
85
+ with self._db_lock:
86
+ if self._conn is not None and not self._conn.closed:
87
+ self._conn.close()
88
+
89
+ # -- core operations -------------------------------------------------
90
+
91
+ def _do_try_acquire(self) -> _core.AcquireOutcome:
92
+ q_select = sql.SQL(_sql.SELECT_FOR_ACQUIRE).format(table=sql.Identifier(self.config.table))
93
+ q_delete = sql.SQL(_sql.DELETE_ROW).format(table=sql.Identifier(self.config.table))
94
+ q_insert = sql.SQL(_sql.INSERT_ROW).format(table=sql.Identifier(self.config.table))
95
+ lock_params = {"lock_name": self.config.lock_name}
96
+ insert_params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
97
+
98
+ with self._db_lock, self._borrow() as conn:
99
+ try:
100
+ with conn.transaction(), conn.cursor() as cur:
101
+ cur.execute(q_select, lock_params)
102
+ row = cur.fetchone()
103
+
104
+ if row is None:
105
+ cur.execute(q_insert, insert_params)
106
+ return _core.AcquireOutcome(acquired=True)
107
+
108
+ holder, seconds_since = row
109
+ if seconds_since is not None and seconds_since >= self.config.stale_threshold:
110
+ cur.execute(q_delete, lock_params)
111
+ cur.execute(q_insert, insert_params)
112
+ return _core.AcquireOutcome(acquired=True, reclaimed_from=holder)
113
+
114
+ return _core.AcquireOutcome(
115
+ acquired=False, holder=holder, seconds_since=seconds_since
116
+ )
117
+ except psycopg.errors.UniqueViolation:
118
+ # SELECT ... FOR UPDATE only serializes against a row that already
119
+ # exists — when the lock is free, two contenders can both see "no
120
+ # row" and both attempt INSERT. The UNIQUE constraint is still the
121
+ # source of truth: exactly one wins, and the loser just lost a race,
122
+ # not an error. Treat it the same as ordinary contention.
123
+ return _core.AcquireOutcome(acquired=False)
124
+
125
+ def _do_heartbeat(self) -> bool:
126
+ query = sql.SQL(_sql.HEARTBEAT).format(table=sql.Identifier(self.config.table))
127
+ params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
128
+ with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
129
+ cur.execute(query, params)
130
+ return cur.fetchone() is not None
131
+
132
+ def _do_release(self) -> bool:
133
+ query = sql.SQL(_sql.RELEASE).format(table=sql.Identifier(self.config.table))
134
+ params = {"lock_name": self.config.lock_name, "instance_id": self.config.instance_id}
135
+ with self._db_lock, self._borrow() as conn, conn.cursor() as cur:
136
+ cur.execute(query, params)
137
+ return cur.fetchone() is not None
db_mutex/exceptions.py ADDED
@@ -0,0 +1,32 @@
1
+ """Exceptions raised by db_mutex."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class DbMutexError(Exception):
7
+ """Base class for all db_mutex errors."""
8
+
9
+
10
+ class LockAcquisitionTimeout(DbMutexError):
11
+ """Raised when a blocking ``acquire()`` times out before the lock frees up."""
12
+
13
+ def __init__(self, lock_name: str, timeout: float) -> None:
14
+ self.lock_name = lock_name
15
+ self.timeout = timeout
16
+ super().__init__(f"timed out after {timeout}s waiting to acquire lock {lock_name!r}")
17
+
18
+
19
+ class LockNotHeldError(DbMutexError):
20
+ """Raised by ``release()`` or ``heartbeat()`` when the caller is not the current holder.
21
+
22
+ This happens when the lock was stolen out from under an instance because its
23
+ heartbeat went stale for longer than ``stale_threshold`` — i.e. another instance
24
+ already decided this one had crashed.
25
+ """
26
+
27
+ def __init__(self, lock_name: str) -> None:
28
+ self.lock_name = lock_name
29
+ super().__init__(
30
+ f"lock {lock_name!r} is not held by this instance "
31
+ "(it may have been reclaimed after a missed heartbeat)"
32
+ )