py-cachify 2.1.1__tar.gz → 3.0.1__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 (23) hide show
  1. {py_cachify-2.1.1 → py_cachify-3.0.1}/PKG-INFO +62 -10
  2. {py_cachify-2.1.1 → py_cachify-3.0.1}/README.md +58 -5
  3. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/__init__.py +1 -4
  4. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_cached.py +66 -30
  5. py_cachify-3.0.1/py_cachify/_backend/_clients.py +62 -0
  6. py_cachify-3.0.1/py_cachify/_backend/_helpers.py +164 -0
  7. py_cachify-3.0.1/py_cachify/_backend/_lib.py +252 -0
  8. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_lock.py +121 -44
  9. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_types/_common.py +19 -10
  10. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_types/_lock_wrap.py +2 -1
  11. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_types/_reset_wrap.py +2 -1
  12. {py_cachify-2.1.1 → py_cachify-3.0.1}/pyproject.toml +25 -12
  13. py_cachify-2.1.1/py_cachify/_backend/_clients.py +0 -40
  14. py_cachify-2.1.1/py_cachify/_backend/_helpers.py +0 -94
  15. py_cachify-2.1.1/py_cachify/_backend/_lib.py +0 -76
  16. {py_cachify-2.1.1 → py_cachify-3.0.1}/.gitignore +0 -0
  17. {py_cachify-2.1.1 → py_cachify-3.0.1}/LICENSE +0 -0
  18. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/__init__.py +0 -0
  19. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_constants.py +0 -0
  20. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_exceptions.py +0 -0
  21. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_logger.py +0 -0
  22. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/_backend/_types/__init__.py +0 -0
  23. {py_cachify-2.1.1 → py_cachify-3.0.1}/py_cachify/py.typed +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: py-cachify
3
- Version: 2.1.1
4
- Summary: Distributed locks, caching, and locking decorators at hand
3
+ Version: 3.0.1
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
7
7
  Author-email: Galtozzy <galtozzy+git@gmail.com>
@@ -16,7 +16,6 @@ Classifier: Operating System :: OS Independent
16
16
  Classifier: Programming Language :: Python
17
17
  Classifier: Programming Language :: Python :: 3
18
18
  Classifier: Programming Language :: Python :: 3 :: Only
19
- Classifier: Programming Language :: Python :: 3.8
20
19
  Classifier: Programming Language :: Python :: 3.9
21
20
  Classifier: Programming Language :: Python :: 3.10
22
21
  Classifier: Programming Language :: Python :: 3.11
@@ -27,8 +26,8 @@ Classifier: Topic :: Software Development
27
26
  Classifier: Topic :: Software Development :: Libraries
28
27
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
28
  Classifier: Typing :: Typed
30
- Requires-Python: <4.0,>=3.8
31
- Requires-Dist: typing-extensions<5,>=4.12.2
29
+ Requires-Python: <4.0,>=3.9
30
+ Requires-Dist: typing-extensions>=4.15.0
32
31
  Description-Content-Type: text/markdown
33
32
 
34
33
  <p align="center">
@@ -78,6 +77,8 @@ Description-Content-Type: text/markdown
78
77
 
79
78
  **Py-Cachify** is a robust library tailored for developers looking to enhance their Python applications with elegant caching and locking mechanisms.
80
79
  Whether you're building synchronous or asynchronous applications, Py-Cachify has you covered!
80
+ It acts as a thin, backend-agnostic wrapper over your favorite cache client, letting you focus on business logic instead of juggling low-level get/set calls.
81
+
81
82
 
82
83
  ## Key Features:
83
84
  - **Flexible Caching**: Effortlessly cache your function results, dramatically reducing execution time for expensive computations and I/O-bound tasks.
@@ -87,7 +88,7 @@ Utilize customizable keys and time-to-live (TTL) parameters.
87
88
  Prevent race conditions and manage shared resources effectively across both sync and async contexts.
88
89
 
89
90
  - **Backend Agnostic**: Easily integrate with different cache backends.
90
- Choose between in-memory, Redis, or any custom backend that adheres to the provided client interfaces.
91
+ Choose between in-memory, Redis, DragonflyDB, or any custom backend that adheres to the provided client interfaces.
91
92
 
92
93
  - **Decorators for Ease**: Use intuitive decorators like `@cached()` and `@lock()` to wrap your functions,
93
94
  maintain clean code, and benefit from automatic cache management.
@@ -128,7 +129,12 @@ from py_cachify import init_cachify
128
129
 
129
130
  init_cachify()
130
131
  ```
131
- By default, it will use an in-memory cache.
132
+
133
+ This call:
134
+
135
+ - Configures the **global** client used by the top-level decorators: `cached`, `lock`, and `once`.
136
+ - Returns a `Cachify` instance, but you don't have to use it if you only work with the global decorators.
137
+ - Uses an in-memory cache by default (both for sync and async usage).
132
138
 
133
139
 
134
140
  If you want to use Redis:
@@ -137,20 +143,47 @@ from py_cachify import init_cachify
137
143
  from redis.asyncio import from_url as async_from_url
138
144
  from redis import from_url
139
145
 
140
- init_cachify(sync_client=from_url(redis_url), async_client=async_from_url(async_redis_client))
146
+
147
+ # Example: configure global cachify with Redis for both sync and async flows
148
+ init_cachify(
149
+ sync_client=from_url(redis_url),
150
+ async_client=async_from_url(redis_url),
151
+ )
141
152
  ```
142
- Normally you wouldn't have to use both sync and async clients since an application usually works in a single mode i.e. sync/async.
153
+ Normally you wouldn't have to use both sync and async clients since an application usually works in a single mode i.e. sync/async. You can pass only `sync_client` **or** only `async_client` if that matches your usage.
154
+
143
155
 
144
156
  Once initialized you can use everything that the library provides straight up without being worried about managing the cache yourself.
145
157
 
146
- ❗ If you forgot to call `init_cachify` the `CachifyInitError` will be raised during runtime.
158
+
159
+ ❗ If you forgot to call `init_cachify` with `is_global=True` at least once, using the global decorators (`cached`, `lock`, `once`) will raise `CachifyInitError` during runtime.
160
+
161
+ You can also create **dedicated instances** without touching the global client:
162
+
163
+ ```python
164
+ from py_cachify import init_cachify
165
+
166
+ # Global initialization for the top-level decorators
167
+ init_cachify()
168
+
169
+ # Local instance that does NOT touch the global client
170
+ local_cache = init_cachify(is_global=False, prefix='LOCAL-')
171
+
172
+ @local_cache.cached(key='local-{x}')
173
+ def compute_local(x: int) -> int:
174
+ return x * 2
175
+ ```
176
+
147
177
 
148
178
  ## Basic examples
149
179
 
180
+
150
181
  ### Caching
151
182
 
183
+
152
184
  Caching by using `@cached` decorator utilizing the flexibility of a dynamic key:
153
185
 
186
+
154
187
  ```python
155
188
  # Cache the result of the following function with dynamic key
156
189
  @cached(key='sum_two-{a}-{b}')
@@ -164,6 +197,25 @@ async def sum_two(a: int, b: int) -> int:
164
197
  await sub_two.reset(a=1, b=2)
165
198
  ```
166
199
 
200
+ ### Multi-layer Usage
201
+
202
+ It is possible to layer caches by stacking `cached` decorators (for example, a global cache inside a local instance cache).
203
+
204
+ ```python
205
+ from py_cachify import cached, init_cachify
206
+
207
+ # Global initialization for the top-level decorators
208
+ init_cachify()
209
+
210
+ # Local instance with a shorter TTL that wraps the global one
211
+ local = init_cachify(is_global=False, prefix='LOCAL-')
212
+
213
+ @local.cached(key='local-expensive-{x}', ttl=5)
214
+ @cached(key='expensive-{x}', ttl=60)
215
+ def expensive(x: int) -> int:
216
+ return x * 10
217
+ ```
218
+
167
219
  Read more about `@cached` [here](https://py-cachify.readthedocs.io/latest/reference/cached/).
168
220
 
169
221
  ### Locking
@@ -45,6 +45,8 @@
45
45
 
46
46
  **Py-Cachify** is a robust library tailored for developers looking to enhance their Python applications with elegant caching and locking mechanisms.
47
47
  Whether you're building synchronous or asynchronous applications, Py-Cachify has you covered!
48
+ It acts as a thin, backend-agnostic wrapper over your favorite cache client, letting you focus on business logic instead of juggling low-level get/set calls.
49
+
48
50
 
49
51
  ## Key Features:
50
52
  - **Flexible Caching**: Effortlessly cache your function results, dramatically reducing execution time for expensive computations and I/O-bound tasks.
@@ -54,7 +56,7 @@ Utilize customizable keys and time-to-live (TTL) parameters.
54
56
  Prevent race conditions and manage shared resources effectively across both sync and async contexts.
55
57
 
56
58
  - **Backend Agnostic**: Easily integrate with different cache backends.
57
- Choose between in-memory, Redis, or any custom backend that adheres to the provided client interfaces.
59
+ Choose between in-memory, Redis, DragonflyDB, or any custom backend that adheres to the provided client interfaces.
58
60
 
59
61
  - **Decorators for Ease**: Use intuitive decorators like `@cached()` and `@lock()` to wrap your functions,
60
62
  maintain clean code, and benefit from automatic cache management.
@@ -95,7 +97,12 @@ from py_cachify import init_cachify
95
97
 
96
98
  init_cachify()
97
99
  ```
98
- By default, it will use an in-memory cache.
100
+
101
+ This call:
102
+
103
+ - Configures the **global** client used by the top-level decorators: `cached`, `lock`, and `once`.
104
+ - Returns a `Cachify` instance, but you don't have to use it if you only work with the global decorators.
105
+ - Uses an in-memory cache by default (both for sync and async usage).
99
106
 
100
107
 
101
108
  If you want to use Redis:
@@ -104,20 +111,47 @@ from py_cachify import init_cachify
104
111
  from redis.asyncio import from_url as async_from_url
105
112
  from redis import from_url
106
113
 
107
- init_cachify(sync_client=from_url(redis_url), async_client=async_from_url(async_redis_client))
114
+
115
+ # Example: configure global cachify with Redis for both sync and async flows
116
+ init_cachify(
117
+ sync_client=from_url(redis_url),
118
+ async_client=async_from_url(redis_url),
119
+ )
108
120
  ```
109
- Normally you wouldn't have to use both sync and async clients since an application usually works in a single mode i.e. sync/async.
121
+ Normally you wouldn't have to use both sync and async clients since an application usually works in a single mode i.e. sync/async. You can pass only `sync_client` **or** only `async_client` if that matches your usage.
122
+
110
123
 
111
124
  Once initialized you can use everything that the library provides straight up without being worried about managing the cache yourself.
112
125
 
113
- ❗ If you forgot to call `init_cachify` the `CachifyInitError` will be raised during runtime.
126
+
127
+ ❗ If you forgot to call `init_cachify` with `is_global=True` at least once, using the global decorators (`cached`, `lock`, `once`) will raise `CachifyInitError` during runtime.
128
+
129
+ You can also create **dedicated instances** without touching the global client:
130
+
131
+ ```python
132
+ from py_cachify import init_cachify
133
+
134
+ # Global initialization for the top-level decorators
135
+ init_cachify()
136
+
137
+ # Local instance that does NOT touch the global client
138
+ local_cache = init_cachify(is_global=False, prefix='LOCAL-')
139
+
140
+ @local_cache.cached(key='local-{x}')
141
+ def compute_local(x: int) -> int:
142
+ return x * 2
143
+ ```
144
+
114
145
 
115
146
  ## Basic examples
116
147
 
148
+
117
149
  ### Caching
118
150
 
151
+
119
152
  Caching by using `@cached` decorator utilizing the flexibility of a dynamic key:
120
153
 
154
+
121
155
  ```python
122
156
  # Cache the result of the following function with dynamic key
123
157
  @cached(key='sum_two-{a}-{b}')
@@ -131,6 +165,25 @@ async def sum_two(a: int, b: int) -> int:
131
165
  await sub_two.reset(a=1, b=2)
132
166
  ```
133
167
 
168
+ ### Multi-layer Usage
169
+
170
+ It is possible to layer caches by stacking `cached` decorators (for example, a global cache inside a local instance cache).
171
+
172
+ ```python
173
+ from py_cachify import cached, init_cachify
174
+
175
+ # Global initialization for the top-level decorators
176
+ init_cachify()
177
+
178
+ # Local instance with a shorter TTL that wraps the global one
179
+ local = init_cachify(is_global=False, prefix='LOCAL-')
180
+
181
+ @local.cached(key='local-expensive-{x}', ttl=5)
182
+ @cached(key='expensive-{x}', ttl=60)
183
+ def expensive(x: int) -> int:
184
+ return x * 10
185
+ ```
186
+
134
187
  Read more about `@cached` [here](https://py-cachify.readthedocs.io/latest/reference/cached/).
135
188
 
136
189
  ### Locking
@@ -1,13 +1,10 @@
1
- from ._backend._cached import async_cached as async_cached
2
1
  from ._backend._cached import cached as cached
3
- from ._backend._cached import sync_cached as sync_cached
4
2
  from ._backend._exceptions import CachifyInitError as CachifyInitError
5
3
  from ._backend._exceptions import CachifyLockError as CachifyLockError
4
+ from ._backend._lib import Cachify as Cachify
6
5
  from ._backend._lib import init_cachify as init_cachify
7
- from ._backend._lock import async_once as async_once
8
6
  from ._backend._lock import lock as lock
9
7
  from ._backend._lock import once as once
10
- from ._backend._lock import sync_once as sync_once
11
8
  from ._backend._types._common import AsyncClient as AsyncClient
12
9
  from ._backend._types._common import Decoder as Decoder
13
10
  from ._backend._types._common import Encoder as Encoder
@@ -1,12 +1,13 @@
1
1
  import inspect
2
+ from collections.abc import Awaitable
2
3
  from functools import partial, wraps
3
- from typing import Awaitable, Callable, Tuple, TypeVar, Union, cast, overload
4
+ from typing import Callable, Optional, TypeVar, Union, cast, overload
4
5
 
5
- from typing_extensions import ParamSpec, deprecated
6
+ from typing_extensions import ParamSpec
6
7
 
7
8
  from ._helpers import a_reset, encode_decode_value, get_full_key_from_signature, is_coroutine, reset
8
- from ._lib import get_cachify
9
- from ._types._common import Decoder, Encoder
9
+ from ._lib import CachifyClient, get_cachify_client
10
+ from ._types._common import UNSET, Decoder, Encoder, UnsetType
10
11
  from ._types._reset_wrap import AsyncResetWrappedF, SyncResetWrappedF, WrappedFunctionReset
11
12
 
12
13
 
@@ -16,7 +17,9 @@ _S = TypeVar('_S')
16
17
 
17
18
 
18
19
  def cached(
19
- key: str, ttl: Union[int, None] = None, enc_dec: Union[Tuple[Encoder, Decoder], None] = None
20
+ key: str,
21
+ ttl: Union[Optional[int], UnsetType] = UNSET,
22
+ enc_dec: Union[tuple[Encoder, Decoder], None] = None,
20
23
  ) -> WrappedFunctionReset:
21
24
  """
22
25
  Decorator that caches the result of a function based on the specified key, time-to-live (ttl),
@@ -24,8 +27,9 @@ def cached(
24
27
 
25
28
  Args:
26
29
  key (str): The key used to identify the cached result, could be a format string.
27
- ttl (Union[int, None], optional): The time-to-live for the cached result.
28
- Defaults to None, means indefinitely.
30
+ ttl (Union[int, None, UnsetType], optional): The time-to-live for the cached result.
31
+ If UNSET (default), the current cachify client's default_cache_ttl is used.
32
+ If None, means indefinitely.
29
33
  enc_dec (Union[Tuple[Encoder, Decoder], None], optional): The encoding and decoding functions for the cached value.
30
34
  Defaults to None.
31
35
 
@@ -35,6 +39,15 @@ def cached(
35
39
  and could be used to reset the cache.
36
40
  """
37
41
 
42
+ return _cached_impl(key=key, ttl=ttl, enc_dec=enc_dec, client_provider=get_cachify_client)
43
+
44
+
45
+ def _cached_impl(
46
+ key: str,
47
+ ttl: Union[Optional[int], UnsetType] = UNSET,
48
+ enc_dec: Union[tuple[Encoder, Decoder], None] = None,
49
+ client_provider: Callable[[], CachifyClient] = get_cachify_client,
50
+ ) -> WrappedFunctionReset:
38
51
  @overload
39
52
  def _cached_inner( # type: ignore[overload-overlap]
40
53
  _func: Callable[_P, Awaitable[_R]],
@@ -54,57 +67,80 @@ def cached(
54
67
  if enc_dec is not None:
55
68
  enc, dec = enc_dec
56
69
 
70
+ def _resolve_ttl(client: CachifyClient) -> Optional[int]:
71
+ if isinstance(ttl, UnsetType):
72
+ return client.default_cache_ttl
73
+ return ttl
74
+
57
75
  if is_coroutine(_func):
58
76
  _awaitable_func = _func
59
77
 
60
78
  @wraps(_awaitable_func)
61
79
  async def _async_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
62
- cachify = get_cachify()
80
+ cachify_client = client_provider()
63
81
  _key = get_full_key_from_signature(
64
82
  bound_args=signature.bind(*args, **kwargs), key=key, operation_postfix='cached'
65
83
  )
66
- if val := await cachify.a_get(key=_key):
84
+ if (val := await cachify_client.a_get(key=_key)) is not None:
67
85
  return cast(_R, encode_decode_value(encoder_decoder=dec, val=val))
68
86
 
69
87
  res = await _awaitable_func(*args, **kwargs)
70
- await cachify.a_set(key=_key, val=encode_decode_value(encoder_decoder=enc, val=res), ttl=ttl)
88
+
89
+ await cachify_client.a_set(
90
+ key=_key,
91
+ val=encode_decode_value(encoder_decoder=enc, val=res),
92
+ ttl=_resolve_ttl(cachify_client),
93
+ )
71
94
  return res
72
95
 
73
- setattr(_async_wrapper, 'reset', partial(a_reset, signature=signature, key=key, operation_postfix='cached'))
96
+ setattr(
97
+ _async_wrapper,
98
+ 'reset',
99
+ partial(
100
+ a_reset,
101
+ _pyc_signature=signature,
102
+ _pyc_key=key,
103
+ _pyc_operation_postfix='cached',
104
+ _pyc_original_func=_awaitable_func,
105
+ _pyc_client_provider=client_provider,
106
+ ),
107
+ )
74
108
 
75
109
  return cast(AsyncResetWrappedF[_P, _R], cast(object, _async_wrapper))
76
110
  else:
77
- _sync_func = _func
111
+ _sync_func = cast(Callable[_P, _R], _func) # type: ignore[redundant-cast]
78
112
 
79
113
  @wraps(_sync_func)
80
114
  def _sync_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
81
- cachify = get_cachify()
115
+ cachify_client = client_provider()
82
116
  _key = get_full_key_from_signature(
83
117
  bound_args=signature.bind(*args, **kwargs), key=key, operation_postfix='cached'
84
118
  )
85
- if val := cachify.get(key=_key):
119
+ if (val := cachify_client.get(key=_key)) is not None:
86
120
  return cast(_R, encode_decode_value(encoder_decoder=dec, val=val))
87
121
 
88
122
  res = _sync_func(*args, **kwargs)
89
- cachify.set(key=_key, val=encode_decode_value(encoder_decoder=enc, val=res), ttl=ttl)
123
+
124
+ cachify_client.set(
125
+ key=_key,
126
+ val=encode_decode_value(encoder_decoder=enc, val=res),
127
+ ttl=_resolve_ttl(cachify_client),
128
+ )
90
129
  return res
91
130
 
92
- setattr(_sync_wrapper, 'reset', partial(reset, signature=signature, key=key, operation_postfix='cached'))
131
+ setattr(
132
+ _sync_wrapper,
133
+ 'reset',
134
+ partial(
135
+ reset,
136
+ _pyc_signature=signature,
137
+ _pyc_key=key,
138
+ _pyc_operation_postfix='cached',
139
+ _pyc_original_func=_sync_func,
140
+ _pyc_client_provider=client_provider,
141
+ ),
142
+ )
93
143
 
94
144
  return cast(SyncResetWrappedF[_P, _R], cast(object, _sync_wrapper))
95
145
 
96
146
  return cast(WrappedFunctionReset, cast(object, _cached_inner))
97
-
98
-
99
- @deprecated('sync_cached is deprecated, use cached instead. Scheduled for removal in 3.0.0')
100
- def sync_cached(
101
- key: str, ttl: Union[int, None] = None, enc_dec: Union[Tuple[Encoder, Decoder], None] = None
102
- ) -> WrappedFunctionReset:
103
- return cached(key=key, ttl=ttl, enc_dec=enc_dec)
104
-
105
-
106
- @deprecated('async_cached is deprecated, use cached instead. Scheduled for removal in 3.0.0')
107
- def async_cached(
108
- key: str, ttl: Union[int, None] = None, enc_dec: Union[Tuple[Encoder, Decoder], None] = None
109
- ) -> WrappedFunctionReset:
110
- return cached(key=key, ttl=ttl, enc_dec=enc_dec)
@@ -0,0 +1,62 @@
1
+ import threading
2
+ import time
3
+ from typing import Any, Optional, Union
4
+
5
+
6
+ class MemoryCache:
7
+ def __init__(self) -> None:
8
+ self._cache: dict[str, tuple[Any, Union[float, None]]] = {}
9
+ self._lock = threading.RLock()
10
+
11
+ def set(self, name: str, value: Any, ex: Union[int, None] = None, nx: bool = False) -> Optional[bool]:
12
+ """
13
+ Set a value with optional NX semantics.
14
+
15
+ - If nx is False: behaves like a normal set, always overwriting the value.
16
+ Returns None to mirror the fact that some backends don't return a meaningful value.
17
+ - If nx is True: only set the value if the key is absent or expired.
18
+ Returns True if the value was set, False if the key already exists and is not expired.
19
+ """
20
+ if not nx:
21
+ self._cache[name] = value, ex and time.time() + ex
22
+ return None
23
+
24
+ # NX path: need atomic check+set
25
+ with self._lock:
26
+ existing = self._cache.get(name)
27
+ if existing is not None:
28
+ _, exp_at = existing
29
+ if exp_at is None or exp_at > time.time():
30
+ return False
31
+
32
+ self._cache[name] = value, ex and time.time() + ex
33
+ return True
34
+
35
+ def get(self, name: str) -> Optional[Any]:
36
+ val, exp_at = self._cache.get(name, (None, None))
37
+ if not exp_at or exp_at > time.time():
38
+ return val
39
+
40
+ self.delete(name)
41
+ return None
42
+
43
+ def delete(self, *names: str) -> None:
44
+ for key in names:
45
+ if key not in self._cache:
46
+ continue
47
+
48
+ del self._cache[key]
49
+
50
+
51
+ class AsyncWrapper:
52
+ def __init__(self, cache: MemoryCache) -> None:
53
+ self._cache = cache
54
+
55
+ async def get(self, name: str) -> Optional[Any]:
56
+ return self._cache.get(name=name)
57
+
58
+ async def delete(self, *names: str) -> Any:
59
+ self._cache.delete(*names)
60
+
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)
@@ -0,0 +1,164 @@
1
+ import asyncio
2
+ import inspect
3
+ from collections.abc import Awaitable
4
+ from typing import Any, Callable, TypeVar, Union
5
+
6
+ from typing_extensions import ParamSpec, TypeIs
7
+
8
+ from ._constants import OperationPostfix
9
+ from ._lib import CachifyClient
10
+ from ._logger import logger
11
+ from ._types._common import Decoder, Encoder
12
+
13
+
14
+ _R = TypeVar('_R', covariant=True)
15
+ _P = ParamSpec('_P')
16
+ _S = TypeVar('_S')
17
+
18
+
19
+ def _call_original(
20
+ _pyc_original_func: Union[Callable[..., Any], None], _pyc_method_name: str, *args: Any, **kwargs: Any
21
+ ) -> Any:
22
+ if not _pyc_original_func:
23
+ return
24
+
25
+ orig_method = getattr(_pyc_original_func, _pyc_method_name, None)
26
+ if not orig_method or not callable(orig_method):
27
+ return
28
+
29
+ try:
30
+ return orig_method(*args, **kwargs)
31
+ except Exception as e:
32
+ logger.debug(f'Error calling original reset: {e}')
33
+
34
+ return None
35
+
36
+
37
+ async def _acall_original(
38
+ _pyc_original_func: Union[Callable[..., Awaitable[Any]], None], _pyc_method_name: str, *args: Any, **kwargs: Any
39
+ ) -> Any:
40
+ if not _pyc_original_func:
41
+ return
42
+
43
+ orig_method = getattr(_pyc_original_func, _pyc_method_name, None)
44
+ if not orig_method or not is_coroutine(orig_method):
45
+ return
46
+
47
+ try:
48
+ return await orig_method(*args, **kwargs)
49
+ except Exception as e:
50
+ logger.debug(f'Error calling original reset: {e}')
51
+
52
+ return None
53
+
54
+
55
+ def get_full_key_from_signature(
56
+ bound_args: inspect.BoundArguments,
57
+ key: str,
58
+ operation_postfix: OperationPostfix,
59
+ ) -> str:
60
+ bound_args.apply_defaults()
61
+ _args_repr = f'{bound_args}'
62
+
63
+ args_dict = bound_args.arguments
64
+ args: tuple[Any, ...] = args_dict.pop('args', ())
65
+ kwargs: dict[str, Any] = args_dict.pop('kwargs', {})
66
+ kwargs.update(args_dict)
67
+
68
+ try:
69
+ return f'{key.format(*args, **kwargs)}-{operation_postfix}'
70
+ except (IndexError, KeyError):
71
+ raise ValueError(f'Arguments in a key({key}) do not match function signature params({_args_repr})') from None
72
+
73
+
74
+ def is_coroutine(
75
+ func: Union[Callable[_P, Awaitable[_R]], Callable[_P, _R]],
76
+ ) -> TypeIs[Callable[_P, Awaitable[_R]]]:
77
+ return asyncio.iscoroutinefunction(func)
78
+
79
+
80
+ def encode_decode_value(encoder_decoder: Union[Encoder, Decoder, None], val: Any) -> Any:
81
+ if not encoder_decoder:
82
+ return val
83
+
84
+ return encoder_decoder(val)
85
+
86
+
87
+ def reset(
88
+ *args: Any,
89
+ _pyc_key: str,
90
+ _pyc_signature: inspect.Signature,
91
+ _pyc_operation_postfix: OperationPostfix,
92
+ _pyc_original_func: Union[Callable[..., Any], None],
93
+ _pyc_client_provider: Callable[..., CachifyClient],
94
+ **kwargs: Any,
95
+ ) -> None:
96
+ client = _pyc_client_provider()
97
+ _key = get_full_key_from_signature(
98
+ bound_args=_pyc_signature.bind(*args, **kwargs),
99
+ key=_pyc_key,
100
+ operation_postfix=_pyc_operation_postfix,
101
+ )
102
+
103
+ client.delete(key=_key)
104
+
105
+ _call_original(_pyc_original_func, 'reset', *args, **kwargs)
106
+
107
+
108
+ async def a_reset(
109
+ *args: Any,
110
+ _pyc_key: str,
111
+ _pyc_signature: inspect.Signature,
112
+ _pyc_operation_postfix: OperationPostfix,
113
+ _pyc_original_func: Union[Callable[..., Awaitable[Any]], None],
114
+ _pyc_client_provider: Callable[..., CachifyClient],
115
+ **kwargs: Any,
116
+ ) -> None:
117
+ client = _pyc_client_provider()
118
+ _key = get_full_key_from_signature(
119
+ bound_args=_pyc_signature.bind(*args, **kwargs), key=_pyc_key, operation_postfix=_pyc_operation_postfix
120
+ )
121
+
122
+ await client.a_delete(key=_key)
123
+
124
+ await _acall_original(_pyc_original_func, 'reset', *args, **kwargs)
125
+
126
+
127
+ async def is_alocked(
128
+ *args: Any,
129
+ _pyc_key: str,
130
+ _pyc_signature: inspect.Signature,
131
+ _pyc_operation_postfix: OperationPostfix,
132
+ _pyc_original_func: Union[Callable[..., Awaitable[Any]], None],
133
+ _pyc_client_provider: Callable[..., CachifyClient],
134
+ **kwargs: Any,
135
+ ) -> bool:
136
+ client = _pyc_client_provider()
137
+ _key = get_full_key_from_signature(
138
+ bound_args=_pyc_signature.bind(*args, **kwargs), key=_pyc_key, operation_postfix=_pyc_operation_postfix
139
+ )
140
+
141
+ if bool(await client.a_get(key=_key)):
142
+ return True
143
+
144
+ return await _acall_original(_pyc_original_func, 'is_locked', *args, **kwargs) or False
145
+
146
+
147
+ def is_locked(
148
+ *args: Any,
149
+ _pyc_key: str,
150
+ _pyc_signature: inspect.Signature,
151
+ _pyc_operation_postfix: OperationPostfix,
152
+ _pyc_original_func: Union[Callable[..., Any], None],
153
+ _pyc_client_provider: Callable[..., CachifyClient],
154
+ **kwargs: Any,
155
+ ) -> bool:
156
+ client = _pyc_client_provider()
157
+ _key = get_full_key_from_signature(
158
+ bound_args=_pyc_signature.bind(*args, **kwargs), key=_pyc_key, operation_postfix=_pyc_operation_postfix
159
+ )
160
+
161
+ if bool(client.get(key=_key)):
162
+ return True
163
+
164
+ return _call_original(_pyc_original_func, 'is_locked', *args, **kwargs) or False