py-cachify 3.0.1__tar.gz → 3.1.0__tar.gz

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.
Files changed (24) hide show
  1. {py_cachify-3.0.1 → py_cachify-3.1.0}/.gitignore +1 -1
  2. {py_cachify-3.0.1 → py_cachify-3.1.0}/PKG-INFO +1 -4
  3. {py_cachify-3.0.1 → py_cachify-3.1.0}/README.md +0 -3
  4. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/__init__.py +6 -0
  5. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_clients.py +11 -9
  6. py_cachify-3.1.0/py_cachify/_backend/_constants.py +4 -0
  7. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_exceptions.py +4 -0
  8. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_helpers.py +6 -2
  9. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_lib.py +113 -6
  10. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_lock.py +6 -2
  11. py_cachify-3.1.0/py_cachify/_backend/_pool.py +440 -0
  12. py_cachify-3.1.0/py_cachify/_backend/_pool_state.py +22 -0
  13. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_types/_common.py +2 -0
  14. py_cachify-3.1.0/py_cachify/_backend/_types/_pool_wrap.py +49 -0
  15. {py_cachify-3.0.1 → py_cachify-3.1.0}/pyproject.toml +7 -17
  16. py_cachify-3.0.1/py_cachify/_backend/_constants.py +0 -4
  17. {py_cachify-3.0.1 → py_cachify-3.1.0}/LICENSE +0 -0
  18. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/__init__.py +0 -0
  19. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_cached.py +0 -0
  20. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_logger.py +0 -0
  21. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_types/__init__.py +0 -0
  22. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_types/_lock_wrap.py +0 -0
  23. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/_backend/_types/_reset_wrap.py +0 -0
  24. {py_cachify-3.0.1 → py_cachify-3.1.0}/py_cachify/py.typed +0 -0
@@ -311,7 +311,7 @@ celerybeat-schedule.*
311
311
 
312
312
  env.bak/
313
313
  venv.bak/
314
-
314
+ scratch
315
315
  *.sublime-project
316
316
 
317
317
  # Package control specific files Package
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: py-cachify
3
- Version: 3.0.1
3
+ Version: 3.1.0
4
4
  Summary: Distributed locks, caching, and locking at hand
5
5
  Project-URL: Homepage, https://github.com/EzyGang/py-cachify
6
6
  Project-URL: Repository, https://github.com/EzyGang/py-cachify
@@ -54,9 +54,6 @@ Description-Content-Type: text/markdown
54
54
  <a href="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" target="_blank">
55
55
  <img src="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" alt="Pre-build checks and Tests">
56
56
  </a>
57
- <a href="https://github.com/EzyGang/py-cachify/actions/workflows/integration-tests.yml/badge.svg" target="_blank">
58
- <img src="https://github.com/EzyGang/py-cachify/actions/workflows/integration-tests.yml/badge.svg" alt="Tests Status">
59
- </a>
60
57
  <a href="https://py-cachify.readthedocs.io/en/latest/?badge=latest" target="_blank">
61
58
  <img src="https://readthedocs.org/projects/py-cachify/badge/?version=latest" alt="Documentation Status">
62
59
  </a>
@@ -22,9 +22,6 @@
22
22
  <a href="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" target="_blank">
23
23
  <img src="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" alt="Pre-build checks and Tests">
24
24
  </a>
25
- <a href="https://github.com/EzyGang/py-cachify/actions/workflows/integration-tests.yml/badge.svg" target="_blank">
26
- <img src="https://github.com/EzyGang/py-cachify/actions/workflows/integration-tests.yml/badge.svg" alt="Tests Status">
27
- </a>
28
25
  <a href="https://py-cachify.readthedocs.io/en/latest/?badge=latest" target="_blank">
29
26
  <img src="https://readthedocs.org/projects/py-cachify/badge/?version=latest" alt="Documentation Status">
30
27
  </a>
@@ -1,10 +1,13 @@
1
1
  from ._backend._cached import cached as cached
2
2
  from ._backend._exceptions import CachifyInitError as CachifyInitError
3
3
  from ._backend._exceptions import CachifyLockError as CachifyLockError
4
+ from ._backend._exceptions import CachifyPoolFullError as CachifyPoolFullError
4
5
  from ._backend._lib import Cachify as Cachify
5
6
  from ._backend._lib import init_cachify as init_cachify
6
7
  from ._backend._lock import lock as lock
7
8
  from ._backend._lock import once as once
9
+ from ._backend._pool import pool as pool
10
+ from ._backend._pool import pooled as pooled
8
11
  from ._backend._types._common import AsyncClient as AsyncClient
9
12
  from ._backend._types._common import Decoder as Decoder
10
13
  from ._backend._types._common import Encoder as Encoder
@@ -12,6 +15,9 @@ from ._backend._types._common import SyncClient as SyncClient
12
15
  from ._backend._types._lock_wrap import AsyncLockWrappedF as AsyncLockWrappedF
13
16
  from ._backend._types._lock_wrap import SyncLockWrappedF as SyncLockWrappedF
14
17
  from ._backend._types._lock_wrap import WrappedFunctionLock as WrappedFunctionLock
18
+ from ._backend._types._pool_wrap import AsyncPoolWrappedF as AsyncPoolWrappedF
19
+ from ._backend._types._pool_wrap import SyncPoolWrappedF as SyncPoolWrappedF
20
+ from ._backend._types._pool_wrap import WrappedFunctionPool as WrappedFunctionPool
15
21
 
16
22
 
17
23
  try:
@@ -1,3 +1,4 @@
1
+ import asyncio
1
2
  import threading
2
3
  import time
3
4
  from typing import Any, Optional, Union
@@ -42,21 +43,22 @@ class MemoryCache:
42
43
 
43
44
  def delete(self, *names: str) -> None:
44
45
  for key in names:
45
- if key not in self._cache:
46
- continue
47
-
48
- del self._cache[key]
46
+ self._cache.pop(key, None)
49
47
 
50
48
 
51
49
  class AsyncWrapper:
52
50
  def __init__(self, cache: MemoryCache) -> None:
53
51
  self._cache = cache
52
+ self._lock = asyncio.Lock()
54
53
 
55
54
  async def get(self, name: str) -> Optional[Any]:
56
- return self._cache.get(name=name)
55
+ async with self._lock:
56
+ return self._cache.get(name)
57
57
 
58
- async def delete(self, *names: str) -> Any:
59
- self._cache.delete(*names)
58
+ async def delete(self, *names: str) -> None:
59
+ async with self._lock:
60
+ self._cache.delete(*names)
60
61
 
61
- async def set(self, name: str, value: Any, ex: Union[int, None] = None, nx: bool = False) -> Optional[Any]:
62
- return self._cache.set(name=name, value=value, ex=ex, nx=nx)
62
+ async def set(self, name: str, value: Any, ex: Union[int, None] = None, nx: bool = False) -> Optional[bool]:
63
+ async with self._lock:
64
+ return self._cache.set(name, value, ex, nx)
@@ -0,0 +1,4 @@
1
+ from typing import Literal
2
+
3
+
4
+ OperationPostfix = Literal['once', 'cached', 'lock', 'pool']
@@ -4,3 +4,7 @@ class CachifyInitError(Exception):
4
4
 
5
5
  class CachifyLockError(Exception):
6
6
  pass
7
+
8
+
9
+ class CachifyPoolFullError(Exception):
10
+ pass
@@ -1,4 +1,4 @@
1
- import asyncio
1
+ import functools
2
2
  import inspect
3
3
  from collections.abc import Awaitable
4
4
  from typing import Any, Callable, TypeVar, Union
@@ -74,7 +74,11 @@ def get_full_key_from_signature(
74
74
  def is_coroutine(
75
75
  func: Union[Callable[_P, Awaitable[_R]], Callable[_P, _R]],
76
76
  ) -> TypeIs[Callable[_P, Awaitable[_R]]]:
77
- return asyncio.iscoroutinefunction(func)
77
+
78
+ while isinstance(func, functools.partial):
79
+ func = func.func
80
+
81
+ return inspect.iscoroutinefunction(func) or (callable(func) and inspect.iscoroutinefunction(func.__call__)) # pyright: ignore[reportFunctionMemberAccess]
78
82
 
79
83
 
80
84
  def encode_decode_value(encoder_decoder: Union[Encoder, Decoder, None], val: Any) -> Any:
@@ -5,11 +5,13 @@ from ._clients import AsyncWrapper, MemoryCache
5
5
  from ._exceptions import CachifyInitError
6
6
  from ._types._common import UNSET, AsyncClient, Decoder, Encoder, SyncClient, UnsetType
7
7
  from ._types._lock_wrap import WrappedFunctionLock
8
+ from ._types._pool_wrap import WrappedFunctionPool
8
9
  from ._types._reset_wrap import WrappedFunctionReset
9
10
 
10
11
 
11
12
  if TYPE_CHECKING:
12
13
  from ._lock import lock as _lock_cls
14
+ from ._pool import pool as _pool_cls
13
15
 
14
16
 
15
17
  class CachifyClient:
@@ -20,18 +22,22 @@ class CachifyClient:
20
22
  default_expiration: Optional[int],
21
23
  prefix: str,
22
24
  default_cache_ttl: Optional[int] = None,
25
+ lock_poll_interval: float = 0.1,
26
+ default_pool_slot_expiration: Optional[int] = 600,
23
27
  ) -> None:
24
28
  self._sync_client = sync_client
25
29
  self._async_client = async_client
26
30
  self._prefix = prefix
27
31
  self.default_expiration = default_expiration
28
32
  self.default_cache_ttl = default_cache_ttl
33
+ self.lock_poll_interval = lock_poll_interval
34
+ self.default_pool_slot_expiration = default_pool_slot_expiration
29
35
 
30
36
  def set(self, key: str, val: Any, ttl: Union[int, None] = None) -> Any:
31
- _ = self._sync_client.set(name=f'{self._prefix}{key}', value=pickle.dumps(val), ex=ttl, nx=False)
37
+ _ = self._sync_client.set(f'{self._prefix}{key}', pickle.dumps(val), ex=ttl, nx=False)
32
38
 
33
39
  def get(self, key: str) -> Any:
34
- return (val := self._sync_client.get(name=f'{self._prefix}{key}')) and pickle.loads(val)
40
+ return (val := self._sync_client.get(f'{self._prefix}{key}')) and pickle.loads(val)
35
41
 
36
42
  def delete(self, key: str) -> Any:
37
43
  return self._sync_client.delete(f'{self._prefix}{key}')
@@ -42,14 +48,14 @@ class CachifyClient:
42
48
  """
43
49
  name = f'{self._prefix}{key}'
44
50
  payload = pickle.dumps(1)
45
- res = self._sync_client.set(name=name, value=payload, ex=ttl, nx=True)
51
+ res = self._sync_client.set(name, payload, ex=ttl, nx=True)
46
52
  return bool(res)
47
53
 
48
54
  async def a_get(self, key: str) -> Any:
49
- return (val := await self._async_client.get(name=f'{self._prefix}{key}')) and pickle.loads(val)
55
+ return (val := await self._async_client.get(f'{self._prefix}{key}')) and pickle.loads(val)
50
56
 
51
57
  async def a_set(self, key: str, val: Any, ttl: Union[int, None] = None) -> Any:
52
- await self._async_client.set(name=f'{self._prefix}{key}', value=pickle.dumps(val), ex=ttl, nx=False)
58
+ await self._async_client.set(f'{self._prefix}{key}', pickle.dumps(val), ex=ttl, nx=False)
53
59
 
54
60
  async def a_delete(self, key: str) -> Any:
55
61
  return await self._async_client.delete(f'{self._prefix}{key}')
@@ -60,7 +66,7 @@ class CachifyClient:
60
66
  """
61
67
  name = f'{self._prefix}{key}'
62
68
  payload = pickle.dumps(1)
63
- res = await self._async_client.set(name=name, value=payload, ex=ttl, nx=True)
69
+ res = await self._async_client.set(name, payload, ex=ttl, nx=True)
64
70
  return bool(res)
65
71
 
66
72
 
@@ -83,6 +89,8 @@ class Cachify:
83
89
  prefix: str,
84
90
  default_expiration: Optional[int],
85
91
  default_cache_ttl: Optional[int],
92
+ lock_poll_interval: float = 0.1,
93
+ default_pool_slot_expiration: Optional[int] = 600,
86
94
  ) -> None:
87
95
  self._client = CachifyClient(
88
96
  sync_client=sync_client,
@@ -90,6 +98,8 @@ class Cachify:
90
98
  default_expiration=default_expiration,
91
99
  default_cache_ttl=default_cache_ttl,
92
100
  prefix=prefix,
101
+ lock_poll_interval=lock_poll_interval,
102
+ default_pool_slot_expiration=default_pool_slot_expiration,
93
103
  )
94
104
 
95
105
  def cached(
@@ -185,6 +195,91 @@ class Cachify:
185
195
  client_provider=lambda: self._client,
186
196
  )
187
197
 
198
+ def pool(
199
+ self,
200
+ key: str,
201
+ max_size: int,
202
+ slot_exp: Union[Optional[int], UnsetType] = UNSET,
203
+ ) -> '_pool_cls':
204
+ """
205
+ Create a pool instance to manage concurrent execution slots with a maximum size.
206
+
207
+ The returned pool instance can be used as a context manager or as a decorator
208
+ to wrap the function in `.pooled()` method on the instance.
209
+
210
+ Args:
211
+ key (str): The key used to identify the pool.
212
+ max_size (int): Maximum number of concurrent slots in the pool.
213
+ slot_exp (Union[int, None, UnsetType], optional): TTL for pool slots in seconds.
214
+ Defaults to UNSET and uses default_pool_slot_expiration from cachify.
215
+
216
+ Returns:
217
+ pool: A pool instance that can be used as a context manager.
218
+
219
+ Example:
220
+ main_pool = cachify.pool(key='worker-pool', max_size=10)
221
+
222
+ async with main_pool:
223
+ ...
224
+
225
+ # Or as decorator via the instance method
226
+ @main_pool.pooled()
227
+ async def process():
228
+ ...
229
+ """
230
+ from ._pool import pool as _pool
231
+
232
+ pl = _pool(key=key, max_size=max_size, slot_exp=slot_exp)
233
+
234
+ pl._cachify = self._client # pyright: ignore[reportPrivateUsage]
235
+
236
+ return pl
237
+
238
+ def pooled(
239
+ self,
240
+ key: str,
241
+ max_size: int,
242
+ on_full: Any = None,
243
+ raise_on_full: bool = False,
244
+ slot_exp: Union[Optional[int], UnsetType] = UNSET,
245
+ ) -> 'WrappedFunctionPool':
246
+ """
247
+ Decorator factory for pooled functions.
248
+
249
+ This is a convenience method equivalent to the standalone `pooled` function.
250
+ Use this when you only need the decorator functionality.
251
+
252
+ Args:
253
+ key (str): The key used to identify the pool. Supports format strings with function arguments.
254
+ max_size (int): Maximum number of concurrent slots in the pool.
255
+ on_full (Callable[..., Any], optional): Callback called when pool is full.
256
+ Receives the same *args, **kwargs as the wrapped function. Defaults to None.
257
+ raise_on_full (bool, optional): If True, raise CachifyPoolFullError when pool is full.
258
+ Defaults to False.
259
+ slot_exp (Union[int, None, UnsetType], optional): TTL for pool slots in seconds.
260
+ Defaults to UNSET and uses default_pool_slot_expiration from cachify.
261
+
262
+ Returns:
263
+ WrappedFunctionPool: A decorator that wraps functions with pool acquisition.
264
+ Attaches method `size(*args, **kwargs)` to check pool size.
265
+
266
+ Example:
267
+ @cachify.pooled(key='task-pool-{user_id}', max_size=10)
268
+ async def process_task(user_id: str) -> None:
269
+ ...
270
+ """
271
+ from ._pool import _pooled_impl # pyright: ignore[reportPrivateUsage]
272
+
273
+ return _pooled_impl(
274
+ key=key,
275
+ max_size=max_size,
276
+ on_full=on_full,
277
+ raise_on_full=raise_on_full,
278
+ slot_exp=slot_exp,
279
+ pool_instance=None,
280
+ client_provider=lambda: self._client,
281
+ )
282
+
188
283
 
189
284
  def init_cachify(
190
285
  sync_client: Optional[SyncClient] = None,
@@ -192,6 +287,8 @@ def init_cachify(
192
287
  default_lock_expiration: Optional[int] = 30,
193
288
  default_cache_ttl: Optional[int] = None,
194
289
  prefix: str = 'PYC-',
290
+ lock_poll_interval: float = 0.1,
291
+ default_pool_slot_expiration: Optional[int] = 600,
195
292
  *,
196
293
  is_global: bool = True,
197
294
  ) -> Cachify:
@@ -209,6 +306,10 @@ def init_cachify(
209
306
  Defaults to None, meaning infinite cache time when ttl is UNSET.
210
307
  prefix (str, optional): The prefix to use for keys.
211
308
  Defaults to 'PYC-'.
309
+ lock_poll_interval (float, optional): The interval in seconds to wait between lock acquisition
310
+ attempts when polling. Defaults to 0.1.
311
+ default_pool_slot_expiration (Optional[int], optional): The default TTL for pool slots in seconds.
312
+ Defaults to 600 (10 minutes).
212
313
  is_global (bool, optional): Whether to register this client as the global instance.
213
314
  Defaults to True.
214
315
  """
@@ -226,6 +327,8 @@ def init_cachify(
226
327
  default_expiration=default_lock_expiration,
227
328
  default_cache_ttl=default_cache_ttl,
228
329
  prefix=prefix,
330
+ lock_poll_interval=lock_poll_interval,
331
+ default_pool_slot_expiration=default_pool_slot_expiration,
229
332
  )
230
333
  # is not needed, but kept to not ruin the function signature
231
334
  return Cachify(
@@ -234,6 +337,8 @@ def init_cachify(
234
337
  prefix=prefix,
235
338
  default_expiration=default_lock_expiration,
236
339
  default_cache_ttl=default_cache_ttl,
340
+ lock_poll_interval=lock_poll_interval,
341
+ default_pool_slot_expiration=default_pool_slot_expiration,
237
342
  )
238
343
 
239
344
  return Cachify(
@@ -242,6 +347,8 @@ def init_cachify(
242
347
  prefix=prefix,
243
348
  default_expiration=default_lock_expiration,
244
349
  default_cache_ttl=default_cache_ttl,
350
+ lock_poll_interval=lock_poll_interval,
351
+ default_pool_slot_expiration=default_pool_slot_expiration,
245
352
  )
246
353
 
247
354
 
@@ -31,6 +31,8 @@ class AsyncLockMethods(LockProtocolBase):
31
31
  async def _a_acquire(self, key: str) -> None:
32
32
  stop_at = self._calc_stop_at()
33
33
  c = 10
34
+ poll_interval = self._cachify.lock_poll_interval
35
+
34
36
  while True:
35
37
  acquired = await self._cachify.a_try_acquire_lock(key=self._key, ttl=self._get_ttl())
36
38
  if acquired:
@@ -43,7 +45,7 @@ class AsyncLockMethods(LockProtocolBase):
43
45
  do_log=bool(c >= 10),
44
46
  )
45
47
 
46
- await asleep(0.1)
48
+ await asleep(poll_interval)
47
49
  c += 1 if c < 10 else -10
48
50
 
49
51
  async def arelease(self) -> None:
@@ -64,6 +66,8 @@ class SyncLockMethods(LockProtocolBase):
64
66
  def _acquire(self, key: str) -> None:
65
67
  stop_at = self._calc_stop_at()
66
68
  c = 10
69
+ poll_interval = self._cachify.lock_poll_interval
70
+
67
71
  while True:
68
72
  acquired = self._cachify.try_acquire_lock(key=self._key, ttl=self._get_ttl())
69
73
  if acquired:
@@ -75,7 +79,7 @@ class SyncLockMethods(LockProtocolBase):
75
79
  do_raise=self._nowait or time.time() > stop_at,
76
80
  do_log=bool(c >= 10),
77
81
  )
78
- time.sleep(0.1)
82
+ time.sleep(poll_interval)
79
83
  c += 1 if c < 10 else -10
80
84
 
81
85
  def release(self) -> None:
@@ -0,0 +1,440 @@
1
+ import contextvars
2
+ import inspect
3
+ import time
4
+ import uuid
5
+ from collections.abc import Awaitable
6
+ from functools import wraps
7
+ from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union, cast
8
+
9
+ from typing_extensions import ParamSpec, Self, final, overload
10
+
11
+ from ._exceptions import CachifyLockError, CachifyPoolFullError
12
+ from ._helpers import get_full_key_from_signature, is_coroutine
13
+ from ._lib import get_cachify_client
14
+ from ._pool_state import PoolState
15
+ from ._types._common import UNSET, UnsetType
16
+ from ._types._pool_wrap import AsyncPoolWrappedF, SyncPoolWrappedF, WrappedFunctionPool
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ from ._lib import CachifyClient
21
+
22
+ _P = ParamSpec('_P')
23
+ _R = TypeVar('_R', covariant=True)
24
+
25
+
26
+ class _PoolBase:
27
+ """Shared pool functionality and state management."""
28
+
29
+ def __init__(
30
+ self,
31
+ key: str,
32
+ max_size: int,
33
+ slot_exp: Union[Optional[int], UnsetType] = UNSET,
34
+ ) -> None:
35
+ self._key = key
36
+ self._max_size = max_size
37
+ self._slot_exp = slot_exp
38
+ self._bound_cachify_client: Optional[CachifyClient] = None
39
+ self._slot_id_var: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(
40
+ f'pool-slot-{key}', default=None
41
+ )
42
+
43
+ @property
44
+ def _cachify(self) -> 'CachifyClient':
45
+ if self._bound_cachify_client is not None:
46
+ return self._bound_cachify_client
47
+ return get_cachify_client()
48
+
49
+ @_cachify.setter
50
+ def _cachify(self, client: 'CachifyClient') -> None:
51
+ self._bound_cachify_client = client
52
+
53
+ def _get_slot_expiration(self) -> Optional[int]:
54
+ if isinstance(self._slot_exp, UnsetType):
55
+ return self._cachify.default_pool_slot_expiration
56
+ return self._slot_exp
57
+
58
+ def _get_meta_lock_key(self) -> str:
59
+ return f'{self._key}-lock'
60
+
61
+ def _get_state_key(self) -> str:
62
+ return f'{self._key}-state'
63
+
64
+ def _get_lock_timeout(self) -> float:
65
+ """Calculate meta-lock timeout based on max_size.
66
+
67
+ Scales from 5s (small pools) to 30s (large pools).
68
+ Formula: min(30, max(5, max_size * 0.1))
69
+ Examples:
70
+ max_size=5 -> 5s
71
+ max_size=10 -> 5s
72
+ max_size=50 -> 5s
73
+ max_size=100 -> 10s
74
+ max_size=300 -> 30s
75
+ """
76
+ return min(30.0, max(5.0, self._max_size * 0.1))
77
+
78
+
79
+ class _PoolSync(_PoolBase):
80
+ """Synchronous pool operations."""
81
+
82
+ def _load_state(self) -> PoolState:
83
+ state_key = self._get_state_key()
84
+ data = self._cachify.get(key=state_key)
85
+ if data and isinstance(data, PoolState):
86
+ return data
87
+
88
+ return PoolState()
89
+
90
+ def _save_state(self, state: PoolState) -> None:
91
+ state_key = self._get_state_key()
92
+ _ = self._cachify.set(key=state_key, val=state)
93
+
94
+ def _acquire_slot(self) -> Optional[str]:
95
+ now = time.time()
96
+ state = self._load_state()
97
+ state.cleanup(now)
98
+
99
+ if state.count >= self._max_size:
100
+ return None
101
+
102
+ slot_id = uuid.uuid4().hex
103
+ slot_exp = self._get_slot_expiration()
104
+ expiration_time = now + slot_exp if slot_exp is not None else float('inf')
105
+ state.slots[slot_id] = expiration_time
106
+ self._save_state(state)
107
+
108
+ return slot_id
109
+
110
+ def _release_slot(self, slot_id: str) -> None:
111
+ state = self._load_state()
112
+ if slot_id in state.slots:
113
+ del state.slots[slot_id]
114
+ self._save_state(state)
115
+
116
+ def _acquire_or_raise(self) -> str:
117
+ """Try to acquire a slot. Raises CachifyPoolFullError if pool is full."""
118
+ from ._lock import lock as _lock_cls
119
+
120
+ meta_lock = _lock_cls(key=self._get_meta_lock_key(), nowait=False, timeout=self._get_lock_timeout())
121
+ meta_lock._cachify = self._cachify # pyright: ignore[reportPrivateUsage]
122
+
123
+ try:
124
+ with meta_lock:
125
+ slot_id = self._acquire_slot()
126
+
127
+ if slot_id is None:
128
+ raise CachifyPoolFullError(f'{self._key} is full (max_size={self._max_size})')
129
+ return slot_id
130
+ except CachifyLockError:
131
+ raise CachifyPoolFullError(f'{self._key} is full (max_size={self._max_size})') from None
132
+
133
+ def _release_with_lock(self, slot_id: str) -> None:
134
+ """Release a slot with meta-lock protection."""
135
+ from ._lock import lock as _lock_cls
136
+
137
+ meta_lock = _lock_cls(key=self._get_meta_lock_key(), nowait=False, timeout=self._get_lock_timeout())
138
+ meta_lock._cachify = self._cachify # pyright: ignore[reportPrivateUsage]
139
+
140
+ with meta_lock:
141
+ self._release_slot(slot_id)
142
+
143
+ def _enter(self) -> Self:
144
+ slot_id = self._acquire_or_raise()
145
+ self._slot_id_var.set(slot_id)
146
+ return self
147
+
148
+ def __enter__(self) -> Self:
149
+ return self._enter()
150
+
151
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
152
+ slot_id = self._slot_id_var.get()
153
+ if slot_id:
154
+ self._release_with_lock(slot_id)
155
+ self._slot_id_var.set(None)
156
+
157
+ def size(self) -> int:
158
+ from ._lock import lock as _lock_cls
159
+
160
+ meta_lock = _lock_cls(key=self._get_meta_lock_key(), nowait=False, timeout=self._get_lock_timeout())
161
+ meta_lock._cachify = self._cachify # pyright: ignore[reportPrivateUsage]
162
+
163
+ with meta_lock:
164
+ state = self._load_state()
165
+ return state.cleanup(time.time())
166
+
167
+
168
+ class _PoolAsync(_PoolBase):
169
+ """Asynchronous pool operations."""
170
+
171
+ async def _aload_state(self) -> PoolState:
172
+ state_key = self._get_state_key()
173
+ data = await self._cachify.a_get(key=state_key)
174
+ if data and isinstance(data, PoolState):
175
+ return data
176
+
177
+ return PoolState()
178
+
179
+ async def _asave_state(self, state: PoolState) -> None:
180
+ state_key = self._get_state_key()
181
+ _ = await self._cachify.a_set(key=state_key, val=state)
182
+
183
+ async def _a_acquire_slot(self) -> Optional[str]:
184
+ now = time.time()
185
+ state = await self._aload_state()
186
+ state.cleanup(now)
187
+
188
+ if state.count >= self._max_size:
189
+ return None
190
+
191
+ slot_id = uuid.uuid4().hex
192
+ slot_exp = self._get_slot_expiration()
193
+ expiration_time = now + slot_exp if slot_exp is not None else float('inf')
194
+ state.slots[slot_id] = expiration_time
195
+ await self._asave_state(state)
196
+
197
+ return slot_id
198
+
199
+ async def _a_release_slot(self, slot_id: str) -> None:
200
+ state = await self._aload_state()
201
+ if slot_id in state.slots:
202
+ del state.slots[slot_id]
203
+ await self._asave_state(state)
204
+
205
+ async def _a_acquire_or_raise(self) -> str:
206
+ """Try to acquire a slot. Raises CachifyPoolFullError if pool is full."""
207
+ from ._lock import lock as _lock_cls
208
+
209
+ meta_lock = _lock_cls(key=self._get_meta_lock_key(), nowait=False, timeout=self._get_lock_timeout())
210
+ meta_lock._cachify = self._cachify # pyright: ignore[reportPrivateUsage]
211
+
212
+ try:
213
+ async with meta_lock:
214
+ slot_id = await self._a_acquire_slot()
215
+
216
+ if slot_id is None:
217
+ raise CachifyPoolFullError(f'{self._key} is full (max_size={self._max_size})')
218
+ return slot_id
219
+ except CachifyLockError:
220
+ raise CachifyPoolFullError(f'{self._key} is full (max_size={self._max_size})') from None
221
+
222
+ async def _a_release_with_lock(self, slot_id: str) -> None:
223
+ """Release a slot with meta-lock protection."""
224
+ from ._lock import lock as _lock_cls
225
+
226
+ meta_lock = _lock_cls(key=self._get_meta_lock_key(), nowait=False, timeout=self._get_lock_timeout())
227
+ meta_lock._cachify = self._cachify # pyright: ignore[reportPrivateUsage]
228
+
229
+ async with meta_lock:
230
+ await self._a_release_slot(slot_id)
231
+
232
+ async def _aenter(self) -> Self:
233
+ slot_id = await self._a_acquire_or_raise()
234
+ self._slot_id_var.set(slot_id)
235
+ return self
236
+
237
+ async def __aenter__(self) -> Self:
238
+ return await self._aenter()
239
+
240
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
241
+ slot_id = self._slot_id_var.get()
242
+ if slot_id:
243
+ await self._a_release_with_lock(slot_id)
244
+ self._slot_id_var.set(None)
245
+
246
+ async def asize(self) -> int:
247
+ from ._lock import lock as _lock_cls
248
+
249
+ meta_lock = _lock_cls(key=self._get_meta_lock_key(), nowait=False, timeout=self._get_lock_timeout())
250
+ meta_lock._cachify = self._cachify # pyright: ignore[reportPrivateUsage]
251
+
252
+ async with meta_lock:
253
+ state = await self._aload_state()
254
+ return state.cleanup(time.time())
255
+
256
+
257
+ @final
258
+ class pool(_PoolSync, _PoolAsync):
259
+ """Pool implementation using counter + meta-lock with set-based state.
260
+
261
+ Manages a pool of slots with a maximum size. Supports both sync and async operations.
262
+
263
+ Args:
264
+ key (str): The key used to identify the pool.
265
+ max_size (int): Maximum number of concurrent slots in the pool.
266
+ raise_on_full (bool): If True, raise CachifyPoolFullError when pool is full. Defaults to False.
267
+ slot_exp (Union[Optional[int], UnsetType]): TTL for pool slots. Uses default_pool_slot_expiration if UNSET.
268
+
269
+ Usage as context manager:
270
+ async with pool(key='worker-pool', max_size=10):
271
+ ...
272
+
273
+ with pool(key='sync-pool', max_size=5):
274
+ ...
275
+
276
+ Usage as decorator via pooled() method:
277
+ main_pool = pool(key='worker-pool', max_size=10)
278
+
279
+ @main_pool.pooled(on_full=handler)
280
+ async def process_task() -> None:
281
+ ...
282
+ """
283
+
284
+ def pooled(
285
+ self,
286
+ on_full: Optional[Callable[..., Any]] = None,
287
+ raise_on_full: bool = False,
288
+ ) -> WrappedFunctionPool:
289
+ """Use pool instance as decorator factory.
290
+
291
+ Args:
292
+ on_full: Optional callback when pool is full. Receives *args, **kwargs from function call.
293
+ raise_on_full: If True, raise CachifyPoolFullError when pool is full instead of calling on_full.
294
+
295
+ Example:
296
+ main_pool = pool(key='worker', max_size=10)
297
+
298
+ @main_pool.pooled(on_full=handler)
299
+ async def process():
300
+ ...
301
+ """
302
+ return _pooled_impl(
303
+ key=self._key,
304
+ max_size=self._max_size,
305
+ on_full=on_full,
306
+ raise_on_full=raise_on_full,
307
+ slot_exp=self._slot_exp,
308
+ pool_instance=self,
309
+ )
310
+
311
+
312
+ def _pooled_impl(
313
+ key: str,
314
+ max_size: int,
315
+ on_full: Optional[Callable[..., Any]] = None,
316
+ raise_on_full: bool = False,
317
+ slot_exp: Union[Optional[int], UnsetType] = UNSET,
318
+ pool_instance: Optional['pool'] = None,
319
+ client_provider: Callable[[], 'CachifyClient'] = get_cachify_client,
320
+ ) -> WrappedFunctionPool:
321
+ """Internal pooled decorator implementation with optional pool_instance or client_provider."""
322
+
323
+ def _get_pool(bound_args: inspect.BoundArguments) -> 'pool':
324
+ """Get pool instance - use provided or create new one."""
325
+ if pool_instance is not None:
326
+ return pool_instance
327
+
328
+ _key = get_full_key_from_signature(bound_args=bound_args, key=key, operation_postfix='pool')
329
+ _pool = pool(key=_key, max_size=max_size, slot_exp=slot_exp)
330
+ _pool._cachify = client_provider() # pyright: ignore[reportPrivateUsage]
331
+
332
+ return _pool
333
+
334
+ @overload
335
+ def _pooled_inner( # type: ignore[overload-overlap]
336
+ _func: Callable[_P, Awaitable[_R]],
337
+ ) -> AsyncPoolWrappedF[_P, Optional[_R]]: ...
338
+
339
+ @overload
340
+ def _pooled_inner(
341
+ _func: Callable[_P, _R],
342
+ ) -> SyncPoolWrappedF[_P, Optional[_R]]: ...
343
+
344
+ def _pooled_inner(
345
+ _func: Union[Callable[_P, _R], Callable[_P, Awaitable[_R]]],
346
+ ) -> Union[AsyncPoolWrappedF[_P, Optional[_R]], SyncPoolWrappedF[_P, Optional[_R]]]:
347
+ signature = inspect.signature(_func)
348
+
349
+ if is_coroutine(_func):
350
+ _awaitable_func = _func
351
+
352
+ @wraps(_awaitable_func)
353
+ async def _async_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> Optional[_R]:
354
+ bound_args = signature.bind(*args, **kwargs)
355
+ _pool = _get_pool(bound_args)
356
+
357
+ try:
358
+ async with _pool:
359
+ return await _awaitable_func(*args, **kwargs)
360
+ except CachifyPoolFullError:
361
+ if raise_on_full:
362
+ raise
363
+ if on_full:
364
+ result = on_full(*args, **kwargs)
365
+ if inspect.iscoroutine(result):
366
+ return await result
367
+ return result
368
+
369
+ return None
370
+
371
+ async def _size(*args: Any, **kwargs: Any) -> int:
372
+ bound_args = signature.bind(*args, **kwargs)
373
+ _pool = _get_pool(bound_args)
374
+ return await _pool.asize()
375
+
376
+ setattr(_async_wrapper, 'size', _size)
377
+ return cast(AsyncPoolWrappedF[_P, Optional[_R]], cast(object, _async_wrapper))
378
+ else:
379
+ _sync_func = cast(Callable[_P, _R], _func)
380
+
381
+ @wraps(_sync_func)
382
+ def _sync_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> Optional[_R]:
383
+ bound_args = signature.bind(*args, **kwargs)
384
+ _pool = _get_pool(bound_args)
385
+
386
+ try:
387
+ with _pool:
388
+ return _sync_func(*args, **kwargs)
389
+ except CachifyPoolFullError:
390
+ if raise_on_full:
391
+ raise
392
+ if on_full:
393
+ return on_full(*args, **kwargs)
394
+
395
+ return None
396
+
397
+ def _sync_size(*args: Any, **kwargs: Any) -> int:
398
+ bound_args = signature.bind(*args, **kwargs)
399
+ _pool = _get_pool(bound_args)
400
+ return _pool.size()
401
+
402
+ setattr(_sync_wrapper, 'size', _sync_size)
403
+ return cast(SyncPoolWrappedF[_P, Optional[_R]], cast(object, _sync_wrapper))
404
+
405
+ return cast(WrappedFunctionPool, cast(object, _pooled_inner))
406
+
407
+
408
+ def pooled(
409
+ key: str,
410
+ max_size: int,
411
+ on_full: Optional[Callable[..., Any]] = None,
412
+ raise_on_full: bool = False,
413
+ slot_exp: Union[Optional[int], UnsetType] = UNSET,
414
+ ) -> WrappedFunctionPool:
415
+ """Standalone decorator factory for pooled functions.
416
+
417
+ Args:
418
+ key: Pool key (supports format strings with function args)
419
+ max_size: Maximum concurrent executions
420
+ on_full: Callback called when pool is full (receives function args)
421
+ raise_on_full: If True, raise CachifyPoolFullError when pool is full instead of calling on_full.
422
+ slot_exp: TTL for pool slots in seconds
423
+
424
+ Returns:
425
+ Decorator that wraps functions with pool acquisition
426
+
427
+ Example:
428
+ @pooled(key='pool-{user_id}', max_size=10, on_full=handle_full)
429
+ async def process(user_id: str) -> None:
430
+ ...
431
+ """
432
+ return _pooled_impl(
433
+ key=key,
434
+ max_size=max_size,
435
+ on_full=on_full,
436
+ raise_on_full=raise_on_full,
437
+ slot_exp=slot_exp,
438
+ pool_instance=None,
439
+ client_provider=get_cachify_client,
440
+ )
@@ -0,0 +1,22 @@
1
+ from dataclasses import dataclass, field
2
+
3
+
4
+ @dataclass
5
+ class PoolState:
6
+ """Pool state stored in the cache backend.
7
+
8
+ Uses a dict as a set with expiration timestamps to track active slots.
9
+ """
10
+
11
+ slots: dict[str, float] = field(default_factory=dict) # slot_id -> expiration_timestamp
12
+
13
+ @property
14
+ def count(self) -> int:
15
+ return len(self.slots)
16
+
17
+ def cleanup(self, now: float) -> int:
18
+ """Remove expired slots and return the cleaned count."""
19
+ expired = [sid for sid, exp in self.slots.items() if now > exp]
20
+ for sid in expired:
21
+ del self.slots[sid]
22
+ return len(self.slots)
@@ -23,6 +23,7 @@ class AsyncClient(Protocol):
23
23
  self,
24
24
  name: str,
25
25
  value: Any,
26
+ *,
26
27
  ex: Union[int, None] = None,
27
28
  nx: bool = False,
28
29
  ) -> Awaitable[Any]:
@@ -40,6 +41,7 @@ class SyncClient(Protocol):
40
41
  self,
41
42
  name: str,
42
43
  value: Any,
44
+ *,
43
45
  ex: Union[int, None] = None,
44
46
  nx: bool = False,
45
47
  ) -> Any:
@@ -0,0 +1,49 @@
1
+ from collections.abc import Awaitable
2
+ from typing import Callable, Union
3
+
4
+ from typing_extensions import ParamSpec, Protocol, TypeVar, overload
5
+
6
+
7
+ _R = TypeVar('_R')
8
+ _P = ParamSpec('_P')
9
+
10
+
11
+ class AsyncPoolWrappedF(Protocol[_P, _R]):
12
+ """Protocol for async functions wrapped with @pooled decorator."""
13
+
14
+ __wrapped__: Callable[_P, Awaitable[_R]] # pragma: no cover
15
+
16
+ async def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... # pragma: no cover
17
+
18
+ async def size(self, *args: _P.args, **kwargs: _P.kwargs) -> int: ... # pragma: no cover
19
+
20
+
21
+ class SyncPoolWrappedF(Protocol[_P, _R]):
22
+ """Protocol for sync functions wrapped with @pooled decorator."""
23
+
24
+ __wrapped__: Callable[_P, _R] # pragma: no cover
25
+
26
+ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... # pragma: no cover
27
+
28
+ def size(self, *args: _P.args, **kwargs: _P.kwargs) -> int: ... # pragma: no cover
29
+
30
+
31
+ class WrappedFunctionPool(Protocol):
32
+ """Protocol for the pooled decorator factory."""
33
+
34
+ @overload
35
+ def __call__(self, _func: Callable[_P, Awaitable[_R]]) -> AsyncPoolWrappedF[_P, _R]: ... # type: ignore[overload-overlap]
36
+
37
+ @overload
38
+ def __call__(self, _func: Callable[_P, _R]) -> SyncPoolWrappedF[_P, _R]: ...
39
+
40
+ def __call__( # pragma: no cover
41
+ self,
42
+ _func: Union[
43
+ Callable[_P, Awaitable[_R]],
44
+ Callable[_P, _R],
45
+ ],
46
+ ) -> Union[
47
+ AsyncPoolWrappedF[_P, _R],
48
+ SyncPoolWrappedF[_P, _R],
49
+ ]: ...
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "py-cachify"
3
3
  description = "Distributed locks, caching, and locking at hand"
4
- version = "3.0.1"
4
+ version = "3.1.0"
5
5
  authors = [{ name = "Galtozzy", email = "galtozzy+git@gmail.com" }]
6
6
  requires-python = ">=3.9,<4.0"
7
7
  readme = "README.md"
@@ -45,7 +45,6 @@ dev = [
45
45
  "pytest-mock>=3.14.0,<4",
46
46
  "pytest-cov>=7.0.0,<8",
47
47
  "taskipy>=1.13.0,<2",
48
- "mypy>=1.11.1,<2",
49
48
  "coverage>=7.6.1,<8",
50
49
  "pytest-asyncio>=1.0.0,<2",
51
50
  "pytest-socket>=0.7.0,<0.8",
@@ -60,9 +59,12 @@ docs = [
60
59
  "beautifulsoup4>=4.12.3,<5",
61
60
  "mkdocs-include-markdown-plugin>=7.2.0",
62
61
  ]
63
- integration = ["redis>=5.0.7,<6"]
62
+ integration = [
63
+ "redis>=5.3.1",
64
+ ]
64
65
 
65
66
  [tool.uv]
67
+ exclude-newer = "5 days"
66
68
  default-groups = [
67
69
  "dev",
68
70
  "docs",
@@ -84,7 +86,7 @@ include = [
84
86
  ]
85
87
 
86
88
  [tool.taskipy.tasks]
87
- format-and-lint = "task ruff && task mypy-lint"
89
+ format-and-lint = "task ruff && task pyright-lint"
88
90
 
89
91
  ruff = "ruff format ./py_cachify/ ./tests/ ./integration_tests/ ./docs/scripts/ && ruff check ./py_cachify/ ./tests/ ./integration_tests/ ./docs/scripts/ --fix --unsafe-fixes"
90
92
  tests = "PYTHONPATH=. pytest tests/ -vvv"
@@ -92,7 +94,7 @@ integration-tests = "PYTHONPATH=. pytest integration_tests/ --no-cov"
92
94
 
93
95
  docs-dev = "mkdocs serve"
94
96
  ruff-lint = "ruff check ./py_cachify"
95
- mypy-lint = "mypy --install-types --non-interactive ./py_cachify/"
97
+ pyright-lint = "basedpyright ./py_cachify/"
96
98
 
97
99
  [tool.ruff]
98
100
  line-length = 120
@@ -135,18 +137,6 @@ known-first-party = ["py_cachify"]
135
137
  [tool.ruff.lint.pyupgrade]
136
138
  keep-runtime-typing = true
137
139
 
138
- [tool.mypy]
139
- # Mypy configuration:
140
- # https://mypy.readthedocs.io/en/latest/config_file.html
141
- strict = true
142
- pretty = true
143
-
144
- exclude = ['test_']
145
-
146
- [[tool.mypy.overrides]]
147
- module = "tests.*"
148
- ignore_errors = true
149
-
150
140
  [tool.pytest.ini_options]
151
141
  minversion = "6.0"
152
142
  addopts = [
@@ -1,4 +0,0 @@
1
- from typing import Literal
2
-
3
-
4
- OperationPostfix = Literal['once', 'cached', 'lock']
File without changes