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,287 @@
1
+ Metadata-Version: 2.5
2
+ Name: db-mutex
3
+ Version: 0.3.0
4
+ Summary: A distributed mutex for Postgres or MySQL. One table, heartbeat-based liveness, automatic crash recovery. No ZooKeeper, no Redis.
5
+ Project-URL: Homepage, https://github.com/rishi-rana/db-mutex
6
+ Project-URL: Repository, https://github.com/rishi-rana/db-mutex
7
+ Project-URL: Issues, https://github.com/rishi-rana/db-mutex/issues
8
+ Author: Rishi Rana
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: distributed-lock,leader-election,mutex,mysql,postgres,postgresql,scheduling,singleton
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Topic :: System :: Distributed Computing
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: psycopg[binary]>=3.1
25
+ Provides-Extra: dev
26
+ Requires-Dist: asyncmy>=0.2; extra == 'dev'
27
+ Requires-Dist: mypy>=1.10; extra == 'dev'
28
+ Requires-Dist: psycopg-pool>=3.1; extra == 'dev'
29
+ Requires-Dist: pymysql>=1.1; extra == 'dev'
30
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
31
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
32
+ Requires-Dist: pytest>=8.0; extra == 'dev'
33
+ Requires-Dist: ruff>=0.6; extra == 'dev'
34
+ Requires-Dist: testcontainers[mysql,postgres]>=4.0; extra == 'dev'
35
+ Requires-Dist: types-pymysql>=1.1; extra == 'dev'
36
+ Provides-Extra: mysql
37
+ Requires-Dist: pymysql>=1.1; extra == 'mysql'
38
+ Provides-Extra: mysql-async
39
+ Requires-Dist: asyncmy>=0.2; extra == 'mysql-async'
40
+ Provides-Extra: pool
41
+ Requires-Dist: psycopg-pool>=3.1; extra == 'pool'
42
+ Description-Content-Type: text/markdown
43
+
44
+ # db-mutex
45
+
46
+ [![PyPI](https://img.shields.io/pypi/v/db-mutex.svg)](https://pypi.org/project/db-mutex/)
47
+ [![Python versions](https://img.shields.io/pypi/pyversions/db-mutex.svg)](https://pypi.org/project/db-mutex/)
48
+ [![CI](https://github.com/rishi-rana/db-mutex/actions/workflows/ci.yml/badge.svg)](https://github.com/rishi-rana/db-mutex/actions/workflows/ci.yml)
49
+ [![License: MIT](https://img.shields.io/pypi/l/db-mutex.svg)](LICENSE)
50
+
51
+ A distributed mutex for Postgres or MySQL. One table, heartbeat-based liveness,
52
+ automatic recovery from crashed lock holders. No ZooKeeper, no Redis, no Consul, no
53
+ etcd.
54
+
55
+ If you already have Postgres or MySQL, you shouldn't need any of those just to run a
56
+ job on exactly one instance at a time.
57
+
58
+ ## Quickstart
59
+
60
+ ```bash
61
+ pip install db-mutex
62
+ ```
63
+
64
+ ```python
65
+ from db_mutex import Mutex
66
+
67
+ mutex = Mutex(dsn="postgres://user:pass@host/db", lock_name="nightly-report-job")
68
+ mutex.create_schema() # creates the mutex_lock table if it doesn't exist; idempotent
69
+
70
+ with mutex.acquire(blocking=False) as acquired:
71
+ if acquired:
72
+ run_the_job()
73
+ else:
74
+ print("another instance is running the job")
75
+ ```
76
+
77
+ Async works the same way:
78
+
79
+ ```python
80
+ async with mutex.acquire_async(blocking=True, timeout=30):
81
+ await run_the_job_async()
82
+ ```
83
+
84
+ Or skip the `if acquired` branch entirely with the decorator:
85
+
86
+ ```python
87
+ @mutex.singleton("nightly-report-job")
88
+ def run_the_job(): ...
89
+ ```
90
+
91
+ ### Supplying connection info
92
+
93
+ Two ways to give `Mutex` a way to reach Postgres — pick one:
94
+
95
+ **`dsn`** (the common case) — any libpq connection string, passed straight to
96
+ psycopg untouched. `Mutex` opens and owns one dedicated connection for it.
97
+
98
+ ```python
99
+ Mutex(dsn="postgres://user:pass@host:5432/dbname?sslmode=require", lock_name="job")
100
+ ```
101
+
102
+ Because it's handed to psycopg unmodified, all the usual libpq conventions work:
103
+ keyword form (`"host=localhost dbname=mydb user=me password=secret"`), partial DSNs
104
+ filled in from `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` /
105
+ `PGSSLMODE`, and `.pgpass` for passwords you don't want in the DSN at all. Where that
106
+ string comes from — an env var, a secrets manager, a config file — is up to you;
107
+ db-mutex just needs a valid one.
108
+
109
+ **`pool` / `async_pool`** — if your app already manages a `psycopg_pool`
110
+ `ConnectionPool` / `AsyncConnectionPool` (e.g. sitting in front of pgbouncer),
111
+ hand it to `Mutex` instead of a `dsn` so it doesn't open an extra always-on
112
+ connection of its own. `Mutex` borrows a connection for the duration of each
113
+ operation (acquire, heartbeat, release) and gives it back — it never owns, opens, or
114
+ closes the pool.
115
+
116
+ ```python
117
+ from psycopg_pool import ConnectionPool
118
+
119
+ pool = ConnectionPool("postgres://...") # owned and closed by your app
120
+ mutex = Mutex(lock_name="nightly-report-job", pool=pool)
121
+ ```
122
+
123
+ Pass `async_pool` instead (or as well, if the same lock is driven from both sync and
124
+ async code) for `acquire_async` / `heartbeat_async` / `release_async`. Requires the
125
+ `psycopg-pool` package (`pip install db-mutex[pool]`).
126
+
127
+ ### MySQL
128
+
129
+ Pass a `mysql://` DSN (or `backend="mysql"` explicitly) — everything else about the
130
+ API is identical:
131
+
132
+ ```bash
133
+ pip install db-mutex[mysql] # sync; add [mysql-async] for acquire_async
134
+ ```
135
+
136
+ ```python
137
+ mutex = Mutex(dsn="mysql://user:pass@host:3306/dbname", lock_name="nightly-report-job")
138
+ ```
139
+
140
+ Requires MySQL >= 8.0.16 (needed for `CHECK` constraints to actually be enforced).
141
+ Pool mode (`pool=`/`async_pool=`) isn't wired up for MySQL yet — only `dsn`.
142
+
143
+ ## How it works
144
+
145
+ One table:
146
+
147
+ ```sql
148
+ CREATE TABLE mutex_lock (
149
+ lock_name VARCHAR(64) NOT NULL,
150
+ locked INT NOT NULL DEFAULT 1,
151
+ instance_id VARCHAR(64) NOT NULL,
152
+ last_heartbeat TIMESTAMPTZ NOT NULL,
153
+ acquired_at TIMESTAMPTZ NOT NULL,
154
+ CONSTRAINT uq_mutex_lock UNIQUE (locked, lock_name),
155
+ CONSTRAINT chk_locked CHECK (locked = 1)
156
+ );
157
+ ```
158
+
159
+ `UNIQUE(locked, lock_name)` combined with `CHECK (locked = 1)` means only one row can
160
+ ever exist per `lock_name`. Acquiring is just "try to insert a row" — whoever's
161
+ `INSERT` lands first wins, enforced by the database itself. No CAS loop, no advisory
162
+ locks, no race conditions to reason about.
163
+
164
+ The lock holder heartbeats every 10 seconds (`UPDATE ... SET last_heartbeat = now()`).
165
+ Every field used for staleness detection — `now()`, the interval comparisons — is
166
+ computed **inside a single Postgres statement**, so results depend only on the
167
+ Postgres server's clock, never on any client's wall clock. Skewed or jumping client
168
+ clocks can't corrupt lock state.
169
+
170
+ ### Dual-threshold stale handling
171
+
172
+ Most distributed-lock tutorials use one timeout. That's the wrong call:
173
+
174
+ - **30 seconds without a heartbeat** → an alert fires (via your metrics hook /
175
+ `on_alert` callback) so on-call can look — is the holder just slow, or actually dead?
176
+ - **10 minutes without a heartbeat** → the lock auto-releases; safe to assume the
177
+ holder crashed.
178
+
179
+ If you release at 30 seconds, a holder that's merely slow (GC pause, a long query, a
180
+ noisy neighbor) loses the lock to another instance that's likely to hit the exact same
181
+ slowness — you can end up in a churn loop where nobody makes progress. The alert
182
+ window buys a human time to intervene before the system self-heals on its own.
183
+
184
+ ### Clean shutdown
185
+
186
+ On graceful shutdown, `release()` deletes the row outright, so the next instance can
187
+ acquire immediately instead of waiting out the stale threshold.
188
+
189
+ ## API
190
+
191
+ ```python
192
+ Mutex(
193
+ dsn: str | None = None, # or pass pool / async_pool instead
194
+ lock_name: str,
195
+ *,
196
+ pool: psycopg_pool.ConnectionPool | None = None,
197
+ async_pool: psycopg_pool.AsyncConnectionPool | None = None,
198
+ instance_id: str | None = None, # default: "<hostname>-<random>"
199
+ table: str = "mutex_lock",
200
+ heartbeat_interval: float = 10.0,
201
+ alert_threshold: float = 30.0,
202
+ stale_threshold: float = 600.0,
203
+ poll_interval: float = 0.5, # blocking-acquire retry interval
204
+ metrics: MetricsHook | None = None,
205
+ )
206
+ ```
207
+
208
+ - `mutex.acquire(blocking=False, timeout=None)` — sync context manager, yields `bool`
209
+ - `mutex.acquire_async(blocking=True, timeout=None)` — async context manager
210
+ - `mutex.release()` / `mutex.release_async()`
211
+ - `mutex.heartbeat()` / `mutex.heartbeat_async()` — manual heartbeat (usually automatic)
212
+ - `mutex.singleton(lock_name=None, *, blocking=False, timeout=None)` — decorator
213
+ - `mutex.singleton_async(...)` — async decorator
214
+ - `mutex.create_schema()` / `mutex.create_schema_async()` — idempotent `CREATE TABLE IF NOT EXISTS`
215
+
216
+ ### Metrics
217
+
218
+ Implement whichever subset of `MetricsHook` you care about (Prometheus, OpenTelemetry,
219
+ statsd, or your own):
220
+
221
+ ```python
222
+ class PrometheusMetrics:
223
+ def acquired(self, lock_name, *, instance_id): ...
224
+ def released(self, lock_name, *, instance_id): ...
225
+ def contended(self, lock_name, *, instance_id): ...
226
+ def stale_reclaimed(self, lock_name, *, instance_id, previous_holder): ...
227
+ def alert(self, lock_name, *, holder, seconds_since_heartbeat): ...
228
+ def heartbeat_latency(self, lock_name, *, instance_id, seconds): ...
229
+
230
+
231
+ mutex = Mutex(dsn, "nightly-report-job", metrics=PrometheusMetrics())
232
+ ```
233
+
234
+ A broken metrics implementation can never break the lock — every call is wrapped in a
235
+ best-effort try/except.
236
+
237
+ ## Why not X?
238
+
239
+ | | Extra infra? | Survives a crash cleanly? | Blocks other queries? | Notes |
240
+ |---|---|---|---|---|
241
+ | **db-mutex** | No — uses Postgres you already have | Yes — heartbeat + dual-threshold auto-release | No | Single table, ~one round trip per acquire |
242
+ | **Redis Redlock** | Yes — Redis (ideally 5 independent nodes) | Depends on TTL tuning | No | Correctness has been [actively debated](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html) for multi-node deployments |
243
+ | **ShedLock** | No extra infra, but adds a dependency + its own table conventions | Yes, similar TTL model | No | Good option if you're already on it; db-mutex is a smaller, dependency-light alternative |
244
+ | **`SELECT ... FOR UPDATE`** | No | No — a crashed holder's transaction rollback releases it, but a hung connection holds the lock indefinitely and blocks readers | Yes — blocks queries waiting on the row/table | Simplest option for short critical sections inside one transaction; not a good fit for "hold across a long job" |
245
+ | **ZooKeeper / Consul / etcd** | Yes — a whole coordination service to run and operate | Yes — ephemeral nodes / sessions | No | Correct and battle-tested, but a lot of infrastructure for "run this job on one instance" |
246
+
247
+ ## Failure modes, explicitly
248
+
249
+ - **Holder crashes**: heartbeat stops. Alert fires at `alert_threshold` (default 30s).
250
+ Lock is reclaimable by any other instance at `stale_threshold` (default 600s).
251
+ - **Holder is just slow** (GC pause, long query): same alert fires at 30s — that's the
252
+ point, so a human can tell "slow" from "dead" before the system takes action.
253
+ - **Network partition** (holder alive, can't reach Postgres): heartbeats fail
254
+ silently and retry; from every other instance's point of view this is
255
+ indistinguishable from a crash, so the same dual-threshold logic applies. If the
256
+ partition heals before `stale_threshold`, the original holder keeps the lock. If not,
257
+ another instance reclaims it, and the original holder's next heartbeat raises
258
+ `LockNotHeldError` — write your job logic to check for that on long-running work if
259
+ split-brain during the alert window is unacceptable for your use case.
260
+ - **Clock skew between instances**: irrelevant. Every staleness check runs `now() -
261
+ last_heartbeat` inside one Postgres statement — only the Postgres server's clock is
262
+ ever consulted.
263
+ - **`instance_id` reused across two live processes**: don't do this — release/heartbeat
264
+ scoping is by `(lock_name, instance_id)`, so two processes sharing an `instance_id`
265
+ can each mutate the other's lock state. The default (`hostname-<random>`) avoids
266
+ this; set your own only if it's genuinely unique per process.
267
+
268
+ ## What's not in v1
269
+
270
+ - No fencing tokens
271
+ - No read/write locks — single mutex only
272
+ - No lock hierarchies
273
+ - No cross-database coordination
274
+ - No SQLite
275
+
276
+ ## Development
277
+
278
+ ```bash
279
+ pip install -e ".[dev]"
280
+ pytest # spins up real Postgres + MySQL via testcontainers — needs Docker
281
+ ruff check .
282
+ mypy
283
+ ```
284
+
285
+ ## License
286
+
287
+ MIT
@@ -0,0 +1,21 @@
1
+ db_mutex/__init__.py,sha256=zAya1H-z347mG2TMKUaDbk03BYivlY1Ha7lXhGrQXMI,660
2
+ db_mutex/_config.py,sha256=J1tEq-01tEcbZAEJHr3z4I8vb8mVHxdDmYev5R_87aQ,2082
3
+ db_mutex/exceptions.py,sha256=ipxWKY67NzptO5drahg2LTakdf3Upi7yE3JSvj-fW9E,1110
4
+ db_mutex/metrics.py,sha256=-_Vc5PtOvzeIl5eTCeQaXfbbB4gyWdXsVdejBqPCAaQ,3087
5
+ db_mutex/mutex.py,sha256=fzz8JwLJpLV2Gy7Ra5jRzZ5qEcp-n5z0i86jvgL9Rl8,13758
6
+ db_mutex/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ db_mutex/backends/__init__.py,sha256=LLUHF0oD66uak1qvEXH7mffAoYubbG_3lEq3pnOoJZM,1549
8
+ db_mutex/backends/_core.py,sha256=Yyrdp24dw5UNZx_5CQoiQM4GZjDWLHBqMKRAqEJY-N8,14090
9
+ db_mutex/backends/mysql/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ db_mutex/backends/mysql/_dsn.py,sha256=mLK1063gALcxVuV0nxypHCUDUeJ1EWVHmNKhPaF8nSo,972
11
+ db_mutex/backends/mysql/_sql.py,sha256=R63zhJQAdR6EgMQv0pEamf3W_RFNd5HV3sJovkIqVas,2893
12
+ db_mutex/backends/mysql/async_.py,sha256=PnqYAILVZnuZpn2nHDFe_QRye6iSJ23KRmVz7iuwQ1c,6022
13
+ db_mutex/backends/mysql/sync.py,sha256=ss9wB28E2CpwEB3vebnPIN-Ni-Ajd5b6wMXEIn6M8KE,6437
14
+ db_mutex/backends/postgres/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ db_mutex/backends/postgres/_sql.py,sha256=wOI_Fj4Jp_VA7CwronMM0EITd4NhWMPW5JcoDZR-6AM,2574
16
+ db_mutex/backends/postgres/async_.py,sha256=yNYFlCHS5EAZbCiCVJWVG88JrLo6MZyLHLwEJMoUnHw,5830
17
+ db_mutex/backends/postgres/sync.py,sha256=aRzlFKsng81qF8nQet4eJ1NU3Z7aQIy_8lMVy_FCEpQ,6093
18
+ db_mutex-0.3.0.dist-info/METADATA,sha256=pXYQzOrh4O-N4K5LockwvIKBjjkEf04m7LOT9xCkQNA,12191
19
+ db_mutex-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
20
+ db_mutex-0.3.0.dist-info/licenses/LICENSE,sha256=PqvBoZmFz07eUUbwFsE4I1CFLngmhk2tEzYvaO-eXss,1067
21
+ db_mutex-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rishi Rana
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.