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.
@@ -0,0 +1,83 @@
1
+ """Async Cache - A flexible asynchronous caching system."""
2
+
3
+ # Core components
4
+ from async_cache.core import AsyncCache, CacheAdapter
5
+
6
+ # Key utilities
7
+ from async_cache.key_utils import (
8
+ CacheKeyContext,
9
+ CacheKeyFn,
10
+ CacheKeyComponent,
11
+ compose_key_functions,
12
+ extract_key_component,
13
+ key_component,
14
+ )
15
+
16
+ # Serialization
17
+ from async_cache.serialization import MsgPackSerializer
18
+
19
+ # Exceptions
20
+ from async_cache.exceptions import (
21
+ CacheError,
22
+ SerializationError,
23
+ InvalidCacheKeyError,
24
+ )
25
+
26
+ # Adapters
27
+ from async_cache.adapters import MemoryCacheAdapter
28
+
29
+ # Try to import Redis adapter if available
30
+ try:
31
+ from async_cache.adapters import RedisCacheAdapter
32
+ __all__ = [
33
+ # Core
34
+ "AsyncCache",
35
+ "CacheAdapter",
36
+
37
+ # Key utils
38
+ "CacheKeyContext",
39
+ "CacheKeyFn",
40
+ "CacheKeyComponent",
41
+ "compose_key_functions",
42
+ "extract_key_component",
43
+ "key_component",
44
+
45
+ # Serialization
46
+ "MsgPackSerializer",
47
+
48
+ # Exceptions
49
+ "CacheError",
50
+ "SerializationError",
51
+ "InvalidCacheKeyError",
52
+
53
+ # Adapters
54
+ "MemoryCacheAdapter",
55
+ "RedisCacheAdapter",
56
+ ]
57
+ except ImportError:
58
+ # Redis is not available
59
+ __all__ = [
60
+ # Core
61
+ "AsyncCache",
62
+ "CacheAdapter",
63
+
64
+ # Key utils
65
+ "CacheKeyContext",
66
+ "CacheKeyFn",
67
+ "CacheKeyComponent",
68
+ "compose_key_functions",
69
+ "extract_key_component",
70
+ "key_component",
71
+
72
+ # Serialization
73
+ "MsgPackSerializer",
74
+
75
+ # Exceptions
76
+ "CacheError",
77
+ "SerializationError",
78
+ "InvalidCacheKeyError",
79
+
80
+ # Adapters
81
+ "MemoryCacheAdapter",
82
+ ]
83
+
@@ -0,0 +1,11 @@
1
+ """Cache adapters for different storage backends."""
2
+
3
+ from async_cache.adapters.memory import MemoryCacheAdapter
4
+
5
+ # Try to import Redis adapter if redis is available
6
+ try:
7
+ from async_cache.adapters.redis import RedisCacheAdapter
8
+ __all__ = ["MemoryCacheAdapter", "RedisCacheAdapter"]
9
+ except ImportError:
10
+ # Redis package is not installed
11
+ __all__ = ["MemoryCacheAdapter"]
@@ -0,0 +1,122 @@
1
+ """
2
+ In-memory cache adapter for the async_cache package.
3
+
4
+ Provides a simple in-memory caching implementation with LRU eviction policy.
5
+ """
6
+
7
+ import asyncio
8
+ import time
9
+ from typing import Any, Dict, Optional, Tuple
10
+
11
+ from async_cache.core import CacheAdapter
12
+
13
+
14
+ class MemoryCacheAdapter(CacheAdapter):
15
+ """
16
+ Simple in-memory cache adapter.
17
+ Supports TTL and max size eviction policies with LRU (Least Recently Used) replacement.
18
+ Thread-safe implementation with asyncio locks.
19
+ """
20
+
21
+ def __init__(self, max_size: Optional[int] = 1000):
22
+ """
23
+ Initialize memory cache.
24
+
25
+ Args:
26
+ max_size: Maximum number of items to store (None for unlimited)
27
+ """
28
+ self._cache: Dict[str, Tuple[Any, Optional[float]]] = {} # key -> (value, expiry)
29
+ self._access_times: Dict[str, float] = {} # key -> last access timestamp
30
+ self.max_size = max_size
31
+ self._lock = asyncio.Lock()
32
+
33
+ async def get(self, key: str) -> Tuple[bool, Any]:
34
+ """
35
+ Get a value from the cache with TTL support.
36
+
37
+ Args:
38
+ key: The cache key
39
+
40
+ Returns:
41
+ Tuple of (hit, value) where hit is True if the item was in cache and not expired
42
+ """
43
+ async with self._lock:
44
+ if key not in self._cache:
45
+ return False, None
46
+
47
+ value, expiry = self._cache[key]
48
+ current_time = time.time()
49
+
50
+ # Update access time for LRU to current timestamp
51
+ self._access_times[key] = current_time
52
+
53
+ # Check if expired
54
+ if expiry is not None and current_time > expiry:
55
+ # Remove expired item
56
+ del self._cache[key]
57
+ del self._access_times[key]
58
+ return False, None
59
+
60
+ return True, value
61
+
62
+ async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
63
+ """
64
+ Set a value in the cache with TTL support.
65
+
66
+ Args:
67
+ key: The cache key
68
+ value: The value to store
69
+ ttl: Optional time-to-live in seconds
70
+ """
71
+ async with self._lock:
72
+ # Calculate expiry time if TTL provided
73
+ expiry = None
74
+ if ttl is not None:
75
+ expiry = time.time() + ttl
76
+
77
+ # Evict if at max capacity and adding a new key
78
+ if self.max_size is not None and len(self._cache) >= self.max_size and key not in self._cache:
79
+ self._evict_one()
80
+
81
+ # Store value and update access time to current timestamp
82
+ self._cache[key] = (value, expiry)
83
+ self._access_times[key] = time.time()
84
+
85
+ async def delete(self, key: str) -> bool:
86
+ """
87
+ Delete a value from the cache.
88
+
89
+ Args:
90
+ key: The cache key
91
+
92
+ Returns:
93
+ True if deleted, False if not found
94
+ """
95
+ async with self._lock:
96
+ if key in self._cache:
97
+ del self._cache[key]
98
+ del self._access_times[key]
99
+ return True
100
+ return False
101
+
102
+ async def clear(self) -> None:
103
+ """Clear all items from the cache."""
104
+ async with self._lock:
105
+ self._cache.clear()
106
+ self._access_times.clear()
107
+
108
+ def _evict_one(self) -> None:
109
+ """
110
+ Evict the least recently used item from the cache.
111
+
112
+ Note: This method should only be called with the lock held.
113
+ """
114
+ if not self._access_times:
115
+ return
116
+
117
+ # Find oldest accessed key (lowest timestamp value)
118
+ oldest_key = min(self._access_times.items(), key=lambda x: x[1])[0]
119
+
120
+ # Remove from cache
121
+ del self._cache[oldest_key]
122
+ del self._access_times[oldest_key]
@@ -0,0 +1,182 @@
1
+ """
2
+ Redis cache adapter for the async_cache package.
3
+
4
+ Provides a caching implementation that uses Redis as the backend.
5
+ Requires the 'redis' package to be installed (available with 'async-cache[redis]').
6
+ """
7
+
8
+ import logging
9
+ from typing import Any, Optional, Tuple
10
+
11
+ from async_cache.core import CacheAdapter
12
+ from async_cache.serialization import MsgPackSerializer
13
+
14
+ try:
15
+ import redis.asyncio as redis
16
+ except ImportError:
17
+ redis = None
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class RedisCacheAdapter(CacheAdapter):
23
+ """
24
+ Redis-based cache adapter.
25
+
26
+ Uses Redis for distributed caching with TTL support.
27
+
28
+ Note:
29
+ Requires the 'redis' package: pip install async-cache[redis]
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ host: str = "localhost",
35
+ port: int = 6379,
36
+ db: int = 0,
37
+ password: Optional[str] = None,
38
+ key_prefix: str = "async_cache:",
39
+ connection_pool: Optional[Any] = None,
40
+ client: Optional[Any] = None,
41
+ **redis_kwargs
42
+ ):
43
+ """
44
+ Initialize Redis cache adapter.
45
+
46
+ Args:
47
+ host: Redis host address
48
+ port: Redis port number
49
+ db: Redis database number
50
+ password: Optional Redis password
51
+ key_prefix: Prefix for all cache keys
52
+ connection_pool: Optional existing Redis connection pool
53
+ client: Optional existing Redis client instance
54
+ **redis_kwargs: Additional arguments to pass to Redis client
55
+
56
+ Raises:
57
+ ImportError: If redis package is not installed
58
+ """
59
+ if redis is None:
60
+ raise ImportError(
61
+ "Redis adapter requires the 'redis' package. "
62
+ "Install with 'pip install async-cache[redis]'"
63
+ )
64
+
65
+ self.key_prefix = key_prefix
66
+
67
+ # Use provided client, or create a new one
68
+ if client:
69
+ self.redis = client
70
+ else:
71
+ if connection_pool:
72
+ self.redis = redis.Redis(connection_pool=connection_pool, **redis_kwargs)
73
+ else:
74
+ self.redis = redis.Redis(
75
+ host=host,
76
+ port=port,
77
+ db=db,
78
+ password=password,
79
+ **redis_kwargs
80
+ )
81
+
82
+ def _prefixed_key(self, key: str) -> str:
83
+ """Add the prefix to a cache key."""
84
+ return f"{self.key_prefix}{key}"
85
+
86
+ async def get(self, key: str) -> Tuple[bool, Any]:
87
+ """
88
+ Get a value from the Redis cache.
89
+
90
+ Args:
91
+ key: The cache key
92
+
93
+ Returns:
94
+ Tuple of (hit, value) where hit is True if the item was in cache
95
+ """
96
+ try:
97
+ # Get from Redis
98
+ prefixed_key = self._prefixed_key(key)
99
+ data = await self.redis.get(prefixed_key)
100
+
101
+ if data is None:
102
+ return False, None
103
+
104
+ # Deserialize
105
+ value = MsgPackSerializer.decode(data)
106
+ return True, value
107
+ except Exception as e:
108
+ logger.warning(f"Error getting from Redis cache: {str(e)}")
109
+ return False, None
110
+
111
+ async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
112
+ """
113
+ Set a value in the Redis cache.
114
+
115
+ Args:
116
+ key: The cache key
117
+ value: The value to store
118
+ ttl: Optional time-to-live in seconds
119
+ """
120
+ try:
121
+ # Serialize
122
+ data = MsgPackSerializer.encode(value)
123
+
124
+ # Store in Redis with TTL
125
+ prefixed_key = self._prefixed_key(key)
126
+ if ttl is not None:
127
+ await self.redis.setex(prefixed_key, ttl, data)
128
+ else:
129
+ await self.redis.set(prefixed_key, data)
130
+ except Exception as e:
131
+ logger.warning(f"Error setting in Redis cache: {str(e)}")
132
+
133
+ async def delete(self, key: str) -> bool:
134
+ """
135
+ Delete a value from the Redis cache.
136
+
137
+ Args:
138
+ key: The cache key
139
+
140
+ Returns:
141
+ True if deleted, False if not found
142
+ """
143
+ try:
144
+ prefixed_key = self._prefixed_key(key)
145
+ result = await self.redis.delete(prefixed_key)
146
+ return result > 0
147
+ except Exception as e:
148
+ logger.warning(f"Error deleting from Redis cache: {str(e)}")
149
+ return False
150
+
151
+ async def clear(self) -> None:
152
+ """
153
+ Clear all items from the cache with the configured prefix.
154
+
155
+ Note: This only clears keys with the specified prefix for safety.
156
+ """
157
+ try:
158
+ # Use scan_iter to find all keys with prefix
159
+ pattern = f"{self.key_prefix}*"
160
+
161
+ # Get all keys matching pattern
162
+ keys = [key async for key in self.redis.scan_iter(match=pattern)]
163
+
164
+ if keys:
165
+ # Delete all matching keys
166
+ await self.redis.delete(*keys)
167
+ logger.info(f"Cleared {len(keys)} keys from Redis cache")
168
+ else:
169
+ logger.debug("No keys found to clear from Redis cache")
170
+ except Exception as e:
171
+ logger.warning(f"Error clearing Redis cache: {str(e)}")
172
+
173
+ async def close(self) -> None:
174
+ """
175
+ Close the Redis connection.
176
+
177
+ This should be called when the adapter is no longer needed.
178
+ """
179
+ try:
180
+ await self.redis.close()
181
+ except Exception as e:
182
+ logger.warning(f"Error closing Redis connection: {str(e)}")