asyncpg-lock 0.0.1__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.
@@ -0,0 +1,38 @@
1
+ import collections
2
+ import re
3
+ import sys
4
+
5
+ from .guard import AdvisoryLockGuard, ConnectFunc, connect_func # noqa
6
+
7
+ __all__: tuple[str, ...] = (
8
+ # guard.py
9
+ "ConnectFunc",
10
+ "AdvisoryLockGuard",
11
+ "connect_func",
12
+ )
13
+
14
+ __version__ = "0.0.1"
15
+
16
+ version = f"{__version__}, Python {sys.version}"
17
+
18
+ VersionInfo = collections.namedtuple("VersionInfo", "major minor micro release_level serial")
19
+
20
+
21
+ def _parse_version(v: str) -> VersionInfo:
22
+ version_re = r"^(?P<major>\d+)\.(?P<minor>\d+)\.(?P<micro>\d+)" r"((?P<release_level>[a-z]+)(?P<serial>\d+)?)?$"
23
+ match = re.match(version_re, v)
24
+ if not match:
25
+ raise ImportError(f"Invalid package version {v}")
26
+ try:
27
+ major = int(match.group("major"))
28
+ minor = int(match.group("minor"))
29
+ micro = int(match.group("micro"))
30
+ levels = {"rc": "candidate", "a": "alpha", "b": "beta", None: "final"}
31
+ release_level = levels[match.group("release_level")]
32
+ serial = int(match.group("serial")) if match.group("serial") else 0
33
+ return VersionInfo(major, minor, micro, release_level, serial)
34
+ except Exception as e:
35
+ raise ImportError(f"Invalid package version {v}") from e
36
+
37
+
38
+ version_info = _parse_version(__version__)
asyncpg_lock/guard.py ADDED
@@ -0,0 +1,138 @@
1
+ import asyncio
2
+ import logging
3
+ import time
4
+ from typing import Any, Callable, Coroutine
5
+
6
+ import asyncpg
7
+
8
+ logger = logging.getLogger(__package__)
9
+
10
+ ConnectFunc = Callable[[], Coroutine[Any, Any, asyncpg.Connection]]
11
+
12
+
13
+ def connect_func(*args: Any, **kwargs: Any) -> ConnectFunc:
14
+ async def _connect() -> asyncpg.Connection:
15
+ return await asyncpg.connect(*args, **kwargs)
16
+
17
+ return _connect
18
+
19
+
20
+ class AdvisoryLockGuard:
21
+ __slots__ = (
22
+ "__connect",
23
+ "__reconnect_delay",
24
+ "__after_acquire_delay",
25
+ "__reacquire_delay",
26
+ )
27
+
28
+ def __init__(
29
+ self,
30
+ *,
31
+ connect: ConnectFunc = asyncpg.connect,
32
+ reconnect_delay: float = 5,
33
+ reacquire_delay: float = 5,
34
+ after_acquire_delay: float = 5,
35
+ ) -> None:
36
+ if reconnect_delay < 0:
37
+ raise ValueError("reconnect_delay must be non-negative")
38
+ if reacquire_delay <= 0:
39
+ raise ValueError("reacquire_delay must be positive")
40
+ if after_acquire_delay <= 0:
41
+ raise ValueError("after_acquire_delay must be positive")
42
+
43
+ self.__reconnect_delay = reconnect_delay
44
+ self.__after_acquire_delay = after_acquire_delay
45
+ self.__reacquire_delay = reacquire_delay
46
+ self.__connect = connect
47
+
48
+ async def run(
49
+ self,
50
+ key: int | tuple[int, int],
51
+ func: Callable[[], Coroutine],
52
+ ) -> None:
53
+ if isinstance(key, int):
54
+ if not (-(2**63) <= key < 2**63):
55
+ raise ValueError("key must be a signed 64-bit integer")
56
+ else:
57
+ if not (-(2**31) <= key[0] < 2**31) or not (-(2**31) <= key[1] < 2**31):
58
+ raise ValueError("key must be a tuple of two signed 32-bit integers")
59
+
60
+ await self.__ensure_connection_established(
61
+ lambda connection: self.__ensure_lock_acquired(connection, key, func)
62
+ )
63
+
64
+ async def __ensure_connection_established(self, func: Callable[[asyncpg.Connection], Coroutine]) -> None:
65
+ failed_attempts = 0
66
+ while True:
67
+ try:
68
+ connection = await self.__connect()
69
+ failed_attempts = 0
70
+ try:
71
+ await func(connection)
72
+ finally:
73
+ await asyncio.shield(connection.close())
74
+ except Exception:
75
+ if failed_attempts > 0:
76
+ logger.exception("Connection closed or not established")
77
+ failed_attempts += 1
78
+
79
+ await asyncio.sleep(self.__reconnect_delay)
80
+
81
+ async def __ensure_lock_acquired(
82
+ self,
83
+ connection: asyncpg.Connection,
84
+ key: int | tuple[int, int],
85
+ func: Callable[[], Coroutine],
86
+ ) -> None:
87
+ logger.info("Acquiring lock %s", key)
88
+ await self.__acquire_lock(connection, key)
89
+ logger.info("Lock %s acquired, waiting for %s s", key, self.__after_acquire_delay)
90
+ await asyncio.sleep(self.__after_acquire_delay)
91
+ logger.info("Lock %s acquired, running", key)
92
+ try:
93
+ async with asyncio.TaskGroup() as tg:
94
+ tg.create_task(self.__ensure_connection_alive(connection, key))
95
+ tg.create_task(self.__run_forever(func))
96
+ finally:
97
+ logger.info("Lock %s might be lost", key)
98
+
99
+ async def __acquire_lock(self, connection: asyncpg.Connection, key: int | tuple[int, int]) -> None:
100
+ while True:
101
+ try:
102
+ if isinstance(key, int):
103
+ acquired = await connection.fetchval("SELECT pg_try_advisory_lock($1)", key)
104
+ else:
105
+ acquired = await connection.fetchval("SELECT pg_try_advisory_lock($1, $2)", key[0], key[1])
106
+ except Exception:
107
+ raise Exception(f"Lock {key} not acquired")
108
+ if acquired:
109
+ return
110
+ await asyncio.sleep(self.__reacquire_delay)
111
+
112
+ async def __ensure_connection_alive(self, connection: asyncpg.Connection, key: int | tuple[int, int]) -> None:
113
+ per_attempt_keep_alive_budget = self.__after_acquire_delay / 3
114
+ while True:
115
+ started_at = time.monotonic()
116
+ if connection.is_closed():
117
+ raise Exception(f"Lock {key} might be lost: connection is closed")
118
+ try:
119
+ await connection.execute("SELECT 1", timeout=per_attempt_keep_alive_budget)
120
+ except asyncio.TimeoutError:
121
+ raise Exception(f"Lock {key} might be lost: keep-alive query timed out")
122
+ except Exception:
123
+ raise Exception(f"Lock {key} might be lost: keep-alive query failed")
124
+
125
+ finished_at = time.monotonic()
126
+ elapsed = finished_at - started_at
127
+ if elapsed > per_attempt_keep_alive_budget * 2:
128
+ raise Exception(f"Lock {key} might be lost: keep-alive query took too long")
129
+ if elapsed < per_attempt_keep_alive_budget:
130
+ await asyncio.sleep(per_attempt_keep_alive_budget - elapsed)
131
+
132
+ @staticmethod
133
+ async def __run_forever(func: Callable[[], Coroutine]) -> None:
134
+ while True:
135
+ try:
136
+ await func()
137
+ except Exception:
138
+ logger.exception("Unexpected exception")
asyncpg_lock/py.typed ADDED
@@ -0,0 +1 @@
1
+ Marker
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Iurii Pliner
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.
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.1
2
+ Name: asyncpg-lock
3
+ Version: 0.0.1
4
+ Summary: Run long-running work exclusively using PostgreSQL advisory locks
5
+ Home-page: https://github.com/Pliner/asyncpg-lock
6
+ Author: Iurii Pliner
7
+ Author-email: yury.pliner@gmail.com
8
+ License: MIT
9
+ Platform: macOS
10
+ Platform: POSIX
11
+ Platform: Windows
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Environment :: Web Environment
21
+ Classifier: Development Status :: 5 - Production/Stable
22
+ Classifier: Framework :: AsyncIO
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: asyncpg>=0.30.0
28
+
29
+ # asyncpg-lock
30
+
31
+ Run long-running work exclusively using PostgreSQL advisory locks.
32
+
33
+ ## Usage
34
+
35
+ ```python
36
+ import asyncio
37
+ import asyncpg
38
+ import asyncpg_lock
39
+
40
+
41
+ async def worker_func() -> None:
42
+ # something very long-running
43
+ while True:
44
+ await asyncio.sleep(100500)
45
+
46
+
47
+ async def main():
48
+ guard = asyncpg_lock.AdvisoryLockGuard(
49
+ connect=lambda: asyncpg.connect("postgresql://localhost/db")
50
+ )
51
+ # worker_func will not be executed concurrently
52
+ key = 100500
53
+ tasks = [
54
+ asyncio.create_task(guard.run(key, worker_func)),
55
+ asyncio.create_task(guard.run(key, worker_func)),
56
+ asyncio.create_task(guard.run(key, worker_func)),
57
+ asyncio.create_task(guard.run(key, worker_func))
58
+ ]
59
+ await asyncio.gather(*tasks)
60
+
61
+
62
+ asyncio.run(main())
63
+ ```
64
+
65
+ ## v0.0.1 (2025-07-07)
66
+
67
+ * Initial release
@@ -0,0 +1,8 @@
1
+ asyncpg_lock/__init__.py,sha256=Uk1WOOUvy2uoU3MRztuA86Nc8SmAGISm_rZo-JyEvOU,1225
2
+ asyncpg_lock/guard.py,sha256=WDsRzOdy3zQIH4_VOzigb1IBqbWJ6KEJf-V9LPe5Uo0,5236
3
+ asyncpg_lock/py.typed,sha256=E84IaZyFwfLqvXjOVW4LS6WH7QOaKEFpNh9TFyzHNQc,6
4
+ asyncpg_lock-0.0.1.dist-info/LICENSE,sha256=6EE2Lo1blA7_eNykqnMxzJjOOzuo_nJxFIdBolhFOwk,1069
5
+ asyncpg_lock-0.0.1.dist-info/METADATA,sha256=d8Jq-zL9uxHH-LvR0Hv1zFYaoSZg_wbjsj-gcw44_Ws,1814
6
+ asyncpg_lock-0.0.1.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
7
+ asyncpg_lock-0.0.1.dist-info/top_level.txt,sha256=rYtYbHwstzUbQw0LMH7TEgJNV52XfUFFIIrVwiY5MNo,13
8
+ asyncpg_lock-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.45.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ asyncpg_lock