python-wrap 0.2.1__py3-none-any.whl → 0.4.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.
Files changed (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,745 @@
1
+ """Async cache stores and ``amemoize``: caching without blocking the event loop.
2
+
3
+ ``memoize(store=RedisStore(...))`` calls its store synchronously, so on an asyncio event
4
+ loop every cache read and write is a blocking network round trip. This module provides
5
+ the native async path: an `AsyncCacheStore` protocol whose methods are coroutines, two
6
+ implementations (`AsyncMemoryStore`, `AsyncRedisStore` for ``redis.asyncio``-compatible
7
+ clients), `ThreadedStore` to run any synchronous store in worker threads, and the
8
+ `amemoize` decorator for ``async def`` functions.
9
+
10
+ Stored entries are opaque ``(value, expires_at)`` pairs; ``expires_at`` is a Unix
11
+ timestamp (or None) read through ``_core.wall_time`` so ``fake_clock`` controls it.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import concurrent.futures
18
+ import contextlib
19
+ import copy
20
+ import datetime
21
+ import functools
22
+ import inspect
23
+ import math
24
+ import pickle
25
+ import random
26
+ import re
27
+ import threading
28
+ from collections import OrderedDict
29
+ from collections.abc import Awaitable, Callable, Hashable
30
+ from typing import Any, Protocol, TypeVar, runtime_checkable
31
+
32
+ from python_wrap import _core, _fork
33
+ from python_wrap._backend import BackendMonitor
34
+ from python_wrap._runtime import digest, stable_digest
35
+ from python_wrap.caching import (
36
+ _TAG_PREFIX,
37
+ CacheInfo,
38
+ _async_tag_clients,
39
+ _async_tag_store_owners,
40
+ _await_shared,
41
+ _decode,
42
+ _exception_types,
43
+ _make_key_builder,
44
+ _register_tag_client,
45
+ _shared_future,
46
+ _tag_versions,
47
+ _ttl_seconds,
48
+ )
49
+ from python_wrap.stores import KEY_FORMAT, InvalidSignature, json_codec
50
+
51
+ __all__ = [
52
+ "AsyncCacheStore",
53
+ "AsyncMemoryStore",
54
+ "AsyncRedisStore",
55
+ "ThreadedStore",
56
+ "amemoize",
57
+ "json_codec",
58
+ ]
59
+
60
+ F = TypeVar("F", bound=Callable[..., Awaitable[Any]])
61
+
62
+
63
+ @runtime_checkable
64
+ class AsyncCacheStore(Protocol):
65
+ """Where `amemoize` keeps its entries. All four methods are coroutines.
66
+
67
+ * ``get(key)`` returns the stored entry or ``None``.
68
+ * ``set(key, entry, ttl)`` stores ``entry``; ``ttl`` is seconds until it is useless
69
+ (``None``: keep until deleted). Entries carry their own deadline, so a store may
70
+ forget entries at any time.
71
+ * ``delete(key)`` returns True if an entry existed.
72
+ * ``clear()`` removes every entry of this store.
73
+ """
74
+
75
+ async def get(self, key: Hashable, /) -> Any | None: ...
76
+
77
+ async def set(self, key: Hashable, entry: Any, ttl: float | None, /) -> None: ...
78
+
79
+ async def delete(self, key: Hashable, /) -> bool: ...
80
+
81
+ async def clear(self) -> None: ...
82
+
83
+
84
+ class AsyncMemoryStore:
85
+ """An in-process LRU `AsyncCacheStore` that respects ttl on read.
86
+
87
+ Operations never await, so they are atomic with respect to other tasks on the loop;
88
+ a lock also makes the store safe to touch from several threads.
89
+
90
+ Args:
91
+ maxsize: Maximum number of entries (least recently used is evicted), or None
92
+ for unbounded.
93
+
94
+ Raises:
95
+ ValueError: If ``maxsize`` is not None or a positive integer.
96
+
97
+ Example:
98
+ ```python
99
+ import asyncio
100
+ from python_wrap.async_cache import AsyncMemoryStore
101
+
102
+ async def main() -> None:
103
+ store = AsyncMemoryStore(maxsize=2)
104
+ await store.set("a", 1, None)
105
+ assert await store.get("a") == 1
106
+
107
+ asyncio.run(main())
108
+ ```
109
+ """
110
+
111
+ def __init__(self, maxsize: int | None = None) -> None:
112
+ if maxsize is not None and (
113
+ isinstance(maxsize, bool) or not isinstance(maxsize, int) or maxsize < 1
114
+ ):
115
+ raise ValueError("maxsize must be None or an integer >= 1")
116
+ self.maxsize = maxsize
117
+ self._data: OrderedDict[Hashable, tuple[Any, float | None]] = OrderedDict()
118
+ self._lock = _fork.ForkSafeLock()
119
+
120
+ async def get(self, key: Hashable, /) -> Any | None:
121
+ """Return the entry, or None if missing or past its ttl."""
122
+ with self._lock:
123
+ found = self._data.get(key)
124
+ if found is None:
125
+ return None
126
+ entry, deadline = found
127
+ if deadline is not None and _core.wall_time() >= deadline:
128
+ del self._data[key]
129
+ return None
130
+ self._data.move_to_end(key)
131
+ return entry
132
+
133
+ async def set(self, key: Hashable, entry: Any, ttl: float | None, /) -> None:
134
+ """Store an entry; a non-positive ttl removes it."""
135
+ with self._lock:
136
+ if ttl is not None and ttl <= 0:
137
+ self._data.pop(key, None)
138
+ return
139
+ deadline = None if ttl is None else _core.wall_time() + ttl
140
+ self._data[key] = (entry, deadline)
141
+ self._data.move_to_end(key)
142
+ while self.maxsize is not None and len(self._data) > self.maxsize:
143
+ self._data.popitem(last=False)
144
+
145
+ async def delete(self, key: Hashable, /) -> bool:
146
+ """Delete one entry; report whether it existed."""
147
+ with self._lock:
148
+ return self._data.pop(key, None) is not None
149
+
150
+ async def clear(self) -> None:
151
+ """Remove every entry."""
152
+ with self._lock:
153
+ self._data.clear()
154
+
155
+ def size(self) -> int:
156
+ """Return the number of stored entries (including not yet purged expired ones)."""
157
+ with self._lock:
158
+ return len(self._data)
159
+
160
+ def __len__(self) -> int:
161
+ return self.size()
162
+
163
+
164
+ class AsyncRedisStore:
165
+ """A namespaced `AsyncCacheStore` for ``redis.asyncio``-compatible clients.
166
+
167
+ Mirrors `RedisStore`: opaque hashed keys under ``prefix``, millisecond ttl, and a
168
+ ``clear()`` that scans only this namespace and deletes in bounded batches (UNLINK
169
+ where available).
170
+
171
+ Warning:
172
+ The default serializer is pickle. Only use it with a Redis instance you fully
173
+ trust; pass ``dumps``/``loads`` from `json_codec` otherwise.
174
+
175
+ Args:
176
+ client: A ``redis.asyncio`` client (awaitable get/set/delete, optionally unlink,
177
+ and an async-iterator ``scan_iter``).
178
+ prefix: A nonempty namespace unique to one cached function.
179
+ dumps: Serializer for entries; defaults to pickle.
180
+ loads: Deserializer matching dumps.
181
+ key_format: Optional function turning a cache key into a stable external key.
182
+ fail_open: Treat backend errors as misses/no-ops and log them, rather than raise.
183
+
184
+ Raises:
185
+ ValueError: If ``prefix`` is empty.
186
+ """
187
+
188
+ def __init__(
189
+ self,
190
+ client: Any,
191
+ prefix: str,
192
+ *,
193
+ dumps: Callable[[Any], bytes] | None = None,
194
+ loads: Callable[[bytes], Any] | None = None,
195
+ key_format: Callable[[Hashable], str] | None = None,
196
+ fail_open: bool = True,
197
+ retry_backend_after: float = 1.0,
198
+ version: int | None = None,
199
+ ) -> None:
200
+ if not prefix:
201
+ raise ValueError("AsyncRedisStore needs a nonempty per-function prefix")
202
+ if version is not None and (
203
+ isinstance(version, bool) or not isinstance(version, int) or version < 1
204
+ ):
205
+ raise ValueError("version must be a positive integer")
206
+ if dumps is None and loads is None:
207
+ from python_wrap.config import get_config
208
+
209
+ codec = get_config().get("cache_codec")
210
+ if codec is None:
211
+ import warnings
212
+
213
+ warnings.warn(
214
+ "implicit pickle cache codec is deprecated; pass a codec",
215
+ DeprecationWarning,
216
+ stacklevel=2,
217
+ )
218
+ codec = (pickle.dumps, pickle.loads)
219
+ dumps, loads = codec
220
+ self.client, self.prefix = client, prefix + (f"v{version}:" if version else "")
221
+ self.dumps, self.loads = dumps or pickle.dumps, loads or pickle.loads
222
+ self.key_format, self.fail_open = key_format, fail_open
223
+ self._monitor = BackendMonitor(
224
+ "cache", prefix, "allow" if fail_open else "raise", retry_backend_after
225
+ )
226
+
227
+ def _key(self, key: Hashable) -> str:
228
+ if self.key_format:
229
+ return self.prefix + self.key_format(key)
230
+ return self.prefix + KEY_FORMAT + stable_digest(key)
231
+
232
+ async def _run(self, action: Callable[[], Awaitable[Any]], default: Any = None) -> Any:
233
+ return await self._monitor.acall("cache", action, lambda: default)
234
+
235
+ async def get(self, key: Hashable, /) -> Any | None:
236
+ """Return a decoded entry, or None on a miss."""
237
+
238
+ async def read() -> Any:
239
+ value = await self.client.get(self._key(key))
240
+ if value is None:
241
+ return None
242
+ try:
243
+ return self.loads(value)
244
+ except InvalidSignature:
245
+ _core.emit("cache.rejected", self.prefix, reason="signature")
246
+ return None
247
+
248
+ return await self._run(read)
249
+
250
+ async def set(self, key: Hashable, entry: Any, ttl: float | None, /) -> None:
251
+ """Store an entry with millisecond TTL precision."""
252
+ if ttl is not None and ttl <= 0:
253
+ await self.delete(key)
254
+ return
255
+ options = {} if ttl is None else {"px": max(1, math.ceil(ttl * 1000))}
256
+
257
+ async def write() -> None:
258
+ await self.client.set(self._key(key), self.dumps(entry), **options)
259
+
260
+ await self._run(write)
261
+
262
+ async def delete(self, key: Hashable, /) -> bool:
263
+ """Delete one entry; report whether it existed."""
264
+
265
+ async def remove() -> Any:
266
+ return await self.client.delete(self._key(key))
267
+
268
+ return bool(await self._run(remove, False))
269
+
270
+ async def clear(self) -> None:
271
+ """Delete this namespace in batches, using UNLINK where supported."""
272
+
273
+ async def clear() -> None:
274
+ pattern = re.sub(r"([\\*?\[\]])", r"\\\1", self.prefix) + "*"
275
+ batch: list[Any] = []
276
+ delete = getattr(self.client, "unlink", None) or self.client.delete
277
+ async for key in self.client.scan_iter(match=pattern, count=200):
278
+ batch.append(key)
279
+ if len(batch) == 200:
280
+ await delete(*batch)
281
+ batch.clear()
282
+ if batch:
283
+ await delete(*batch)
284
+
285
+ await self._run(clear)
286
+
287
+ def size(self) -> None:
288
+ """Return None: an exact distributed entry count is intentionally not scanned."""
289
+ return None
290
+
291
+
292
+ class ThreadedStore:
293
+ """Use a synchronous `CacheStore` from async code without blocking the event loop.
294
+
295
+ Every ``get``/``set``/``delete``/``clear`` call runs the wrapped store's method in a
296
+ worker thread (``asyncio.to_thread``, or ``executor`` when given), so a network
297
+ store such as `python_wrap.stores.RedisStore` with a plain ``redis.Redis`` client
298
+ becomes an `AsyncCacheStore` for `amemoize`. Prefer `AsyncRedisStore` when a
299
+ ``redis.asyncio`` client is available: it needs no threads.
300
+
301
+ The wrapped store must be thread-safe (the `CacheStore` contract already requires
302
+ it). A worker thread cannot be interrupted, so a cancelled caller stops waiting but
303
+ the store call still finishes in the background.
304
+
305
+ Args:
306
+ store: Any synchronous `CacheStore`.
307
+ executor: A `concurrent.futures.Executor` to run the calls in; ``None`` uses the
308
+ event loop's default executor (via ``asyncio.to_thread``, which keeps context
309
+ variables).
310
+
311
+ Example:
312
+ ```python
313
+ import asyncio
314
+
315
+ from python_wrap.async_cache import ThreadedStore, amemoize
316
+
317
+
318
+ class DictStore: # stands in for RedisStore(redis.Redis(...), prefix=...)
319
+ def __init__(self) -> None:
320
+ self.data: dict[object, object] = {}
321
+
322
+ def get(self, key):
323
+ return self.data.get(key)
324
+
325
+ def set(self, key, entry, ttl):
326
+ self.data[key] = entry
327
+
328
+ def delete(self, key):
329
+ return self.data.pop(key, None) is not None
330
+
331
+ def clear(self):
332
+ self.data.clear()
333
+
334
+ def __len__(self):
335
+ return len(self.data)
336
+
337
+
338
+ calls = []
339
+
340
+
341
+ @amemoize(store=ThreadedStore(DictStore()))
342
+ async def lookup(user_id: int) -> str:
343
+ calls.append(user_id)
344
+ return f"user-{user_id}"
345
+
346
+
347
+ async def main() -> None:
348
+ assert await lookup(1) == await lookup(1) == "user-1"
349
+ assert calls == [1]
350
+
351
+
352
+ asyncio.run(main())
353
+ ```
354
+ """
355
+
356
+ def __init__(self, store: Any, *, executor: concurrent.futures.Executor | None = None):
357
+ for method in ("get", "set", "delete", "clear"):
358
+ if not callable(getattr(store, method, None)):
359
+ raise TypeError(f"store must have a callable {method}() method")
360
+ if inspect.iscoroutinefunction(getattr(store, method)):
361
+ raise TypeError("store is already asynchronous; pass it to amemoize directly")
362
+ self.store, self.executor = store, executor
363
+
364
+ async def _call(self, func: Callable[..., Any], *args: Any) -> Any:
365
+ if self.executor is None:
366
+ return await asyncio.to_thread(func, *args)
367
+ return await asyncio.get_running_loop().run_in_executor(self.executor, func, *args)
368
+
369
+ async def get(self, key: Hashable, /) -> Any | None:
370
+ """Return the wrapped store's entry, read in a worker thread."""
371
+ return await self._call(self.store.get, key)
372
+
373
+ async def set(self, key: Hashable, entry: Any, ttl: float | None, /) -> None:
374
+ """Store an entry from a worker thread."""
375
+ await self._call(self.store.set, key, entry, ttl)
376
+
377
+ async def delete(self, key: Hashable, /) -> bool:
378
+ """Delete one entry from a worker thread; report whether it existed."""
379
+ return bool(await self._call(self.store.delete, key))
380
+
381
+ async def clear(self) -> None:
382
+ """Clear the wrapped store from a worker thread."""
383
+ await self._call(self.store.clear)
384
+
385
+ def size(self) -> int | None:
386
+ """The wrapped store's ``size()`` (None if unknown), else ``len()``, else None."""
387
+ size = getattr(self.store, "size", None)
388
+ if callable(size):
389
+ value = size()
390
+ return None if value is None else int(value)
391
+ try:
392
+ return len(self.store)
393
+ except TypeError:
394
+ return None
395
+
396
+
397
+ def _split(entry: Any) -> tuple[Any, float | None, bool, float | None] | None:
398
+ """Validate a stored entry (a JSON codec yields lists); None means unusable.
399
+
400
+ Entries are ``(value, expires)`` or, for stale-while-revalidate and cached
401
+ exceptions, ``(value, expires, is_exception, fresh_until)``.
402
+ """
403
+ if isinstance(entry, (tuple, list)) and len(entry) == 2:
404
+ return entry[0], entry[1], False, entry[1]
405
+ if isinstance(entry, (tuple, list)) and len(entry) in (4, 5):
406
+ return entry[0], entry[1], bool(entry[2]), entry[3]
407
+ return None
408
+
409
+
410
+ def amemoize(
411
+ *,
412
+ ttl: float | None = None,
413
+ key: Callable[..., Hashable] | None = None,
414
+ store: AsyncCacheStore | None = None,
415
+ cache_none: bool = True,
416
+ copy_result: bool = False,
417
+ singleflight: bool = True,
418
+ stale_ttl: float | datetime.timedelta | None = None,
419
+ cache_exceptions: type[BaseException] | tuple[type[BaseException], ...] = (),
420
+ exception_ttl: float | datetime.timedelta | None = None,
421
+ logger: _core.LoggerLike = None,
422
+ lock: Any = None,
423
+ lock_ttl: float = 30,
424
+ lock_wait: float = 5,
425
+ tags: Callable[..., Any] | None = None,
426
+ ttl_jitter: float = 0.0,
427
+ ) -> Callable[[F], F]:
428
+ """Cache the results of an ``async def`` function in an `AsyncCacheStore`.
429
+
430
+ ``stale_ttl``, ``cache_exceptions`` and ``exception_ttl`` behave as in
431
+ `python_wrap.caching.memoize`: a stale entry is served at once while one background
432
+ task refreshes it (a failed refresh keeps the stale value, logs a warning and emits
433
+ ``cache.refresh_failed``), and a listed exception is stored and re-raised on hits.
434
+ Cached exceptions are never served stale; a shared store needs a codec that can
435
+ encode them.
436
+
437
+ Concurrent misses for one key on one event loop share a single computation when
438
+ ``singleflight`` is true. Exceptions are never cached and reach every waiter;
439
+ cancelling one waiter does not cancel the shared computation for the others. While
440
+ ``python_wrap.testing.disable_caching()`` is active the store is neither read nor
441
+ written. Emits ``cache.hit`` and ``cache.miss`` events (sharing an in-flight
442
+ computation counts as a hit).
443
+
444
+ The wrapper has ``await cache_clear()``, ``await cache_delete(*args, **kwargs)`` and
445
+ ``cache_info()``.
446
+
447
+ Args:
448
+ ttl: Seconds an entry stays valid, or None for no expiry.
449
+ key: Optional function with the wrapped signature returning a hashable key.
450
+ store: Where to keep entries; defaults to a private `AsyncMemoryStore`.
451
+ cache_none: Cache ``None`` results. If False, None is recomputed every time.
452
+ copy_result: Deepcopy values on write and on delivery.
453
+ singleflight: Share one in-flight computation between concurrent misses.
454
+ stale_ttl: Seconds after ``ttl`` during which the stale value is still served
455
+ while a background refresh runs. Requires ``ttl``.
456
+ cache_exceptions: Exception class (or tuple) cached and re-raised like results.
457
+ ``asyncio.CancelledError`` never is.
458
+ exception_ttl: Seconds a cached exception stays valid; defaults to ``ttl``.
459
+ logger: Logger (or name) for failed background refreshes.
460
+ lock: A lease backend shared by every process (prefer `AsyncRedisLock`): one
461
+ process computes a missing key, the others wait up to ``lock_wait`` and read
462
+ the store again. Stale refreshes take it without waiting. Needs ``store``.
463
+ lock_ttl: Seconds the stampede lease lives (renewed while computing).
464
+ lock_wait: Seconds a process waits for another's computation.
465
+ tags: ``tags(*args, **kwargs)`` returning tag names; see
466
+ `python_wrap.caching.invalidate_tags` and ``ainvalidate_tags``.
467
+ ttl_jitter: Shorten each ttl by a random share up to this (0 to 1).
468
+
469
+ Raises:
470
+ TypeError: If the decorated function is not ``async def``, or an option has the
471
+ wrong type.
472
+ ValueError: If ``ttl`` is not positive and finite.
473
+
474
+ Example:
475
+ ```python
476
+ import asyncio
477
+ from python_wrap.async_cache import amemoize
478
+
479
+ calls = 0
480
+
481
+ @amemoize(ttl=60)
482
+ async def square(n: int) -> int:
483
+ global calls
484
+ calls += 1
485
+ return n * n
486
+
487
+ async def main() -> None:
488
+ assert await square(4) == 16
489
+ assert await square(4) == 16
490
+ assert calls == 1
491
+
492
+ asyncio.run(main())
493
+ ```
494
+ """
495
+ if ttl is not None and (
496
+ isinstance(ttl, bool)
497
+ or not isinstance(ttl, (int, float))
498
+ or not math.isfinite(ttl)
499
+ or ttl <= 0
500
+ ):
501
+ raise ValueError("ttl must be None or a positive finite number")
502
+ for opt, val in (
503
+ ("cache_none", cache_none),
504
+ ("copy_result", copy_result),
505
+ ("singleflight", singleflight),
506
+ ):
507
+ if not isinstance(val, bool):
508
+ raise TypeError(f"{opt} must be bool")
509
+ if stale_ttl is not None and ttl is None:
510
+ raise ValueError("stale_ttl requires ttl")
511
+ if lock is not None and store is None:
512
+ raise ValueError("lock= coordinates processes through a shared store; pass store=")
513
+ if not 0 <= ttl_jitter < 1:
514
+ raise ValueError("ttl_jitter must be in [0, 1)")
515
+ tag_client: Any = getattr(store, "client", None) if tags is not None else None
516
+ tag_async = tag_client is not None and _core.is_async(tag_client.get)
517
+ if tag_async:
518
+ _register_tag_client(_async_tag_clients, _async_tag_store_owners, tag_client, store)
519
+ elif tag_client is not None:
520
+ from python_wrap.caching import _tag_clients, _tag_store_owners
521
+
522
+ _register_tag_client(_tag_clients, _tag_store_owners, tag_client, store)
523
+
524
+ async def versions(names: list[str]) -> dict[str, str] | None:
525
+ if not tag_async:
526
+ return _tag_versions(names, tag_client)
527
+ try:
528
+ return {n: _decode(await tag_client.get(_TAG_PREFIX + digest(n))) for n in names}
529
+ except Exception: # unknown versions read as a miss
530
+ return None
531
+
532
+ stale_s = _ttl_seconds(stale_ttl)
533
+ exc_types = _exception_types(cache_exceptions)
534
+ exc_ttl = _ttl_seconds(exception_ttl) if exception_ttl is not None else ttl
535
+
536
+ def decorate(func: F) -> F:
537
+ if not inspect.iscoroutinefunction(func):
538
+ raise TypeError("amemoize only supports async def functions; use memoize for sync")
539
+ backend: AsyncCacheStore = store if store is not None else AsyncMemoryStore()
540
+ build_key = _make_key_builder(func, False, key)
541
+ name = _core.qualname(func)
542
+ hits = misses = 0
543
+ stats_lock = threading.Lock()
544
+ inflight: dict[tuple[int, Hashable], asyncio.Future[Any]] = {}
545
+ background: set[asyncio.Future[Any]] = set() # strong refs to refresh tasks
546
+
547
+ def isolate(value: Any) -> Any:
548
+ return copy.deepcopy(value) if copy_result else value
549
+
550
+ def lookup(raw: Any) -> tuple[bool, Any, bool, bool]:
551
+ """``(found, value, is_exception, stale)`` for a raw store entry."""
552
+ parts = _split(raw)
553
+ if parts is None:
554
+ return False, None, False, False
555
+ value, expires, is_exc, fresh = parts
556
+ now = _core.wall_time()
557
+ if expires is not None and now >= expires:
558
+ return False, None, False, False
559
+ return True, value, is_exc, fresh is not None and now >= fresh
560
+
561
+ def count(hit: bool) -> None:
562
+ nonlocal hits, misses
563
+ with stats_lock:
564
+ if hit:
565
+ hits += 1
566
+ else:
567
+ misses += 1
568
+ if _core.listeners:
569
+ _core.emit("cache.hit" if hit else "cache.miss", name)
570
+
571
+ async def save(k: Hashable, value: Any, is_exc: bool, tv: Any = None) -> None:
572
+ life = exc_ttl if is_exc else ttl
573
+ if ttl_jitter and life:
574
+ life *= 1 - random.random() * ttl_jitter # nosec B311 - not security
575
+ keep = life if is_exc or life is None or stale_s is None else life + stale_s
576
+ now = _core.wall_time()
577
+ expires = None if keep is None else now + keep
578
+ fresh = None if life is None else now + life
579
+ plain = not is_exc and fresh == expires and tags is None # old readers: 2-tuples
580
+ entry: tuple[Any, ...] = (value, expires) if plain else (value, expires, is_exc, fresh)
581
+ if tags is not None:
582
+ entry = (*entry, tv)
583
+ await backend.set(k, entry, keep)
584
+
585
+ async def run(k: Hashable, args: Any, kwargs: Any) -> Any:
586
+ tv = None if tags is None else await versions(list(tags(*args, **kwargs)))
587
+ try:
588
+ result = await func(*args, **kwargs)
589
+ except exc_types as exc:
590
+ if not isinstance(exc, asyncio.CancelledError):
591
+ await save(k, exc, True, tv)
592
+ raise
593
+ if result is not None or cache_none:
594
+ await save(k, isolate(result), False, tv)
595
+ return result
596
+
597
+ def lease_for(k: Hashable, wait: bool) -> Any:
598
+ from python_wrap.coordination import Lease
599
+
600
+ return Lease(
601
+ f"amemo:{digest(name)}:{stable_digest(k)}",
602
+ backend=lock,
603
+ ttl=lock_ttl,
604
+ wait=wait,
605
+ timeout=lock_wait if wait else None,
606
+ )
607
+
608
+ async def compute(k: Hashable, args: Any, kwargs: Any, refreshing: bool = False) -> Any:
609
+ """Compute and store, once across processes when ``lock`` is set."""
610
+ if lock is None:
611
+ return await run(k, args, kwargs)
612
+ from python_wrap.coordination import AlreadyRunning
613
+
614
+ lease = lease_for(k, not refreshing)
615
+ try:
616
+ await lease.__aenter__()
617
+ except AlreadyRunning:
618
+ lease = None
619
+ try:
620
+ if lease is None or not refreshing:
621
+ found, value, is_exc, stale = await read(k)
622
+ if found and (lease is None or not stale):
623
+ if is_exc:
624
+ raise value
625
+ return value # another process computed (or is refreshing) it
626
+ return await run(k, args, kwargs)
627
+ finally:
628
+ if lease is not None:
629
+ with contextlib.suppress(Exception):
630
+ await lease.__aexit__(None, None, None)
631
+
632
+ async def read(k: Hashable) -> tuple[bool, Any, bool, bool]:
633
+ raw = await backend.get(k)
634
+ found, value, is_exc, stale = lookup(raw)
635
+ if found and tags is not None:
636
+ recorded = raw[4] if isinstance(raw, (tuple, list)) and len(raw) == 5 else None
637
+ if recorded and await versions(list(recorded)) != recorded:
638
+ return False, None, False, False
639
+ return found, value, is_exc, stale
640
+
641
+ def start(
642
+ fkey: tuple[int, Hashable],
643
+ k: Hashable,
644
+ args: Any,
645
+ kwargs: Any,
646
+ refreshing: bool = False,
647
+ ) -> Any:
648
+ """Run one computation for ``fkey`` and return the future its callers share."""
649
+ shared = _shared_future()
650
+ inflight[fkey] = shared
651
+
652
+ def finish(task: asyncio.Future[Any]) -> None:
653
+ if inflight.get(fkey) is shared:
654
+ del inflight[fkey]
655
+ if shared.done():
656
+ if not task.cancelled():
657
+ task.exception()
658
+ elif task.cancelled():
659
+ shared.cancel()
660
+ elif (exc := task.exception()) is not None:
661
+ shared.set_exception(exc)
662
+ else:
663
+ shared.set_result(task.result())
664
+
665
+ try:
666
+ task = asyncio.ensure_future(compute(k, args, kwargs, refreshing))
667
+ except BaseException:
668
+ inflight.pop(fkey, None)
669
+ raise
670
+ task.add_done_callback(finish)
671
+ return shared
672
+
673
+ def refresh(k: Hashable, args: Any, kwargs: Any) -> None:
674
+ fkey = (id(asyncio.get_running_loop()), k)
675
+ if fkey in inflight:
676
+ return # a refresh (or a miss) for this key is already running
677
+ shared = start(fkey, k, args, kwargs, refreshing=True)
678
+
679
+ def failed(fut: asyncio.Future[Any]) -> None:
680
+ if not fut.cancelled() and (exc := fut.exception()) is not None:
681
+ _core.get_logger(logger).warning(
682
+ "amemoize: background refresh of %s failed; keeping the stale value",
683
+ name,
684
+ exc_info=exc,
685
+ )
686
+ _core.emit("cache.refresh_failed", name, exception=exc)
687
+
688
+ shared.add_done_callback(failed)
689
+ background.add(shared)
690
+ shared.add_done_callback(background.discard)
691
+ if _core.listeners:
692
+ _core.emit("cache.stale", name)
693
+
694
+ @functools.wraps(func)
695
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
696
+ if _core.overrides.disable_caching:
697
+ return await func(*args, **kwargs)
698
+ k = build_key(args, kwargs)
699
+ found, value, is_exc, stale = await read(k)
700
+ if found:
701
+ count(True)
702
+ if stale and not is_exc:
703
+ refresh(k, args, kwargs)
704
+ if is_exc:
705
+ raise value
706
+ return isolate(value)
707
+ if not singleflight:
708
+ count(False)
709
+ return await compute(k, args, kwargs)
710
+ fkey = (id(asyncio.get_running_loop()), k)
711
+ shared = inflight.get(fkey)
712
+ if shared is not None:
713
+ count(True)
714
+ return isolate(await _await_shared(shared))
715
+ count(False)
716
+ return isolate(await _await_shared(start(fkey, k, args, kwargs)))
717
+
718
+ async def cache_clear() -> None:
719
+ """Remove every entry from the store and reset the statistics."""
720
+ nonlocal hits, misses
721
+ await backend.clear()
722
+ with stats_lock:
723
+ hits = misses = 0
724
+
725
+ async def cache_delete(*args: Any, **kwargs: Any) -> bool:
726
+ """Remove the entry for these arguments; True if one existed."""
727
+ return await backend.delete(build_key(args, kwargs))
728
+
729
+ def cache_info() -> CacheInfo:
730
+ """Return hits, misses, maxsize and current size (None if unknown)."""
731
+ size = getattr(backend, "size", None)
732
+ with stats_lock:
733
+ return CacheInfo(
734
+ hits,
735
+ misses,
736
+ getattr(backend, "maxsize", None),
737
+ size() if callable(size) else None,
738
+ )
739
+
740
+ wrapper.cache_clear = cache_clear # type: ignore[attr-defined]
741
+ wrapper.cache_delete = cache_delete # type: ignore[attr-defined]
742
+ wrapper.cache_info = cache_info # type: ignore[attr-defined]
743
+ return wrapper # type: ignore[return-value]
744
+
745
+ return decorate