async-task-worker 0.4.2__tar.gz → 0.4.3__tar.gz
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_task_worker-0.4.3/CLAUDE.md +60 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/PKG-INFO +2 -2
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/pyproject.toml +3 -3
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/core.py +45 -19
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/executor.py +24 -12
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/pool.py +11 -8
- async_task_worker-0.4.3/uv.lock +416 -0
- async_task_worker-0.4.2/CLAUDE.md +0 -22
- async_task_worker-0.4.2/uv.lock +0 -416
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/.gitignore +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/LICENSE +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/README.md +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_cache/__init__.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_cache/adapters/__init__.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_cache/adapters/memory.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_cache/adapters/redis.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_cache/core.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_cache/exceptions.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_cache/key_utils.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_cache/serialization.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_events/__init__.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_events/event_manager.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_events/sse_client.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/__init__.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/adapters/__init__.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/adapters/cache_adapter.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/api.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/exceptions.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/futures.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/queue.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/registry.py +0 -0
- {async_task_worker-0.4.2 → async_task_worker-0.4.3}/src/async_task_worker/status.py +0 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
+
|
|
5
|
+
## Build and Test Commands
|
|
6
|
+
- Setup environment: `uv venv && source .venv/bin/activate && uv sync --all-groups`
|
|
7
|
+
- Build: `hatch build`
|
|
8
|
+
- Run tests: `pytest`
|
|
9
|
+
- Run single test: `pytest tests/test_file.py::test_function_name`
|
|
10
|
+
- Skip integration tests: `pytest -m "not integration"` (default)
|
|
11
|
+
- Run only asyncio tests: `pytest -m asyncio`
|
|
12
|
+
- Never perform git add. I manage git manually.
|
|
13
|
+
|
|
14
|
+
## Architecture Overview
|
|
15
|
+
|
|
16
|
+
This is a multi-package async task worker system with three main packages:
|
|
17
|
+
|
|
18
|
+
### Core Packages
|
|
19
|
+
1. **async_task_worker**: Main task execution and management system
|
|
20
|
+
- `AsyncTaskWorker`: Central coordinator integrating all components
|
|
21
|
+
- `WorkerPool`: Manages worker lifecycle and task execution processing
|
|
22
|
+
- `TaskQueue`: Priority-based task queuing and retrieval
|
|
23
|
+
- `TaskExecutor`: Individual task execution with timeout and caching
|
|
24
|
+
- `TaskRegistry`: Global registry for task handlers with `@task` decorator
|
|
25
|
+
- `AsyncCacheAdapter`: Integration with async_cache for result caching
|
|
26
|
+
|
|
27
|
+
2. **async_cache**: Flexible caching system with composable key generation
|
|
28
|
+
- `AsyncCache`: Core cache with TTL and LRU eviction
|
|
29
|
+
- `MemoryCacheAdapter`, `RedisCacheAdapter`: Storage backends
|
|
30
|
+
- Key composition with `compose_key_functions` and `extract_key_component`
|
|
31
|
+
- MsgPack serialization for efficient storage
|
|
32
|
+
|
|
33
|
+
3. **async_events**: Event management and SSE support
|
|
34
|
+
- `EventManager`: Pub/sub system with group-based filtering
|
|
35
|
+
- `SSEClient`: Server-sent events client for real-time updates
|
|
36
|
+
- Task state change events for reactive architectures
|
|
37
|
+
|
|
38
|
+
### Component Integration
|
|
39
|
+
- Tasks registered with `@task("task_type")` decorator go into global registry
|
|
40
|
+
- `AsyncTaskWorker` coordinates `WorkerPool`, `TaskQueue`, and `TaskExecutor`
|
|
41
|
+
- Optional caching via `AsyncCacheAdapter` wrapping `async_cache.AsyncCache`
|
|
42
|
+
- Event integration allows task state changes to publish events
|
|
43
|
+
- FastAPI router in `api.py` exposes REST endpoints for task management
|
|
44
|
+
|
|
45
|
+
### Key Patterns
|
|
46
|
+
- **Task Functions**: Must be async, can accept `progress_callback` parameter
|
|
47
|
+
- **Cache Key Generation**: Flexible, composable functions based on args/kwargs/metadata
|
|
48
|
+
- **Error Hierarchy**: Structured exceptions inheriting from `TaskError`
|
|
49
|
+
- **Resource Cleanup**: All async contexts use proper try/finally with cancellation handling
|
|
50
|
+
- **Worker Pool Architecture**: Decoupled design allowing independent scaling
|
|
51
|
+
|
|
52
|
+
## Code Style Guidelines
|
|
53
|
+
- Python 3.11+ with strict type annotations
|
|
54
|
+
- Imports: standard library first, third-party second, local modules third
|
|
55
|
+
- Error handling: Use structured hierarchy with `TaskError` base class
|
|
56
|
+
- Async patterns: Proper cancellation handling with try/finally and asyncio.timeout
|
|
57
|
+
- Naming: CamelCase for classes, snake_case for functions/methods, UPPER_SNAKE_CASE for constants
|
|
58
|
+
- Documentation: Docstrings with type annotations in code
|
|
59
|
+
- Testing: Use pytest fixtures with proper async teardown
|
|
60
|
+
- Clean code: maintain proper resource cleanup in all async contexts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: async-task-worker
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.3
|
|
4
4
|
Summary: Async Test Worker
|
|
5
5
|
Project-URL: Homepage, https://github.com/descoped/async-task-worker
|
|
6
6
|
Project-URL: Repository, https://github.com/descoped/async-task-worker
|
|
@@ -16,7 +16,7 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.13
|
|
17
17
|
Requires-Python: >=3.11
|
|
18
18
|
Requires-Dist: msgpack>=1.1.0
|
|
19
|
-
Requires-Dist: pydantic>=2.11.
|
|
19
|
+
Requires-Dist: pydantic>=2.11.5
|
|
20
20
|
Description-Content-Type: text/markdown
|
|
21
21
|
|
|
22
22
|
# Async Task Worker
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "async-task-worker"
|
|
3
|
-
version = "0.4.
|
|
3
|
+
version = "0.4.3"
|
|
4
4
|
description = "Async Test Worker"
|
|
5
5
|
authors = [
|
|
6
6
|
{ name = "Ove Ranheim", email = "oranheim@gmail.com" }
|
|
@@ -18,7 +18,7 @@ classifiers = [
|
|
|
18
18
|
]
|
|
19
19
|
dependencies = [
|
|
20
20
|
"msgpack>=1.1.0",
|
|
21
|
-
"pydantic>=2.11.
|
|
21
|
+
"pydantic>=2.11.5",
|
|
22
22
|
]
|
|
23
23
|
|
|
24
24
|
[dependency-groups]
|
|
@@ -26,7 +26,7 @@ dev = [
|
|
|
26
26
|
"httpx>=0.28.1",
|
|
27
27
|
"fastapi>=0.115.12",
|
|
28
28
|
"pyyaml>=6.0.2",
|
|
29
|
-
"redis>=
|
|
29
|
+
"redis>=6.1.0",
|
|
30
30
|
]
|
|
31
31
|
test = [
|
|
32
32
|
"pytest>=8.3.0",
|
|
@@ -267,23 +267,40 @@ class AsyncTaskWorker:
|
|
|
267
267
|
if cache_ttl is not None:
|
|
268
268
|
kwargs["cache_ttl"] = cache_ttl
|
|
269
269
|
|
|
270
|
-
# For caching,
|
|
271
|
-
#
|
|
272
|
-
if use_cache and self.cache.enabled
|
|
273
|
-
#
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
270
|
+
# For caching, we need to decide between normal caching (function+args based)
|
|
271
|
+
# and task-specific caching (task_id based for invalidation purposes)
|
|
272
|
+
if use_cache and self.cache.enabled:
|
|
273
|
+
# For normal caching, we should NOT include task_id in the cache key
|
|
274
|
+
# This allows tasks with same function and arguments to share cache entries
|
|
275
|
+
# Only use task_id for reverse mapping/invalidation purposes
|
|
276
|
+
if hasattr(self.cache, 'generate_entry_id'):
|
|
277
|
+
# We store the original task_id in metadata to keep track of it
|
|
278
|
+
if metadata is None:
|
|
279
|
+
metadata = {}
|
|
280
|
+
|
|
281
|
+
# Generate a composite entry ID for reverse mapping only
|
|
282
|
+
# This is used for cache invalidation by task_id
|
|
283
|
+
safe_task_id = str(task_id) if task_id is not None else None
|
|
284
|
+
entry_id = self.cache.generate_entry_id(task_func.__name__, safe_task_id)
|
|
285
|
+
|
|
286
|
+
# The task_id in kwargs is what's used for entry_id by the executor for reverse mapping
|
|
287
|
+
kwargs["_cache_entry_id"] = entry_id
|
|
288
|
+
|
|
289
|
+
logger.debug(f"Generated composite cache entry ID: {entry_id} for task {task_id}")
|
|
290
|
+
|
|
291
|
+
# For the actual cache key, use a function that only considers function name and arguments
|
|
292
|
+
# This ensures tasks with same function and args share cache entries regardless of task_id
|
|
293
|
+
from async_cache.key_utils import compose_key_functions, extract_key_component
|
|
294
|
+
|
|
295
|
+
# Create a cache key function that only uses function name and arguments
|
|
296
|
+
normal_cache_key_fn = compose_key_functions(
|
|
297
|
+
extract_key_component("func_name"),
|
|
298
|
+
extract_key_component("args"),
|
|
299
|
+
extract_key_component("kwargs")
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
# Store the normal cache key function for the executor to use
|
|
303
|
+
kwargs["_normal_cache_key_fn"] = normal_cache_key_fn
|
|
287
304
|
|
|
288
305
|
# Add to queue with priority - outside the lock
|
|
289
306
|
await self.queue.put(priority, task_id, task_func, args, kwargs, effective_timeout)
|
|
@@ -387,8 +404,17 @@ class AsyncTaskWorker:
|
|
|
387
404
|
if result:
|
|
388
405
|
return True
|
|
389
406
|
|
|
390
|
-
# Try regular invalidation
|
|
391
|
-
|
|
407
|
+
# Try regular invalidation using the same cache key function as caching
|
|
408
|
+
from async_cache.key_utils import compose_key_functions, extract_key_component
|
|
409
|
+
|
|
410
|
+
# Create the same cache key function that's used for caching
|
|
411
|
+
normal_cache_key_fn = compose_key_functions(
|
|
412
|
+
extract_key_component("func_name"),
|
|
413
|
+
extract_key_component("args"),
|
|
414
|
+
extract_key_component("kwargs")
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
result = await self.cache.invalidate(func_name, args, kwargs, cache_key_fn=normal_cache_key_fn)
|
|
392
418
|
if result:
|
|
393
419
|
return True
|
|
394
420
|
|
|
@@ -78,7 +78,8 @@ class TaskExecutor:
|
|
|
78
78
|
task_func: Callable[..., Awaitable[T]],
|
|
79
79
|
args: Tuple,
|
|
80
80
|
kwargs: Dict[str, Any],
|
|
81
|
-
timeout: Optional[float] = None
|
|
81
|
+
timeout: Optional[float] = None,
|
|
82
|
+
on_complete: Optional[Callable[[str, Any], Awaitable[None]]] = None
|
|
82
83
|
) -> T:
|
|
83
84
|
"""
|
|
84
85
|
Execute a task with timeout and error handling.
|
|
@@ -90,6 +91,7 @@ class TaskExecutor:
|
|
|
90
91
|
args: Positional arguments
|
|
91
92
|
kwargs: Keyword arguments
|
|
92
93
|
timeout: Optional timeout in seconds
|
|
94
|
+
on_complete: Optional callback for task completion (including cache hits)
|
|
93
95
|
|
|
94
96
|
Returns:
|
|
95
97
|
Task execution result
|
|
@@ -110,31 +112,35 @@ class TaskExecutor:
|
|
|
110
112
|
# Extract cache options from kwargs if present
|
|
111
113
|
use_cache: bool = kwargs.pop("use_cache", True)
|
|
112
114
|
cache_ttl: Optional[int] = kwargs.pop("cache_ttl", None)
|
|
115
|
+
normal_cache_key_fn = kwargs.pop("_normal_cache_key_fn", None)
|
|
113
116
|
|
|
114
117
|
# Remove special cache control parameters that should not be passed to task function
|
|
115
|
-
|
|
116
|
-
kwargs.pop("_cache_entry_id")
|
|
118
|
+
cache_entry_id = kwargs.pop("_cache_entry_id", task_id)
|
|
117
119
|
|
|
118
120
|
# Try to get from cache if caching is enabled
|
|
119
121
|
if use_cache and self.cache_manager and self.cache_manager.enabled:
|
|
120
122
|
try:
|
|
121
123
|
func_name = task_func.__name__
|
|
122
|
-
#
|
|
123
|
-
|
|
124
|
-
function_kwargs = kwargs.copy()
|
|
125
|
-
cache_entry_id = function_kwargs.pop("_cache_entry_id", task_id)
|
|
126
|
-
cache_kwargs = {k: v for k, v in function_kwargs.items()
|
|
124
|
+
# Prepare cache kwargs - exclude progress_callback for cache key
|
|
125
|
+
cache_kwargs = {k: v for k, v in kwargs.items()
|
|
127
126
|
if k != "progress_callback"}
|
|
128
127
|
|
|
129
128
|
cache_hit, cached_result = await self.cache_manager.get(
|
|
130
129
|
func_name,
|
|
131
130
|
args,
|
|
132
131
|
cache_kwargs,
|
|
132
|
+
cache_key_fn=normal_cache_key_fn,
|
|
133
133
|
task_id=cache_entry_id
|
|
134
134
|
)
|
|
135
135
|
|
|
136
136
|
if cache_hit:
|
|
137
137
|
logger.info(f"Task {task_id} using cached result")
|
|
138
|
+
# Trigger completion callback for cache hits
|
|
139
|
+
if on_complete:
|
|
140
|
+
try:
|
|
141
|
+
await on_complete(task_id, cached_result)
|
|
142
|
+
except Exception as callback_error:
|
|
143
|
+
logger.error(f"Error in completion callback for cached task {task_id}: {str(callback_error)}")
|
|
138
144
|
return cached_result
|
|
139
145
|
except Exception as e:
|
|
140
146
|
error_msg = f"Cache retrieval error for task {task_id}: {str(e)}"
|
|
@@ -195,10 +201,8 @@ class TaskExecutor:
|
|
|
195
201
|
try:
|
|
196
202
|
func_name = task_func.__name__
|
|
197
203
|
|
|
198
|
-
#
|
|
199
|
-
|
|
200
|
-
cache_entry_id = function_kwargs.pop("_cache_entry_id", task_id)
|
|
201
|
-
cache_kwargs = {k: v for k, v in function_kwargs.items()
|
|
204
|
+
# Prepare cache kwargs - exclude progress_callback for cache key
|
|
205
|
+
cache_kwargs = {k: v for k, v in kwargs.items()
|
|
202
206
|
if k != "progress_callback"}
|
|
203
207
|
|
|
204
208
|
await self.cache_manager.set(
|
|
@@ -207,6 +211,7 @@ class TaskExecutor:
|
|
|
207
211
|
cache_kwargs,
|
|
208
212
|
result,
|
|
209
213
|
ttl=cache_ttl,
|
|
214
|
+
cache_key_fn=normal_cache_key_fn,
|
|
210
215
|
task_id=cache_entry_id
|
|
211
216
|
)
|
|
212
217
|
except Exception as e:
|
|
@@ -225,6 +230,13 @@ class TaskExecutor:
|
|
|
225
230
|
execution_time = time.time() - start_time
|
|
226
231
|
logger.info(f"Task {task_id} completed successfully in {execution_time:.3f}s")
|
|
227
232
|
|
|
233
|
+
# Trigger completion callback for non-cached results
|
|
234
|
+
if on_complete:
|
|
235
|
+
try:
|
|
236
|
+
await on_complete(task_id, result)
|
|
237
|
+
except Exception as callback_error:
|
|
238
|
+
logger.error(f"Error in completion callback for task {task_id}: {str(callback_error)}")
|
|
239
|
+
|
|
228
240
|
return result
|
|
229
241
|
|
|
230
242
|
except TimeoutError:
|
|
@@ -240,10 +240,18 @@ class WorkerPool:
|
|
|
240
240
|
except Exception as e:
|
|
241
241
|
logger.error(f"Error in task start callback for {task_id}: {str(e)}")
|
|
242
242
|
|
|
243
|
+
# Create completion callback that will be called for both cached and non-cached results
|
|
244
|
+
async def completion_callback(completed_task_id: str, task_result: Any) -> None:
|
|
245
|
+
if self.on_task_complete:
|
|
246
|
+
try:
|
|
247
|
+
await self.on_task_complete(completed_task_id, task_info, task_result)
|
|
248
|
+
except Exception as ex:
|
|
249
|
+
logger.error(f"Error in task complete callback for {completed_task_id}: {str(ex)}")
|
|
250
|
+
|
|
243
251
|
# Execute the task
|
|
244
252
|
execution_task = asyncio.create_task(
|
|
245
253
|
self.task_executor.execute_task(
|
|
246
|
-
task_id, None, task_func, task_args, task_kwargs, timeout
|
|
254
|
+
task_id, None, task_func, task_args, task_kwargs, timeout, completion_callback
|
|
247
255
|
)
|
|
248
256
|
)
|
|
249
257
|
execution_task.set_name(f"exec_{task_id}")
|
|
@@ -254,14 +262,9 @@ class WorkerPool:
|
|
|
254
262
|
self._task_to_worker[task_id] = execution_task
|
|
255
263
|
|
|
256
264
|
try:
|
|
265
|
+
# noinspection PyUnusedLocal
|
|
257
266
|
result = await execution_task
|
|
258
|
-
|
|
259
|
-
# Notify task completed
|
|
260
|
-
if self.on_task_complete:
|
|
261
|
-
try:
|
|
262
|
-
await self.on_task_complete(task_id, task_info, result)
|
|
263
|
-
except Exception as e:
|
|
264
|
-
logger.error(f"Error in task complete callback for {task_id}: {str(e)}")
|
|
267
|
+
# Note: completion callback is now handled inside the executor for both cached and non-cached results
|
|
265
268
|
|
|
266
269
|
except asyncio.CancelledError:
|
|
267
270
|
logger.info(f"Task {task_id} execution cancelled")
|