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/__init__.py +83 -0
- async_cache/adapters/__init__.py +11 -0
- async_cache/adapters/memory.py +122 -0
- async_cache/adapters/redis.py +182 -0
- async_cache/core.py +680 -0
- async_cache/exceptions.py +16 -0
- async_cache/key_utils.py +136 -0
- async_cache/serialization.py +230 -0
- async_task_worker/__init__.py +93 -0
- async_task_worker/adapters/__init__.py +3 -0
- async_task_worker/adapters/cache_adapter.py +206 -0
- async_task_worker/api.py +371 -0
- async_task_worker/core.py +717 -0
- async_task_worker/exceptions.py +245 -0
- async_task_worker/executor.py +204 -0
- async_task_worker/futures.py +232 -0
- async_task_worker/pool.py +343 -0
- async_task_worker/queue.py +265 -0
- async_task_worker/registry.py +96 -0
- async_task_worker/status.py +243 -0
- async_task_worker-0.3.0.dist-info/METADATA +1144 -0
- async_task_worker-0.3.0.dist-info/RECORD +24 -0
- async_task_worker-0.3.0.dist-info/WHEEL +4 -0
- async_task_worker-0.3.0.dist-info/licenses/LICENSE +21 -0
async_cache/key_utils.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Key utilities for the async_cache package.
|
|
3
|
+
|
|
4
|
+
Provides functions for generating and composing cache keys.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import functools
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Dict, Callable
|
|
10
|
+
|
|
11
|
+
from async_cache.exceptions import InvalidCacheKeyError
|
|
12
|
+
|
|
13
|
+
# Type for context dictionaries used in custom cache key generation
|
|
14
|
+
CacheKeyContext = Dict[str, Any]
|
|
15
|
+
|
|
16
|
+
# Type for cache key generation functions
|
|
17
|
+
CacheKeyFn = Callable[[CacheKeyContext], str]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class CacheKeyComponent:
|
|
22
|
+
"""A component of a cache key, used for composition."""
|
|
23
|
+
name: str
|
|
24
|
+
value: Any
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def compose_key_functions(*funcs: CacheKeyFn) -> CacheKeyFn:
|
|
28
|
+
"""
|
|
29
|
+
Compose multiple key functions into a single function.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
*funcs: One or more cache key functions to compose
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
A new function that applies all key functions and joins the results
|
|
36
|
+
|
|
37
|
+
Example:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
# Create a composite key function from two lambdas
|
|
41
|
+
key_fn = compose_key_functions(
|
|
42
|
+
lambda ctx: ctx["func_name"],
|
|
43
|
+
lambda ctx: str(ctx["kwargs"].get("user_id", "anonymous"))
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# Use it to generate a key
|
|
47
|
+
key = key_fn({"func_name": "get_data", "kwargs": {"user_id": 123}})
|
|
48
|
+
# key will be 'get_data:123'
|
|
49
|
+
```
|
|
50
|
+
"""
|
|
51
|
+
if not funcs:
|
|
52
|
+
raise ValueError("At least one key function must be provided")
|
|
53
|
+
|
|
54
|
+
def composed(context: CacheKeyContext) -> str:
|
|
55
|
+
parts = []
|
|
56
|
+
for func in funcs:
|
|
57
|
+
part = func(context)
|
|
58
|
+
if not isinstance(part, str):
|
|
59
|
+
raise InvalidCacheKeyError(f"Key function {func.__name__} returned {type(part)}, expected str")
|
|
60
|
+
parts.append(part)
|
|
61
|
+
return ":".join(parts)
|
|
62
|
+
|
|
63
|
+
return composed
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def extract_key_component(key_path: str) -> CacheKeyFn:
|
|
67
|
+
"""
|
|
68
|
+
Create a key function that extracts a component from the context.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
key_path: Dot-notation path to extract (e.g., "kwargs.user_id")
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
A function that extracts the value at the specified path
|
|
75
|
+
|
|
76
|
+
Example:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# Create an extractor for a specific path
|
|
80
|
+
key_fn = extract_key_component("kwargs.user_id")
|
|
81
|
+
|
|
82
|
+
# Use it to extract a value
|
|
83
|
+
key = key_fn({"kwargs": {"user_id": 123}})
|
|
84
|
+
# key will be '123'
|
|
85
|
+
```
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def extract(context: CacheKeyContext) -> str:
|
|
89
|
+
parts = key_path.split(".")
|
|
90
|
+
value = context
|
|
91
|
+
|
|
92
|
+
for part in parts:
|
|
93
|
+
if isinstance(value, dict) and part in value:
|
|
94
|
+
value = value[part]
|
|
95
|
+
else:
|
|
96
|
+
return "none"
|
|
97
|
+
|
|
98
|
+
return str(value)
|
|
99
|
+
|
|
100
|
+
return extract
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def key_component(name: str = None) -> Callable[[CacheKeyFn], CacheKeyFn]:
|
|
104
|
+
"""
|
|
105
|
+
Decorator for creating named cache key components.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
name: Optional name for the component
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
A decorator function
|
|
112
|
+
|
|
113
|
+
Example:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
# Create a named component for version extraction
|
|
117
|
+
@key_component("version")
|
|
118
|
+
def version_key(context):
|
|
119
|
+
return context.get("metadata", {}).get("version", "1.0")
|
|
120
|
+
|
|
121
|
+
# Using the decorated function
|
|
122
|
+
key = version_key({"metadata": {"version": "2.0"}})
|
|
123
|
+
# key will be 'version:2.0'
|
|
124
|
+
```
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def decorator(func: CacheKeyFn) -> CacheKeyFn:
|
|
128
|
+
@functools.wraps(func)
|
|
129
|
+
def wrapper(context: CacheKeyContext) -> str:
|
|
130
|
+
result = func(context)
|
|
131
|
+
component_name = name or func.__name__
|
|
132
|
+
return f"{component_name}:{result}"
|
|
133
|
+
|
|
134
|
+
return wrapper
|
|
135
|
+
|
|
136
|
+
return decorator
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Serialization utilities for the async_cache package.
|
|
3
|
+
|
|
4
|
+
Provides efficient serialization with support for complex Python types.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import datetime
|
|
8
|
+
import types
|
|
9
|
+
import uuid
|
|
10
|
+
from typing import Any, Dict
|
|
11
|
+
|
|
12
|
+
import msgpack
|
|
13
|
+
|
|
14
|
+
from async_cache.exceptions import SerializationError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MsgPackSerializer:
|
|
18
|
+
"""Handler for msgpack serialization and deserialization with custom type support."""
|
|
19
|
+
|
|
20
|
+
# Type codes for custom types
|
|
21
|
+
TYPE_DATETIME = 1
|
|
22
|
+
TYPE_CUSTOM_OBJECT = 2
|
|
23
|
+
TYPE_UUID = 3
|
|
24
|
+
TYPE_STRING_FALLBACK = 99 # Special code for string fallback representations
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def encode(obj: Any, fallback: bool = False) -> bytes:
|
|
28
|
+
"""
|
|
29
|
+
Serialize an object to bytes using msgpack.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
obj: The object to serialize
|
|
33
|
+
fallback: Whether to fallback to string representation for unsupported types
|
|
34
|
+
IMPORTANT: If True, may not roundtrip correctly
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
Serialized bytes
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
SerializationError: If serialization fails and fallback is False
|
|
41
|
+
"""
|
|
42
|
+
try:
|
|
43
|
+
return msgpack.packb(
|
|
44
|
+
obj,
|
|
45
|
+
default=lambda o: MsgPackSerializer._encode_hook(o, fallback),
|
|
46
|
+
use_bin_type=True
|
|
47
|
+
)
|
|
48
|
+
except Exception as e:
|
|
49
|
+
raise SerializationError(f"Failed to serialize object: {str(e)}")
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def decode(data: bytes) -> Any:
|
|
53
|
+
"""
|
|
54
|
+
Deserialize bytes back to an object.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
data: The serialized data
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
Deserialized object
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
SerializationError: If deserialization fails
|
|
64
|
+
"""
|
|
65
|
+
try:
|
|
66
|
+
return msgpack.unpackb(data, object_hook=MsgPackSerializer._decode_hook, raw=False)
|
|
67
|
+
except Exception as e:
|
|
68
|
+
raise SerializationError(f"Failed to deserialize data: {str(e)}")
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def _encode_hook(obj: Any, fallback: bool = False) -> Any:
|
|
72
|
+
"""
|
|
73
|
+
Custom encoder for handling Python types not natively supported by msgpack.
|
|
74
|
+
|
|
75
|
+
Note: When fallback is True, objects that can't be properly serialized
|
|
76
|
+
will be converted to a special string representation format that includes
|
|
77
|
+
the original type. These won't roundtrip to their original type.
|
|
78
|
+
"""
|
|
79
|
+
# Handle datetime objects - fully supported for roundtrip
|
|
80
|
+
if isinstance(obj, datetime.datetime):
|
|
81
|
+
return {
|
|
82
|
+
"__type_code": MsgPackSerializer.TYPE_DATETIME,
|
|
83
|
+
"data": obj.isoformat()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
# Handle UUID objects - fully supported for roundtrip
|
|
87
|
+
if isinstance(obj, uuid.UUID):
|
|
88
|
+
return {
|
|
89
|
+
"__type_code": MsgPackSerializer.TYPE_UUID,
|
|
90
|
+
"data": str(obj)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
# Explicitly handle functions (including lambdas)
|
|
94
|
+
if isinstance(obj, types.FunctionType):
|
|
95
|
+
if fallback:
|
|
96
|
+
return {
|
|
97
|
+
"__type_code": MsgPackSerializer.TYPE_STRING_FALLBACK,
|
|
98
|
+
"type": type(obj).__name__,
|
|
99
|
+
"data": str(obj)
|
|
100
|
+
}
|
|
101
|
+
else:
|
|
102
|
+
raise SerializationError(f"Functions of type {type(obj).__name__} are not serializable")
|
|
103
|
+
|
|
104
|
+
# Handle objects with __dict__
|
|
105
|
+
if hasattr(obj, "__dict__"):
|
|
106
|
+
try:
|
|
107
|
+
# Ensure the __dict__ is serializable
|
|
108
|
+
serializable_dict = {}
|
|
109
|
+
for key, value in obj.__dict__.items():
|
|
110
|
+
try:
|
|
111
|
+
# Test each value for serializability
|
|
112
|
+
msgpack.packb(
|
|
113
|
+
value,
|
|
114
|
+
default=lambda o: MsgPackSerializer._encode_hook(o, fallback=False),
|
|
115
|
+
use_bin_type=True
|
|
116
|
+
)
|
|
117
|
+
serializable_dict[key] = value
|
|
118
|
+
except Exception:
|
|
119
|
+
if fallback:
|
|
120
|
+
# If value can't be serialized, use string representation with type info
|
|
121
|
+
serializable_dict[key] = {
|
|
122
|
+
"__type_code": MsgPackSerializer.TYPE_STRING_FALLBACK,
|
|
123
|
+
"type": type(value).__name__,
|
|
124
|
+
"data": str(value)
|
|
125
|
+
}
|
|
126
|
+
else:
|
|
127
|
+
# Without fallback, propagate the exception
|
|
128
|
+
raise
|
|
129
|
+
|
|
130
|
+
return {
|
|
131
|
+
"__type_code": MsgPackSerializer.TYPE_CUSTOM_OBJECT,
|
|
132
|
+
"type": obj.__class__.__name__,
|
|
133
|
+
"module": obj.__class__.__module__,
|
|
134
|
+
"data": serializable_dict
|
|
135
|
+
}
|
|
136
|
+
except Exception as e:
|
|
137
|
+
if fallback:
|
|
138
|
+
return {
|
|
139
|
+
"__type_code": MsgPackSerializer.TYPE_STRING_FALLBACK,
|
|
140
|
+
"type": type(obj).__name__,
|
|
141
|
+
"data": str(obj)
|
|
142
|
+
}
|
|
143
|
+
raise SerializationError(f"Object of type {type(obj).__name__} is not serializable: {str(e)}")
|
|
144
|
+
|
|
145
|
+
# Handle objects with __slots__
|
|
146
|
+
if hasattr(obj, "__slots__"):
|
|
147
|
+
try:
|
|
148
|
+
slot_dict = {}
|
|
149
|
+
for slot in obj.__slots__:
|
|
150
|
+
if hasattr(obj, slot):
|
|
151
|
+
value = getattr(obj, slot)
|
|
152
|
+
try:
|
|
153
|
+
# Test each value for serializability
|
|
154
|
+
msgpack.packb(
|
|
155
|
+
value,
|
|
156
|
+
default=lambda o: MsgPackSerializer._encode_hook(o, fallback=False),
|
|
157
|
+
use_bin_type=True
|
|
158
|
+
)
|
|
159
|
+
slot_dict[slot] = value
|
|
160
|
+
except Exception:
|
|
161
|
+
if fallback:
|
|
162
|
+
# If value can't be serialized, use string representation with type info
|
|
163
|
+
slot_dict[slot] = {
|
|
164
|
+
"__type_code": MsgPackSerializer.TYPE_STRING_FALLBACK,
|
|
165
|
+
"type": type(value).__name__,
|
|
166
|
+
"data": str(value)
|
|
167
|
+
}
|
|
168
|
+
else:
|
|
169
|
+
# Without fallback, propagate the exception
|
|
170
|
+
raise
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
"__type_code": MsgPackSerializer.TYPE_CUSTOM_OBJECT,
|
|
174
|
+
"type": obj.__class__.__name__,
|
|
175
|
+
"module": obj.__class__.__module__,
|
|
176
|
+
"data": slot_dict
|
|
177
|
+
}
|
|
178
|
+
except Exception as e:
|
|
179
|
+
if fallback:
|
|
180
|
+
return {
|
|
181
|
+
"__type_code": MsgPackSerializer.TYPE_STRING_FALLBACK,
|
|
182
|
+
"type": type(obj).__name__,
|
|
183
|
+
"data": str(obj)
|
|
184
|
+
}
|
|
185
|
+
raise SerializationError(f"Object of type {type(obj).__name__} is not serializable: {str(e)}")
|
|
186
|
+
|
|
187
|
+
# As a last resort, if fallback is enabled, convert to string but preserve type info
|
|
188
|
+
if fallback:
|
|
189
|
+
return {
|
|
190
|
+
"__type_code": MsgPackSerializer.TYPE_STRING_FALLBACK,
|
|
191
|
+
"type": type(obj).__name__,
|
|
192
|
+
"data": str(obj)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
# If we reach here without returning and fallback is False, raise an error
|
|
196
|
+
raise SerializationError(f"Object of type {type(obj).__name__} is not serializable")
|
|
197
|
+
|
|
198
|
+
@staticmethod
|
|
199
|
+
def _decode_hook(obj: Dict[str, Any]) -> Any:
|
|
200
|
+
"""Custom decoder for handling Python types not natively supported by msgpack."""
|
|
201
|
+
# Only process dictionaries with a type code
|
|
202
|
+
if not isinstance(obj, dict) or "__type_code" not in obj:
|
|
203
|
+
return obj
|
|
204
|
+
|
|
205
|
+
type_code = obj["__type_code"]
|
|
206
|
+
|
|
207
|
+
# Handle datetime objects
|
|
208
|
+
if type_code == MsgPackSerializer.TYPE_DATETIME:
|
|
209
|
+
return datetime.datetime.fromisoformat(obj["data"])
|
|
210
|
+
|
|
211
|
+
# Handle UUID objects
|
|
212
|
+
if type_code == MsgPackSerializer.TYPE_UUID:
|
|
213
|
+
return uuid.UUID(obj["data"])
|
|
214
|
+
|
|
215
|
+
# Handle string fallback representations - return with clear type annotation
|
|
216
|
+
if type_code == MsgPackSerializer.TYPE_STRING_FALLBACK:
|
|
217
|
+
return {
|
|
218
|
+
"__serialized_string_of_type": obj["type"],
|
|
219
|
+
"value": obj["data"]
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
# Handle custom objects
|
|
223
|
+
if type_code == MsgPackSerializer.TYPE_CUSTOM_OBJECT:
|
|
224
|
+
return {
|
|
225
|
+
"__type": obj["type"],
|
|
226
|
+
"__module": obj["module"],
|
|
227
|
+
**obj["data"]
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return obj
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Async Task Worker
|
|
3
|
+
A robust asynchronous task worker system for Python applications.
|
|
4
|
+
"""
|
|
5
|
+
# Export cache adapter
|
|
6
|
+
from async_task_worker.adapters.cache_adapter import AsyncCacheAdapter
|
|
7
|
+
# Export main AsyncTaskWorker class
|
|
8
|
+
from async_task_worker.core import (
|
|
9
|
+
AsyncTaskWorker,
|
|
10
|
+
)
|
|
11
|
+
# Export error handling classes
|
|
12
|
+
from async_task_worker.exceptions import (
|
|
13
|
+
ErrorCategory,
|
|
14
|
+
TaskError,
|
|
15
|
+
TaskDefinitionError,
|
|
16
|
+
TaskExecutionError,
|
|
17
|
+
TaskTimeoutError,
|
|
18
|
+
TaskCancellationError,
|
|
19
|
+
ErrorHandler,
|
|
20
|
+
)
|
|
21
|
+
# Export task executor
|
|
22
|
+
from async_task_worker.executor import (
|
|
23
|
+
ProgressCallback,
|
|
24
|
+
TaskExecutor,
|
|
25
|
+
)
|
|
26
|
+
# Export task future functionality
|
|
27
|
+
from async_task_worker.futures import (
|
|
28
|
+
TaskFutureManager,
|
|
29
|
+
)
|
|
30
|
+
# Export WorkerPool and related types
|
|
31
|
+
from async_task_worker.pool import (
|
|
32
|
+
WorkerPool,
|
|
33
|
+
TaskStatusCallback,
|
|
34
|
+
)
|
|
35
|
+
# Export task queue
|
|
36
|
+
from async_task_worker.queue import (
|
|
37
|
+
TaskQueue,
|
|
38
|
+
QueueStats,
|
|
39
|
+
)
|
|
40
|
+
from async_task_worker.registry import (
|
|
41
|
+
task,
|
|
42
|
+
register_task,
|
|
43
|
+
get_task_function,
|
|
44
|
+
get_all_task_types,
|
|
45
|
+
)
|
|
46
|
+
# Export task status module
|
|
47
|
+
from async_task_worker.status import (
|
|
48
|
+
TaskStatus,
|
|
49
|
+
TaskInfo,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Define what gets imported with `from async_task_worker import *`
|
|
53
|
+
__all__ = [
|
|
54
|
+
# Main class
|
|
55
|
+
'AsyncTaskWorker',
|
|
56
|
+
|
|
57
|
+
# WorkerPool
|
|
58
|
+
'WorkerPool',
|
|
59
|
+
'TaskStatusCallback',
|
|
60
|
+
|
|
61
|
+
# Task status and info
|
|
62
|
+
'TaskInfo',
|
|
63
|
+
'TaskStatus',
|
|
64
|
+
|
|
65
|
+
# Task execution
|
|
66
|
+
'ProgressCallback',
|
|
67
|
+
'TaskExecutor',
|
|
68
|
+
|
|
69
|
+
# Task registration
|
|
70
|
+
'task',
|
|
71
|
+
'register_task',
|
|
72
|
+
'get_task_function',
|
|
73
|
+
'get_all_task_types',
|
|
74
|
+
|
|
75
|
+
# Caching
|
|
76
|
+
'AsyncCacheAdapter',
|
|
77
|
+
|
|
78
|
+
# Error handling
|
|
79
|
+
'ErrorCategory',
|
|
80
|
+
'TaskError',
|
|
81
|
+
'TaskDefinitionError',
|
|
82
|
+
'TaskExecutionError',
|
|
83
|
+
'TaskTimeoutError',
|
|
84
|
+
'TaskCancellationError',
|
|
85
|
+
'ErrorHandler',
|
|
86
|
+
|
|
87
|
+
# Futures
|
|
88
|
+
'TaskFutureManager',
|
|
89
|
+
|
|
90
|
+
# Queue
|
|
91
|
+
'TaskQueue',
|
|
92
|
+
'QueueStats',
|
|
93
|
+
]
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Cache adapter for AsyncTaskWorker to use async_cache.
|
|
3
|
+
|
|
4
|
+
Provides a clean integration between AsyncTaskWorker and AsyncCache.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from typing import Any, Dict, Tuple, Optional, Callable
|
|
9
|
+
|
|
10
|
+
from async_cache import AsyncCache
|
|
11
|
+
from async_cache.adapters import MemoryCacheAdapter
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AsyncCacheAdapter:
|
|
17
|
+
"""
|
|
18
|
+
Adapter that provides a bridge between AsyncTaskWorker and async_cache package.
|
|
19
|
+
|
|
20
|
+
This adapter translates between task-specific concepts in AsyncTaskWorker and
|
|
21
|
+
the more generic caching concepts in AsyncCache.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
default_ttl: Optional[int] = None,
|
|
27
|
+
enabled: bool = True,
|
|
28
|
+
max_serialized_size: int = 10 * 1024 * 1024,
|
|
29
|
+
validate_keys: bool = False,
|
|
30
|
+
cleanup_interval: int = 900,
|
|
31
|
+
max_size: Optional[int] = 1000
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Initialize the cache adapter.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
default_ttl: Default time-to-live in seconds (None for no expiry)
|
|
38
|
+
enabled: Whether caching is enabled by default
|
|
39
|
+
max_serialized_size: Maximum size in bytes for serialized objects
|
|
40
|
+
validate_keys: Whether to validate generated cache keys
|
|
41
|
+
cleanup_interval: Interval in seconds for automatic cleanup of stale mappings
|
|
42
|
+
max_size: Maximum number of items to store in memory cache (None for unlimited)
|
|
43
|
+
"""
|
|
44
|
+
# Create memory adapter
|
|
45
|
+
self._adapter = MemoryCacheAdapter(max_size=max_size)
|
|
46
|
+
|
|
47
|
+
# Create AsyncCache instance
|
|
48
|
+
self._cache = AsyncCache(
|
|
49
|
+
adapter=self._adapter,
|
|
50
|
+
default_ttl=default_ttl,
|
|
51
|
+
enabled=enabled,
|
|
52
|
+
max_serialized_size=max_serialized_size,
|
|
53
|
+
validate_keys=validate_keys,
|
|
54
|
+
cleanup_interval=cleanup_interval
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
async def start_cleanup_task(self) -> None:
|
|
58
|
+
"""Start the periodic cleanup task."""
|
|
59
|
+
await self._cache.start_cleanup_task()
|
|
60
|
+
|
|
61
|
+
async def stop_cleanup_task(self) -> None:
|
|
62
|
+
"""Stop the periodic cleanup task."""
|
|
63
|
+
await self._cache.stop_cleanup_task()
|
|
64
|
+
|
|
65
|
+
async def get(
|
|
66
|
+
self,
|
|
67
|
+
func_name: str,
|
|
68
|
+
args: tuple,
|
|
69
|
+
kwargs: dict,
|
|
70
|
+
cache_key_fn: Optional[Callable] = None,
|
|
71
|
+
task_id: Optional[str] = None,
|
|
72
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
73
|
+
) -> Tuple[bool, Any]:
|
|
74
|
+
"""
|
|
75
|
+
Get cached result for a task.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
func_name: Name of the task function
|
|
79
|
+
args: Positional arguments
|
|
80
|
+
kwargs: Keyword arguments
|
|
81
|
+
cache_key_fn: Optional custom key generation function
|
|
82
|
+
task_id: Optional task ID for reverse mapping
|
|
83
|
+
metadata: Optional metadata for custom key generation
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
Tuple of (cache_hit, result)
|
|
87
|
+
"""
|
|
88
|
+
# Map task_id to entry_id for async_cache
|
|
89
|
+
return await self._cache.get(
|
|
90
|
+
func_name, args, kwargs,
|
|
91
|
+
cache_key_fn=cache_key_fn,
|
|
92
|
+
entry_id=task_id,
|
|
93
|
+
metadata=metadata
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
async def set(
|
|
97
|
+
self,
|
|
98
|
+
func_name: str,
|
|
99
|
+
args: tuple,
|
|
100
|
+
kwargs: dict,
|
|
101
|
+
result: Any,
|
|
102
|
+
ttl: Optional[int] = None,
|
|
103
|
+
cache_key_fn: Optional[Callable] = None,
|
|
104
|
+
task_id: Optional[str] = None,
|
|
105
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
106
|
+
) -> bool:
|
|
107
|
+
"""
|
|
108
|
+
Store result in cache.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
func_name: Name of the task function
|
|
112
|
+
args: Positional arguments
|
|
113
|
+
kwargs: Keyword arguments
|
|
114
|
+
result: Result to cache
|
|
115
|
+
ttl: Time-to-live override (uses default if None)
|
|
116
|
+
cache_key_fn: Optional custom key generation function
|
|
117
|
+
task_id: Optional task ID for reverse mapping
|
|
118
|
+
metadata: Optional metadata for custom key generation
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
True if successfully cached, False otherwise
|
|
122
|
+
"""
|
|
123
|
+
# Map task_id to entry_id for async_cache
|
|
124
|
+
return await self._cache.set(
|
|
125
|
+
func_name, args, kwargs, result,
|
|
126
|
+
ttl=ttl,
|
|
127
|
+
cache_key_fn=cache_key_fn,
|
|
128
|
+
entry_id=task_id,
|
|
129
|
+
metadata=metadata
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
async def invalidate(
|
|
133
|
+
self,
|
|
134
|
+
func_name: str,
|
|
135
|
+
args: tuple,
|
|
136
|
+
kwargs: dict,
|
|
137
|
+
cache_key_fn: Optional[Callable] = None,
|
|
138
|
+
task_id: Optional[str] = None,
|
|
139
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
140
|
+
) -> bool:
|
|
141
|
+
"""
|
|
142
|
+
Invalidate a specific cache entry.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
func_name: Name of the task function
|
|
146
|
+
args: Positional arguments
|
|
147
|
+
kwargs: Keyword arguments
|
|
148
|
+
cache_key_fn: Optional custom key generation function
|
|
149
|
+
task_id: Optional task ID for lookup
|
|
150
|
+
metadata: Optional metadata for custom key generation
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
True if invalidated, False if not found
|
|
154
|
+
"""
|
|
155
|
+
return await self._cache.invalidate(
|
|
156
|
+
func_name, args, kwargs,
|
|
157
|
+
cache_key_fn=cache_key_fn,
|
|
158
|
+
entry_id=task_id,
|
|
159
|
+
metadata=metadata
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
async def invalidate_by_task_id(self, task_id: str) -> bool:
|
|
163
|
+
"""
|
|
164
|
+
Invalidate a cache entry using a task ID.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
task_id: Task ID associated with the cache entry
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
True if invalidated, False if not found
|
|
171
|
+
"""
|
|
172
|
+
return await self._cache.invalidate_by_id(task_id)
|
|
173
|
+
|
|
174
|
+
async def clear(self) -> None:
|
|
175
|
+
"""Clear all cached results."""
|
|
176
|
+
await self._cache.clear()
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def enabled(self) -> bool:
|
|
180
|
+
"""Get cache enabled status."""
|
|
181
|
+
return self._cache.enabled
|
|
182
|
+
|
|
183
|
+
@enabled.setter
|
|
184
|
+
def enabled(self, value: bool) -> None:
|
|
185
|
+
"""Set cache enabled status."""
|
|
186
|
+
self._cache.enabled = value
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def default_ttl(self) -> Optional[int]:
|
|
190
|
+
"""Get default TTL setting."""
|
|
191
|
+
return self._cache.default_ttl
|
|
192
|
+
|
|
193
|
+
@default_ttl.setter
|
|
194
|
+
def default_ttl(self, value: Optional[int]) -> None:
|
|
195
|
+
"""Set default TTL setting."""
|
|
196
|
+
self._cache.default_ttl = value
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def cleanup_interval(self) -> int:
|
|
200
|
+
"""Get cleanup interval setting."""
|
|
201
|
+
return self._cache.cleanup_interval
|
|
202
|
+
|
|
203
|
+
@cleanup_interval.setter
|
|
204
|
+
def cleanup_interval(self, value: int) -> None:
|
|
205
|
+
"""Set cleanup interval setting."""
|
|
206
|
+
self._cache.cleanup_interval = value
|