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/metrics.py ADDED
@@ -0,0 +1,77 @@
1
+ """Metrics hook interface.
2
+
3
+ db_mutex has no hard dependency on any metrics backend. Instead it defines a small
4
+ protocol that Prometheus (``prometheus_client``), OpenTelemetry, statsd, or a
5
+ homegrown metrics object can all satisfy without db_mutex knowing about any of them.
6
+
7
+ Every method is called synchronously and must not raise — a broken metrics backend
8
+ should never take down the lock. ``Mutex`` wraps every call in a best-effort try/except.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ from typing import Protocol, runtime_checkable
15
+
16
+
17
+ @runtime_checkable
18
+ class MetricsHook(Protocol):
19
+ """Implement whichever subset of these you care about; unset methods are no-ops.
20
+
21
+ A minimal Prometheus adapter, for example, might implement ``acquired`` as
22
+ ``counter.labels(lock_name=lock_name).inc()`` and ``heartbeat_latency`` as
23
+ ``histogram.labels(lock_name=lock_name).observe(seconds)``.
24
+ """
25
+
26
+ def acquired(self, lock_name: str, *, instance_id: str) -> None:
27
+ """Called every time this instance successfully acquires the lock."""
28
+
29
+ def released(self, lock_name: str, *, instance_id: str) -> None:
30
+ """Called every time this instance cleanly releases the lock."""
31
+
32
+ def contended(self, lock_name: str, *, instance_id: str) -> None:
33
+ """Called every time an acquire attempt finds the lock already held."""
34
+
35
+ def stale_reclaimed(self, lock_name: str, *, instance_id: str, previous_holder: str) -> None:
36
+ """Called when this instance steals a lock whose holder went stale (>10min)."""
37
+
38
+ def alert(self, lock_name: str, *, holder: str, seconds_since_heartbeat: float) -> None:
39
+ """Called when a holder's heartbeat is stale enough to page on-call (>30s)."""
40
+
41
+ def heartbeat_latency(self, lock_name: str, *, instance_id: str, seconds: float) -> None:
42
+ """Called after each heartbeat UPDATE with the round-trip latency."""
43
+
44
+
45
+ class NullMetrics:
46
+ """Default no-op metrics hook used when the caller doesn't supply one."""
47
+
48
+ def acquired(self, lock_name: str, *, instance_id: str) -> None:
49
+ pass
50
+
51
+ def released(self, lock_name: str, *, instance_id: str) -> None:
52
+ pass
53
+
54
+ def contended(self, lock_name: str, *, instance_id: str) -> None:
55
+ pass
56
+
57
+ def stale_reclaimed(self, lock_name: str, *, instance_id: str, previous_holder: str) -> None:
58
+ pass
59
+
60
+ def alert(self, lock_name: str, *, holder: str, seconds_since_heartbeat: float) -> None:
61
+ pass
62
+
63
+ def heartbeat_latency(self, lock_name: str, *, instance_id: str, seconds: float) -> None:
64
+ pass
65
+
66
+
67
+ def safe_call(hook: object, method: str, /, **kwargs: object) -> None:
68
+ """Call ``hook.<method>(**kwargs)`` if present, swallowing any exception it raises.
69
+
70
+ A user-supplied metrics backend must never be able to break lock acquisition or
71
+ release. If it raises, we drop the metric on the floor rather than propagate.
72
+ """
73
+ fn = getattr(hook, method, None)
74
+ if fn is None:
75
+ return
76
+ with contextlib.suppress(Exception): # metrics must never break the mutex
77
+ fn(**kwargs)
db_mutex/mutex.py ADDED
@@ -0,0 +1,333 @@
1
+ """Public ``Mutex`` API: sync and async acquire/release/heartbeat, context managers,
2
+ and the ``@mutex.singleton`` decorator.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import contextlib
8
+ import dataclasses
9
+ import functools
10
+ import logging
11
+ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
12
+ from typing import ParamSpec, TypeVar
13
+
14
+ from ._config import MutexConfig, default_instance_id
15
+ from .backends import BackendName, backend_from_dsn, resolve_async_core, resolve_sync_core
16
+ from .backends._core import AsyncConnectionPool, AsyncCoreBase, SyncConnectionPool, SyncCoreBase
17
+ from .metrics import MetricsHook
18
+
19
+ logger = logging.getLogger("db_mutex")
20
+
21
+ P = ParamSpec("P")
22
+ R = TypeVar("R")
23
+
24
+
25
+ class Mutex:
26
+ """A distributed mutex backed by a single Postgres table.
27
+
28
+ One ``Mutex`` maps to one ``lock_name``. Construct it once and reuse it — sync and
29
+ async operations are both available on the same instance, though a given lock is
30
+ typically driven from one side or the other in a given process.
31
+
32
+ Supply exactly one connection source:
33
+
34
+ - ``dsn`` (the common case): a libpq connection string passed straight to
35
+ psycopg. Mutex opens and owns one dedicated connection per side (sync/async)
36
+ used for it — fine for typical singleton-job / leader-election use, but it's an
37
+ extra always-open connection per ``Mutex`` instance.
38
+ - ``pool`` / ``async_pool``: an existing ``psycopg_pool.ConnectionPool`` /
39
+ ``AsyncConnectionPool`` that your application already manages (e.g. behind
40
+ pgbouncer). Mutex borrows a connection for the duration of each operation
41
+ (acquire, heartbeat, release) and returns it — it never owns or closes the
42
+ pool. Pass both if you use the mutex from both sync and async code.
43
+
44
+ Example::
45
+
46
+ mutex = Mutex(dsn="postgres://...", lock_name="nightly-report-job")
47
+ with mutex.acquire(blocking=False) as acquired:
48
+ if acquired:
49
+ run_the_job()
50
+ else:
51
+ log.info("another instance is running the job")
52
+
53
+ Or, reusing a pool your app already has::
54
+
55
+ mutex = Mutex(lock_name="nightly-report-job", pool=app_pool)
56
+
57
+ Args:
58
+ dsn: libpq connection string / URL passed straight to psycopg. Omit if
59
+ passing ``pool``/``async_pool`` instead.
60
+ lock_name: name of the lock, unique per table. Max 64 characters.
61
+ pool: a ``psycopg_pool.ConnectionPool`` to borrow sync connections from,
62
+ instead of ``dsn``.
63
+ async_pool: a ``psycopg_pool.AsyncConnectionPool`` to borrow async
64
+ connections from, instead of ``dsn``.
65
+ backend: ``"postgres"`` or ``"mysql"``. If omitted, inferred from the
66
+ ``dsn`` scheme (``postgres://``/``postgresql://`` or ``mysql://``);
67
+ defaults to ``"postgres"`` if that can't be inferred (e.g. a
68
+ scheme-less ``pool``/``async_pool`` with no ``dsn``). MySQL support
69
+ requires the ``db-mutex[mysql]`` extra and MySQL >= 8.0.16.
70
+ instance_id: identifies this process as the holder. Defaults to
71
+ ``<hostname>-<random>``; set explicitly if you want stable, recognizable
72
+ IDs in logs and alerts (e.g. ``f"{hostname}-pid{os.getpid()}"``).
73
+ table: name of the lock table. Defaults to ``mutex_lock``; override to run
74
+ multiple independent lock tables in the same database.
75
+ heartbeat_interval: seconds between heartbeats while the lock is held.
76
+ alert_threshold: seconds of missed heartbeat before ``on_alert``/metrics fire,
77
+ signalling on-call should investigate a possibly-stuck holder.
78
+ stale_threshold: seconds of missed heartbeat before another instance is
79
+ allowed to reclaim the lock outright, assuming the holder crashed.
80
+ poll_interval: seconds between retries while blocking on ``acquire``.
81
+ metrics: optional ``MetricsHook`` implementation (Prometheus, OTel, etc).
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ dsn: str | None = None,
87
+ lock_name: str = "",
88
+ *,
89
+ pool: SyncConnectionPool | None = None,
90
+ async_pool: AsyncConnectionPool | None = None,
91
+ backend: BackendName | None = None,
92
+ instance_id: str | None = None,
93
+ table: str = "mutex_lock",
94
+ heartbeat_interval: float = 10.0,
95
+ alert_threshold: float = 30.0,
96
+ stale_threshold: float = 600.0,
97
+ poll_interval: float = 0.5,
98
+ metrics: MetricsHook | None = None,
99
+ ) -> None:
100
+ if dsn is None and pool is None and async_pool is None:
101
+ raise ValueError("Mutex needs a connection source: pass dsn, pool, or async_pool")
102
+ self.dsn = dsn
103
+ self.pool = pool
104
+ self.async_pool = async_pool
105
+ resolved_backend = backend
106
+ if resolved_backend is None and dsn is not None:
107
+ resolved_backend = backend_from_dsn(dsn)
108
+ self.backend: BackendName = resolved_backend or "postgres"
109
+ self.config = MutexConfig(
110
+ lock_name=lock_name,
111
+ instance_id=instance_id or default_instance_id(),
112
+ table=table,
113
+ heartbeat_interval=heartbeat_interval,
114
+ alert_threshold=alert_threshold,
115
+ stale_threshold=stale_threshold,
116
+ poll_interval=poll_interval,
117
+ )
118
+ self.metrics = metrics
119
+ self._sync_core: SyncCoreBase | None = None
120
+ self._async_core: AsyncCoreBase | None = None
121
+
122
+ # -- properties -------------------------------------------------
123
+
124
+ @property
125
+ def lock_name(self) -> str:
126
+ return self.config.lock_name
127
+
128
+ @property
129
+ def instance_id(self) -> str:
130
+ return self.config.instance_id
131
+
132
+ @property
133
+ def held(self) -> bool:
134
+ """Best-effort local flag: was the lock acquired and not yet released/lost?
135
+
136
+ This reflects local state, not a fresh read of the database — a heartbeat
137
+ failure updates it asynchronously (within one ``heartbeat_interval``), it
138
+ does not poll on every access.
139
+ """
140
+ if self._sync_core is not None and self._sync_core._held:
141
+ return True
142
+ return bool(self._async_core is not None and self._async_core._held)
143
+
144
+ # -- lazy core accessors -------------------------------------------------
145
+
146
+ def _sync(self) -> SyncCoreBase:
147
+ if self._sync_core is None:
148
+ if self.dsn is None and self.pool is None:
149
+ raise ValueError(
150
+ "this Mutex has no sync connection source configured "
151
+ "(pass dsn or pool) — only async_pool was given"
152
+ )
153
+ core_cls = resolve_sync_core(self.backend)
154
+ self._sync_core = core_cls(self.config, self.metrics, dsn=self.dsn, pool=self.pool)
155
+ return self._sync_core
156
+
157
+ def _async(self) -> AsyncCoreBase:
158
+ if self._async_core is None:
159
+ if self.dsn is None and self.async_pool is None:
160
+ raise ValueError(
161
+ "this Mutex has no async connection source configured "
162
+ "(pass dsn or async_pool) — only pool was given"
163
+ )
164
+ core_cls = resolve_async_core(self.backend)
165
+ self._async_core = core_cls(
166
+ self.config, self.metrics, dsn=self.dsn, pool=self.async_pool
167
+ )
168
+ return self._async_core
169
+
170
+ # -- schema -------------------------------------------------
171
+
172
+ def create_schema(self) -> None:
173
+ """Create the lock table if it doesn't already exist. Safe to call repeatedly."""
174
+ self._sync().ensure_schema()
175
+
176
+ async def create_schema_async(self) -> None:
177
+ """Async counterpart to ``create_schema``."""
178
+ await self._async().ensure_schema()
179
+
180
+ # -- sync API -------------------------------------------------
181
+
182
+ @contextlib.contextmanager
183
+ def acquire(self, blocking: bool = False, timeout: float | None = None) -> Iterator[bool]:
184
+ """Context manager. Yields ``True`` if the lock was acquired, ``False`` otherwise.
185
+
186
+ With ``blocking=False`` (default), returns immediately either way — check the
187
+ yielded value to decide whether to proceed. With ``blocking=True``, waits
188
+ (polling every ``poll_interval`` seconds) until the lock frees up or
189
+ ``timeout`` elapses, raising ``LockAcquisitionTimeout`` on timeout.
190
+
191
+ The lock is released automatically on exiting the ``with`` block, regardless
192
+ of whether the body raises.
193
+ """
194
+ core = self._sync()
195
+ acquired = core.acquire(blocking=blocking, timeout=timeout)
196
+ try:
197
+ yield acquired
198
+ finally:
199
+ if acquired:
200
+ core.release()
201
+
202
+ def release(self) -> None:
203
+ """Release the lock outright (deletes the row) and stop the heartbeat thread.
204
+
205
+ Prefer the ``acquire()`` context manager, which calls this for you. Raises
206
+ ``LockNotHeldError`` if this instance no longer holds the lock (e.g. it was
207
+ reclaimed after a missed heartbeat).
208
+ """
209
+ self._sync().release()
210
+
211
+ def heartbeat(self) -> None:
212
+ """Manually send one heartbeat. Not usually needed — ``acquire()`` starts a
213
+ background thread that does this automatically. Raises ``LockNotHeldError``
214
+ if the lock was reclaimed by another instance.
215
+ """
216
+ self._sync().heartbeat()
217
+
218
+ def singleton(
219
+ self,
220
+ lock_name: str | None = None,
221
+ *,
222
+ blocking: bool = False,
223
+ timeout: float | None = None,
224
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]:
225
+ """Decorator: run the wrapped function only if the lock is acquired.
226
+
227
+ Returns ``None`` (and logs at INFO level) instead of calling the function
228
+ when another instance already holds the lock and ``blocking=False``::
229
+
230
+ @mutex.singleton("nightly-report-job")
231
+ def run_the_job():
232
+ ...
233
+ """
234
+ target = self if lock_name is None else self._sibling(lock_name)
235
+
236
+ def decorator(func: Callable[P, R]) -> Callable[P, R | None]:
237
+ @functools.wraps(func)
238
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
239
+ with target.acquire(blocking=blocking, timeout=timeout) as acquired:
240
+ if not acquired:
241
+ logger.info(
242
+ "db_mutex: skipping %s — lock %r held elsewhere",
243
+ func.__name__,
244
+ target.lock_name,
245
+ )
246
+ return None
247
+ return func(*args, **kwargs)
248
+
249
+ return wrapper
250
+
251
+ return decorator
252
+
253
+ # -- async API -------------------------------------------------
254
+
255
+ @contextlib.asynccontextmanager
256
+ async def acquire_async(
257
+ self, blocking: bool = True, timeout: float | None = None
258
+ ) -> AsyncIterator[bool]:
259
+ """Async counterpart to ``acquire()``. Note the different default: ``blocking``
260
+ defaults to ``True`` here, matching the common async usage pattern of awaiting
261
+ a turn rather than polling manually.
262
+ """
263
+ core = self._async()
264
+ acquired = await core.acquire(blocking=blocking, timeout=timeout)
265
+ try:
266
+ yield acquired
267
+ finally:
268
+ if acquired:
269
+ await core.release()
270
+
271
+ async def release_async(self) -> None:
272
+ await self._async().release()
273
+
274
+ async def heartbeat_async(self) -> None:
275
+ await self._async().heartbeat()
276
+
277
+ def singleton_async(
278
+ self,
279
+ lock_name: str | None = None,
280
+ *,
281
+ blocking: bool = True,
282
+ timeout: float | None = None,
283
+ ) -> Callable[[Callable[P, Awaitable[R]]], Callable[P, Awaitable[R | None]]]:
284
+ """Async counterpart to ``singleton()``."""
285
+ target = self if lock_name is None else self._sibling(lock_name)
286
+
287
+ def decorator(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R | None]]:
288
+ @functools.wraps(func)
289
+ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
290
+ async with target.acquire_async(blocking=blocking, timeout=timeout) as acquired:
291
+ if not acquired:
292
+ logger.info(
293
+ "db_mutex: skipping %s — lock %r held elsewhere",
294
+ func.__name__,
295
+ target.lock_name,
296
+ )
297
+ return None
298
+ return await func(*args, **kwargs)
299
+
300
+ return wrapper
301
+
302
+ return decorator
303
+
304
+ # -- lifecycle -------------------------------------------------
305
+
306
+ def close(self) -> None:
307
+ """Close the underlying sync connection. Does not release the lock — call
308
+ ``release()`` first if you want a clean shutdown.
309
+ """
310
+ if self._sync_core is not None:
311
+ self._sync_core.close()
312
+
313
+ async def close_async(self) -> None:
314
+ if self._async_core is not None:
315
+ await self._async_core.close()
316
+
317
+ # -- internals -------------------------------------------------
318
+
319
+ def _sibling(self, lock_name: str) -> Mutex:
320
+ """A new Mutex for a different lock_name, same connection source/config/metrics."""
321
+ overrides = dataclasses.replace(
322
+ self.config, lock_name=lock_name, instance_id=self.config.instance_id
323
+ )
324
+ sibling = Mutex.__new__(Mutex)
325
+ sibling.dsn = self.dsn
326
+ sibling.pool = self.pool
327
+ sibling.async_pool = self.async_pool
328
+ sibling.backend = self.backend
329
+ sibling.config = overrides
330
+ sibling.metrics = self.metrics
331
+ sibling._sync_core = None
332
+ sibling._async_core = None
333
+ return sibling
db_mutex/py.typed ADDED
File without changes