async-task-worker 0.5.0__tar.gz → 0.5.1__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.5.0 → async_task_worker-0.5.1}/PKG-INFO +662 -458
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/README.md +660 -456
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/pyproject.toml +2 -2
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_cache/key_utils.py +2 -2
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/adapters/cache_adapter.py +4 -3
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/core.py +44 -45
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/executor.py +12 -1
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/pool.py +18 -3
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/uv.lock +1 -1
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/.coveragerc +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/.gitignore +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/LICENSE +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_cache/__init__.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_cache/adapters/__init__.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_cache/adapters/memory.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_cache/adapters/redis.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_cache/core.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_cache/exceptions.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_cache/serialization.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_events/__init__.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_events/event_manager.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_events/sse_client.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/__init__.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/adapters/__init__.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/api.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/exceptions.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/futures.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/queue.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/registry.py +0 -0
- {async_task_worker-0.5.0 → async_task_worker-0.5.1}/src/async_task_worker/status.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: async-task-worker
|
|
3
|
-
Version: 0.5.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 0.5.1
|
|
4
|
+
Summary: Asyncio task worker with priority queueing, progress tracking, result caching, events and a FastAPI router
|
|
5
5
|
Project-URL: Homepage, https://github.com/descoped/async-task-worker
|
|
6
6
|
Project-URL: Repository, https://github.com/descoped/async-task-worker
|
|
7
7
|
Project-URL: Issues, https://github.com/descoped/async-task-worker/issues
|
|
@@ -46,6 +46,8 @@ A robust asynchronous task worker system for Python applications with built-in c
|
|
|
46
46
|
|
|
47
47
|
```bash
|
|
48
48
|
pip install async-task-worker
|
|
49
|
+
# or
|
|
50
|
+
uv add async-task-worker
|
|
49
51
|
```
|
|
50
52
|
|
|
51
53
|
Optional features are installed as extras:
|
|
@@ -61,7 +63,7 @@ Optional features are installed as extras:
|
|
|
61
63
|
pip install "async-task-worker[all]"
|
|
62
64
|
```
|
|
63
65
|
|
|
64
|
-
Requires Python 3.11 or newer (
|
|
66
|
+
Requires Python 3.11 or newer (supports 3.11 to 3.15).
|
|
65
67
|
|
|
66
68
|
## Features
|
|
67
69
|
|
|
@@ -100,7 +102,7 @@ The system follows a modular, decoupled design:
|
|
|
100
102
|
2. **WorkerPool**: Handles worker lifecycle and task execution processing
|
|
101
103
|
3. **TaskQueue**: Manages prioritized task queuing and retrieval
|
|
102
104
|
4. **TaskExecutor**: Executes individual tasks with timeout and caching
|
|
103
|
-
5. **
|
|
105
|
+
5. **Task registry** (`async_task_worker.registry`): Module-level functions (`task`, `register_task`, `get_task_function`, `get_all_task_types`) over one global registry of task handlers
|
|
104
106
|
6. **AsyncCacheAdapter**: Provides integration with the async_cache package for efficient result caching
|
|
105
107
|
|
|
106
108
|
The workflow proceeds as follows:
|
|
@@ -109,7 +111,7 @@ The workflow proceeds as follows:
|
|
|
109
111
|
2. Worker coroutines from the `WorkerPool` pick tasks from the queue based on priority
|
|
110
112
|
3. The `TaskExecutor` executes the task function and captures results or errors
|
|
111
113
|
4. Task status and progress are tracked in a `TaskInfo` object maintained by the `AsyncTaskWorker`
|
|
112
|
-
5. Progress updates
|
|
114
|
+
5. Progress reported through the task's `progress_callback` updates `TaskInfo.progress` while the task runs
|
|
113
115
|
6. Results can optionally be cached for future reuse
|
|
114
116
|
|
|
115
117
|
```python
|
|
@@ -178,7 +180,7 @@ async def main():
|
|
|
178
180
|
|
|
179
181
|
# Monitor task progress
|
|
180
182
|
while True:
|
|
181
|
-
info = worker.get_task_info(task_id)
|
|
183
|
+
info = await worker.get_task_info(task_id)
|
|
182
184
|
print(f"Progress: {info.progress * 100:.1f}%")
|
|
183
185
|
|
|
184
186
|
if info.status not in ("pending", "running"):
|
|
@@ -187,7 +189,7 @@ async def main():
|
|
|
187
189
|
await asyncio.sleep(0.5)
|
|
188
190
|
|
|
189
191
|
# Get task result
|
|
190
|
-
info = worker.get_task_info(task_id)
|
|
192
|
+
info = await worker.get_task_info(task_id)
|
|
191
193
|
if info.status == "completed":
|
|
192
194
|
print(f"Result: {info.result}")
|
|
193
195
|
else:
|
|
@@ -216,19 +218,27 @@ There are two ways to work with tasks:
|
|
|
216
218
|
##### Method 1: Direct Function References
|
|
217
219
|
|
|
218
220
|
```python
|
|
221
|
+
from async_task_worker import task
|
|
222
|
+
|
|
223
|
+
|
|
219
224
|
# Define and register a task
|
|
220
225
|
@task("process_data")
|
|
221
226
|
async def process_data(data, progress_callback=None):
|
|
222
227
|
# Task implementation
|
|
223
228
|
return result
|
|
224
229
|
|
|
225
|
-
|
|
226
|
-
|
|
230
|
+
|
|
231
|
+
async def submit(worker, data):
|
|
232
|
+
# Execute by passing the function directly
|
|
233
|
+
task_id = await worker.add_task(process_data, data)
|
|
227
234
|
```
|
|
228
235
|
|
|
229
236
|
##### Method 2: Task Type References
|
|
230
237
|
|
|
231
238
|
```python
|
|
239
|
+
from async_task_worker import get_task_function, task
|
|
240
|
+
|
|
241
|
+
|
|
232
242
|
# Define and register a task
|
|
233
243
|
@task("process_data")
|
|
234
244
|
async def process_data(data, progress_callback=None):
|
|
@@ -236,13 +246,12 @@ async def process_data(data, progress_callback=None):
|
|
|
236
246
|
return result
|
|
237
247
|
|
|
238
248
|
|
|
239
|
-
|
|
240
|
-
from
|
|
241
|
-
|
|
242
|
-
task_func = get_task_function("process_data")
|
|
249
|
+
async def submit(worker, data):
|
|
250
|
+
# Get the function from the registry by task type name (a coroutine)
|
|
251
|
+
task_func = await get_task_function("process_data")
|
|
243
252
|
|
|
244
|
-
# Execute the task
|
|
245
|
-
|
|
253
|
+
# Execute the task
|
|
254
|
+
return await worker.add_task(task_func, data)
|
|
246
255
|
```
|
|
247
256
|
|
|
248
257
|
The second method is particularly useful when:
|
|
@@ -265,8 +274,10 @@ async def process_data_task(data):
|
|
|
265
274
|
return {"processed": True}
|
|
266
275
|
|
|
267
276
|
|
|
268
|
-
|
|
269
|
-
|
|
277
|
+
async def lookup():
|
|
278
|
+
# Get a registered task function (the registry lookups are coroutines)
|
|
279
|
+
task_func = await get_task_function("process_data")
|
|
280
|
+
return task_func
|
|
270
281
|
```
|
|
271
282
|
|
|
272
283
|
### Task Functions and Progress Reporting
|
|
@@ -299,6 +310,8 @@ async def process_items(items, progress_callback=None):
|
|
|
299
310
|
The `AsyncTaskWorker` class manages all aspects of task execution:
|
|
300
311
|
|
|
301
312
|
```python
|
|
313
|
+
from async_task_worker import AsyncTaskWorker
|
|
314
|
+
|
|
302
315
|
worker = AsyncTaskWorker(
|
|
303
316
|
max_workers=10, # Maximum number of concurrent tasks
|
|
304
317
|
task_timeout=None, # Default timeout for tasks in seconds (None = no timeout)
|
|
@@ -306,10 +319,17 @@ worker = AsyncTaskWorker(
|
|
|
306
319
|
cache_enabled=False, # Whether to enable result caching
|
|
307
320
|
cache_ttl=3600, # Default cache TTL in seconds (1 hour)
|
|
308
321
|
cache_max_size=1000, # Maximum cache entries (LRU eviction)
|
|
309
|
-
cache_adapter=None
|
|
322
|
+
cache_adapter=None, # Custom cache adapter (defaults to an in-memory AsyncCacheAdapter)
|
|
323
|
+
cache_cleanup_interval=900, # Seconds between cleanups of stale cache entry mappings (0 = disabled)
|
|
324
|
+
max_queue_size=None, # Maximum number of queued tasks (None = unbounded)
|
|
325
|
+
task_retention_days=7, # Days to keep finished tasks (None = keep forever)
|
|
326
|
+
cleanup_interval=3600 # Seconds between cleanups of old finished tasks
|
|
310
327
|
)
|
|
311
328
|
```
|
|
312
329
|
|
|
330
|
+
When you pass `cache_adapter`, the `cache_enabled`, `cache_ttl`, `cache_max_size` and `cache_cleanup_interval`
|
|
331
|
+
arguments are not applied to it: the adapter's own `enabled`, `default_ttl`, `max_size` and `cleanup_interval` count.
|
|
332
|
+
|
|
313
333
|
#### Task Registration
|
|
314
334
|
|
|
315
335
|
The `@task` decorator registers a function in the global task registry:
|
|
@@ -368,21 +388,22 @@ When you add a task to the worker:
|
|
|
368
388
|
5. When complete, you can access the result or error
|
|
369
389
|
|
|
370
390
|
```python
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
391
|
+
async def run(worker):
|
|
392
|
+
# Add a task
|
|
393
|
+
task_id = await worker.add_task(
|
|
394
|
+
process_items, # Task function
|
|
395
|
+
["item1", "item2", "item3"], # Args
|
|
396
|
+
priority=1, # Lower number = higher priority
|
|
397
|
+
metadata={"description": "Processing batch"} # Optional metadata
|
|
398
|
+
)
|
|
378
399
|
|
|
379
|
-
# Check status
|
|
380
|
-
task_info = worker.get_task_info(task_id)
|
|
381
|
-
print(f"Status: {task_info.status}, Progress: {task_info.progress:.0%}")
|
|
400
|
+
# Check status
|
|
401
|
+
task_info = await worker.get_task_info(task_id)
|
|
402
|
+
print(f"Status: {task_info.status}, Progress: {task_info.progress:.0%}")
|
|
382
403
|
|
|
383
|
-
# Get result when complete
|
|
384
|
-
if task_info.status == "completed":
|
|
385
|
-
|
|
404
|
+
# Get result when complete
|
|
405
|
+
if task_info.status == "completed":
|
|
406
|
+
result = task_info.result
|
|
386
407
|
```
|
|
387
408
|
|
|
388
409
|
### Task Management
|
|
@@ -390,63 +411,69 @@ if task_info.status == "completed":
|
|
|
390
411
|
#### Adding Tasks
|
|
391
412
|
|
|
392
413
|
```python
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
414
|
+
async def add_tasks(worker, my_task, arg1, arg2, val1, val2):
|
|
415
|
+
# Basic usage
|
|
416
|
+
task_id = await worker.add_task(my_task, arg1, arg2)
|
|
417
|
+
|
|
418
|
+
# With all options
|
|
419
|
+
task_id = await worker.add_task(
|
|
420
|
+
my_task, # Task function or await get_task_function("task_type")
|
|
421
|
+
arg1, arg2, # Positional arguments passed to task
|
|
422
|
+
kw1=val1, kw2=val2, # Keyword arguments passed to task
|
|
423
|
+
priority=0, # Task priority (lower number = higher priority)
|
|
424
|
+
task_id="custom-id", # Custom task ID (default: auto-generated UUID)
|
|
425
|
+
metadata={"key": "value"}, # Custom metadata to store with task
|
|
426
|
+
timeout=30, # Task-specific timeout in seconds
|
|
427
|
+
use_cache=True, # Whether to use cache for this task
|
|
428
|
+
cache_ttl=60, # Custom TTL for this task's cache entry
|
|
429
|
+
cache_key_fn=None # Custom cache key function (default: function name and arguments)
|
|
430
|
+
)
|
|
408
431
|
```
|
|
409
432
|
|
|
410
433
|
#### Tracking Tasks
|
|
411
434
|
|
|
412
435
|
```python
|
|
413
|
-
# Get information about a specific task
|
|
414
|
-
info = worker.get_task_info(task_id)
|
|
415
|
-
print(f"Task ID: {info.id}")
|
|
416
|
-
print(f"Status: {info.status}") # 'pending', 'running', 'completed', 'failed', 'cancelled'
|
|
417
|
-
print(f"Progress: {info.progress * 100:.1f}%")
|
|
418
|
-
print(f"Created: {info.created_at}")
|
|
419
|
-
print(f"Started: {info.started_at}")
|
|
420
|
-
print(f"Completed: {info.completed_at}")
|
|
421
|
-
print(f"Result: {info.result}") # Only for completed tasks
|
|
422
|
-
print(f"Error: {info.error}") # Only for failed tasks
|
|
423
|
-
print(f"Metadata: {info.metadata}")
|
|
424
|
-
|
|
425
|
-
# Get multiple tasks with filtering
|
|
426
436
|
from datetime import timedelta
|
|
437
|
+
|
|
427
438
|
from async_task_worker import TaskStatus
|
|
428
439
|
|
|
429
|
-
tasks = worker.get_all_tasks(
|
|
430
|
-
status=TaskStatus.COMPLETED, # Filter by status
|
|
431
|
-
limit=10, # Maximum number to return
|
|
432
|
-
older_than=timedelta(hours=1) # Filter by age
|
|
433
|
-
)
|
|
434
440
|
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
441
|
+
async def track(worker, task_id):
|
|
442
|
+
# Get information about a specific task
|
|
443
|
+
info = await worker.get_task_info(task_id)
|
|
444
|
+
print(f"Task ID: {info.id}")
|
|
445
|
+
print(f"Status: {info.status}") # 'pending', 'running', 'completed', 'failed', 'cancelled'
|
|
446
|
+
print(f"Progress: {info.progress * 100:.1f}%")
|
|
447
|
+
print(f"Created: {info.created_at}")
|
|
448
|
+
print(f"Started: {info.started_at}")
|
|
449
|
+
print(f"Completed: {info.completed_at}")
|
|
450
|
+
print(f"Result: {info.result}") # Only for completed tasks
|
|
451
|
+
print(f"Error: {info.error}") # Only for failed tasks
|
|
452
|
+
print(f"Metadata: {info.metadata}")
|
|
453
|
+
|
|
454
|
+
# Get multiple tasks with filtering
|
|
455
|
+
tasks = await worker.get_all_tasks(
|
|
456
|
+
status=TaskStatus.COMPLETED, # Filter by one status
|
|
457
|
+
limit=10, # Maximum number to return
|
|
458
|
+
older_than=timedelta(hours=1) # Filter by age
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
# Tasks are sorted by creation time (newest first)
|
|
462
|
+
for task in tasks:
|
|
463
|
+
print(f"{task.id}: {task.status}")
|
|
438
464
|
```
|
|
439
465
|
|
|
440
466
|
#### Task Cancellation
|
|
441
467
|
|
|
442
468
|
```python
|
|
443
|
-
|
|
444
|
-
|
|
469
|
+
async def cancel(worker, task_id):
|
|
470
|
+
# Cancel a task (running or pending)
|
|
471
|
+
cancelled = await worker.cancel_task(task_id)
|
|
445
472
|
|
|
446
|
-
if cancelled:
|
|
447
|
-
|
|
448
|
-
else:
|
|
449
|
-
|
|
473
|
+
if cancelled:
|
|
474
|
+
print("Task was cancelled successfully")
|
|
475
|
+
else:
|
|
476
|
+
print("Task could not be cancelled (not found or already finished)")
|
|
450
477
|
```
|
|
451
478
|
|
|
452
479
|
#### Waiting for Tasks
|
|
@@ -454,27 +481,30 @@ else:
|
|
|
454
481
|
The worker provides ways to wait for task completion:
|
|
455
482
|
|
|
456
483
|
```python
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
#
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
#
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
print(f"Task {
|
|
484
|
+
from async_task_worker import TaskError
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
async def wait(worker, task_id, task_id1, task_id2):
|
|
488
|
+
# Get a future that resolves when the task completes
|
|
489
|
+
future = await worker.get_task_future(task_id)
|
|
490
|
+
|
|
491
|
+
try:
|
|
492
|
+
# Raises TaskError if the task fails or is cancelled
|
|
493
|
+
result = await future
|
|
494
|
+
print(f"Task completed with result: {result}")
|
|
495
|
+
except TaskError as e:
|
|
496
|
+
# A cancelled task fails with a TaskError ("Task cancelled"), not asyncio.CancelledError
|
|
497
|
+
print(f"Task failed or was cancelled: {e}")
|
|
498
|
+
|
|
499
|
+
# Wait for multiple tasks: results in the same order as the IDs.
|
|
500
|
+
# Raises TimeoutError on timeout, and a TaskError if one of the tasks failed or was cancelled.
|
|
501
|
+
results = await worker.wait_for_tasks([task_id1, task_id2], timeout=30)
|
|
502
|
+
|
|
503
|
+
for task_id, result in zip([task_id1, task_id2], results):
|
|
504
|
+
print(f"Task {task_id} result: {result}")
|
|
505
|
+
|
|
506
|
+
# Wait for whichever task completes first: returns (result, task_id)
|
|
507
|
+
result, first_task_id = await worker.wait_for_any_task([task_id1, task_id2], timeout=30)
|
|
478
508
|
```
|
|
479
509
|
|
|
480
510
|
### Context Manager Support
|
|
@@ -482,6 +512,9 @@ for i, result in enumerate(results):
|
|
|
482
512
|
The worker can be used as an async context manager:
|
|
483
513
|
|
|
484
514
|
```python
|
|
515
|
+
from async_task_worker import AsyncTaskWorker
|
|
516
|
+
|
|
517
|
+
|
|
485
518
|
async def main():
|
|
486
519
|
async with AsyncTaskWorker(max_workers=5) as worker:
|
|
487
520
|
# Worker is automatically started
|
|
@@ -556,12 +589,15 @@ The task worker includes an optional caching system that stores task results to
|
|
|
556
589
|
|
|
557
590
|
#### How Caching Works
|
|
558
591
|
|
|
559
|
-
1. **Flexible Cache Key Generation**:
|
|
592
|
+
1. **Flexible Cache Key Generation**: By default (`default_task_cache_key_fn` in `async_task_worker.core`), the key
|
|
593
|
+
is built from:
|
|
560
594
|
- Task function name
|
|
561
595
|
- Positional arguments
|
|
562
596
|
- Keyword arguments
|
|
563
|
-
|
|
564
|
-
|
|
597
|
+
|
|
598
|
+
The task ID is left out, so tasks calling the same function with the same arguments share one cache entry. A
|
|
599
|
+
per-task `cache_key_fn` can build the key from other parts of the context instead, including the task's
|
|
600
|
+
`metadata` (see [Customizable Cache Key Generation](#customizable-cache-key-generation)).
|
|
565
601
|
|
|
566
602
|
2. **Lookup Process**:
|
|
567
603
|
- Before executing a task, the worker checks if the result is already in cache
|
|
@@ -577,6 +613,8 @@ The task worker includes an optional caching system that stores task results to
|
|
|
577
613
|
#### Global Cache Settings
|
|
578
614
|
|
|
579
615
|
```python
|
|
616
|
+
from async_task_worker import AsyncTaskWorker
|
|
617
|
+
|
|
580
618
|
# Enable caching with default settings
|
|
581
619
|
worker = AsyncTaskWorker(
|
|
582
620
|
cache_enabled=True, # Enable the cache
|
|
@@ -585,47 +623,51 @@ worker = AsyncTaskWorker(
|
|
|
585
623
|
cache_cleanup_interval=900 # Cleanup interval for stale mappings (15 min)
|
|
586
624
|
)
|
|
587
625
|
|
|
588
|
-
# Disable cache
|
|
626
|
+
# Disable the cache (the default). Per-task use_cache=True has no effect then.
|
|
589
627
|
worker = AsyncTaskWorker(
|
|
590
628
|
cache_enabled=False # Globally disabled
|
|
591
629
|
)
|
|
592
630
|
|
|
593
|
-
# Disable automatic cleanup of stale mappings
|
|
631
|
+
# Disable automatic cleanup of stale entry ID mappings
|
|
594
632
|
worker = AsyncTaskWorker(
|
|
595
633
|
cache_enabled=True,
|
|
596
|
-
|
|
634
|
+
cache_cleanup_interval=0 # Disable automatic mapping cleanup
|
|
597
635
|
)
|
|
598
636
|
```
|
|
599
637
|
|
|
638
|
+
Do not confuse `cache_cleanup_interval` with `cleanup_interval`: the latter sets how often old finished tasks are
|
|
639
|
+
removed (see `task_retention_days`) and must be greater than 0.
|
|
640
|
+
|
|
600
641
|
#### Per-Task Cache Options
|
|
601
642
|
|
|
602
643
|
```python
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
)
|
|
644
|
+
async def per_task_options(worker, my_task, arg1, arg2, my_custom_key_function):
|
|
645
|
+
# Override global cache settings for specific task (only when the worker's cache is enabled)
|
|
646
|
+
task_id = await worker.add_task(
|
|
647
|
+
my_task,
|
|
648
|
+
arg1,
|
|
649
|
+
arg2,
|
|
650
|
+
use_cache=True, # Use the cache for this task (the default)
|
|
651
|
+
cache_ttl=120, # Custom TTL: 2 minutes
|
|
652
|
+
metadata={"version": "1.2"} # Stored with the task; also passed to cache_key_fn (the default key ignores it)
|
|
653
|
+
)
|
|
612
654
|
|
|
613
|
-
# Bypass cache for a specific task even if globally enabled
|
|
614
|
-
task_id = await worker.add_task(
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
)
|
|
655
|
+
# Bypass cache for a specific task even if globally enabled
|
|
656
|
+
task_id = await worker.add_task(
|
|
657
|
+
my_task,
|
|
658
|
+
arg1,
|
|
659
|
+
arg2,
|
|
660
|
+
use_cache=False # Disable caching for this task
|
|
661
|
+
)
|
|
620
662
|
|
|
621
|
-
# Use a custom cache key function
|
|
622
|
-
task_id = await worker.add_task(
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
)
|
|
663
|
+
# Use a custom cache key function
|
|
664
|
+
task_id = await worker.add_task(
|
|
665
|
+
my_task,
|
|
666
|
+
arg1,
|
|
667
|
+
arg2,
|
|
668
|
+
use_cache=True,
|
|
669
|
+
cache_key_fn=my_custom_key_function # Custom cache key generator: context dict -> str
|
|
670
|
+
)
|
|
629
671
|
```
|
|
630
672
|
|
|
631
673
|
### Using the Cache Adapter
|
|
@@ -633,14 +675,14 @@ task_id = await worker.add_task(
|
|
|
633
675
|
AsyncTaskWorker uses `AsyncCacheAdapter` which provides a clean integration with the `async_cache` package, enabling efficient caching with flexible key generation and storage strategies:
|
|
634
676
|
|
|
635
677
|
```python
|
|
636
|
-
from async_task_worker import AsyncCacheAdapter
|
|
678
|
+
from async_task_worker import AsyncCacheAdapter, AsyncTaskWorker
|
|
637
679
|
from async_cache.adapters import RedisCacheAdapter
|
|
638
680
|
|
|
639
681
|
# Using Redis as a cache backend
|
|
640
682
|
import redis.asyncio as redis
|
|
641
683
|
|
|
642
684
|
redis_client = redis.Redis(host='localhost', port=6379, db=0)
|
|
643
|
-
redis_adapter = RedisCacheAdapter(redis_client)
|
|
685
|
+
redis_adapter = RedisCacheAdapter(client=redis_client) # or RedisCacheAdapter(host="localhost", port=6379)
|
|
644
686
|
|
|
645
687
|
cache_adapter = AsyncCacheAdapter(
|
|
646
688
|
default_ttl=3600, # Default TTL: 1 hour
|
|
@@ -648,14 +690,14 @@ cache_adapter = AsyncCacheAdapter(
|
|
|
648
690
|
max_serialized_size=5_242_880, # 5MB max serialized size
|
|
649
691
|
validate_keys=True, # Validate cache keys
|
|
650
692
|
cleanup_interval=900, # Cleanup every 15 minutes
|
|
651
|
-
adapter=redis_adapter #
|
|
693
|
+
adapter=redis_adapter # Storage backend (default: MemoryCacheAdapter(max_size))
|
|
652
694
|
)
|
|
653
695
|
|
|
654
|
-
# Then pass to AsyncTaskWorker
|
|
696
|
+
# Then pass to AsyncTaskWorker. The adapter's own enabled/default_ttl settings apply;
|
|
697
|
+
# the worker's cache_enabled and cache_ttl arguments are not used for a given adapter.
|
|
655
698
|
worker = AsyncTaskWorker(
|
|
656
699
|
max_workers=5,
|
|
657
|
-
cache_adapter=cache_adapter
|
|
658
|
-
cache_enabled=True
|
|
700
|
+
cache_adapter=cache_adapter
|
|
659
701
|
)
|
|
660
702
|
```
|
|
661
703
|
|
|
@@ -669,14 +711,17 @@ Each cache key function receives a context dictionary containing:
|
|
|
669
711
|
|
|
670
712
|
```python
|
|
671
713
|
context = {
|
|
672
|
-
"
|
|
673
|
-
"args": (arg1, arg2
|
|
674
|
-
"kwargs": {"key1": value1
|
|
675
|
-
"entry_id": "
|
|
676
|
-
"metadata": {"version": "1.0"
|
|
714
|
+
"fn_name": "task_function_name",
|
|
715
|
+
"args": ("arg1", "arg2"), # Positional arguments
|
|
716
|
+
"kwargs": {"key1": "value1"}, # Keyword arguments (without progress_callback)
|
|
717
|
+
"entry_id": "task_function_name:<task_id>", # Entry ID the worker records for the task
|
|
718
|
+
"metadata": {"version": "1.0"} # The task's metadata, present only if the task has any
|
|
677
719
|
}
|
|
678
720
|
```
|
|
679
721
|
|
|
722
|
+
Without a `cache_key_fn`, the worker uses `default_task_cache_key_fn`, which joins `fn_name`, `args` and `kwargs`,
|
|
723
|
+
e.g. `process_data:(1, 2):{'mode': 'fast'}`.
|
|
724
|
+
|
|
680
725
|
#### Basic Custom Key Function
|
|
681
726
|
|
|
682
727
|
You can create a custom key function to control exactly how cache keys are generated:
|
|
@@ -684,18 +729,20 @@ You can create a custom key function to control exactly how cache keys are gener
|
|
|
684
729
|
```python
|
|
685
730
|
def version_based_key(context):
|
|
686
731
|
"""Generate a cache key based on function name and version."""
|
|
687
|
-
func = context["
|
|
732
|
+
func = context["fn_name"]
|
|
688
733
|
version = context.get("metadata", {}).get("version", "1.0")
|
|
689
734
|
return f"{func}:v{version}"
|
|
690
735
|
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
736
|
+
|
|
737
|
+
async def add_versioned(worker, process_data, dataset):
|
|
738
|
+
# Use the custom key function
|
|
739
|
+
task_id = await worker.add_task(
|
|
740
|
+
process_data,
|
|
741
|
+
dataset,
|
|
742
|
+
use_cache=True,
|
|
743
|
+
metadata={"version": "2.0"},
|
|
744
|
+
cache_key_fn=version_based_key
|
|
745
|
+
)
|
|
699
746
|
```
|
|
700
747
|
|
|
701
748
|
#### Composable Cache Keys
|
|
@@ -708,20 +755,22 @@ from async_cache import compose_key_functions, extract_key_component
|
|
|
708
755
|
# Create component extractors
|
|
709
756
|
user_id = extract_key_component("kwargs.user_id")
|
|
710
757
|
api_version = extract_key_component("metadata.version")
|
|
711
|
-
func_name = extract_key_component("
|
|
758
|
+
func_name = extract_key_component("fn_name")
|
|
712
759
|
|
|
713
760
|
# Compose them into a single key function
|
|
714
761
|
composite_key = compose_key_functions(func_name, user_id, api_version)
|
|
715
762
|
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
763
|
+
|
|
764
|
+
async def add_user_data(worker, get_user_data):
|
|
765
|
+
# Use the composite key function
|
|
766
|
+
task_id = await worker.add_task(
|
|
767
|
+
get_user_data,
|
|
768
|
+
user_id=123,
|
|
769
|
+
use_cache=True,
|
|
770
|
+
metadata={"version": "v2"},
|
|
771
|
+
cache_key_fn=composite_key
|
|
772
|
+
)
|
|
773
|
+
# Will generate a key like: "get_user_data:123:v2"
|
|
725
774
|
```
|
|
726
775
|
|
|
727
776
|
#### Key Component Decorator
|
|
@@ -747,63 +796,76 @@ def timestamp(context):
|
|
|
747
796
|
# Compose named components
|
|
748
797
|
composite_key = compose_key_functions(user_component, region_component, timestamp)
|
|
749
798
|
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
799
|
+
|
|
800
|
+
async def add_regional(worker, get_regional_data):
|
|
801
|
+
# Use in a task
|
|
802
|
+
task_id = await worker.add_task(
|
|
803
|
+
get_regional_data,
|
|
804
|
+
user_id=123,
|
|
805
|
+
region="eu-west",
|
|
806
|
+
use_cache=True,
|
|
807
|
+
metadata={"timestamp": "2023-04-01"},
|
|
808
|
+
cache_key_fn=composite_key
|
|
809
|
+
)
|
|
810
|
+
# Will generate a key like: "user:123:region:eu-west:timestamp:2023-04-01"
|
|
760
811
|
```
|
|
761
812
|
|
|
762
813
|
#### Cache Utilities
|
|
763
814
|
|
|
764
815
|
```python
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
#
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
816
|
+
async def cache_utilities(worker, my_task, arg1, arg2):
|
|
817
|
+
# Bypass the cache for one task
|
|
818
|
+
task_id = await worker.add_task(my_task, arg1, arg2, use_cache=False)
|
|
819
|
+
|
|
820
|
+
# Turn the cache off and on for the whole worker. Tasks run later on a worker,
|
|
821
|
+
# so the setting that counts is the one in effect when the task executes.
|
|
822
|
+
worker.cache.enabled = False
|
|
823
|
+
# ...
|
|
824
|
+
worker.cache.enabled = True
|
|
825
|
+
|
|
826
|
+
# Generate a composite entry ID for consistent cache access
|
|
827
|
+
func_name = "my_func" # the task function's __name__
|
|
828
|
+
task_id = "b4fd93c8-57e3-4fea-bcc6-04be7499b28f"
|
|
829
|
+
entry_id = worker.cache.generate_entry_id(func_name, task_id) # "my_func:b4fd93c8-..."
|
|
830
|
+
|
|
831
|
+
# Get cached result using the composite entry ID
|
|
832
|
+
hit, result = await worker.cache.get_by_task_id(entry_id)
|
|
833
|
+
if hit:
|
|
834
|
+
print(f"Retrieved cached result: {result}")
|
|
835
|
+
|
|
836
|
+
# Invalidate cache by the same entry ID
|
|
837
|
+
success = await worker.cache.invalidate_by_task_id(entry_id)
|
|
838
|
+
if success:
|
|
839
|
+
print("Cache entry successfully invalidated")
|
|
840
|
+
|
|
841
|
+
# Control the background cleanup task (the worker starts and stops it for you)
|
|
842
|
+
await worker.cache.start_cleanup_task() # Start periodic cleanup
|
|
843
|
+
await worker.cache.stop_cleanup_task() # Stop periodic cleanup
|
|
789
844
|
```
|
|
790
845
|
|
|
791
846
|
### Cache Management
|
|
792
847
|
|
|
793
848
|
```python
|
|
794
|
-
# Invalidate a specific cache entry
|
|
795
|
-
invalidated = await worker.invalidate_cache(my_task, arg1, arg2)
|
|
796
|
-
if invalidated:
|
|
797
|
-
print("Cache entry was removed")
|
|
798
|
-
|
|
799
|
-
# Invalidate using task type name
|
|
800
849
|
from async_task_worker import get_task_function
|
|
801
850
|
|
|
802
|
-
task_func = get_task_function("my_task_type")
|
|
803
|
-
invalidated = await worker.invalidate_cache(task_func, arg1, arg2)
|
|
804
851
|
|
|
805
|
-
|
|
806
|
-
|
|
852
|
+
async def manage_cache(worker, my_task, arg1, arg2, my_custom_key_function):
|
|
853
|
+
# Invalidate a specific cache entry
|
|
854
|
+
invalidated = await worker.invalidate_cache(my_task, arg1, arg2)
|
|
855
|
+
if invalidated:
|
|
856
|
+
print("Cache entry was removed")
|
|
857
|
+
|
|
858
|
+
# Invalidate using task type name
|
|
859
|
+
task_func = await get_task_function("my_task_type")
|
|
860
|
+
invalidated = await worker.invalidate_cache(task_func, arg1, arg2)
|
|
861
|
+
|
|
862
|
+
# A task added with its own cache_key_fn (and metadata the key uses) is invalidated with the same ones
|
|
863
|
+
invalidated = await worker.invalidate_cache(
|
|
864
|
+
my_task, arg1, arg2, cache_key_fn=my_custom_key_function, metadata={"version": "1.2"}
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
# Clear the entire cache
|
|
868
|
+
await worker.clear_cache()
|
|
807
869
|
```
|
|
808
870
|
|
|
809
871
|
### Cache Adapters
|
|
@@ -811,12 +873,12 @@ await worker.clear_cache()
|
|
|
811
873
|
The `async_cache` package provides several cache adapters that can be used with AsyncTaskWorker:
|
|
812
874
|
|
|
813
875
|
1. **MemoryCacheAdapter**: In-memory LRU cache (default)
|
|
814
|
-
2. **RedisCacheAdapter**: Redis-backed distributed cache
|
|
876
|
+
2. **RedisCacheAdapter**: Redis-backed distributed cache. Install it with `pip install "async-task-worker[redis]"`.
|
|
815
877
|
|
|
816
878
|
```python
|
|
817
879
|
# Using Memory Adapter (default)
|
|
818
880
|
from async_cache.adapters import MemoryCacheAdapter
|
|
819
|
-
from async_task_worker import AsyncCacheAdapter
|
|
881
|
+
from async_task_worker import AsyncCacheAdapter, AsyncTaskWorker
|
|
820
882
|
|
|
821
883
|
memory_adapter = MemoryCacheAdapter(max_size=10000)
|
|
822
884
|
cache_adapter = AsyncCacheAdapter(adapter=memory_adapter)
|
|
@@ -826,15 +888,15 @@ from async_cache.adapters import RedisCacheAdapter
|
|
|
826
888
|
import redis.asyncio as redis
|
|
827
889
|
|
|
828
890
|
redis_client = redis.Redis(host='localhost', port=6379, db=0)
|
|
829
|
-
redis_adapter = RedisCacheAdapter(redis_client,
|
|
830
|
-
|
|
831
|
-
|
|
891
|
+
redis_adapter = RedisCacheAdapter(client=redis_client, key_prefix="tasks:")
|
|
892
|
+
# or let the adapter create the client:
|
|
893
|
+
# redis_adapter = RedisCacheAdapter(host="localhost", port=6379, db=0, key_prefix="tasks:")
|
|
832
894
|
|
|
833
|
-
cache_adapter = AsyncCacheAdapter(adapter=redis_adapter)
|
|
895
|
+
cache_adapter = AsyncCacheAdapter(adapter=redis_adapter, default_ttl=3600)
|
|
834
896
|
|
|
835
|
-
# Pass to AsyncTaskWorker
|
|
897
|
+
# Pass to AsyncTaskWorker. Caching is on through the adapter (enabled=True by default);
|
|
898
|
+
# the worker's cache_enabled and cache_ttl arguments are not applied to a given adapter.
|
|
836
899
|
worker = AsyncTaskWorker(
|
|
837
|
-
cache_enabled=True,
|
|
838
900
|
cache_adapter=cache_adapter
|
|
839
901
|
)
|
|
840
902
|
```
|
|
@@ -844,51 +906,58 @@ worker = AsyncTaskWorker(
|
|
|
844
906
|
#### Version-based Cache Invalidation
|
|
845
907
|
|
|
846
908
|
```python
|
|
847
|
-
# Create a cache key function that includes API version
|
|
909
|
+
# Create a cache key function that includes the user and the API version
|
|
848
910
|
def versioned_cache_key(context):
|
|
849
|
-
func = context["
|
|
911
|
+
func = context["fn_name"]
|
|
912
|
+
user_id = context["kwargs"].get("user_id")
|
|
850
913
|
version = context.get("metadata", {}).get("api_version", "v1")
|
|
851
|
-
return f"{func}:{version}"
|
|
852
|
-
|
|
853
|
-
# User requests data with v1 API
|
|
854
|
-
task_id1 = await worker.add_task(
|
|
855
|
-
get_user_data,
|
|
856
|
-
user_id=123,
|
|
857
|
-
use_cache=True,
|
|
858
|
-
metadata={"api_version": "v1"},
|
|
859
|
-
cache_key_fn=versioned_cache_key
|
|
860
|
-
)
|
|
914
|
+
return f"{func}:{user_id}:{version}"
|
|
861
915
|
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
916
|
+
|
|
917
|
+
async def add_versioned_requests(worker, get_user_data):
|
|
918
|
+
# User requests data with v1 API
|
|
919
|
+
task_id1 = await worker.add_task(
|
|
920
|
+
get_user_data,
|
|
921
|
+
user_id=123,
|
|
922
|
+
use_cache=True,
|
|
923
|
+
metadata={"api_version": "v1"},
|
|
924
|
+
cache_key_fn=versioned_cache_key
|
|
925
|
+
)
|
|
926
|
+
|
|
927
|
+
# Later, after API update, same data with v2 API
|
|
928
|
+
# Will use a different cache key, not reusing v1 cached result
|
|
929
|
+
task_id2 = await worker.add_task(
|
|
930
|
+
get_user_data,
|
|
931
|
+
user_id=123,
|
|
932
|
+
use_cache=True,
|
|
933
|
+
metadata={"api_version": "v2"},
|
|
934
|
+
cache_key_fn=versioned_cache_key
|
|
935
|
+
)
|
|
871
936
|
```
|
|
872
937
|
|
|
873
938
|
#### Multi-tenant Cache Isolation
|
|
874
939
|
|
|
875
940
|
```python
|
|
941
|
+
from async_cache import compose_key_functions, extract_key_component
|
|
942
|
+
|
|
876
943
|
# Create a key function that isolates cache by tenant
|
|
877
944
|
tenant_key = compose_key_functions(
|
|
878
|
-
extract_key_component("
|
|
945
|
+
extract_key_component("fn_name"),
|
|
879
946
|
extract_key_component("metadata.tenant_id"),
|
|
880
|
-
|
|
947
|
+
lambda ctx: str(ctx["args"][0]) # First arg value (extract_key_component reads dict keys only)
|
|
881
948
|
)
|
|
882
949
|
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
950
|
+
|
|
951
|
+
async def add_tenant_tasks(worker, process_data):
|
|
952
|
+
# Different tenants share same function but get isolated cache
|
|
953
|
+
for tenant_id in ["tenant1", "tenant2", "tenant3"]:
|
|
954
|
+
task_id = await worker.add_task(
|
|
955
|
+
process_data,
|
|
956
|
+
"sample_data",
|
|
957
|
+
use_cache=True,
|
|
958
|
+
metadata={"tenant_id": tenant_id},
|
|
959
|
+
cache_key_fn=tenant_key
|
|
960
|
+
)
|
|
892
961
|
```
|
|
893
962
|
|
|
894
963
|
### Automatic Cleanup of Stale Mappings
|
|
@@ -896,35 +965,40 @@ for tenant_id in ["tenant1", "tenant2", "tenant3"]:
|
|
|
896
965
|
The cache system includes an automatic cleanup mechanism to prevent memory leaks from orphaned task ID mappings when cache entries expire through TTL:
|
|
897
966
|
|
|
898
967
|
```python
|
|
899
|
-
|
|
900
|
-
worker = AsyncTaskWorker(
|
|
901
|
-
cache_enabled=True,
|
|
902
|
-
cache_ttl=3600, # 1 hour cache TTL
|
|
903
|
-
cleanup_interval=900 # Clean up stale mappings every 15 minutes
|
|
904
|
-
)
|
|
968
|
+
from async_task_worker import AsyncTaskWorker
|
|
905
969
|
|
|
906
|
-
# The sequence of events:
|
|
907
|
-
# 1. Add a task with caching enabled
|
|
908
|
-
task_id = await worker.add_task(
|
|
909
|
-
process_data,
|
|
910
|
-
dataset,
|
|
911
|
-
use_cache=True,
|
|
912
|
-
cache_ttl=60 # 1 minute TTL
|
|
913
|
-
)
|
|
914
970
|
|
|
915
|
-
|
|
971
|
+
async def cleanup_example(process_data, dataset):
|
|
972
|
+
# Configure a worker with cleanup enabled
|
|
973
|
+
worker = AsyncTaskWorker(
|
|
974
|
+
cache_enabled=True,
|
|
975
|
+
cache_ttl=3600, # 1 hour cache TTL
|
|
976
|
+
cache_cleanup_interval=900 # Clean up stale mappings every 15 minutes
|
|
977
|
+
)
|
|
978
|
+
await worker.start()
|
|
979
|
+
|
|
980
|
+
# The sequence of events:
|
|
981
|
+
# 1. Add a task with caching enabled
|
|
982
|
+
task_id = await worker.add_task(
|
|
983
|
+
process_data,
|
|
984
|
+
dataset,
|
|
985
|
+
use_cache=True,
|
|
986
|
+
cache_ttl=60 # 1 minute TTL
|
|
987
|
+
)
|
|
988
|
+
|
|
989
|
+
# 2. The task's entry ID ("process_data:<task_id>") is mapped to its cache key in entry_key_map
|
|
916
990
|
|
|
917
|
-
# 3. After 1 minute, the cache entry expires due to TTL
|
|
991
|
+
# 3. After 1 minute, the cache entry expires due to TTL
|
|
918
992
|
|
|
919
|
-
# 4. Without cleanup, the mapping would remain in memory indefinitely
|
|
993
|
+
# 4. Without cleanup, the mapping would remain in memory indefinitely
|
|
920
994
|
|
|
921
|
-
# 5. With cleanup enabled, the background task periodically checks
|
|
922
|
-
# all mappings and removes any where the cache entry is gone
|
|
995
|
+
# 5. With cleanup enabled, the background task periodically checks
|
|
996
|
+
# all mappings and removes any where the cache entry is gone
|
|
923
997
|
|
|
924
|
-
# 6. Result: No memory leaks from expired cache entries
|
|
998
|
+
# 6. Result: No memory leaks from expired cache entries
|
|
925
999
|
```
|
|
926
1000
|
|
|
927
|
-
The cleanup task starts automatically with the worker and runs at the configured interval. It only removes mappings when the actual cache entries have expired or been removed, ensuring that all valid mappings are preserved.
|
|
1001
|
+
The cleanup task starts automatically with the worker (unless `cache_cleanup_interval` is 0) and runs at the configured interval. It only removes mappings when the actual cache entries have expired or been removed, ensuring that all valid mappings are preserved.
|
|
928
1002
|
|
|
929
1003
|
## Advanced Usage
|
|
930
1004
|
|
|
@@ -935,17 +1009,19 @@ The task registry provides ways to discover and lookup registered tasks:
|
|
|
935
1009
|
```python
|
|
936
1010
|
from async_task_worker import get_task_function, get_all_task_types
|
|
937
1011
|
|
|
938
|
-
# Get all registered task types
|
|
939
|
-
task_types = get_all_task_types()
|
|
940
|
-
print(f"Available tasks: {task_types}")
|
|
941
1012
|
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
1013
|
+
async def run_by_type(worker, data):
|
|
1014
|
+
# Get all registered task types
|
|
1015
|
+
task_types = await get_all_task_types()
|
|
1016
|
+
print(f"Available tasks: {task_types}")
|
|
1017
|
+
|
|
1018
|
+
# Get a task function by type
|
|
1019
|
+
task_func = await get_task_function("process_data")
|
|
1020
|
+
if task_func:
|
|
1021
|
+
# Execute the task
|
|
1022
|
+
return await worker.add_task(task_func, data)
|
|
1023
|
+
else:
|
|
1024
|
+
print("Task type not found")
|
|
949
1025
|
```
|
|
950
1026
|
|
|
951
1027
|
### Manual Task Registration
|
|
@@ -953,7 +1029,7 @@ else:
|
|
|
953
1029
|
Besides the decorator, you can manually register tasks:
|
|
954
1030
|
|
|
955
1031
|
```python
|
|
956
|
-
from async_task_worker import register_task
|
|
1032
|
+
from async_task_worker import get_task_function, register_task
|
|
957
1033
|
|
|
958
1034
|
|
|
959
1035
|
async def my_task(data):
|
|
@@ -961,12 +1037,14 @@ async def my_task(data):
|
|
|
961
1037
|
return result
|
|
962
1038
|
|
|
963
1039
|
|
|
964
|
-
# Register the task
|
|
1040
|
+
# Register the task (synchronous)
|
|
965
1041
|
register_task("custom_task", my_task)
|
|
966
1042
|
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
1043
|
+
|
|
1044
|
+
async def run_custom(worker, data):
|
|
1045
|
+
# Later, retrieve and execute
|
|
1046
|
+
task_func = await get_task_function("custom_task")
|
|
1047
|
+
return await worker.add_task(task_func, data)
|
|
970
1048
|
```
|
|
971
1049
|
|
|
972
1050
|
### Progress Reporting
|
|
@@ -974,6 +1052,11 @@ task_id = await worker.add_task(task_func, data)
|
|
|
974
1052
|
Tasks can report progress through the `progress_callback` parameter:
|
|
975
1053
|
|
|
976
1054
|
```python
|
|
1055
|
+
import asyncio
|
|
1056
|
+
|
|
1057
|
+
from async_task_worker import task
|
|
1058
|
+
|
|
1059
|
+
|
|
977
1060
|
@task("long_running_task")
|
|
978
1061
|
async def long_running_task(items, progress_callback=None):
|
|
979
1062
|
total = len(items)
|
|
@@ -994,54 +1077,74 @@ async def long_running_task(items, progress_callback=None):
|
|
|
994
1077
|
return "Completed"
|
|
995
1078
|
```
|
|
996
1079
|
|
|
997
|
-
The
|
|
1080
|
+
The worker passes `progress_callback` only to functions that declare it (or accept `**kwargs`); values are clamped
|
|
1081
|
+
to 0.0-1.0. Progress reaches `TaskInfo.progress` while the task runs and can be read with
|
|
1082
|
+
`await worker.get_task_info(task_id)`. Updates are throttled by `ProgressUpdateStrategy`: one is applied when at least 0.1 s
|
|
1083
|
+
has passed or progress moved by at least 0.02 since the last applied update, and 1.0 is always applied.
|
|
1084
|
+
`TaskInfo.get_current_progress()` returns the latest reported value, including a throttled one. Progress is set to
|
|
1085
|
+
1.0 when the task completes.
|
|
998
1086
|
|
|
999
1087
|
## Error Handling
|
|
1000
1088
|
|
|
1001
1089
|
The task worker captures exceptions raised by tasks:
|
|
1002
1090
|
|
|
1003
1091
|
```python
|
|
1092
|
+
import asyncio
|
|
1093
|
+
|
|
1094
|
+
from async_task_worker import TaskStatus, task
|
|
1095
|
+
|
|
1096
|
+
|
|
1004
1097
|
@task("might_fail")
|
|
1005
1098
|
async def might_fail(value):
|
|
1006
1099
|
if value < 0:
|
|
1007
1100
|
raise ValueError("Value cannot be negative")
|
|
1008
1101
|
return value * 2
|
|
1009
1102
|
|
|
1010
|
-
# Execute task that will fail
|
|
1011
|
-
task_id = await worker.add_task(might_fail, -5)
|
|
1012
1103
|
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1104
|
+
async def run(worker):
|
|
1105
|
+
# Execute task that will fail
|
|
1106
|
+
task_id = await worker.add_task(might_fail, -5)
|
|
1107
|
+
await asyncio.sleep(1) # or wait with worker.get_task_future(task_id)
|
|
1108
|
+
|
|
1109
|
+
# Check the result
|
|
1110
|
+
info = await worker.get_task_info(task_id)
|
|
1111
|
+
assert info.status == TaskStatus.FAILED
|
|
1112
|
+
# The stored error contains the original message, e.g.
|
|
1113
|
+
# "Task <id>: [ErrorCategory.TASK_EXECUTION] Task execution failed: Value cannot be negative"
|
|
1114
|
+
assert "Value cannot be negative" in info.error
|
|
1017
1115
|
```
|
|
1018
1116
|
|
|
1019
1117
|
## API Reference
|
|
1020
1118
|
|
|
1021
1119
|
### AsyncTaskWorker
|
|
1022
1120
|
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
- `
|
|
1027
|
-
- `
|
|
1028
|
-
- `
|
|
1029
|
-
- `
|
|
1030
|
-
- `
|
|
1031
|
-
- `
|
|
1032
|
-
- `
|
|
1033
|
-
- `
|
|
1034
|
-
- `
|
|
1121
|
+
Methods marked *async* are coroutines and must be awaited. The worker is also an async context manager
|
|
1122
|
+
(`async with AsyncTaskWorker(...) as worker:` starts and stops it).
|
|
1123
|
+
|
|
1124
|
+
- `__init__(max_workers=10, task_timeout=None, worker_poll_interval=1.0, cache_enabled=False, cache_ttl=3600, cache_max_size=1000, cache_adapter=None, cache_cleanup_interval=900, max_queue_size=None, task_retention_days=7, cleanup_interval=3600)`: Initialize the worker. `cache_enabled`, `cache_ttl`, `cache_max_size` and `cache_cleanup_interval` configure the default cache and are not applied to a given `cache_adapter`
|
|
1125
|
+
- `start()` *async*: Start the worker pool and the cleanup tasks
|
|
1126
|
+
- `stop(timeout=5.0)` *async*: Stop the worker pool
|
|
1127
|
+
- `add_task(task_func, *args, priority=0, task_id=None, metadata=None, timeout=None, use_cache=True, cache_ttl=None, cache_key_fn=None, **kwargs)` *async*: Add a task to the queue and return its ID. `cache_key_fn` receives a context dict with `fn_name`, `args`, `kwargs`, `entry_id` and `metadata` (default: `default_task_cache_key_fn`)
|
|
1128
|
+
- `get_task_info(task_id)` *async*: Get information about a task (`TaskInfo` or `None`)
|
|
1129
|
+
- `get_all_tasks(status=None, limit=None, older_than=None)` *async*: Get filtered list of tasks, newest first. `status` is one `TaskStatus`
|
|
1130
|
+
- `cancel_task(task_id)` *async*: Cancel a running or pending task
|
|
1131
|
+
- `get_task_future(task_id)` *async*: Get a future that resolves when the task completes (raises `KeyError` for an unknown task)
|
|
1132
|
+
- `wait_for_tasks(task_ids, timeout=None)` *async*: Wait for multiple tasks to complete; returns their results in order
|
|
1133
|
+
- `wait_for_any_task(task_ids, timeout=None)` *async*: Wait for any of the specified tasks to complete; returns `(result, task_id)`
|
|
1134
|
+
- `invalidate_cache(task_func, *args, cache_key_fn=None, metadata=None, **kwargs)` *async*: Invalidate a specific cache entry; pass the `cache_key_fn` and `metadata` the task was added with
|
|
1135
|
+
- `clear_cache()` *async*: Clear all cache entries
|
|
1136
|
+
- `get_cache()`: Get the cache adapter (also available as `worker.cache`)
|
|
1137
|
+
- `cleanup_old_tasks()` *async*: Remove finished tasks older than `task_retention_days`; returns the number removed (also run every `cleanup_interval` seconds)
|
|
1035
1138
|
|
|
1036
1139
|
### AsyncCacheAdapter
|
|
1037
1140
|
|
|
1038
|
-
- `__init__(default_ttl=None, enabled=True, max_serialized_size=10485760, validate_keys=False, cleanup_interval=900, max_size=1000)`: Initialize the cache adapter
|
|
1141
|
+
- `__init__(default_ttl=None, enabled=True, max_serialized_size=10485760, validate_keys=False, cleanup_interval=900, max_size=1000, adapter=None)`: Initialize the cache adapter. `adapter` is the storage backend, e.g. `RedisCacheAdapter` (default: `MemoryCacheAdapter(max_size)`)
|
|
1039
1142
|
- `get(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Get cached result
|
|
1040
1143
|
- `set(func_name, args, kwargs, result, ttl=None, cache_key_fn=None, task_id=None, metadata=None)`: Store result in cache
|
|
1041
1144
|
- `invalidate(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Invalidate specific cache entry
|
|
1042
1145
|
- `generate_entry_id(func_name, task_id)`: Generate a composite entry ID for cache operations
|
|
1043
|
-
- `get_by_task_id(task_id)`: Get cached result
|
|
1044
|
-
- `invalidate_by_task_id(task_id)`: Invalidate cache entry by
|
|
1146
|
+
- `get_by_task_id(task_id)`: Get cached result by entry ID (from `generate_entry_id`); returns `(hit, result)`
|
|
1147
|
+
- `invalidate_by_task_id(task_id)`: Invalidate cache entry by entry ID (from `generate_entry_id`)
|
|
1045
1148
|
- `clear()`: Clear the entire cache
|
|
1046
1149
|
- `start_cleanup_task()`: Start the periodic cleanup task
|
|
1047
1150
|
- `stop_cleanup_task()`: Stop the periodic cleanup task
|
|
@@ -1051,21 +1154,25 @@ print(f"Task failed: {info.error}") # "Value cannot be negative"
|
|
|
1051
1154
|
|
|
1052
1155
|
### WorkerPool
|
|
1053
1156
|
|
|
1054
|
-
- `__init__(task_queue, task_executor, max_workers=10)`: Initialize the worker pool
|
|
1055
|
-
- `start()
|
|
1056
|
-
- `stop(timeout=5.0)
|
|
1057
|
-
- `cancel_running_task(task_id)
|
|
1157
|
+
- `__init__(task_queue, task_executor, max_workers=10, worker_poll_interval=1.0, on_task_start=None, on_task_complete=None, on_task_failed=None, on_task_cancelled=None, log_idle_workers=False, on_task_progress=None)`: Initialize the worker pool. The `on_task_*` status callbacks are coroutines; `on_task_progress(task_id, progress)` is a plain function
|
|
1158
|
+
- `start()` *async*: Start the worker pool
|
|
1159
|
+
- `stop(timeout=5.0)` *async*: Stop the worker pool gracefully
|
|
1160
|
+
- `cancel_running_task(task_id)` *async*: Cancel a task that is currently running in a worker
|
|
1161
|
+
- `active_tasks_count`: Property with the number of tasks currently running
|
|
1162
|
+
- `worker_count`: Property with the number of workers
|
|
1058
1163
|
|
|
1059
1164
|
### Task Registry
|
|
1060
1165
|
|
|
1166
|
+
Module-level functions in `async_task_worker.registry`, also exported from `async_task_worker`:
|
|
1167
|
+
|
|
1061
1168
|
- `@task(task_type)`: Decorator to register a task function
|
|
1062
1169
|
- `register_task(task_type, task_func)`: Manually register a task function
|
|
1063
|
-
- `get_task_function(task_type)
|
|
1064
|
-
- `get_all_task_types()
|
|
1170
|
+
- `get_task_function(task_type)` *async*: Get the function for a task type (`None` if not registered)
|
|
1171
|
+
- `get_all_task_types()` *async*: Get all registered task types
|
|
1065
1172
|
|
|
1066
1173
|
### API Router
|
|
1067
1174
|
|
|
1068
|
-
- `create_task_worker_router(worker, prefix="", tags=None)`: Create a FastAPI router for task management
|
|
1175
|
+
- `create_task_worker_router(worker, prefix="", tags=None)`: Create a FastAPI router for task management (import from `async_task_worker.api`)
|
|
1069
1176
|
|
|
1070
1177
|
## API Router - Control API for Task Worker (optional)
|
|
1071
1178
|
|
|
@@ -1082,7 +1189,8 @@ pip install "async-task-worker[api]"
|
|
|
1082
1189
|
```python
|
|
1083
1190
|
from fastapi import FastAPI
|
|
1084
1191
|
from contextlib import asynccontextmanager
|
|
1085
|
-
from async_task_worker import AsyncTaskWorker
|
|
1192
|
+
from async_task_worker import AsyncTaskWorker
|
|
1193
|
+
from async_task_worker.api import create_task_worker_router
|
|
1086
1194
|
|
|
1087
1195
|
# Create task worker
|
|
1088
1196
|
worker = AsyncTaskWorker(max_workers=10, cache_enabled=True)
|
|
@@ -1108,6 +1216,11 @@ app.include_router(create_task_worker_router(worker))
|
|
|
1108
1216
|
You can customize the router with the following options:
|
|
1109
1217
|
|
|
1110
1218
|
```python
|
|
1219
|
+
from async_task_worker import AsyncTaskWorker
|
|
1220
|
+
from async_task_worker.api import create_task_worker_router
|
|
1221
|
+
|
|
1222
|
+
worker = AsyncTaskWorker()
|
|
1223
|
+
|
|
1111
1224
|
task_router = create_task_worker_router(
|
|
1112
1225
|
worker,
|
|
1113
1226
|
prefix="/api/v1", # Add a URL prefix to all routes
|
|
@@ -1119,14 +1232,27 @@ task_router = create_task_worker_router(
|
|
|
1119
1232
|
|
|
1120
1233
|
The router provides the following endpoints:
|
|
1121
1234
|
|
|
1122
|
-
| Method | Endpoint | Description |
|
|
1123
|
-
|
|
1124
|
-
| POST | `/tasks` | Submit a new task for execution |
|
|
1125
|
-
| GET | `/tasks/{task_id}` | Get status and results of a specific task |
|
|
1126
|
-
| DELETE | `/tasks/{task_id}` | Cancel a running or pending task |
|
|
1127
|
-
| GET | `/tasks` | List tasks with optional filtering |
|
|
1128
|
-
| GET | `/
|
|
1129
|
-
| GET | `/health` | Check the health of the task worker service |
|
|
1235
|
+
| Method | Endpoint | Description | Response |
|
|
1236
|
+
|--------|----------|-------------|----------|
|
|
1237
|
+
| POST | `/tasks` | Submit a new task for execution | 201, `TaskResponse` |
|
|
1238
|
+
| GET | `/tasks/{task_id}` | Get status and results of a specific task | 200, `TaskResponse` |
|
|
1239
|
+
| DELETE | `/tasks/{task_id}` | Cancel a running or pending task (no-op for a finished task) | 204, no body |
|
|
1240
|
+
| GET | `/tasks` | List tasks with optional filtering, newest first | 200, `{"tasks": [TaskResponse, ...], "count": n}` |
|
|
1241
|
+
| GET | `/types` | Get a list of all registered task types | 200, `{"task_types": [...]}` |
|
|
1242
|
+
| GET | `/health` | Check the health of the task worker service | 200, `{"status": "ok" or "stopped", "worker_count": n, "queue_size": n}` |
|
|
1243
|
+
|
|
1244
|
+
`GET /tasks` takes the query parameters `task_status` (one of `pending`, `running`, `completed`, `failed`,
|
|
1245
|
+
`cancelled`), `limit` (1-100, default 50) and `older_than_minutes` (only tasks created more than that many minutes
|
|
1246
|
+
ago).
|
|
1247
|
+
|
|
1248
|
+
`POST /tasks` takes a JSON body with `task_type` (required), `params` (keyword arguments for the task function),
|
|
1249
|
+
`priority` (default 0), `task_id`, `metadata`, `timeout`, `use_cache` (default `true`) and `cache_ttl`. The task type
|
|
1250
|
+
is added to the task's metadata as `task_type`.
|
|
1251
|
+
|
|
1252
|
+
`TaskResponse` has the fields `id`, `status`, `progress`, `metadata`, `result`, `error` and `from_cache`.
|
|
1253
|
+
|
|
1254
|
+
Errors are returned with a `detail` object (`message`, `error_type`, and when known `category`, `task_id`,
|
|
1255
|
+
`is_retryable`): an unknown task type gives 400, an unknown task ID 404.
|
|
1130
1256
|
|
|
1131
1257
|
### Example: Submitting a Task
|
|
1132
1258
|
|
|
@@ -1187,75 +1313,75 @@ async def get_cached_result(task_worker, func_name, task_id):
|
|
|
1187
1313
|
else:
|
|
1188
1314
|
print(f"No cached result found for function {func_name}, task {task_id}")
|
|
1189
1315
|
# Fall back to retrieving via task info
|
|
1190
|
-
|
|
1316
|
+
info = await task_worker.get_task_info(task_id)
|
|
1317
|
+
return info.result if info else None
|
|
1191
1318
|
```
|
|
1192
1319
|
|
|
1193
1320
|
## Event System Integration
|
|
1194
1321
|
|
|
1195
|
-
The async_task_worker library can be integrated with the `async_events` package to
|
|
1322
|
+
The async_task_worker library can be integrated with the `async_events` package to build a reactive system where events about tasks are published to subscribers. The worker does not publish events by itself: nothing in `async_task_worker` uses `async_events`. Events exist only when your code calls `event_manager.publish_event(...)`, for example inside a task function or in a monitor that polls the worker, as shown below. This enables building event-driven architectures with real-time notifications and monitoring.
|
|
1196
1323
|
|
|
1197
1324
|
### Features
|
|
1198
1325
|
|
|
1199
|
-
- **Event-driven Architecture**:
|
|
1200
|
-
- **Real-time Notifications**:
|
|
1201
|
-
- **Filtered Event Streams**: Subscribe to events for
|
|
1202
|
-
- **Historical Event Access**: Query recent events even after they occurred
|
|
1203
|
-
- **Server-Sent Events Support**:
|
|
1326
|
+
- **Event-driven Architecture**: Publish events from your tasks, or from code that watches the worker, and let subscribers react to them
|
|
1327
|
+
- **Real-time Notifications**: Subscribers receive an event as soon as it is published
|
|
1328
|
+
- **Filtered Event Streams**: Subscribe to events for one group (`group_id`); an event goes only to the subscribers of its group
|
|
1329
|
+
- **Historical Event Access**: Query recent events (kept for `result_ttl` seconds, 300 by default) even after they occurred
|
|
1330
|
+
- **Server-Sent Events Support**: Serve events to browsers as SSE, and consume an SSE stream in Python with `SSEClient`
|
|
1204
1331
|
|
|
1205
1332
|
### Getting Started with Events
|
|
1206
1333
|
|
|
1334
|
+
`event_manager` is a shared `EventManager` instance. `subscribe(group_id)` returns `(subscriber_id, queue)`: read
|
|
1335
|
+
events with `await queue.get()` and call `unsubscribe(subscriber_id)` when done. A subscriber gets only the events
|
|
1336
|
+
published after it subscribed (use `get_recent_events` for earlier ones). `publish_event` publishes each `event_id`
|
|
1337
|
+
once and skips an ID it has seen before, so give every event a unique ID.
|
|
1338
|
+
|
|
1207
1339
|
```python
|
|
1208
1340
|
import asyncio
|
|
1209
|
-
|
|
1210
|
-
|
|
1341
|
+
import time
|
|
1342
|
+
|
|
1343
|
+
from async_events import event_manager
|
|
1344
|
+
from async_task_worker import TaskStatus, task
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
# The worker publishes no events, so watch it and publish task state changes yourself
|
|
1348
|
+
async def monitor_worker(worker):
|
|
1349
|
+
while True:
|
|
1350
|
+
for task_info in await worker.get_all_tasks():
|
|
1351
|
+
# Publish each finished task once
|
|
1352
|
+
if task_info.is_terminal_state() and not event_manager.is_processed(task_info.id):
|
|
1353
|
+
# Build event data based on task state
|
|
1354
|
+
event_data = {
|
|
1355
|
+
"task_id": task_info.id,
|
|
1356
|
+
"status": task_info.status.value,
|
|
1357
|
+
"timestamp": time.time()
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
# Add status-specific data
|
|
1361
|
+
if task_info.status == TaskStatus.COMPLETED:
|
|
1362
|
+
event_data["result"] = task_info.result
|
|
1363
|
+
elif task_info.status == TaskStatus.FAILED:
|
|
1364
|
+
event_data["error"] = task_info.error
|
|
1365
|
+
|
|
1366
|
+
# Get group ID from metadata or use task_id as fallback
|
|
1367
|
+
group_id = task_info.metadata.get("group_id", task_info.id)
|
|
1368
|
+
|
|
1369
|
+
# Publish the event
|
|
1370
|
+
await event_manager.publish_event(
|
|
1371
|
+
event_id=task_info.id,
|
|
1372
|
+
group_id=group_id,
|
|
1373
|
+
event_data=event_data
|
|
1374
|
+
)
|
|
1375
|
+
|
|
1376
|
+
# Short sleep to avoid CPU spinning
|
|
1377
|
+
await asyncio.sleep(0.1)
|
|
1211
1378
|
|
|
1212
|
-
# Global event manager instance
|
|
1213
|
-
event_manager = EventManager()
|
|
1214
1379
|
|
|
1215
|
-
# Configure task worker to publish events
|
|
1216
1380
|
async def configure_task_worker_events(worker):
|
|
1217
|
-
# Start the event manager
|
|
1381
|
+
# Start the event manager and the monitoring task
|
|
1218
1382
|
await event_manager.start()
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
while True:
|
|
1222
|
-
# Get all tasks in terminal states
|
|
1223
|
-
terminal_tasks = await worker.get_all_tasks(
|
|
1224
|
-
status=["completed", "failed", "cancelled"]
|
|
1225
|
-
)
|
|
1226
|
-
|
|
1227
|
-
for task_info in terminal_tasks:
|
|
1228
|
-
# Check if we've already published an event for this task
|
|
1229
|
-
if not event_manager.is_processed(task_info.id):
|
|
1230
|
-
# Build event data based on task state
|
|
1231
|
-
event_data = {
|
|
1232
|
-
"task_id": task_info.id,
|
|
1233
|
-
"status": task_info.status,
|
|
1234
|
-
"timestamp": asyncio.get_event_loop().time()
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
# Add status-specific data
|
|
1238
|
-
if task_info.status == "completed":
|
|
1239
|
-
event_data["result"] = task_info.result
|
|
1240
|
-
elif task_info.status == "failed":
|
|
1241
|
-
event_data["error"] = task_info.error
|
|
1242
|
-
|
|
1243
|
-
# Get group ID from metadata or use task_id as fallback
|
|
1244
|
-
group_id = task_info.metadata.get("group_id", task_info.id)
|
|
1245
|
-
|
|
1246
|
-
# Publish the event
|
|
1247
|
-
await event_manager.publish_event(
|
|
1248
|
-
event_id=task_info.id,
|
|
1249
|
-
group_id=group_id,
|
|
1250
|
-
event_data=event_data
|
|
1251
|
-
)
|
|
1252
|
-
|
|
1253
|
-
# Short sleep to avoid CPU spinning
|
|
1254
|
-
await asyncio.sleep(0.1)
|
|
1255
|
-
|
|
1256
|
-
# Start the monitoring task
|
|
1257
|
-
monitor_task = asyncio.create_task(monitor_worker())
|
|
1258
|
-
return monitor_task
|
|
1383
|
+
return asyncio.create_task(monitor_worker(worker))
|
|
1384
|
+
|
|
1259
1385
|
|
|
1260
1386
|
# Define a task that reports progress events
|
|
1261
1387
|
@task("computation_task")
|
|
@@ -1263,31 +1389,26 @@ async def computation_task(data, computation_id, delay=0.5):
|
|
|
1263
1389
|
"""Task that reports progress via events."""
|
|
1264
1390
|
result = {"status": "processing", "computation_id": computation_id}
|
|
1265
1391
|
total_steps = 5
|
|
1266
|
-
|
|
1392
|
+
|
|
1267
1393
|
for step in range(1, total_steps + 1):
|
|
1268
1394
|
# Simulate work
|
|
1269
1395
|
await asyncio.sleep(delay)
|
|
1270
|
-
|
|
1271
|
-
# Update progress
|
|
1272
|
-
progress = step / total_steps
|
|
1273
|
-
|
|
1396
|
+
|
|
1274
1397
|
# Publish step completion event
|
|
1275
|
-
event_data = {
|
|
1276
|
-
"computation_id": computation_id,
|
|
1277
|
-
"step": step,
|
|
1278
|
-
"total_steps": total_steps,
|
|
1279
|
-
"progress": progress
|
|
1280
|
-
}
|
|
1281
|
-
|
|
1282
1398
|
await event_manager.publish_event(
|
|
1283
1399
|
event_id=f"{computation_id}_step_{step}",
|
|
1284
1400
|
group_id=computation_id,
|
|
1285
|
-
event_data=
|
|
1401
|
+
event_data={
|
|
1402
|
+
"computation_id": computation_id,
|
|
1403
|
+
"step": step,
|
|
1404
|
+
"total_steps": total_steps,
|
|
1405
|
+
"progress": step / total_steps
|
|
1406
|
+
}
|
|
1286
1407
|
)
|
|
1287
|
-
|
|
1408
|
+
|
|
1288
1409
|
# Update final status
|
|
1289
1410
|
result["status"] = "completed"
|
|
1290
|
-
|
|
1411
|
+
|
|
1291
1412
|
# Publish completion event
|
|
1292
1413
|
await event_manager.publish_event(
|
|
1293
1414
|
event_id=f"{computation_id}_completed",
|
|
@@ -1298,20 +1419,23 @@ async def computation_task(data, computation_id, delay=0.5):
|
|
|
1298
1419
|
"result": result
|
|
1299
1420
|
}
|
|
1300
1421
|
)
|
|
1301
|
-
|
|
1422
|
+
|
|
1302
1423
|
return result
|
|
1303
1424
|
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1425
|
+
|
|
1426
|
+
# Example of subscribing to events: collect events until the completion event
|
|
1427
|
+
async def subscribe_to_task_events(computation_id, timeout=30.0):
|
|
1428
|
+
subscriber_id, queue = await event_manager.subscribe(computation_id)
|
|
1429
|
+
events = []
|
|
1430
|
+
try:
|
|
1431
|
+
async with asyncio.timeout(timeout): # raises TimeoutError
|
|
1432
|
+
while True:
|
|
1433
|
+
event = await queue.get()
|
|
1434
|
+
events.append(event)
|
|
1435
|
+
if event.get("status") == "completed":
|
|
1436
|
+
return events
|
|
1437
|
+
finally:
|
|
1438
|
+
await event_manager.unsubscribe(subscriber_id)
|
|
1315
1439
|
```
|
|
1316
1440
|
|
|
1317
1441
|
### Complete Example with Web Integration
|
|
@@ -1321,39 +1445,47 @@ Here's a full example showing how to integrate task events with a web applicatio
|
|
|
1321
1445
|
```python
|
|
1322
1446
|
import asyncio
|
|
1323
1447
|
import uuid
|
|
1324
|
-
from fastapi import FastAPI, WebSocket
|
|
1325
1448
|
from contextlib import asynccontextmanager
|
|
1326
|
-
|
|
1327
|
-
from
|
|
1449
|
+
|
|
1450
|
+
from fastapi import FastAPI, WebSocket
|
|
1451
|
+
from async_events import GroupFilter, event_manager
|
|
1452
|
+
from async_task_worker import AsyncTaskWorker, task
|
|
1453
|
+
from async_task_worker.api import create_task_worker_router
|
|
1328
1454
|
|
|
1329
1455
|
# Create worker
|
|
1330
1456
|
worker = AsyncTaskWorker(max_workers=5)
|
|
1331
1457
|
|
|
1332
|
-
|
|
1333
|
-
|
|
1458
|
+
|
|
1459
|
+
# A task that publishes its own progress and completion events
|
|
1460
|
+
@task("computation_task")
|
|
1461
|
+
async def computation_task(data, computation_id, delay=0.5):
|
|
1462
|
+
total_steps = 5
|
|
1463
|
+
for step in range(1, total_steps + 1):
|
|
1464
|
+
await asyncio.sleep(delay) # Simulate work
|
|
1465
|
+
await event_manager.publish_event(
|
|
1466
|
+
event_id=f"{computation_id}_step_{step}",
|
|
1467
|
+
group_id=computation_id,
|
|
1468
|
+
event_data={"computation_id": computation_id, "progress": step / total_steps}
|
|
1469
|
+
)
|
|
1470
|
+
|
|
1471
|
+
result = {"computation_id": computation_id, "data": data}
|
|
1472
|
+
await event_manager.publish_event(
|
|
1473
|
+
event_id=f"{computation_id}_completed",
|
|
1474
|
+
group_id=computation_id,
|
|
1475
|
+
event_data={"computation_id": computation_id, "status": "completed", "result": result}
|
|
1476
|
+
)
|
|
1477
|
+
return result
|
|
1478
|
+
|
|
1334
1479
|
|
|
1335
1480
|
@asynccontextmanager
|
|
1336
1481
|
async def lifespan(app: FastAPI):
|
|
1337
|
-
|
|
1338
|
-
# Start worker
|
|
1482
|
+
# Start worker and event manager
|
|
1339
1483
|
await worker.start()
|
|
1340
|
-
|
|
1341
|
-
# Start event manager
|
|
1342
1484
|
await event_manager.start()
|
|
1343
|
-
|
|
1344
|
-
# Configure event monitoring
|
|
1345
|
-
event_monitor_task = await configure_task_worker_events(worker)
|
|
1346
|
-
|
|
1485
|
+
|
|
1347
1486
|
yield
|
|
1348
|
-
|
|
1487
|
+
|
|
1349
1488
|
# Cleanup
|
|
1350
|
-
if event_monitor_task:
|
|
1351
|
-
event_monitor_task.cancel()
|
|
1352
|
-
try:
|
|
1353
|
-
await event_monitor_task
|
|
1354
|
-
except asyncio.CancelledError:
|
|
1355
|
-
pass
|
|
1356
|
-
|
|
1357
1489
|
await event_manager.stop()
|
|
1358
1490
|
await worker.stop()
|
|
1359
1491
|
|
|
@@ -1468,9 +1600,14 @@ async function startComputation(data) {
|
|
|
1468
1600
|
#### Reactive Task Monitoring Dashboard
|
|
1469
1601
|
|
|
1470
1602
|
```python
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1603
|
+
import asyncio
|
|
1604
|
+
|
|
1605
|
+
from async_events import event_manager
|
|
1606
|
+
|
|
1607
|
+
|
|
1608
|
+
async def monitor_all_tasks(worker, update_dashboard):
|
|
1609
|
+
"""Create a real-time dashboard of all tasks. update_dashboard(event) is your own async UI update."""
|
|
1610
|
+
# Subscribe to the "all_tasks" group, which the monitor below publishes to
|
|
1474
1611
|
subscriber_id, queue = await event_manager.subscribe("all_tasks")
|
|
1475
1612
|
|
|
1476
1613
|
# Task to forward all task events to the dashboard
|
|
@@ -1478,26 +1615,26 @@ async def monitor_all_tasks(worker, dashboard_id):
|
|
|
1478
1615
|
while True:
|
|
1479
1616
|
event = await queue.get()
|
|
1480
1617
|
# Update dashboard UI with event data
|
|
1481
|
-
await update_dashboard(
|
|
1618
|
+
await update_dashboard(event)
|
|
1482
1619
|
|
|
1483
|
-
#
|
|
1620
|
+
# Poll the worker and publish its task states (the worker publishes no events itself)
|
|
1484
1621
|
async def process_task_events():
|
|
1485
1622
|
while True:
|
|
1486
1623
|
tasks = await worker.get_all_tasks()
|
|
1487
1624
|
|
|
1488
|
-
for
|
|
1625
|
+
for task_info in tasks:
|
|
1489
1626
|
# Create event data from task info
|
|
1490
1627
|
event_data = {
|
|
1491
|
-
"task_id":
|
|
1492
|
-
"status":
|
|
1493
|
-
"progress":
|
|
1494
|
-
"created_at":
|
|
1495
|
-
"type":
|
|
1628
|
+
"task_id": task_info.id,
|
|
1629
|
+
"status": task_info.status.value,
|
|
1630
|
+
"progress": task_info.progress,
|
|
1631
|
+
"created_at": task_info.created_at.isoformat(),
|
|
1632
|
+
"type": task_info.metadata.get("task_type", "unknown")
|
|
1496
1633
|
}
|
|
1497
1634
|
|
|
1498
|
-
# Publish to
|
|
1635
|
+
# Publish to the dashboard group; the event ID makes it one event per task and status
|
|
1499
1636
|
await event_manager.publish_event(
|
|
1500
|
-
event_id=f"{
|
|
1637
|
+
event_id=f"{task_info.id}_{task_info.status.value}",
|
|
1501
1638
|
group_id="all_tasks", # Dashboard group
|
|
1502
1639
|
event_data=event_data
|
|
1503
1640
|
)
|
|
@@ -1508,15 +1645,21 @@ async def monitor_all_tasks(worker, dashboard_id):
|
|
|
1508
1645
|
event_task = asyncio.create_task(forward_events())
|
|
1509
1646
|
monitor_task = asyncio.create_task(process_task_events())
|
|
1510
1647
|
|
|
1511
|
-
return event_task, monitor_task
|
|
1648
|
+
return event_task, monitor_task, subscriber_id
|
|
1512
1649
|
```
|
|
1513
1650
|
|
|
1514
1651
|
#### Chained Task Processing with Events
|
|
1515
1652
|
|
|
1516
1653
|
```python
|
|
1654
|
+
import asyncio
|
|
1655
|
+
|
|
1656
|
+
from async_events import event_manager
|
|
1657
|
+
from async_task_worker import task
|
|
1658
|
+
|
|
1659
|
+
|
|
1517
1660
|
@task("initial_processor")
|
|
1518
1661
|
async def initial_processor(data):
|
|
1519
|
-
result =
|
|
1662
|
+
result = {"id": data["id"], "value": data["value"] * 2} # Your initial processing
|
|
1520
1663
|
|
|
1521
1664
|
# Publish completion event
|
|
1522
1665
|
await event_manager.publish_event(
|
|
@@ -1534,7 +1677,7 @@ async def initial_processor(data):
|
|
|
1534
1677
|
@task("secondary_processor")
|
|
1535
1678
|
async def secondary_processor(initial_result):
|
|
1536
1679
|
# Process the result from the initial task
|
|
1537
|
-
final_result =
|
|
1680
|
+
final_result = {"id": initial_result["id"], "value": initial_result["value"] + 1}
|
|
1538
1681
|
|
|
1539
1682
|
# Publish completion event
|
|
1540
1683
|
await event_manager.publish_event(
|
|
@@ -1549,46 +1692,56 @@ async def secondary_processor(initial_result):
|
|
|
1549
1692
|
|
|
1550
1693
|
return final_result
|
|
1551
1694
|
|
|
1695
|
+
|
|
1696
|
+
async def wait_for_stage(queue, stage, timeout):
|
|
1697
|
+
"""Wait for the event of one stage; raises TimeoutError."""
|
|
1698
|
+
async with asyncio.timeout(timeout):
|
|
1699
|
+
while True:
|
|
1700
|
+
event = await queue.get()
|
|
1701
|
+
if event.get("stage") == stage:
|
|
1702
|
+
return event
|
|
1703
|
+
|
|
1704
|
+
|
|
1552
1705
|
# Event-driven task chain
|
|
1553
|
-
async def process_data_chain(data):
|
|
1706
|
+
async def process_data_chain(worker, data):
|
|
1554
1707
|
data_id = data["id"]
|
|
1555
1708
|
|
|
1556
|
-
#
|
|
1557
|
-
|
|
1709
|
+
# Subscribe before starting, so no event is missed
|
|
1710
|
+
subscriber_id, queue = await event_manager.subscribe(data_id)
|
|
1711
|
+
try:
|
|
1558
1712
|
# Start initial processing
|
|
1559
|
-
|
|
1713
|
+
await worker.add_task(
|
|
1560
1714
|
initial_processor,
|
|
1561
1715
|
data=data,
|
|
1562
1716
|
metadata={"group_id": data_id}
|
|
1563
1717
|
)
|
|
1564
1718
|
|
|
1565
1719
|
# Wait for initial processing event
|
|
1566
|
-
initial_event = await
|
|
1567
|
-
|
|
1568
|
-
if not initial_event:
|
|
1569
|
-
raise TimeoutError("Initial processing timed out")
|
|
1720
|
+
initial_event = await wait_for_stage(queue, "initial", timeout=30.0)
|
|
1570
1721
|
|
|
1571
1722
|
# Start secondary processing with the result from the initial task
|
|
1572
|
-
|
|
1723
|
+
await worker.add_task(
|
|
1573
1724
|
secondary_processor,
|
|
1574
1725
|
initial_result=initial_event["result"],
|
|
1575
1726
|
metadata={"group_id": data_id}
|
|
1576
1727
|
)
|
|
1577
1728
|
|
|
1578
1729
|
# Wait for secondary processing event
|
|
1579
|
-
secondary_event = await
|
|
1580
|
-
|
|
1581
|
-
if not secondary_event:
|
|
1582
|
-
raise TimeoutError("Secondary processing timed out")
|
|
1730
|
+
secondary_event = await wait_for_stage(queue, "secondary", timeout=30.0)
|
|
1583
1731
|
|
|
1584
1732
|
return secondary_event["result"]
|
|
1733
|
+
finally:
|
|
1734
|
+
await event_manager.unsubscribe(subscriber_id)
|
|
1585
1735
|
```
|
|
1586
1736
|
|
|
1587
1737
|
### Server-Sent Events (SSE) Integration
|
|
1588
1738
|
|
|
1589
|
-
For web applications, you can
|
|
1739
|
+
For web applications, you can stream task events to browsers as Server-Sent Events from a FastAPI endpoint:
|
|
1590
1740
|
|
|
1591
1741
|
```python
|
|
1742
|
+
import asyncio
|
|
1743
|
+
import json
|
|
1744
|
+
|
|
1592
1745
|
from fastapi import FastAPI, Request
|
|
1593
1746
|
from fastapi.responses import StreamingResponse
|
|
1594
1747
|
from async_events import event_manager
|
|
@@ -1602,7 +1755,7 @@ async def event_stream(request: Request, task_id: str):
|
|
|
1602
1755
|
subscriber_id, queue = await event_manager.subscribe(task_id)
|
|
1603
1756
|
|
|
1604
1757
|
try:
|
|
1605
|
-
# Send
|
|
1758
|
+
# Send an initial event
|
|
1606
1759
|
yield "event: connected\ndata: {\"task_id\":\"" + task_id + "\"}\n\n"
|
|
1607
1760
|
|
|
1608
1761
|
# Stream events until client disconnects
|
|
@@ -1631,24 +1784,65 @@ async def event_stream(request: Request, task_id: str):
|
|
|
1631
1784
|
)
|
|
1632
1785
|
```
|
|
1633
1786
|
|
|
1787
|
+
### Consuming an SSE Stream with SSEClient
|
|
1788
|
+
|
|
1789
|
+
`SSEClient` is an httpx-based client that consumes a Server-Sent Events stream, such as the endpoint above, from
|
|
1790
|
+
Python (for example in tests or another service). It does not serve events. It needs the `sse` extra:
|
|
1791
|
+
|
|
1792
|
+
```bash
|
|
1793
|
+
pip install "async-task-worker[sse]"
|
|
1794
|
+
```
|
|
1795
|
+
|
|
1796
|
+
```python
|
|
1797
|
+
from async_events import SSEClient
|
|
1798
|
+
|
|
1799
|
+
|
|
1800
|
+
async def follow_task_events(task_id):
|
|
1801
|
+
client = SSEClient(
|
|
1802
|
+
f"http://localhost:8000/events/{task_id}",
|
|
1803
|
+
headers=None, # Extra request headers
|
|
1804
|
+
event_callback=lambda event_type, data: print(event_type, data), # Optional, called for each event
|
|
1805
|
+
timeout=60, # httpx timeout in seconds
|
|
1806
|
+
)
|
|
1807
|
+
await client.start() # Connects in a background task and reconnects after connection errors
|
|
1808
|
+
try:
|
|
1809
|
+
# Wait for a given event type (returns None on timeout)
|
|
1810
|
+
completed = await client.wait_for_event("completed", timeout=30.0)
|
|
1811
|
+
if completed:
|
|
1812
|
+
print(f"Task completed: {completed['data']}")
|
|
1813
|
+
|
|
1814
|
+
print(f"{len(client.get_events())} events received, running: {client.is_running}")
|
|
1815
|
+
finally:
|
|
1816
|
+
await client.stop()
|
|
1817
|
+
```
|
|
1818
|
+
|
|
1819
|
+
Each event is a dict `{"event": <event type>, "data": <parsed JSON>, "id": <event id or None>}`; events whose data is
|
|
1820
|
+
not JSON are skipped. `await client.get_event(timeout)` returns the next event from the queue (or `None` on timeout),
|
|
1821
|
+
`get_events()` returns all events received so far, and `wait_for_event(event_type, timeout=30.0)` returns the first
|
|
1822
|
+
event of that type, including one already received.
|
|
1823
|
+
|
|
1634
1824
|
### Configuration Options
|
|
1635
1825
|
|
|
1636
1826
|
The event system provides several configuration options:
|
|
1637
1827
|
|
|
1638
1828
|
```python
|
|
1639
|
-
|
|
1640
|
-
custom_event_manager = EventManager(
|
|
1641
|
-
result_ttl=1800, # Keep events in memory for 30 minutes
|
|
1642
|
-
)
|
|
1829
|
+
from async_events import EventManager
|
|
1643
1830
|
|
|
1644
|
-
# Start the event manager
|
|
1645
|
-
await custom_event_manager.start()
|
|
1646
1831
|
|
|
1647
|
-
|
|
1648
|
-
|
|
1832
|
+
async def run_with_own_event_manager():
|
|
1833
|
+
# Create event manager with custom settings (the shared event_manager uses result_ttl=300)
|
|
1834
|
+
custom_event_manager = EventManager(
|
|
1835
|
+
result_ttl=1800, # Keep events in memory for 30 minutes
|
|
1836
|
+
)
|
|
1837
|
+
|
|
1838
|
+
# Start the event manager
|
|
1839
|
+
await custom_event_manager.start()
|
|
1840
|
+
|
|
1841
|
+
# Clean up when done
|
|
1842
|
+
await custom_event_manager.stop()
|
|
1649
1843
|
```
|
|
1650
1844
|
|
|
1651
|
-
By
|
|
1845
|
+
By publishing events from your tasks, or from a monitor that polls the worker, you can build real-time dashboards, notification systems, and event-driven processing chains that react immediately to task state changes.
|
|
1652
1846
|
|
|
1653
1847
|
|
|
1654
1848
|
## License
|
|
@@ -1659,13 +1853,23 @@ MIT
|
|
|
1659
1853
|
|
|
1660
1854
|
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
1661
1855
|
|
|
1662
|
-
###
|
|
1856
|
+
### Development
|
|
1663
1857
|
|
|
1664
1858
|
```bash
|
|
1665
1859
|
git clone https://github.com/descoped/async-task-worker.git
|
|
1666
1860
|
cd async-task-worker
|
|
1667
|
-
uv venv
|
|
1668
|
-
|
|
1669
|
-
uv
|
|
1670
|
-
|
|
1861
|
+
uv sync --all-groups # creates .venv with all extras, dev and test tools
|
|
1862
|
+
|
|
1863
|
+
uv run pytest # run the tests
|
|
1864
|
+
uv run ruff check . # lint
|
|
1865
|
+
uv run ruff format . # format
|
|
1671
1866
|
```
|
|
1867
|
+
|
|
1868
|
+
CI runs ruff and the tests on Python 3.11 and 3.15, the oldest and newest supported versions, for every pull request
|
|
1869
|
+
and every push to `master`.
|
|
1870
|
+
|
|
1871
|
+
### Releasing
|
|
1872
|
+
|
|
1873
|
+
Releases are published to PyPI by the `Release to PyPI` workflow, started by hand with the version to release. It
|
|
1874
|
+
tests, builds, publishes to PyPI and then creates the `vX.Y.Z` tag and GitHub release. See
|
|
1875
|
+
[.github/RELEASE.md](.github/RELEASE.md).
|