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.
- db_mutex/__init__.py +23 -0
- db_mutex/_config.py +52 -0
- db_mutex/backends/__init__.py +49 -0
- db_mutex/backends/_core.py +418 -0
- db_mutex/backends/mysql/__init__.py +0 -0
- db_mutex/backends/mysql/_dsn.py +29 -0
- db_mutex/backends/mysql/_sql.py +74 -0
- db_mutex/backends/mysql/async_.py +142 -0
- db_mutex/backends/mysql/sync.py +149 -0
- db_mutex/backends/postgres/__init__.py +0 -0
- db_mutex/backends/postgres/_sql.py +69 -0
- db_mutex/backends/postgres/async_.py +128 -0
- db_mutex/backends/postgres/sync.py +137 -0
- db_mutex/exceptions.py +32 -0
- db_mutex/metrics.py +77 -0
- db_mutex/mutex.py +333 -0
- db_mutex/py.typed +0 -0
- db_mutex-0.3.0.dist-info/METADATA +287 -0
- db_mutex-0.3.0.dist-info/RECORD +21 -0
- db_mutex-0.3.0.dist-info/WHEEL +4 -0
- db_mutex-0.3.0.dist-info/licenses/LICENSE +21 -0
db_mutex/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""db_mutex: a zero-dependency distributed mutex for your database.
|
|
2
|
+
|
|
3
|
+
One table, heartbeat-based liveness, automatic recovery from crashed lock holders.
|
|
4
|
+
No ZooKeeper, no Redis, no Consul, no etcd — if you already have Postgres or
|
|
5
|
+
MySQL, you shouldn't need any of those just to run a job on exactly one instance
|
|
6
|
+
at a time.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .exceptions import DbMutexError, LockAcquisitionTimeout, LockNotHeldError
|
|
10
|
+
from .metrics import MetricsHook, NullMetrics
|
|
11
|
+
from .mutex import Mutex
|
|
12
|
+
|
|
13
|
+
__version__ = "0.3.0"
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Mutex",
|
|
17
|
+
"DbMutexError",
|
|
18
|
+
"LockAcquisitionTimeout",
|
|
19
|
+
"LockNotHeldError",
|
|
20
|
+
"MetricsHook",
|
|
21
|
+
"NullMetrics",
|
|
22
|
+
"__version__",
|
|
23
|
+
]
|
db_mutex/_config.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Configuration and validation for a Mutex instance."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import socket
|
|
7
|
+
import uuid
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
_VALID_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def default_instance_id() -> str:
|
|
14
|
+
"""A reasonably unique, human-traceable default: ``<hostname>-<8 hex chars>``."""
|
|
15
|
+
return f"{socket.gethostname()}-{uuid.uuid4().hex[:8]}"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class MutexConfig:
|
|
20
|
+
"""Validated, immutable configuration for one lock.
|
|
21
|
+
|
|
22
|
+
The dual-threshold defaults (30s alert / 600s auto-release) match the design
|
|
23
|
+
rationale in the project README: a single timeout forces a choice between
|
|
24
|
+
releasing too eagerly (handing the lock to another instance that hits the same
|
|
25
|
+
slow-processing problem) or too slowly (leaving a crashed holder's job undone
|
|
26
|
+
for ages). The alert window gives on-call a chance to intervene before the
|
|
27
|
+
system self-heals.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
lock_name: str
|
|
31
|
+
instance_id: str = field(default_factory=default_instance_id)
|
|
32
|
+
table: str = "mutex_lock"
|
|
33
|
+
heartbeat_interval: float = 10.0
|
|
34
|
+
alert_threshold: float = 30.0
|
|
35
|
+
stale_threshold: float = 600.0
|
|
36
|
+
poll_interval: float = 0.5
|
|
37
|
+
|
|
38
|
+
def __post_init__(self) -> None:
|
|
39
|
+
if not self.lock_name or len(self.lock_name) > 64:
|
|
40
|
+
raise ValueError("lock_name must be non-empty and <= 64 characters")
|
|
41
|
+
if not self.instance_id or len(self.instance_id) > 64:
|
|
42
|
+
raise ValueError("instance_id must be non-empty and <= 64 characters")
|
|
43
|
+
if not _VALID_IDENTIFIER.match(self.table):
|
|
44
|
+
raise ValueError(f"invalid table name: {self.table!r}")
|
|
45
|
+
if not (0 < self.heartbeat_interval < self.alert_threshold < self.stale_threshold):
|
|
46
|
+
raise ValueError(
|
|
47
|
+
"require 0 < heartbeat_interval < alert_threshold < stale_threshold "
|
|
48
|
+
f"(got {self.heartbeat_interval}, {self.alert_threshold}, "
|
|
49
|
+
f"{self.stale_threshold})"
|
|
50
|
+
)
|
|
51
|
+
if self.poll_interval <= 0:
|
|
52
|
+
raise ValueError("poll_interval must be > 0")
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Backend resolution: maps a backend name to its sync/async core classes.
|
|
2
|
+
|
|
3
|
+
Imports are deferred into the resolver functions so that a user who only uses
|
|
4
|
+
Postgres never needs ``pymysql``/``asyncmy`` installed, and vice versa.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from ._core import AsyncCoreBase, SyncCoreBase
|
|
12
|
+
|
|
13
|
+
BackendName = Literal["postgres", "mysql"]
|
|
14
|
+
|
|
15
|
+
_SCHEME_TO_BACKEND: dict[str, BackendName] = {
|
|
16
|
+
"postgres": "postgres",
|
|
17
|
+
"postgresql": "postgres",
|
|
18
|
+
"mysql": "mysql",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def backend_from_dsn(dsn: str) -> BackendName | None:
|
|
23
|
+
"""Sniff a backend from a DSN's URL scheme, or None if it isn't recognized."""
|
|
24
|
+
scheme = dsn.split("://", 1)[0] if "://" in dsn else None
|
|
25
|
+
return None if scheme is None else _SCHEME_TO_BACKEND.get(scheme)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def resolve_sync_core(backend: BackendName) -> type[SyncCoreBase]:
|
|
29
|
+
if backend == "postgres":
|
|
30
|
+
from .postgres.sync import SyncMutexCore as PostgresSyncCore
|
|
31
|
+
|
|
32
|
+
return PostgresSyncCore
|
|
33
|
+
if backend == "mysql":
|
|
34
|
+
from .mysql.sync import SyncMutexCore as MysqlSyncCore
|
|
35
|
+
|
|
36
|
+
return MysqlSyncCore
|
|
37
|
+
raise ValueError(f"unknown backend: {backend!r}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def resolve_async_core(backend: BackendName) -> type[AsyncCoreBase]:
|
|
41
|
+
if backend == "postgres":
|
|
42
|
+
from .postgres.async_ import AsyncMutexCore as PostgresAsyncCore
|
|
43
|
+
|
|
44
|
+
return PostgresAsyncCore
|
|
45
|
+
if backend == "mysql":
|
|
46
|
+
from .mysql.async_ import AsyncMutexCore as MysqlAsyncCore
|
|
47
|
+
|
|
48
|
+
return MysqlAsyncCore
|
|
49
|
+
raise ValueError(f"unknown backend: {backend!r}")
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Backend-agnostic control flow shared by every backend's sync/async core.
|
|
2
|
+
|
|
3
|
+
The heartbeat thread/task, the blocking-poll loop, and alert logic are identical
|
|
4
|
+
regardless of which database is underneath — only the actual SQL/connection/
|
|
5
|
+
exception handling differs per backend. Putting that control flow here, once, means
|
|
6
|
+
a new backend can't silently drift from the proven Postgres behavior by getting the
|
|
7
|
+
locking logic slightly wrong in its own copy.
|
|
8
|
+
|
|
9
|
+
Each backend's sync module implements ``_SyncCoreBase``; each async module implements
|
|
10
|
+
``_AsyncCoreBase``. The abstract methods are exactly the parts that touch the
|
|
11
|
+
database: running the acquire sequence, sending a heartbeat, releasing, and ensuring
|
|
12
|
+
the schema exists.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import abc
|
|
18
|
+
import asyncio
|
|
19
|
+
import contextlib
|
|
20
|
+
import dataclasses
|
|
21
|
+
import logging
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
from typing import Any, Protocol
|
|
25
|
+
|
|
26
|
+
from .._config import MutexConfig
|
|
27
|
+
from ..exceptions import LockAcquisitionTimeout, LockNotHeldError
|
|
28
|
+
from ..metrics import MetricsHook, NullMetrics, safe_call
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger("db_mutex")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SyncConnectionPool(Protocol):
|
|
34
|
+
"""Shape of a caller-supplied sync connection pool (e.g. ``psycopg_pool.ConnectionPool``):
|
|
35
|
+
any object exposing a ``connection()`` context manager. Matched structurally so
|
|
36
|
+
db_mutex doesn't need any particular pool package as a hard dependency.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def connection(self, timeout: float | None = None) -> Any: ... # context manager
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AsyncConnectionPool(Protocol):
|
|
43
|
+
"""Async counterpart to ``SyncConnectionPool``."""
|
|
44
|
+
|
|
45
|
+
def connection(self, timeout: float | None = None) -> Any: ... # async context manager
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclasses.dataclass
|
|
49
|
+
class AcquireOutcome:
|
|
50
|
+
"""Result of one acquire attempt, as reported by a backend's ``_do_try_acquire``."""
|
|
51
|
+
|
|
52
|
+
acquired: bool
|
|
53
|
+
reclaimed_from: str | None = None
|
|
54
|
+
holder: str | None = None
|
|
55
|
+
seconds_since: float | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _AlertMixin:
|
|
59
|
+
"""Shared on-call-alert throttling, used by both the sync and async base."""
|
|
60
|
+
|
|
61
|
+
config: MutexConfig
|
|
62
|
+
metrics: MetricsHook
|
|
63
|
+
_last_alert_at: float
|
|
64
|
+
|
|
65
|
+
def _fire_alert(self, holder: str, seconds_since: float) -> None:
|
|
66
|
+
now = time.monotonic()
|
|
67
|
+
if now - self._last_alert_at < self.config.alert_threshold:
|
|
68
|
+
return # already alerted recently; don't page repeatedly every poll
|
|
69
|
+
self._last_alert_at = now
|
|
70
|
+
|
|
71
|
+
logger.warning(
|
|
72
|
+
"db_mutex: lock %r held by %r with no heartbeat for %.1fs (alert threshold %.1fs)",
|
|
73
|
+
self.config.lock_name,
|
|
74
|
+
holder,
|
|
75
|
+
seconds_since,
|
|
76
|
+
self.config.alert_threshold,
|
|
77
|
+
)
|
|
78
|
+
safe_call(
|
|
79
|
+
self.metrics,
|
|
80
|
+
"alert",
|
|
81
|
+
lock_name=self.config.lock_name,
|
|
82
|
+
holder=holder,
|
|
83
|
+
seconds_since_heartbeat=seconds_since,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class SyncCoreBase(_AlertMixin, abc.ABC):
|
|
88
|
+
"""Shared sync control flow. Subclasses supply the DB-specific operations."""
|
|
89
|
+
|
|
90
|
+
def __init__(
|
|
91
|
+
self,
|
|
92
|
+
config: MutexConfig,
|
|
93
|
+
metrics: MetricsHook | None,
|
|
94
|
+
*,
|
|
95
|
+
dsn: str | None = None,
|
|
96
|
+
pool: SyncConnectionPool | None = None,
|
|
97
|
+
) -> None:
|
|
98
|
+
self.config = config
|
|
99
|
+
self.metrics = metrics or NullMetrics()
|
|
100
|
+
self.dsn = dsn
|
|
101
|
+
self.pool = pool
|
|
102
|
+
self._held = False
|
|
103
|
+
self._lost = threading.Event()
|
|
104
|
+
self._last_alert_at = 0.0
|
|
105
|
+
self._heartbeat_thread: threading.Thread | None = None
|
|
106
|
+
self._stop_heartbeat = threading.Event()
|
|
107
|
+
|
|
108
|
+
# -- DB-specific hooks, implemented per backend -------------------------------
|
|
109
|
+
|
|
110
|
+
@abc.abstractmethod
|
|
111
|
+
def ensure_schema(self) -> None: ...
|
|
112
|
+
|
|
113
|
+
@abc.abstractmethod
|
|
114
|
+
def _do_try_acquire(self) -> AcquireOutcome: ...
|
|
115
|
+
|
|
116
|
+
@abc.abstractmethod
|
|
117
|
+
def _do_heartbeat(self) -> bool:
|
|
118
|
+
"""Send one heartbeat; return True if a row for this instance was matched."""
|
|
119
|
+
|
|
120
|
+
@abc.abstractmethod
|
|
121
|
+
def _do_release(self) -> bool:
|
|
122
|
+
"""Delete this instance's row; return True if a row was matched."""
|
|
123
|
+
|
|
124
|
+
@abc.abstractmethod
|
|
125
|
+
def close(self) -> None: ...
|
|
126
|
+
|
|
127
|
+
# -- shared control flow -------------------------------------------------
|
|
128
|
+
|
|
129
|
+
def try_acquire(self) -> bool:
|
|
130
|
+
outcome = self._do_try_acquire()
|
|
131
|
+
|
|
132
|
+
if not outcome.acquired:
|
|
133
|
+
safe_call(
|
|
134
|
+
self.metrics,
|
|
135
|
+
"contended",
|
|
136
|
+
lock_name=self.config.lock_name,
|
|
137
|
+
instance_id=self.config.instance_id,
|
|
138
|
+
)
|
|
139
|
+
if (
|
|
140
|
+
outcome.holder is not None
|
|
141
|
+
and outcome.seconds_since is not None
|
|
142
|
+
and outcome.seconds_since >= self.config.alert_threshold
|
|
143
|
+
):
|
|
144
|
+
self._fire_alert(outcome.holder, outcome.seconds_since)
|
|
145
|
+
return False
|
|
146
|
+
|
|
147
|
+
self._held = True
|
|
148
|
+
self._lost.clear()
|
|
149
|
+
if outcome.reclaimed_from is not None:
|
|
150
|
+
safe_call(
|
|
151
|
+
self.metrics,
|
|
152
|
+
"stale_reclaimed",
|
|
153
|
+
lock_name=self.config.lock_name,
|
|
154
|
+
instance_id=self.config.instance_id,
|
|
155
|
+
previous_holder=outcome.reclaimed_from,
|
|
156
|
+
)
|
|
157
|
+
logger.warning(
|
|
158
|
+
"db_mutex: reclaimed lock %r from stale holder %r (instance %r)",
|
|
159
|
+
self.config.lock_name,
|
|
160
|
+
outcome.reclaimed_from,
|
|
161
|
+
self.config.instance_id,
|
|
162
|
+
)
|
|
163
|
+
safe_call(
|
|
164
|
+
self.metrics,
|
|
165
|
+
"acquired",
|
|
166
|
+
lock_name=self.config.lock_name,
|
|
167
|
+
instance_id=self.config.instance_id,
|
|
168
|
+
)
|
|
169
|
+
return True
|
|
170
|
+
|
|
171
|
+
def heartbeat(self) -> None:
|
|
172
|
+
start = time.monotonic()
|
|
173
|
+
matched = self._do_heartbeat()
|
|
174
|
+
elapsed = time.monotonic() - start
|
|
175
|
+
|
|
176
|
+
if not matched:
|
|
177
|
+
self._held = False
|
|
178
|
+
self._lost.set()
|
|
179
|
+
raise LockNotHeldError(self.config.lock_name)
|
|
180
|
+
|
|
181
|
+
safe_call(
|
|
182
|
+
self.metrics,
|
|
183
|
+
"heartbeat_latency",
|
|
184
|
+
lock_name=self.config.lock_name,
|
|
185
|
+
instance_id=self.config.instance_id,
|
|
186
|
+
seconds=elapsed,
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
def release(self) -> None:
|
|
190
|
+
self.stop_heartbeat()
|
|
191
|
+
matched = self._do_release()
|
|
192
|
+
self._held = False
|
|
193
|
+
if not matched:
|
|
194
|
+
raise LockNotHeldError(self.config.lock_name)
|
|
195
|
+
|
|
196
|
+
safe_call(
|
|
197
|
+
self.metrics,
|
|
198
|
+
"released",
|
|
199
|
+
lock_name=self.config.lock_name,
|
|
200
|
+
instance_id=self.config.instance_id,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
# -- background heartbeat thread -------------------------------------------------
|
|
204
|
+
|
|
205
|
+
def start_heartbeat(self) -> None:
|
|
206
|
+
if self._heartbeat_thread is not None:
|
|
207
|
+
return
|
|
208
|
+
self._stop_heartbeat.clear()
|
|
209
|
+
self._heartbeat_thread = threading.Thread(
|
|
210
|
+
target=self._heartbeat_loop,
|
|
211
|
+
name=f"db-mutex-heartbeat-{self.config.lock_name}",
|
|
212
|
+
daemon=True,
|
|
213
|
+
)
|
|
214
|
+
self._heartbeat_thread.start()
|
|
215
|
+
|
|
216
|
+
def stop_heartbeat(self) -> None:
|
|
217
|
+
self._stop_heartbeat.set()
|
|
218
|
+
thread, self._heartbeat_thread = self._heartbeat_thread, None
|
|
219
|
+
if thread is not None and thread.is_alive() and thread is not threading.current_thread():
|
|
220
|
+
thread.join(timeout=self.config.heartbeat_interval)
|
|
221
|
+
|
|
222
|
+
def _heartbeat_loop(self) -> None:
|
|
223
|
+
while not self._stop_heartbeat.wait(self.config.heartbeat_interval):
|
|
224
|
+
try:
|
|
225
|
+
self.heartbeat()
|
|
226
|
+
except LockNotHeldError:
|
|
227
|
+
logger.error(
|
|
228
|
+
"db_mutex: lost lock %r (instance %r) — heartbeat missed the "
|
|
229
|
+
"stale window and another instance reclaimed it",
|
|
230
|
+
self.config.lock_name,
|
|
231
|
+
self.config.instance_id,
|
|
232
|
+
)
|
|
233
|
+
return
|
|
234
|
+
except Exception:
|
|
235
|
+
logger.exception(
|
|
236
|
+
"db_mutex: heartbeat failed for lock %r (instance %r); will retry",
|
|
237
|
+
self.config.lock_name,
|
|
238
|
+
self.config.instance_id,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
# -- blocking wait -------------------------------------------------
|
|
242
|
+
|
|
243
|
+
def acquire(self, blocking: bool, timeout: float | None) -> bool:
|
|
244
|
+
if self.try_acquire():
|
|
245
|
+
self.start_heartbeat()
|
|
246
|
+
return True
|
|
247
|
+
if not blocking:
|
|
248
|
+
return False
|
|
249
|
+
|
|
250
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
251
|
+
while True:
|
|
252
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
253
|
+
raise LockAcquisitionTimeout(self.config.lock_name, timeout) # type: ignore[arg-type]
|
|
254
|
+
time.sleep(self.config.poll_interval)
|
|
255
|
+
if self.try_acquire():
|
|
256
|
+
self.start_heartbeat()
|
|
257
|
+
return True
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class AsyncCoreBase(_AlertMixin, abc.ABC):
|
|
261
|
+
"""Shared async control flow. Subclasses supply the DB-specific operations."""
|
|
262
|
+
|
|
263
|
+
def __init__(
|
|
264
|
+
self,
|
|
265
|
+
config: MutexConfig,
|
|
266
|
+
metrics: MetricsHook | None,
|
|
267
|
+
*,
|
|
268
|
+
dsn: str | None = None,
|
|
269
|
+
pool: AsyncConnectionPool | None = None,
|
|
270
|
+
) -> None:
|
|
271
|
+
self.config = config
|
|
272
|
+
self.metrics = metrics or NullMetrics()
|
|
273
|
+
self.dsn = dsn
|
|
274
|
+
self.pool = pool
|
|
275
|
+
self._held = False
|
|
276
|
+
self._lost = asyncio.Event()
|
|
277
|
+
self._last_alert_at = 0.0
|
|
278
|
+
self._heartbeat_task: asyncio.Task[None] | None = None
|
|
279
|
+
|
|
280
|
+
@abc.abstractmethod
|
|
281
|
+
async def ensure_schema(self) -> None: ...
|
|
282
|
+
|
|
283
|
+
@abc.abstractmethod
|
|
284
|
+
async def _do_try_acquire(self) -> AcquireOutcome: ...
|
|
285
|
+
|
|
286
|
+
@abc.abstractmethod
|
|
287
|
+
async def _do_heartbeat(self) -> bool: ...
|
|
288
|
+
|
|
289
|
+
@abc.abstractmethod
|
|
290
|
+
async def _do_release(self) -> bool: ...
|
|
291
|
+
|
|
292
|
+
@abc.abstractmethod
|
|
293
|
+
async def close(self) -> None: ...
|
|
294
|
+
|
|
295
|
+
async def try_acquire(self) -> bool:
|
|
296
|
+
outcome = await self._do_try_acquire()
|
|
297
|
+
|
|
298
|
+
if not outcome.acquired:
|
|
299
|
+
safe_call(
|
|
300
|
+
self.metrics,
|
|
301
|
+
"contended",
|
|
302
|
+
lock_name=self.config.lock_name,
|
|
303
|
+
instance_id=self.config.instance_id,
|
|
304
|
+
)
|
|
305
|
+
if (
|
|
306
|
+
outcome.holder is not None
|
|
307
|
+
and outcome.seconds_since is not None
|
|
308
|
+
and outcome.seconds_since >= self.config.alert_threshold
|
|
309
|
+
):
|
|
310
|
+
self._fire_alert(outcome.holder, outcome.seconds_since)
|
|
311
|
+
return False
|
|
312
|
+
|
|
313
|
+
self._held = True
|
|
314
|
+
self._lost = asyncio.Event()
|
|
315
|
+
if outcome.reclaimed_from is not None:
|
|
316
|
+
safe_call(
|
|
317
|
+
self.metrics,
|
|
318
|
+
"stale_reclaimed",
|
|
319
|
+
lock_name=self.config.lock_name,
|
|
320
|
+
instance_id=self.config.instance_id,
|
|
321
|
+
previous_holder=outcome.reclaimed_from,
|
|
322
|
+
)
|
|
323
|
+
logger.warning(
|
|
324
|
+
"db_mutex: reclaimed lock %r from stale holder %r (instance %r)",
|
|
325
|
+
self.config.lock_name,
|
|
326
|
+
outcome.reclaimed_from,
|
|
327
|
+
self.config.instance_id,
|
|
328
|
+
)
|
|
329
|
+
safe_call(
|
|
330
|
+
self.metrics,
|
|
331
|
+
"acquired",
|
|
332
|
+
lock_name=self.config.lock_name,
|
|
333
|
+
instance_id=self.config.instance_id,
|
|
334
|
+
)
|
|
335
|
+
return True
|
|
336
|
+
|
|
337
|
+
async def heartbeat(self) -> None:
|
|
338
|
+
start = time.monotonic()
|
|
339
|
+
matched = await self._do_heartbeat()
|
|
340
|
+
elapsed = time.monotonic() - start
|
|
341
|
+
|
|
342
|
+
if not matched:
|
|
343
|
+
self._held = False
|
|
344
|
+
self._lost.set()
|
|
345
|
+
raise LockNotHeldError(self.config.lock_name)
|
|
346
|
+
|
|
347
|
+
safe_call(
|
|
348
|
+
self.metrics,
|
|
349
|
+
"heartbeat_latency",
|
|
350
|
+
lock_name=self.config.lock_name,
|
|
351
|
+
instance_id=self.config.instance_id,
|
|
352
|
+
seconds=elapsed,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
async def release(self) -> None:
|
|
356
|
+
await self.stop_heartbeat()
|
|
357
|
+
matched = await self._do_release()
|
|
358
|
+
self._held = False
|
|
359
|
+
if not matched:
|
|
360
|
+
raise LockNotHeldError(self.config.lock_name)
|
|
361
|
+
|
|
362
|
+
safe_call(
|
|
363
|
+
self.metrics,
|
|
364
|
+
"released",
|
|
365
|
+
lock_name=self.config.lock_name,
|
|
366
|
+
instance_id=self.config.instance_id,
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
def start_heartbeat(self) -> None:
|
|
370
|
+
if self._heartbeat_task is not None:
|
|
371
|
+
return
|
|
372
|
+
self._heartbeat_task = asyncio.ensure_future(self._heartbeat_loop())
|
|
373
|
+
|
|
374
|
+
async def stop_heartbeat(self) -> None:
|
|
375
|
+
task, self._heartbeat_task = self._heartbeat_task, None
|
|
376
|
+
if task is not None and not task.done():
|
|
377
|
+
task.cancel()
|
|
378
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
379
|
+
await task
|
|
380
|
+
|
|
381
|
+
async def _heartbeat_loop(self) -> None:
|
|
382
|
+
try:
|
|
383
|
+
while True:
|
|
384
|
+
await asyncio.sleep(self.config.heartbeat_interval)
|
|
385
|
+
try:
|
|
386
|
+
await self.heartbeat()
|
|
387
|
+
except LockNotHeldError:
|
|
388
|
+
logger.error(
|
|
389
|
+
"db_mutex: lost lock %r (instance %r) — heartbeat missed the "
|
|
390
|
+
"stale window and another instance reclaimed it",
|
|
391
|
+
self.config.lock_name,
|
|
392
|
+
self.config.instance_id,
|
|
393
|
+
)
|
|
394
|
+
return
|
|
395
|
+
except Exception:
|
|
396
|
+
logger.exception(
|
|
397
|
+
"db_mutex: heartbeat failed for lock %r (instance %r); will retry",
|
|
398
|
+
self.config.lock_name,
|
|
399
|
+
self.config.instance_id,
|
|
400
|
+
)
|
|
401
|
+
except asyncio.CancelledError:
|
|
402
|
+
raise
|
|
403
|
+
|
|
404
|
+
async def acquire(self, blocking: bool, timeout: float | None) -> bool:
|
|
405
|
+
if await self.try_acquire():
|
|
406
|
+
self.start_heartbeat()
|
|
407
|
+
return True
|
|
408
|
+
if not blocking:
|
|
409
|
+
return False
|
|
410
|
+
|
|
411
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
412
|
+
while True:
|
|
413
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
414
|
+
raise LockAcquisitionTimeout(self.config.lock_name, timeout) # type: ignore[arg-type]
|
|
415
|
+
await asyncio.sleep(self.config.poll_interval)
|
|
416
|
+
if await self.try_acquire():
|
|
417
|
+
self.start_heartbeat()
|
|
418
|
+
return True
|
|
File without changes
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Parse a ``mysql://user:pass@host:port/dbname`` DSN into PyMySQL/asyncmy connect
|
|
2
|
+
kwargs. Postgres's ``dsn`` is handed straight to psycopg (which accepts libpq URLs
|
|
3
|
+
natively); MySQL drivers don't take a URL, so db_mutex parses it here instead
|
|
4
|
+
of pushing that parsing onto every caller.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
from urllib.parse import unquote, urlparse
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def parse_mysql_dsn(dsn: str) -> dict[str, Any]:
|
|
14
|
+
parsed = urlparse(dsn)
|
|
15
|
+
if parsed.scheme not in ("mysql", "mysql+pymysql"):
|
|
16
|
+
raise ValueError(f"not a mysql:// DSN: {dsn!r}")
|
|
17
|
+
|
|
18
|
+
kwargs: dict[str, Any] = {
|
|
19
|
+
"host": parsed.hostname or "127.0.0.1",
|
|
20
|
+
"port": parsed.port or 3306,
|
|
21
|
+
}
|
|
22
|
+
if parsed.username:
|
|
23
|
+
kwargs["user"] = unquote(parsed.username)
|
|
24
|
+
if parsed.password:
|
|
25
|
+
kwargs["password"] = unquote(parsed.password)
|
|
26
|
+
database = parsed.path.lstrip("/")
|
|
27
|
+
if database:
|
|
28
|
+
kwargs["database"] = database
|
|
29
|
+
return kwargs
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Raw SQL for the mutex_lock table — MySQL dialect.
|
|
2
|
+
|
|
3
|
+
Mirrors ``backends/postgres/_sql.py`` with the dialect differences spelled out below
|
|
4
|
+
(see the project plan for the full rationale):
|
|
5
|
+
|
|
6
|
+
- No ``RETURNING`` on UPDATE/DELETE — callers check ``cursor.rowcount`` instead.
|
|
7
|
+
- ``TIMESTAMPDIFF(SECOND, ...)`` in place of ``EXTRACT(EPOCH FROM ...)``.
|
|
8
|
+
- ``DATETIME(6)`` + explicit ``UTC_TIMESTAMP()`` in place of ``TIMESTAMPTZ`` +
|
|
9
|
+
``now()``, so a connection's session ``time_zone`` is never load-bearing.
|
|
10
|
+
- Backtick identifier quoting (handled by ``quote_identifier`` below, not psycopg's
|
|
11
|
+
``sql`` module).
|
|
12
|
+
- ``ENGINE=InnoDB`` pinned explicitly (needed for ``FOR UPDATE`` row locks and
|
|
13
|
+
transactions; also the default engine, but don't rely on that staying true).
|
|
14
|
+
- ``CHECK (locked = 1)`` requires MySQL >= 8.0.16 to actually be enforced rather than
|
|
15
|
+
silently ignored — this backend is MySQL 8.0.16+ only.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def quote_identifier(name: str) -> str:
|
|
22
|
+
"""Backtick-quote an identifier, escaping any literal backtick in the name."""
|
|
23
|
+
return "`" + name.replace("`", "``") + "`"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
CREATE_TABLE = """
|
|
27
|
+
CREATE TABLE IF NOT EXISTS {table} (
|
|
28
|
+
lock_name VARCHAR(64) NOT NULL,
|
|
29
|
+
locked INT NOT NULL DEFAULT 1,
|
|
30
|
+
instance_id VARCHAR(64) NOT NULL,
|
|
31
|
+
last_heartbeat DATETIME(6) NOT NULL,
|
|
32
|
+
acquired_at DATETIME(6) NOT NULL,
|
|
33
|
+
CONSTRAINT {table_uq} UNIQUE (locked, lock_name),
|
|
34
|
+
CONSTRAINT {table_chk} CHECK (locked = 1)
|
|
35
|
+
) ENGINE=InnoDB
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
# Same locate-then-act sequence as the Postgres backend (see its _sql.py for the full
|
|
39
|
+
# rationale on why this isn't a single INSERT ... ON DUPLICATE KEY statement): run
|
|
40
|
+
# inside one explicit transaction, SELECT ... FOR UPDATE to serialize concurrent
|
|
41
|
+
# acquirers for the same lock_name against an existing row, then branch on whether a
|
|
42
|
+
# row exists and how stale it is.
|
|
43
|
+
SELECT_FOR_ACQUIRE = """
|
|
44
|
+
SELECT instance_id,
|
|
45
|
+
TIMESTAMPDIFF(SECOND, last_heartbeat, UTC_TIMESTAMP(6)) AS seconds_since_heartbeat
|
|
46
|
+
FROM {table}
|
|
47
|
+
WHERE lock_name = %(lock_name)s
|
|
48
|
+
FOR UPDATE
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
DELETE_ROW = """
|
|
52
|
+
DELETE FROM {table}
|
|
53
|
+
WHERE lock_name = %(lock_name)s
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
INSERT_ROW = """
|
|
57
|
+
INSERT INTO {table} (lock_name, locked, instance_id, last_heartbeat, acquired_at)
|
|
58
|
+
VALUES (%(lock_name)s, 1, %(instance_id)s, UTC_TIMESTAMP(6), UTC_TIMESTAMP(6))
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
# No RETURNING in MySQL — the caller checks cursor.rowcount instead of fetching a row.
|
|
62
|
+
HEARTBEAT = """
|
|
63
|
+
UPDATE {table}
|
|
64
|
+
SET last_heartbeat = UTC_TIMESTAMP(6)
|
|
65
|
+
WHERE lock_name = %(lock_name)s AND instance_id = %(instance_id)s
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
# Clean shutdown: delete the row outright so the next instance doesn't wait out the
|
|
69
|
+
# stale_threshold. Scoped to instance_id so a holder that already lost the lock to a
|
|
70
|
+
# stale-reclaim can't accidentally delete the new holder's row.
|
|
71
|
+
RELEASE = """
|
|
72
|
+
DELETE FROM {table}
|
|
73
|
+
WHERE lock_name = %(lock_name)s AND instance_id = %(instance_id)s
|
|
74
|
+
"""
|