async-task-worker 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
async_cache/core.py ADDED
@@ -0,0 +1,680 @@
1
+ """
2
+ Core components for the async_cache package.
3
+
4
+ Provides the CacheAdapter abstract base class and AsyncCache for caching operations.
5
+ """
6
+
7
+ import asyncio
8
+ import contextlib
9
+ import hashlib
10
+ import logging
11
+ import uuid
12
+ from abc import ABC, abstractmethod
13
+ from typing import Any, Dict, Optional, Tuple, Set, Iterator
14
+
15
+ from async_cache.exceptions import SerializationError, InvalidCacheKeyError
16
+ from async_cache.key_utils import CacheKeyContext, CacheKeyFn
17
+ from async_cache.serialization import MsgPackSerializer
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class CacheAdapter(ABC):
23
+ """
24
+ Abstract base class for cache adapters.
25
+ Implementations should provide concrete storage mechanisms.
26
+ """
27
+
28
+ @abstractmethod
29
+ async def get(self, key: str) -> Tuple[bool, Any]:
30
+ """
31
+ Get a value from the cache.
32
+
33
+ Args:
34
+ key: The cache key
35
+
36
+ Returns:
37
+ Tuple of (hit, value) where hit is True if item was in cache
38
+ """
39
+ pass
40
+
41
+ @abstractmethod
42
+ async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
43
+ """
44
+ Set a value in the cache.
45
+
46
+ Args:
47
+ key: The cache key
48
+ value: The value to store
49
+ ttl: Optional time-to-live in seconds
50
+ """
51
+ pass
52
+
53
+ @abstractmethod
54
+ async def delete(self, key: str) -> bool:
55
+ """
56
+ Delete a value from the cache.
57
+
58
+ Args:
59
+ key: The cache key
60
+
61
+ Returns:
62
+ True if deleted, False if not found
63
+ """
64
+ pass
65
+
66
+ @abstractmethod
67
+ async def clear(self) -> None:
68
+ """Clear all items from the cache."""
69
+ pass
70
+
71
+
72
+ class AsyncCache:
73
+ """
74
+ Async cache manager with customizable key generation.
75
+
76
+ Features:
77
+ - Supports multiple cache backends through adapter interface
78
+ - Thread-safe and async-ready
79
+ - Customizable key generation
80
+ - Automatic cleanup of stale mappings
81
+ - TTL support
82
+ - Comprehensive serialization
83
+
84
+ Examples:
85
+ Basic usage:
86
+
87
+ ```python
88
+ # Create a cache with memory adapter
89
+ cache = AsyncCache(MemoryCacheAdapter())
90
+
91
+ # Store a result in the cache
92
+ await cache.set("my_function", args=(1, 2), kwargs={"a": "b"}, result="result")
93
+
94
+ # Retrieve from cache
95
+ hit, value = await cache.get("my_function", args=(1, 2), kwargs={"a": "b"})
96
+ ```
97
+
98
+ With custom key function:
99
+
100
+ ```python
101
+ # Define a custom key function based on version
102
+ def version_key(context):
103
+ return f"v{context['metadata']['version']}"
104
+
105
+ # Store with custom key function and metadata
106
+ await cache.set("get_user", args=(), kwargs={}, result="result",
107
+ metadata={"version": "1.2"}, cache_key_fn=version_key)
108
+ ```
109
+
110
+ With composed key functions:
111
+
112
+ ```python
113
+ # Create component extractors
114
+ user_key = extract_key_component("kwargs.user_id")
115
+ version_key = extract_key_component("metadata.version")
116
+
117
+ # Compose them into a single key function
118
+ combined_key = compose_key_functions(user_key, version_key)
119
+
120
+ # Use the composite key function
121
+ await cache.set("get_data", args=(), kwargs={"user_id": 123},
122
+ result="result", metadata={"version": "1.0"},
123
+ cache_key_fn=combined_key)
124
+ ```
125
+ """
126
+
127
+ def __init__(
128
+ self,
129
+ adapter: CacheAdapter,
130
+ default_ttl: Optional[int] = None,
131
+ enabled: bool = True,
132
+ max_serialized_size: int = 10 * 1024 * 1024, # 10 MB default
133
+ validate_keys: bool = False,
134
+ cleanup_interval: int = 900, # 15 minutes default
135
+ ):
136
+ """
137
+ Initialize the cache.
138
+
139
+ Args:
140
+ adapter: Cache adapter implementation
141
+ default_ttl: Default time-to-live in seconds (None for no expiry)
142
+ enabled: Whether caching is enabled by default
143
+ max_serialized_size: Maximum size in bytes for serialized objects
144
+ validate_keys: Whether to validate generated cache keys for format/uniqueness
145
+ cleanup_interval: Interval in seconds for automatic cleanup of stale entry ID mappings
146
+ Set to 0 to disable automatic cleanup
147
+ """
148
+ self.adapter = adapter
149
+ self.default_ttl = default_ttl
150
+ self.enabled = enabled
151
+ self.max_serialized_size = max_serialized_size
152
+ self.validate_keys = validate_keys
153
+ self.cleanup_interval = cleanup_interval
154
+ # Mapping of entry_id to cache key for reverse lookups
155
+ self.entry_key_map: Dict[str, str] = {}
156
+ # Lock for thread-safe access to entry_key_map
157
+ self._map_lock = asyncio.Lock()
158
+ # Optional set of generated keys for validation
159
+ self._generated_keys: Optional[Set[str]] = set() if validate_keys else None
160
+ # Flag for string fallback in serialization
161
+ self.fallback_to_str: bool = False
162
+ # Cleanup task reference
163
+ self._cleanup_task: Optional[asyncio.Task] = None
164
+ # Flag to signal cleanup task to stop
165
+ self._cleanup_running = False
166
+
167
+ def _build_context(self, fn_name: str, args: tuple, kwargs: dict, entry_id: Optional[str] = None,
168
+ metadata: Optional[Dict[str, Any]] = None) -> CacheKeyContext:
169
+ """
170
+ Build a context dictionary for cache key generation.
171
+
172
+ Args:
173
+ fn_name: Name of the function
174
+ args: Positional arguments
175
+ kwargs: Keyword arguments
176
+ entry_id: Optional entry ID
177
+ metadata: Optional metadata dictionary
178
+
179
+ Returns:
180
+ Context dictionary for cache key generation
181
+ """
182
+ context = {
183
+ "fn_name": fn_name,
184
+ "args": args,
185
+ "kwargs": kwargs,
186
+ }
187
+
188
+ if entry_id is not None:
189
+ context["entry_id"] = entry_id
190
+
191
+ if metadata is not None:
192
+ context["metadata"] = metadata
193
+
194
+ return context
195
+
196
+ @staticmethod
197
+ def default_key_fn(context: CacheKeyContext) -> str:
198
+ """
199
+ Default cache key generation function.
200
+ Creates a deterministic hash from function name and arguments.
201
+
202
+ Args:
203
+ context: Context dictionary with entry information
204
+
205
+ Returns:
206
+ Cache key string
207
+ """
208
+ try:
209
+ # Extract required elements from context
210
+ fn_name = context["fn_name"]
211
+ args = context["args"]
212
+ kwargs = context["kwargs"]
213
+
214
+ # Sort kwargs by key for consistent serialization
215
+ sorted_kwargs = dict(sorted(kwargs.items()))
216
+
217
+ # Create a data structure to serialize
218
+ data_to_hash = [fn_name, args, sorted_kwargs]
219
+
220
+ # Serialize with msgpack
221
+ packed_data = MsgPackSerializer.encode(data_to_hash)
222
+
223
+ # Generate MD5 hash of the serialized data
224
+ return hashlib.md5(packed_data).hexdigest()
225
+ except (KeyError, SerializationError) as e:
226
+ # Extract fn_name safely, with fallback
227
+ try:
228
+ fn_name = context.get("fn_name", "unknown")
229
+ except:
230
+ fn_name = "unknown"
231
+
232
+ logger.warning(f"Error generating cache key: {str(e)}")
233
+ # Generate a unique key that won't match anything else
234
+ return f"error_{fn_name}_{uuid.uuid4().hex}"
235
+
236
+ def _validate_key(self, key: str) -> None:
237
+ """
238
+ Validate a cache key for format and uniqueness.
239
+
240
+ Args:
241
+ key: The cache key to validate
242
+
243
+ Raises:
244
+ InvalidCacheKeyError: If the key is invalid or already in use
245
+ """
246
+ if not self.validate_keys:
247
+ return
248
+
249
+ # Basic format validation
250
+ if not key or not isinstance(key, str):
251
+ raise InvalidCacheKeyError(f"Invalid cache key: {key}")
252
+
253
+ # Check for uniqueness if tracking is enabled
254
+ if self._generated_keys is not None:
255
+ if key in self._generated_keys:
256
+ logger.warning(f"Duplicate cache key detected: {key}")
257
+ else:
258
+ self._generated_keys.add(key)
259
+
260
+ @contextlib.contextmanager
261
+ def temporarily_disabled(self) -> Iterator[None]:
262
+ """
263
+ Context manager that temporarily disables the cache.
264
+
265
+ Example:
266
+
267
+ ```python
268
+ # Temporarily disable the cache
269
+ with cache.temporarily_disabled():
270
+ # Cache operations in this block will be skipped
271
+ await cache.set("func", args=(), kwargs={}, result="data")
272
+ # All cache lookups will return misses
273
+ hit, _ = await cache.get("func", args=(), kwargs={}) # hit will be False
274
+ ```
275
+
276
+ Yields:
277
+ None
278
+ """
279
+ original_state = self.enabled
280
+ try:
281
+ self.enabled = False
282
+ yield
283
+ finally:
284
+ self.enabled = original_state
285
+
286
+ async def get(
287
+ self,
288
+ fn_name: str,
289
+ args: tuple,
290
+ kwargs: dict,
291
+ cache_key_fn: Optional[CacheKeyFn] = None,
292
+ entry_id: Optional[str] = None,
293
+ metadata: Optional[Dict[str, Any]] = None
294
+ ) -> Tuple[bool, Any]:
295
+ """
296
+ Get cached result.
297
+
298
+ Args:
299
+ fn_name: Name of the function
300
+ args: Positional arguments
301
+ kwargs: Keyword arguments
302
+ cache_key_fn: Optional custom key generation function
303
+ entry_id: Optional entry ID for reverse mapping
304
+ metadata: Optional metadata for custom key generation
305
+
306
+ Returns:
307
+ Tuple of (cache_hit, result)
308
+
309
+ Raises:
310
+ InvalidCacheKeyError: If key validation is enabled and the key is invalid
311
+ """
312
+ if not self.enabled:
313
+ return False, None
314
+
315
+ try:
316
+ # Build context for key generation
317
+ context = self._build_context(fn_name, args, kwargs, entry_id, metadata)
318
+
319
+ # Generate key using provided function or default
320
+ key_fn = cache_key_fn or self.default_key_fn
321
+ try:
322
+ key = key_fn(context)
323
+ # Validate key if enabled
324
+ self._validate_key(key)
325
+ except Exception as e:
326
+ if isinstance(e, InvalidCacheKeyError):
327
+ raise
328
+ logger.warning(f"Error in cache key function: {str(e)}")
329
+ # Fall back to default key generation
330
+ key = self.default_key_fn(context)
331
+
332
+ # Store entry_id to key mapping if provided
333
+ if entry_id is not None:
334
+ async with self._map_lock:
335
+ self.entry_key_map[entry_id] = key
336
+
337
+ # Get from cache
338
+ return await self.adapter.get(key)
339
+ except InvalidCacheKeyError as e:
340
+ # Re-raise validation errors for better handling
341
+ raise
342
+ except Exception as e:
343
+ logger.warning(f"Error retrieving from cache: {str(e)}")
344
+ return False, None
345
+
346
+ async def set(
347
+ self,
348
+ fn_name: str,
349
+ args: tuple,
350
+ kwargs: dict,
351
+ result: Any,
352
+ ttl: Optional[int] = None,
353
+ cache_key_fn: Optional[CacheKeyFn] = None,
354
+ entry_id: Optional[str] = None,
355
+ metadata: Optional[Dict[str, Any]] = None
356
+ ) -> bool:
357
+ """
358
+ Store result in cache.
359
+
360
+ Args:
361
+ fn_name: Name of the function
362
+ args: Positional arguments
363
+ kwargs: Keyword arguments
364
+ result: Result to cache
365
+ ttl: Time-to-live override (uses default if None)
366
+ cache_key_fn: Optional custom key generation function
367
+ entry_id: Optional entry ID for reverse mapping
368
+ metadata: Optional metadata for custom key generation
369
+
370
+ Returns:
371
+ True if successfully cached, False otherwise
372
+
373
+ Raises:
374
+ InvalidCacheKeyError: If key validation is enabled and the key is invalid
375
+ """
376
+ if not self.enabled:
377
+ return False
378
+
379
+ try:
380
+ # Try to serialize the result.
381
+ # By default, do not use string fallback to ensure proper round-trip serialization
382
+ try:
383
+ serialized = MsgPackSerializer.encode(
384
+ result,
385
+ fallback=self.fallback_to_str
386
+ )
387
+
388
+ # If fallback is enabled, add a warning log to help diagnose potential issues
389
+ if self.fallback_to_str:
390
+ logger.debug(f"Serializing result for {fn_name} with string fallback enabled")
391
+ except SerializationError as e:
392
+ logger.warning(f"Result for {fn_name} is not serializable: {str(e)}")
393
+ return False
394
+
395
+ # Check if the serialized result exceeds the maximum allowed size
396
+ if len(serialized) > self.max_serialized_size:
397
+ logger.warning(
398
+ f"Serialized result size {len(serialized)} exceeds maximum allowed size {self.max_serialized_size}"
399
+ )
400
+ return False
401
+
402
+ # Build context for key generation
403
+ context = self._build_context(fn_name, args, kwargs, entry_id, metadata)
404
+
405
+ # Generate key using provided function or default
406
+ key_fn = cache_key_fn or self.default_key_fn
407
+ try:
408
+ key = key_fn(context)
409
+ # Validate key if enabled
410
+ self._validate_key(key)
411
+ except Exception as e:
412
+ if isinstance(e, InvalidCacheKeyError):
413
+ raise
414
+ logger.warning(f"Error in cache key function: {str(e)}")
415
+ # Fall back to default key generation
416
+ key = self.default_key_fn(context)
417
+
418
+ # Store entry_id to key mapping if provided
419
+ if entry_id is not None:
420
+ async with self._map_lock:
421
+ self.entry_key_map[entry_id] = key
422
+
423
+ effective_ttl = ttl if ttl is not None else self.default_ttl
424
+ await self.adapter.set(key, result, effective_ttl)
425
+ return True
426
+ except InvalidCacheKeyError as e:
427
+ # Re-raise validation errors for better handling
428
+ raise
429
+ except Exception as e:
430
+ logger.warning(f"Error storing in cache: {str(e)}")
431
+ return False
432
+
433
+ async def invalidate(
434
+ self,
435
+ fn_name: str,
436
+ args: tuple,
437
+ kwargs: dict,
438
+ cache_key_fn: Optional[CacheKeyFn] = None,
439
+ entry_id: Optional[str] = None,
440
+ metadata: Optional[Dict[str, Any]] = None
441
+ ) -> bool:
442
+ """
443
+ Invalidate a specific cache entry.
444
+
445
+ Args:
446
+ fn_name: Name of the function
447
+ args: Positional arguments
448
+ kwargs: Keyword arguments
449
+ cache_key_fn: Optional custom key generation function
450
+ entry_id: Optional entry ID for lookup
451
+ metadata: Optional metadata for custom key generation
452
+
453
+ Returns:
454
+ True if invalidated, False if not found
455
+
456
+ Raises:
457
+ InvalidCacheKeyError: If key validation is enabled and the key is invalid
458
+ """
459
+ try:
460
+ # Build context for key generation
461
+ context = self._build_context(fn_name, args, kwargs, entry_id, metadata)
462
+
463
+ # Generate key using provided function or default
464
+ key_fn = cache_key_fn or self.default_key_fn
465
+ try:
466
+ key = key_fn(context)
467
+ # No need to validate on invalidation, just use the key
468
+ except Exception as e:
469
+ if isinstance(e, InvalidCacheKeyError):
470
+ raise
471
+ logger.warning(f"Error in cache key function during invalidation: {str(e)}")
472
+ # Fall back to default key generation
473
+ key = self.default_key_fn(context)
474
+
475
+ # Remove from entry_id mapping if it exists
476
+ if entry_id is not None:
477
+ async with self._map_lock:
478
+ if entry_id in self.entry_key_map:
479
+ del self.entry_key_map[entry_id]
480
+
481
+ # Remove from generated keys if tracking is enabled
482
+ if self._generated_keys is not None and key in self._generated_keys:
483
+ self._generated_keys.remove(key)
484
+
485
+ return await self.adapter.delete(key)
486
+ except InvalidCacheKeyError as e:
487
+ # Re-raise validation errors for better handling
488
+ raise
489
+ except Exception as e:
490
+ logger.warning(f"Error invalidating cache: {str(e)}")
491
+ return False
492
+
493
+ async def invalidate_by_id(self, entry_id: str) -> bool:
494
+ """
495
+ Invalidate a cache entry using an entry ID.
496
+
497
+ Args:
498
+ entry_id: Entry ID associated with the cache entry
499
+
500
+ Returns:
501
+ True if invalidated, False if not found
502
+ """
503
+ # Check if entry ID exists with lock to avoid race condition
504
+ async with self._map_lock:
505
+ if entry_id not in self.entry_key_map:
506
+ return False
507
+ key = self.entry_key_map[entry_id]
508
+
509
+ try:
510
+ success = await self.adapter.delete(key)
511
+
512
+ if success:
513
+ async with self._map_lock:
514
+ if entry_id in self.entry_key_map:
515
+ del self.entry_key_map[entry_id]
516
+
517
+ # Remove from generated keys if tracking is enabled
518
+ if self._generated_keys is not None and key in self._generated_keys:
519
+ self._generated_keys.remove(key)
520
+
521
+ return success
522
+ except Exception as e:
523
+ logger.warning(f"Error invalidating cache by entry ID: {str(e)}")
524
+ return False
525
+
526
+ async def get_cache_key_for_id(self, entry_id: str) -> Optional[str]:
527
+ """
528
+ Get the cache key associated with an entry ID.
529
+
530
+ Args:
531
+ entry_id: Entry ID to lookup
532
+
533
+ Returns:
534
+ Cache key or None if not found
535
+ """
536
+ async with self._map_lock:
537
+ return self.entry_key_map.get(entry_id)
538
+
539
+ async def get_id_key_mapping(self) -> Dict[str, str]:
540
+ """
541
+ Get a copy of the current entry ID to cache key mapping.
542
+
543
+ Useful for diagnostics or high-performance operations.
544
+
545
+ Returns:
546
+ Dictionary mapping entry IDs to cache keys
547
+ """
548
+ async with self._map_lock:
549
+ return self.entry_key_map.copy()
550
+
551
+ async def clear(self) -> None:
552
+ """Clear all cached results."""
553
+ try:
554
+ await self.adapter.clear()
555
+ # Clear entry key map with lock
556
+ async with self._map_lock:
557
+ self.entry_key_map.clear()
558
+ # Clear generated keys tracking if enabled
559
+ if self._generated_keys is not None:
560
+ self._generated_keys.clear()
561
+ except Exception as e:
562
+ logger.error(f"Error clearing cache: {str(e)}")
563
+
564
+ async def start_cleanup_task(self) -> None:
565
+ """
566
+ Start the periodic cleanup task to remove stale entry ID mappings.
567
+
568
+ This task runs in the background at the interval specified in the constructor
569
+ and removes any entry_id -> key mappings where the key no longer exists in the cache,
570
+ preventing memory leaks from expired or deleted cache entries.
571
+
572
+ The task only runs if cleanup_interval > 0.
573
+ """
574
+ if self.cleanup_interval <= 0 or self._cleanup_task is not None:
575
+ return
576
+
577
+ self._cleanup_running = True
578
+ self._cleanup_task = asyncio.create_task(self._run_cleanup_task())
579
+
580
+ async def stop_cleanup_task(self) -> None:
581
+ """
582
+ Stop the periodic cleanup task.
583
+
584
+ This method should be called when shutting down the cache to properly
585
+ clean up the background task.
586
+ """
587
+ self._cleanup_running = False
588
+
589
+ if self._cleanup_task is not None:
590
+ self._cleanup_task.cancel()
591
+ try:
592
+ await self._cleanup_task
593
+ except asyncio.CancelledError:
594
+ pass
595
+ finally:
596
+ self._cleanup_task = None
597
+
598
+ async def _run_cleanup_task(self) -> None:
599
+ """
600
+ Background task that periodically cleans up stale entry ID mappings.
601
+ Automatically restarts after errors with a backoff delay.
602
+ """
603
+ backoff_delay = 5 # Start with 5 seconds before retry
604
+ max_backoff = 300 # Maximum backoff of 5 minutes
605
+
606
+ while self._cleanup_running:
607
+ try:
608
+ await asyncio.sleep(self.cleanup_interval)
609
+ await self._cleanup_stale_mappings()
610
+ # Reset backoff on successful execution
611
+ backoff_delay = 5
612
+ except asyncio.CancelledError:
613
+ # Task was cancelled, exit gracefully
614
+ break
615
+ except Exception as e:
616
+ # Log the error but don't crash
617
+ logger.error(f"Error in cache cleanup task: {str(e)}")
618
+
619
+ if self._cleanup_running:
620
+ # Wait before retrying with exponential backoff
621
+ logger.info(f"Cleanup task will retry in {backoff_delay} seconds")
622
+ await asyncio.sleep(backoff_delay)
623
+ # Increase backoff for next failure, capped at max_backoff
624
+ backoff_delay = min(backoff_delay * 2, max_backoff)
625
+
626
+ async def _cleanup_stale_mappings(self) -> None:
627
+ """
628
+ Remove any entry_id -> key mappings where the key no longer exists in the cache.
629
+
630
+ This prevents memory leaks from expired cache entries.
631
+ """
632
+ # Check if map is empty (with lock to avoid race condition)
633
+ async with self._map_lock:
634
+ if not self.entry_key_map:
635
+ return
636
+ # Make a copy to avoid modification during iteration
637
+ entry_ids_to_check = list(self.entry_key_map.keys())
638
+
639
+ try:
640
+ stale_count = 0
641
+ stale_entry_ids = []
642
+ stale_keys = []
643
+
644
+ # First, check all keys without holding the lock for too long
645
+ for entry_id in entry_ids_to_check:
646
+ # Get key (with lock) - entry_id may be gone by now due to concurrent operations
647
+ key = None
648
+ async with self._map_lock:
649
+ if entry_id in self.entry_key_map:
650
+ key = self.entry_key_map[entry_id]
651
+ else:
652
+ continue
653
+
654
+ # Check if key exists in cache - outside lock to avoid holding it during I/O
655
+ if key:
656
+ hit, _ = await self.adapter.get(key)
657
+ if not hit:
658
+ # Found a stale mapping - save for later batch removal
659
+ stale_entry_ids.append(entry_id)
660
+ stale_keys.append(key)
661
+
662
+ # Remove stale mappings in one batch operation with the lock
663
+ if stale_entry_ids:
664
+ async with self._map_lock:
665
+ for entry_id in stale_entry_ids:
666
+ if entry_id in self.entry_key_map:
667
+ del self.entry_key_map[entry_id]
668
+ stale_count += 1
669
+
670
+ # Remove from generated keys if tracking (no lock needed)
671
+ if self._generated_keys is not None:
672
+ for key in stale_keys:
673
+ if key in self._generated_keys:
674
+ self._generated_keys.remove(key)
675
+
676
+ if stale_count > 0:
677
+ logger.debug(f"Cleaned up {stale_count} stale entry ID mappings")
678
+
679
+ except Exception as e:
680
+ logger.warning(f"Error during entry mapping cleanup: {str(e)}")
@@ -0,0 +1,16 @@
1
+ """Exceptions for the async_cache package."""
2
+
3
+
4
+ class CacheError(Exception):
5
+ """Base exception for all cache-related errors."""
6
+ pass
7
+
8
+
9
+ class SerializationError(CacheError):
10
+ """Exception raised when serialization or deserialization fails."""
11
+ pass
12
+
13
+
14
+ class InvalidCacheKeyError(CacheError):
15
+ """Exception raised when a cache key is invalid."""
16
+ pass