async-task-worker 0.1.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,9 @@
1
+ src/async_task_worker/__init__.py,sha256=0hY8Qc88MKq__AGZHrg4o48UjAZy3Zv3-ztvw9msRx8,814
2
+ src/async_task_worker/task_cache.py,sha256=DOdY_0mqHf5_6tfaAJ_r9B9UruUnNls1YVxJ20SZAjs,7680
3
+ src/async_task_worker/task_registry.py,sha256=xXK8Rch8a2xqkhAZCJBWZ-MK8fcN2UY-p32rsUK_5aw,2101
4
+ src/async_task_worker/task_worker.py,sha256=pgr_BrXN0rq9r2dsyZo3K8wHK6C1SnWnQHs_LzKoHzY,23137
5
+ src/async_task_worker/task_worker_api.py,sha256=sFYC46pfWFILV0-Ob-39IfVvWEXl661nWt93lVi7CNM,7978
6
+ async_task_worker-0.1.0.dist-info/METADATA,sha256=Q0ULaFr_z8Bgqq2hs3qT8bftMHg075a5mLTSaIEW5w4,24213
7
+ async_task_worker-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
8
+ async_task_worker-0.1.0.dist-info/licenses/LICENSE,sha256=ReuYWxqSV34yoz01y9AGKlYpFlZDkeL2df9pdjE2Hkg,1065
9
+ async_task_worker-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Descoped
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,38 @@
1
+ """
2
+ Async Task Worker
3
+ A robust asynchronous task worker system for Python applications.
4
+ """
5
+ # Export cache-related classes
6
+ from async_task_worker.task_cache import (
7
+ CacheAdapter,
8
+ MemoryCacheAdapter,
9
+ TaskCache,
10
+ )
11
+ from async_task_worker.task_registry import (
12
+ task,
13
+ register_task,
14
+ get_task_function,
15
+ get_all_task_types,
16
+ )
17
+ # Export main classes and functions
18
+ from async_task_worker.task_worker import (
19
+ AsyncTaskWorker,
20
+ TaskInfo,
21
+ TaskStatus,
22
+ ProgressCallback,
23
+ )
24
+
25
+ # Define what gets imported with `from async_task_worker import *`
26
+ __all__ = [
27
+ 'AsyncTaskWorker',
28
+ 'TaskInfo',
29
+ 'TaskStatus',
30
+ 'ProgressCallback',
31
+ 'task',
32
+ 'register_task',
33
+ 'get_task_function',
34
+ 'get_all_task_types',
35
+ 'CacheAdapter',
36
+ 'MemoryCacheAdapter',
37
+ 'TaskCache',
38
+ ]
@@ -0,0 +1,262 @@
1
+ """
2
+ Task Cache System
3
+
4
+ This module provides caching functionality for the AsyncTaskWorker
5
+ to store and retrieve task results.
6
+ """
7
+
8
+ import hashlib
9
+ import json
10
+ import logging
11
+ import pickle
12
+ import time
13
+ from abc import ABC, abstractmethod
14
+ from typing import Any, Dict, Optional, Tuple
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class CacheAdapter(ABC):
20
+ """
21
+ Abstract base class for cache adapters.
22
+ Implementations should provide concrete storage mechanisms.
23
+ """
24
+
25
+ @abstractmethod
26
+ async def get(self, key: str) -> Tuple[bool, Any]:
27
+ """
28
+ Get a value from the cache.
29
+
30
+ Args:
31
+ key: The cache key
32
+
33
+ Returns:
34
+ Tuple of (hit, value) where hit is True if item was in cache
35
+ """
36
+ pass
37
+
38
+ @abstractmethod
39
+ async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
40
+ """
41
+ Set a value in the cache.
42
+
43
+ Args:
44
+ key: The cache key
45
+ value: The value to store
46
+ ttl: Optional time-to-live in seconds
47
+ """
48
+ pass
49
+
50
+ @abstractmethod
51
+ async def delete(self, key: str) -> bool:
52
+ """
53
+ Delete a value from the cache.
54
+
55
+ Args:
56
+ key: The cache key
57
+
58
+ Returns:
59
+ True if deleted, False if not found
60
+ """
61
+ pass
62
+
63
+ @abstractmethod
64
+ async def clear(self) -> None:
65
+ """Clear all items from the cache."""
66
+ pass
67
+
68
+
69
+ class MemoryCacheAdapter(CacheAdapter):
70
+ """
71
+ Simple in-memory cache adapter.
72
+ Supports TTL and max size eviction policies.
73
+ """
74
+
75
+ def __init__(self, max_size: Optional[int] = 1000):
76
+ """
77
+ Initialize memory cache.
78
+
79
+ Args:
80
+ max_size: Maximum number of items to store (None for unlimited)
81
+ """
82
+ self._cache: Dict[str, Tuple[Any, Optional[float]]] = {} # key -> (value, expiry)
83
+ self._access_times: Dict[str, float] = {} # key -> last access timestamp
84
+ self.max_size = max_size
85
+
86
+ async def get(self, key: str) -> Tuple[bool, Any]:
87
+ """Get a value from the cache with TTL support."""
88
+ if key not in self._cache:
89
+ return False, None
90
+
91
+ value, expiry = self._cache[key]
92
+ current_time = time.time()
93
+
94
+ # Update access time for LRU to current timestamp
95
+ self._access_times[key] = current_time
96
+
97
+ # Check if expired
98
+ if expiry is not None and current_time > expiry:
99
+ # Remove expired item
100
+ del self._cache[key]
101
+ del self._access_times[key]
102
+ return False, None
103
+
104
+ return True, value
105
+
106
+ async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
107
+ """Set a value in the cache with TTL support."""
108
+ # Calculate expiry time if TTL provided
109
+ expiry = None
110
+ if ttl is not None:
111
+ expiry = time.time() + ttl
112
+
113
+ # Evict if at max capacity and adding a new key
114
+ if self.max_size is not None and len(self._cache) >= self.max_size and key not in self._cache:
115
+ self._evict_one()
116
+
117
+ # Store value and update access time to current timestamp
118
+ self._cache[key] = (value, expiry)
119
+ self._access_times[key] = time.time()
120
+
121
+ async def delete(self, key: str) -> bool:
122
+ """Delete a value from the cache."""
123
+ if key in self._cache:
124
+ del self._cache[key]
125
+ del self._access_times[key]
126
+ return True
127
+ return False
128
+
129
+ async def clear(self) -> None:
130
+ """Clear all items from the cache."""
131
+ self._cache.clear()
132
+ self._access_times.clear()
133
+
134
+ def _evict_one(self) -> None:
135
+ """Evict the least recently used item from the cache."""
136
+ if not self._access_times:
137
+ return
138
+
139
+ # Find oldest accessed key (lowest timestamp value)
140
+ oldest_key = min(self._access_times.items(), key=lambda x: x[1])[0]
141
+
142
+ # Remove from cache
143
+ del self._cache[oldest_key]
144
+ del self._access_times[oldest_key]
145
+ logger.debug(f"Evicted cache item: {oldest_key}")
146
+
147
+
148
+ class TaskCache:
149
+ """
150
+ Task cache manager for AsyncTaskWorker.
151
+ Handles cache key generation and serialization.
152
+ """
153
+
154
+ def __init__(
155
+ self,
156
+ adapter: CacheAdapter,
157
+ default_ttl: Optional[int] = None,
158
+ enabled: bool = True
159
+ ):
160
+ """
161
+ Initialize the task cache.
162
+
163
+ Args:
164
+ adapter: Cache adapter implementation
165
+ default_ttl: Default time-to-live in seconds (None for no expiry)
166
+ enabled: Whether caching is enabled by default
167
+ """
168
+ self.adapter = adapter
169
+ self.default_ttl = default_ttl
170
+ self.enabled = enabled
171
+
172
+ @staticmethod
173
+ def generate_key(func_name: str, args: tuple, kwargs: dict) -> str:
174
+ """
175
+ Generate a cache key from function name and arguments.
176
+
177
+ Args:
178
+ func_name: Name of the task function
179
+ args: Positional arguments
180
+ kwargs: Keyword arguments
181
+
182
+ Returns:
183
+ Cache key string
184
+ """
185
+ # Serialize arguments
186
+ try:
187
+ # Try JSON first for better readability and performance
188
+ key_parts = [func_name, json.dumps(args), json.dumps(kwargs, sort_keys=True)]
189
+ key_string = ":".join(key_parts)
190
+ except (TypeError, ValueError):
191
+ # Fall back to pickle for non-JSON-serializable objects
192
+ try:
193
+ pickled = pickle.dumps((args, kwargs))
194
+ key_string = f"{func_name}:{hashlib.md5(pickled).hexdigest()}"
195
+ except Exception:
196
+ # Last resort - use string representation
197
+ key_string = f"{func_name}:{str(args)}:{str(sorted(kwargs.items()))}"
198
+
199
+ # Create a hash for the final key
200
+ return hashlib.md5(key_string.encode()).hexdigest()
201
+
202
+ async def get(self, func_name: str, args: tuple, kwargs: dict) -> Tuple[bool, Any]:
203
+ """
204
+ Get cached result for a task.
205
+
206
+ Args:
207
+ func_name: Name of the task function
208
+ args: Positional arguments
209
+ kwargs: Keyword arguments
210
+
211
+ Returns:
212
+ Tuple of (cache_hit, result)
213
+ """
214
+ if not self.enabled:
215
+ return False, None
216
+
217
+ key = self.generate_key(func_name, args, kwargs)
218
+ return await self.adapter.get(key)
219
+
220
+ async def set(
221
+ self,
222
+ func_name: str,
223
+ args: tuple,
224
+ kwargs: dict,
225
+ result: Any,
226
+ ttl: Optional[int] = None
227
+ ) -> None:
228
+ """
229
+ Store result in cache.
230
+
231
+ Args:
232
+ func_name: Name of the task function
233
+ args: Positional arguments
234
+ kwargs: Keyword arguments
235
+ result: Result to cache
236
+ ttl: Time-to-live override (uses default if None)
237
+ """
238
+ if not self.enabled:
239
+ return
240
+
241
+ key = self.generate_key(func_name, args, kwargs)
242
+ effective_ttl = ttl if ttl is not None else self.default_ttl
243
+ await self.adapter.set(key, result, effective_ttl)
244
+
245
+ async def invalidate(self, func_name: str, args: tuple, kwargs: dict) -> bool:
246
+ """
247
+ Invalidate a specific cache entry.
248
+
249
+ Args:
250
+ func_name: Name of the task function
251
+ args: Positional arguments
252
+ kwargs: Keyword arguments
253
+
254
+ Returns:
255
+ True if invalidated, False if not found
256
+ """
257
+ key = self.generate_key(func_name, args, kwargs)
258
+ return await self.adapter.delete(key)
259
+
260
+ async def clear(self) -> None:
261
+ """Clear all cached results."""
262
+ await self.adapter.clear()
@@ -0,0 +1,83 @@
1
+ """
2
+ Task Registry System
3
+
4
+ This module provides a task registration system with manual registration.
5
+ """
6
+
7
+ import inspect
8
+ import logging
9
+ from functools import wraps
10
+ from typing import Any, Awaitable, Callable, Dict, List, Optional
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Type definitions
15
+ TaskFunc = Callable[..., Awaitable[Any]]
16
+
17
+ # Global task registry
18
+ _TASK_REGISTRY: Dict[str, TaskFunc] = {}
19
+
20
+
21
+ def task(task_type: str) -> Callable[[TaskFunc], TaskFunc]:
22
+ """
23
+ Decorator to register a function as a task handler.
24
+
25
+ Example:
26
+ @task("process_data")
27
+ async def process_data_task(data: dict, config: dict) -> dict:
28
+ # Process data
29
+ return result
30
+ """
31
+
32
+ def decorator(func: TaskFunc) -> TaskFunc:
33
+ register_task(task_type, func)
34
+
35
+ @wraps(func)
36
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
37
+ return await func(*args, **kwargs)
38
+
39
+ return wrapper
40
+
41
+ return decorator
42
+
43
+
44
+ def register_task(task_type: str, task_func: TaskFunc) -> None:
45
+ """
46
+ Register a task function for a specific task type.
47
+
48
+ Args:
49
+ task_type: Unique identifier for the task type
50
+ task_func: Async function that implements the task
51
+ """
52
+ if task_type in _TASK_REGISTRY:
53
+ logger.warning(f"Overriding existing task handler for {task_type}")
54
+
55
+ # Ensure task_func is an async function
56
+ if not inspect.iscoroutinefunction(task_func):
57
+ raise TypeError(f"Task function for {task_type} must be an async function")
58
+
59
+ _TASK_REGISTRY[task_type] = task_func
60
+ logger.info(f"Registered task handler for {task_type}")
61
+
62
+
63
+ def get_task_function(task_type: str) -> Optional[TaskFunc]:
64
+ """
65
+ Get the task function for a specific task type.
66
+
67
+ Args:
68
+ task_type: The task type to look up
69
+
70
+ Returns:
71
+ The task function or None if not found
72
+ """
73
+ return _TASK_REGISTRY.get(task_type)
74
+
75
+
76
+ def get_all_task_types() -> List[str]:
77
+ """
78
+ Get a list of all registered task types.
79
+
80
+ Returns:
81
+ List of registered task type names
82
+ """
83
+ return list(_TASK_REGISTRY.keys())