async-task-worker 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- async_task_worker-0.1.0.dist-info/METADATA +872 -0
- async_task_worker-0.1.0.dist-info/RECORD +9 -0
- async_task_worker-0.1.0.dist-info/WHEEL +4 -0
- async_task_worker-0.1.0.dist-info/licenses/LICENSE +21 -0
- src/async_task_worker/__init__.py +38 -0
- src/async_task_worker/task_cache.py +262 -0
- src/async_task_worker/task_registry.py +83 -0
- src/async_task_worker/task_worker.py +633 -0
- src/async_task_worker/task_worker_api.py +248 -0
|
@@ -0,0 +1,872 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: async-task-worker
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async Test Worker
|
|
5
|
+
Project-URL: Homepage, https://github.com/descoped/async-task-worker
|
|
6
|
+
Project-URL: Repository, https://github.com/descoped/async-task-worker
|
|
7
|
+
Project-URL: Issues, https://github.com/descoped/async-task-worker/issues
|
|
8
|
+
Author-email: Ove Ranheim <oranheim@gmail.com>
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: asyncio,cache,processor,task,worker
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Requires-Dist: pydantic>=2.11.2
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# Async Task Worker
|
|
22
|
+
|
|
23
|
+
A robust asynchronous task worker system for Python applications with built-in caching support. This library provides a flexible framework for executing and managing background tasks with features like priority scheduling, progress tracking, and result caching.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install async-async-task-worker
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
- **Asynchronous Execution**: Built on Python's asyncio for efficient concurrent task processing
|
|
34
|
+
- **Priority Queuing**: Tasks can be assigned priorities for execution order control
|
|
35
|
+
- **Task Tracking**: Comprehensive status monitoring and progress reporting
|
|
36
|
+
- **Cancellation Support**: Ability to cancel running or pending tasks
|
|
37
|
+
- **Result Caching**: Optional caching system with time-to-live (TTL) and size limits
|
|
38
|
+
- **Progress Reporting**: Built-in callback mechanism for task progress updates
|
|
39
|
+
- **Flexible Design**: Customizable cache adapters and task registration
|
|
40
|
+
- **Concurrent Task Processing**: Run multiple asynchronous tasks concurrently
|
|
41
|
+
- **Status Tracking**: Monitor task status, progress, and results
|
|
42
|
+
- **Task Registry**: Register task handlers by type
|
|
43
|
+
|
|
44
|
+
## Sequence Diagrams
|
|
45
|
+
|
|
46
|
+
- [Task Registry Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Registry%20Sequence%20Diagram.mmd)
|
|
47
|
+
- [AsyncTaskWorker Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/AsyncTaskWorker%20Sequence%20Diagram.mmd)
|
|
48
|
+
- [Task Cache Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Cache%20Sequence%20Diagram.mmd)
|
|
49
|
+
- [Task Worker API Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Worker%20API%20Sequence%20Diagram.mmd)
|
|
50
|
+
- [AsyncTaskWorker Class Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/AsyncTaskWorker%20Class%20Diagram.mmd)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
## How It Works
|
|
54
|
+
|
|
55
|
+
### Task Worker
|
|
56
|
+
|
|
57
|
+
The `AsyncTaskWorker` manages a pool of worker coroutines that process tasks from a priority queue:
|
|
58
|
+
|
|
59
|
+
1. When you add a task, it's placed in a priority queue
|
|
60
|
+
2. Worker coroutines pick tasks from the queue based on priority
|
|
61
|
+
3. The worker executes the task function and captures results or errors
|
|
62
|
+
4. Task status and progress are tracked in a `TaskInfo` object
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import asyncio
|
|
66
|
+
from async_task_worker import AsyncTaskWorker
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def main():
|
|
70
|
+
# Create worker with 3 concurrent workers and 60s timeout
|
|
71
|
+
worker = AsyncTaskWorker(max_workers=3, task_timeout=60)
|
|
72
|
+
await worker.start()
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
# Use the worker...
|
|
76
|
+
pass
|
|
77
|
+
finally:
|
|
78
|
+
# Graceful shutdown
|
|
79
|
+
await worker.stop()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
asyncio.run(main())
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Quick Start
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import asyncio
|
|
89
|
+
from async_task_worker import AsyncTaskWorker, task
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# Define a task with the decorator
|
|
93
|
+
@task("process_data")
|
|
94
|
+
async def process_data(data, progress_callback=None):
|
|
95
|
+
total = len(data)
|
|
96
|
+
result = []
|
|
97
|
+
|
|
98
|
+
for i, item in enumerate(data):
|
|
99
|
+
# Process item
|
|
100
|
+
processed = item * 2
|
|
101
|
+
result.append(processed)
|
|
102
|
+
|
|
103
|
+
# Report progress (0.0 to 1.0)
|
|
104
|
+
if progress_callback:
|
|
105
|
+
progress_callback((i + 1) / total)
|
|
106
|
+
|
|
107
|
+
# Simulate work
|
|
108
|
+
await asyncio.sleep(0.1)
|
|
109
|
+
|
|
110
|
+
return result
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
async def main():
|
|
114
|
+
# Create worker with 5 concurrent workers
|
|
115
|
+
worker = AsyncTaskWorker(max_workers=5)
|
|
116
|
+
|
|
117
|
+
# Start the worker pool
|
|
118
|
+
await worker.start()
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
# Add a task by referencing the function directly
|
|
122
|
+
task_id = await worker.add_task(
|
|
123
|
+
process_data,
|
|
124
|
+
[1, 2, 3, 4, 5],
|
|
125
|
+
priority=0
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
# Monitor task progress
|
|
129
|
+
while True:
|
|
130
|
+
info = worker.get_task_info(task_id)
|
|
131
|
+
print(f"Progress: {info.progress * 100:.1f}%")
|
|
132
|
+
|
|
133
|
+
if info.status not in ("pending", "running"):
|
|
134
|
+
break
|
|
135
|
+
|
|
136
|
+
await asyncio.sleep(0.5)
|
|
137
|
+
|
|
138
|
+
# Get task result
|
|
139
|
+
info = worker.get_task_info(task_id)
|
|
140
|
+
if info.status == "completed":
|
|
141
|
+
print(f"Result: {info.result}")
|
|
142
|
+
else:
|
|
143
|
+
print(f"Task failed: {info.error}")
|
|
144
|
+
|
|
145
|
+
finally:
|
|
146
|
+
# Stop the worker pool
|
|
147
|
+
await worker.stop()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
if __name__ == "__main__":
|
|
151
|
+
asyncio.run(main())
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
## Detailed Documentation
|
|
155
|
+
|
|
156
|
+
### Core Components
|
|
157
|
+
|
|
158
|
+
#### Task Registration and Execution
|
|
159
|
+
|
|
160
|
+
There are two ways to work with tasks:
|
|
161
|
+
|
|
162
|
+
1. **Direct Function References**: Pass the function object directly to `add_task`
|
|
163
|
+
2. **Task Type References**: Use the task registry with task type names
|
|
164
|
+
|
|
165
|
+
##### Method 1: Direct Function References
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
# Define and register a task
|
|
169
|
+
@task("process_data")
|
|
170
|
+
async def process_data(data, progress_callback=None):
|
|
171
|
+
# Task implementation
|
|
172
|
+
return result
|
|
173
|
+
|
|
174
|
+
# Execute by passing the function directly
|
|
175
|
+
task_id = await worker.add_task(process_data, data)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
##### Method 2: Task Type References
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
# Define and register a task
|
|
182
|
+
@task("process_data")
|
|
183
|
+
async def process_data(data, progress_callback=None):
|
|
184
|
+
# Task implementation
|
|
185
|
+
return result
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# Get the function from the registry by task type name
|
|
189
|
+
from async_task_worker import get_task_function
|
|
190
|
+
|
|
191
|
+
task_func = get_task_function("process_data")
|
|
192
|
+
|
|
193
|
+
# Execute the task
|
|
194
|
+
task_id = await worker.add_task(task_func, data)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
The second method is particularly useful when:
|
|
198
|
+
- Tasks are registered in different modules
|
|
199
|
+
- You want to decouple task execution from task implementation
|
|
200
|
+
- You're building a dynamic system where task types are determined at runtime
|
|
201
|
+
|
|
202
|
+
### Task Registry
|
|
203
|
+
|
|
204
|
+
The task registry provides a way to register and retrieve task functions by type:
|
|
205
|
+
|
|
206
|
+
```python
|
|
207
|
+
from async_task_worker import task, get_task_function
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# Register a task function using decorator
|
|
211
|
+
@task("process_data")
|
|
212
|
+
async def process_data_task(data):
|
|
213
|
+
# Process data
|
|
214
|
+
return {"processed": True}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# Get a registered task function
|
|
218
|
+
task_func = get_task_function("process_data")
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### Task Functions and Progress Reporting
|
|
222
|
+
|
|
223
|
+
Task functions must be async and can accept a progress_callback:
|
|
224
|
+
|
|
225
|
+
```python
|
|
226
|
+
from async_task_worker import task
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@task("process_items")
|
|
230
|
+
async def process_items(items, progress_callback=None):
|
|
231
|
+
total = len(items)
|
|
232
|
+
results = []
|
|
233
|
+
|
|
234
|
+
for i, item in enumerate(items):
|
|
235
|
+
# Do work
|
|
236
|
+
result = await process_item(item)
|
|
237
|
+
results.append(result)
|
|
238
|
+
|
|
239
|
+
# Report progress (0.0 to 1.0)
|
|
240
|
+
if progress_callback:
|
|
241
|
+
progress_callback((i + 1) / total)
|
|
242
|
+
|
|
243
|
+
return results
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
#### Task Worker Configuration
|
|
247
|
+
|
|
248
|
+
The `AsyncTaskWorker` class manages all aspects of task execution:
|
|
249
|
+
|
|
250
|
+
```python
|
|
251
|
+
worker = AsyncTaskWorker(
|
|
252
|
+
max_workers=10, # Maximum number of concurrent tasks
|
|
253
|
+
task_timeout=None, # Default timeout for tasks in seconds (None = no timeout)
|
|
254
|
+
worker_poll_interval=1.0, # How frequently workers check for new tasks (seconds)
|
|
255
|
+
cache_enabled=False, # Whether to enable result caching
|
|
256
|
+
cache_ttl=3600, # Default cache TTL in seconds (1 hour)
|
|
257
|
+
cache_max_size=1000, # Maximum cache entries (LRU eviction)
|
|
258
|
+
cache_adapter=None # Custom cache adapter (defaults to in-memory)
|
|
259
|
+
)
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
#### Task Registration
|
|
263
|
+
|
|
264
|
+
The `@task` decorator registers a function in the global task registry:
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
from async_task_worker import task
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@task("unique_task_type")
|
|
271
|
+
async def my_task(arg1, arg2, progress_callback=None):
|
|
272
|
+
"""
|
|
273
|
+
Task implementation.
|
|
274
|
+
|
|
275
|
+
Args:
|
|
276
|
+
arg1: First argument
|
|
277
|
+
arg2: Second argument
|
|
278
|
+
progress_callback: Optional callback for reporting progress
|
|
279
|
+
|
|
280
|
+
Returns:
|
|
281
|
+
The task result
|
|
282
|
+
"""
|
|
283
|
+
# Initialization
|
|
284
|
+
|
|
285
|
+
# Report 50% progress
|
|
286
|
+
if progress_callback:
|
|
287
|
+
progress_callback(0.5)
|
|
288
|
+
|
|
289
|
+
# Perform task work
|
|
290
|
+
|
|
291
|
+
return result
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Key points about task functions:
|
|
295
|
+
- Must be **async** functions
|
|
296
|
+
- Can accept a `progress_callback` parameter for reporting progress
|
|
297
|
+
- Can return any result that will be stored in the task info
|
|
298
|
+
- Can raise exceptions which will be captured and reported
|
|
299
|
+
|
|
300
|
+
#### Task Status Lifecycle
|
|
301
|
+
|
|
302
|
+
Tasks go through the following states:
|
|
303
|
+
- **PENDING**: Task is queued but not yet running
|
|
304
|
+
- **RUNNING**: Task is currently executing
|
|
305
|
+
- **COMPLETED**: Task finished successfully
|
|
306
|
+
- **FAILED**: Task raised an exception
|
|
307
|
+
- **CANCELLED**: Task was explicitly cancelled
|
|
308
|
+
|
|
309
|
+
### Adding and Executing Tasks
|
|
310
|
+
|
|
311
|
+
When you add a task to the worker:
|
|
312
|
+
|
|
313
|
+
1. A unique task ID is generated (or you can provide one)
|
|
314
|
+
2. The task is added to the queue with its priority
|
|
315
|
+
3. A worker picks up the task when available
|
|
316
|
+
4. You can monitor the task's status and progress
|
|
317
|
+
5. When complete, you can access the result or error
|
|
318
|
+
|
|
319
|
+
```python
|
|
320
|
+
# Add a task
|
|
321
|
+
task_id = await worker.add_task(
|
|
322
|
+
process_items, # Task function
|
|
323
|
+
["item1", "item2", "item3"], # Args
|
|
324
|
+
priority=1, # Lower number = higher priority
|
|
325
|
+
metadata={"description": "Processing batch"} # Optional metadata
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
# Check status
|
|
329
|
+
task_info = worker.get_task_info(task_id)
|
|
330
|
+
print(f"Status: {task_info.status}, Progress: {task_info.progress:.0%}")
|
|
331
|
+
|
|
332
|
+
# Get result when complete
|
|
333
|
+
if task_info.status == "completed":
|
|
334
|
+
result = task_info.result
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
### Task Management
|
|
338
|
+
|
|
339
|
+
#### Adding Tasks
|
|
340
|
+
|
|
341
|
+
```python
|
|
342
|
+
# Basic usage
|
|
343
|
+
task_id = await worker.add_task(my_task, arg1, arg2)
|
|
344
|
+
|
|
345
|
+
# With all options
|
|
346
|
+
task_id = await worker.add_task(
|
|
347
|
+
my_task, # Task function or get_task_function("task_type")
|
|
348
|
+
arg1, arg2, # Positional arguments passed to task
|
|
349
|
+
kw1=val1, kw2=val2, # Keyword arguments passed to task
|
|
350
|
+
priority=0, # Task priority (lower number = higher priority)
|
|
351
|
+
task_id="custom-id", # Custom task ID (default: auto-generated UUID)
|
|
352
|
+
metadata={"key": "value"}, # Custom metadata to store with task
|
|
353
|
+
timeout=30, # Task-specific timeout in seconds
|
|
354
|
+
use_cache=True, # Whether to use cache for this task
|
|
355
|
+
cache_ttl=60 # Custom TTL for this task's cache entry
|
|
356
|
+
)
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
#### Tracking Tasks
|
|
360
|
+
|
|
361
|
+
```python
|
|
362
|
+
# Get information about a specific task
|
|
363
|
+
info = worker.get_task_info(task_id)
|
|
364
|
+
print(f"Task ID: {info.id}")
|
|
365
|
+
print(f"Status: {info.status}") # 'pending', 'running', 'completed', 'failed', 'cancelled'
|
|
366
|
+
print(f"Progress: {info.progress * 100:.1f}%")
|
|
367
|
+
print(f"Created: {info.created_at}")
|
|
368
|
+
print(f"Started: {info.started_at}")
|
|
369
|
+
print(f"Completed: {info.completed_at}")
|
|
370
|
+
print(f"Result: {info.result}") # Only for completed tasks
|
|
371
|
+
print(f"Error: {info.error}") # Only for failed tasks
|
|
372
|
+
print(f"Metadata: {info.metadata}")
|
|
373
|
+
|
|
374
|
+
# Get multiple tasks with filtering
|
|
375
|
+
from datetime import timedelta
|
|
376
|
+
from async_task_worker import TaskStatus
|
|
377
|
+
|
|
378
|
+
tasks = worker.get_all_tasks(
|
|
379
|
+
status=TaskStatus.COMPLETED, # Filter by status
|
|
380
|
+
limit=10, # Maximum number to return
|
|
381
|
+
older_than=timedelta(hours=1) # Filter by age
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
# Tasks are sorted by creation time (newest first)
|
|
385
|
+
for task in tasks:
|
|
386
|
+
print(f"{task.id}: {task.status}")
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
#### Task Cancellation
|
|
390
|
+
|
|
391
|
+
```python
|
|
392
|
+
# Cancel a task (running or pending)
|
|
393
|
+
cancelled = await worker.cancel_task(task_id)
|
|
394
|
+
|
|
395
|
+
if cancelled:
|
|
396
|
+
print("Task was cancelled successfully")
|
|
397
|
+
else:
|
|
398
|
+
print("Task could not be cancelled (not found or already finished)")
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
#### Waiting for Tasks
|
|
402
|
+
|
|
403
|
+
The worker provides ways to wait for task completion:
|
|
404
|
+
|
|
405
|
+
```python
|
|
406
|
+
# Get a future that resolves when the task completes
|
|
407
|
+
future = worker.get_task_future(task_id)
|
|
408
|
+
|
|
409
|
+
try:
|
|
410
|
+
# Will raise exception if task fails
|
|
411
|
+
result = await future
|
|
412
|
+
print(f"Task completed with result: {result}")
|
|
413
|
+
except asyncio.CancelledError:
|
|
414
|
+
print("Task was cancelled")
|
|
415
|
+
except Exception as e:
|
|
416
|
+
print(f"Task failed: {str(e)}")
|
|
417
|
+
|
|
418
|
+
# Wait for multiple tasks
|
|
419
|
+
futures = worker.get_task_futures([task_id1, task_id2])
|
|
420
|
+
results = await asyncio.gather(*futures, return_exceptions=True)
|
|
421
|
+
|
|
422
|
+
for i, result in enumerate(results):
|
|
423
|
+
if isinstance(result, Exception):
|
|
424
|
+
print(f"Task {i} failed: {result}")
|
|
425
|
+
else:
|
|
426
|
+
print(f"Task {i} result: {result}")
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
### Context Manager Support
|
|
430
|
+
|
|
431
|
+
The worker can be used as an async context manager:
|
|
432
|
+
|
|
433
|
+
```python
|
|
434
|
+
async def main():
|
|
435
|
+
async with AsyncTaskWorker(max_workers=5) as worker:
|
|
436
|
+
# Worker is automatically started
|
|
437
|
+
task_id = await worker.add_task(my_task, arg1, arg2)
|
|
438
|
+
# ...
|
|
439
|
+
# Worker is automatically stopped at the end of context
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
### Using AsyncTaskWorker as a Daemon
|
|
443
|
+
|
|
444
|
+
To use the worker as a headless daemon in your application:
|
|
445
|
+
|
|
446
|
+
```python
|
|
447
|
+
import asyncio
|
|
448
|
+
import signal
|
|
449
|
+
from async_task_worker import AsyncTaskWorker, task
|
|
450
|
+
|
|
451
|
+
# Global worker
|
|
452
|
+
worker = None
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
@task("background_task")
|
|
456
|
+
async def background_task(data, progress_callback=None):
|
|
457
|
+
# Long-running task implementation
|
|
458
|
+
return {"status": "completed"}
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
async def start_worker():
|
|
462
|
+
global worker
|
|
463
|
+
worker = AsyncTaskWorker(max_workers=5)
|
|
464
|
+
await worker.start()
|
|
465
|
+
print("Worker started")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
async def stop_worker():
|
|
469
|
+
if worker:
|
|
470
|
+
await worker.stop()
|
|
471
|
+
print("Worker stopped")
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
async def main():
|
|
475
|
+
# Handle signals for graceful shutdown
|
|
476
|
+
loop = asyncio.get_running_loop()
|
|
477
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
478
|
+
loop.add_signal_handler(sig, lambda: asyncio.create_task(stop_worker()))
|
|
479
|
+
|
|
480
|
+
# Start worker
|
|
481
|
+
await start_worker()
|
|
482
|
+
|
|
483
|
+
# Add tasks as needed
|
|
484
|
+
task_id = await worker.add_task(background_task, {"key": "value"})
|
|
485
|
+
|
|
486
|
+
# Keep the daemon running
|
|
487
|
+
try:
|
|
488
|
+
while True:
|
|
489
|
+
await asyncio.sleep(1)
|
|
490
|
+
except asyncio.CancelledError:
|
|
491
|
+
pass
|
|
492
|
+
finally:
|
|
493
|
+
await stop_worker()
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
if __name__ == "__main__":
|
|
497
|
+
asyncio.run(main())
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
## Caching System
|
|
501
|
+
|
|
502
|
+
### Caching Overview
|
|
503
|
+
|
|
504
|
+
The task worker includes an optional caching system that stores task results to avoid redundant computation. This can dramatically improve performance for frequently executed tasks with the same arguments.
|
|
505
|
+
|
|
506
|
+
#### How Caching Works
|
|
507
|
+
|
|
508
|
+
1. **Cache Key Generation**: A unique key is created for each task based on:
|
|
509
|
+
- Task function name
|
|
510
|
+
- Positional arguments
|
|
511
|
+
- Keyword arguments
|
|
512
|
+
|
|
513
|
+
2. **Lookup Process**:
|
|
514
|
+
- Before executing a task, the worker checks if the result is already in cache
|
|
515
|
+
- If found and not expired, the cached result is returned immediately
|
|
516
|
+
- If not found, the task is executed and the result is stored in cache
|
|
517
|
+
|
|
518
|
+
3. **Eviction Policies**:
|
|
519
|
+
- **TTL (Time-To-Live)**: Entries can expire after a set time
|
|
520
|
+
- **LRU (Least Recently Used)**: When the cache size limit is reached, the least recently accessed entries are removed
|
|
521
|
+
|
|
522
|
+
### Cache Configuration
|
|
523
|
+
|
|
524
|
+
#### Global Cache Settings
|
|
525
|
+
|
|
526
|
+
```python
|
|
527
|
+
# Enable caching with default settings
|
|
528
|
+
worker = AsyncTaskWorker(
|
|
529
|
+
cache_enabled=True, # Enable the cache
|
|
530
|
+
cache_ttl=3600, # Default time-to-live: 1 hour (in seconds)
|
|
531
|
+
cache_max_size=1000 # Maximum number of entries
|
|
532
|
+
)
|
|
533
|
+
|
|
534
|
+
# Disable cache globally but allow per-task override
|
|
535
|
+
worker = AsyncTaskWorker(
|
|
536
|
+
cache_enabled=False # Globally disabled
|
|
537
|
+
)
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
#### Per-Task Cache Options
|
|
541
|
+
|
|
542
|
+
```python
|
|
543
|
+
# Override global cache settings for specific task
|
|
544
|
+
task_id = await worker.add_task(
|
|
545
|
+
my_task,
|
|
546
|
+
arg1,
|
|
547
|
+
arg2,
|
|
548
|
+
use_cache=True, # Enable caching for this task
|
|
549
|
+
cache_ttl=120 # Custom TTL: 2 minutes
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
# Bypass cache for a specific task even if globally enabled
|
|
553
|
+
task_id = await worker.add_task(
|
|
554
|
+
my_task,
|
|
555
|
+
arg1,
|
|
556
|
+
arg2,
|
|
557
|
+
use_cache=False # Disable caching for this task
|
|
558
|
+
)
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
### Cache Management
|
|
562
|
+
|
|
563
|
+
```python
|
|
564
|
+
# Invalidate a specific cache entry
|
|
565
|
+
invalidated = await worker.invalidate_cache(my_task, arg1, arg2)
|
|
566
|
+
if invalidated:
|
|
567
|
+
print("Cache entry was removed")
|
|
568
|
+
|
|
569
|
+
# Invalidate using task type name
|
|
570
|
+
from async_task_worker import get_task_function
|
|
571
|
+
|
|
572
|
+
task_func = get_task_function("my_task_type")
|
|
573
|
+
invalidated = await worker.invalidate_cache(task_func, arg1, arg2)
|
|
574
|
+
|
|
575
|
+
# Clear the entire cache
|
|
576
|
+
await worker.clear_cache()
|
|
577
|
+
```
|
|
578
|
+
|
|
579
|
+
### Custom Cache Adapters
|
|
580
|
+
|
|
581
|
+
By default, the task worker uses an in-memory cache, but you can create custom cache adapters for persistent storage or distributed caching.
|
|
582
|
+
|
|
583
|
+
```python
|
|
584
|
+
from async_task_worker import CacheAdapter
|
|
585
|
+
from typing import Any, Optional, Tuple
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
class RedisCache(CacheAdapter):
|
|
589
|
+
"""Example Redis-based cache adapter"""
|
|
590
|
+
|
|
591
|
+
def __init__(self, redis_client):
|
|
592
|
+
self.redis = redis_client
|
|
593
|
+
|
|
594
|
+
async def get(self, key: str) -> Tuple[bool, Any]:
|
|
595
|
+
"""Get a value from the cache"""
|
|
596
|
+
value = await self.redis.get(key)
|
|
597
|
+
if value is None:
|
|
598
|
+
return False, None
|
|
599
|
+
# Deserialize value (e.g., from JSON or pickle)
|
|
600
|
+
deserialized = self._deserialize(value)
|
|
601
|
+
return True, deserialized
|
|
602
|
+
|
|
603
|
+
async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
|
|
604
|
+
"""Set a value in the cache"""
|
|
605
|
+
# Serialize value (e.g., to JSON or pickle)
|
|
606
|
+
serialized = self._serialize(value)
|
|
607
|
+
await self.redis.set(key, serialized, ex=ttl)
|
|
608
|
+
|
|
609
|
+
async def delete(self, key: str) -> bool:
|
|
610
|
+
"""Delete a value from the cache"""
|
|
611
|
+
result = await self.redis.delete(key)
|
|
612
|
+
return result > 0
|
|
613
|
+
|
|
614
|
+
async def clear(self) -> None:
|
|
615
|
+
"""Clear all items (matching a pattern)"""
|
|
616
|
+
# Implementation depends on your Redis usage pattern
|
|
617
|
+
# For example, using a prefix for all keys
|
|
618
|
+
keys = await self.redis.keys("task_cache:*")
|
|
619
|
+
if keys:
|
|
620
|
+
await self.redis.delete(*keys)
|
|
621
|
+
|
|
622
|
+
def _serialize(self, value):
|
|
623
|
+
# Implementation
|
|
624
|
+
pass
|
|
625
|
+
|
|
626
|
+
def _deserialize(self, data):
|
|
627
|
+
# Implementation
|
|
628
|
+
pass
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
# Use custom adapter
|
|
632
|
+
import redis.asyncio as redis
|
|
633
|
+
|
|
634
|
+
redis_client = redis.Redis(host='localhost', port=6379, db=0)
|
|
635
|
+
|
|
636
|
+
worker = AsyncTaskWorker(
|
|
637
|
+
cache_enabled=True,
|
|
638
|
+
cache_adapter=RedisCache(redis_client)
|
|
639
|
+
)
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
## Advanced Usage
|
|
643
|
+
|
|
644
|
+
### Task Registry
|
|
645
|
+
|
|
646
|
+
The task registry provides ways to discover and lookup registered tasks:
|
|
647
|
+
|
|
648
|
+
```python
|
|
649
|
+
from async_task_worker import get_task_function, get_all_task_types
|
|
650
|
+
|
|
651
|
+
# Get all registered task types
|
|
652
|
+
task_types = get_all_task_types()
|
|
653
|
+
print(f"Available tasks: {task_types}")
|
|
654
|
+
|
|
655
|
+
# Get a task function by type
|
|
656
|
+
task_func = get_task_function("process_data")
|
|
657
|
+
if task_func:
|
|
658
|
+
# Execute the task
|
|
659
|
+
task_id = await worker.add_task(task_func, data)
|
|
660
|
+
else:
|
|
661
|
+
print("Task type not found")
|
|
662
|
+
```
|
|
663
|
+
|
|
664
|
+
### Manual Task Registration
|
|
665
|
+
|
|
666
|
+
Besides the decorator, you can manually register tasks:
|
|
667
|
+
|
|
668
|
+
```python
|
|
669
|
+
from async_task_worker import register_task
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
async def my_task(data):
|
|
673
|
+
# Task implementation
|
|
674
|
+
return result
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
# Register the task
|
|
678
|
+
register_task("custom_task", my_task)
|
|
679
|
+
|
|
680
|
+
# Later, retrieve and execute
|
|
681
|
+
task_func = get_task_function("custom_task")
|
|
682
|
+
task_id = await worker.add_task(task_func, data)
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
### Progress Reporting
|
|
686
|
+
|
|
687
|
+
Tasks can report progress through the `progress_callback` parameter:
|
|
688
|
+
|
|
689
|
+
```python
|
|
690
|
+
@task("long_running_task")
|
|
691
|
+
async def long_running_task(items, progress_callback=None):
|
|
692
|
+
total = len(items)
|
|
693
|
+
|
|
694
|
+
for i, item in enumerate(items):
|
|
695
|
+
# Process item
|
|
696
|
+
|
|
697
|
+
# Report progress as a value between 0.0 and 1.0
|
|
698
|
+
if progress_callback:
|
|
699
|
+
progress_callback(i / total)
|
|
700
|
+
|
|
701
|
+
await asyncio.sleep(0.1)
|
|
702
|
+
|
|
703
|
+
# Final progress update
|
|
704
|
+
if progress_callback:
|
|
705
|
+
progress_callback(1.0)
|
|
706
|
+
|
|
707
|
+
return "Completed"
|
|
708
|
+
```
|
|
709
|
+
|
|
710
|
+
The progress is stored in the task info and can be retrieved with `get_task_info()`.
|
|
711
|
+
|
|
712
|
+
## Error Handling
|
|
713
|
+
|
|
714
|
+
The task worker captures exceptions raised by tasks:
|
|
715
|
+
|
|
716
|
+
```python
|
|
717
|
+
@task("might_fail")
|
|
718
|
+
async def might_fail(value):
|
|
719
|
+
if value < 0:
|
|
720
|
+
raise ValueError("Value cannot be negative")
|
|
721
|
+
return value * 2
|
|
722
|
+
|
|
723
|
+
# Execute task that will fail
|
|
724
|
+
task_id = await worker.add_task(might_fail, -5)
|
|
725
|
+
|
|
726
|
+
# Check the result
|
|
727
|
+
info = worker.get_task_info(task_id)
|
|
728
|
+
assert info.status == TaskStatus.FAILED
|
|
729
|
+
print(f"Task failed: {info.error}") # "Value cannot be negative"
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
## API Reference
|
|
733
|
+
|
|
734
|
+
### AsyncTaskWorker
|
|
735
|
+
|
|
736
|
+
- `__init__(max_workers=10, task_timeout=None)`: Initialize worker pool
|
|
737
|
+
- `start()`: Start the worker pool
|
|
738
|
+
- `stop(timeout=5.0)`: Stop the worker pool
|
|
739
|
+
- `add_task(task_func, *args, priority=0, task_id=None, metadata=None, **kwargs)`: Add a task to the queue
|
|
740
|
+
- `get_task_info(task_id)`: Get information about a task
|
|
741
|
+
- `get_all_tasks(status=None, limit=None, older_than=None)`: Get filtered list of tasks
|
|
742
|
+
- `cancel_task(task_id)`: Cancel a running or pending task
|
|
743
|
+
|
|
744
|
+
### Task Registry
|
|
745
|
+
|
|
746
|
+
- `@task(task_type)`: Decorator to register a task function
|
|
747
|
+
- `register_task(task_type, task_func)`: Manually register a task function
|
|
748
|
+
- `get_task_function(task_type)`: Get the function for a task type
|
|
749
|
+
- `get_all_task_types()`: Get all registered task types
|
|
750
|
+
|
|
751
|
+
## API Router - Control API for Task Worker (optional)
|
|
752
|
+
|
|
753
|
+
The AsyncTaskWorker library includes a FastAPI router that you can integrate into your existing FastAPI applications to expose the task worker functionality via a RESTful API.
|
|
754
|
+
|
|
755
|
+
### Install requirement
|
|
756
|
+
|
|
757
|
+
```bash
|
|
758
|
+
pip install fastapi
|
|
759
|
+
```
|
|
760
|
+
|
|
761
|
+
### Quick Start
|
|
762
|
+
|
|
763
|
+
```python
|
|
764
|
+
from fastapi import FastAPI
|
|
765
|
+
from contextlib import asynccontextmanager
|
|
766
|
+
from async_task_worker.task_worker_api import AsyncTaskWorker, create_task_worker_router
|
|
767
|
+
|
|
768
|
+
# Create task worker
|
|
769
|
+
worker = AsyncTaskWorker(max_workers=10, cache_enabled=True)
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
# Define application lifespan
|
|
773
|
+
@asynccontextmanager
|
|
774
|
+
async def lifespan(app: FastAPI):
|
|
775
|
+
await worker.start() # Start worker when app starts
|
|
776
|
+
yield
|
|
777
|
+
await worker.stop() # Stop worker when app shuts down
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
# Create FastAPI app with lifespan
|
|
781
|
+
app = FastAPI(lifespan=lifespan)
|
|
782
|
+
|
|
783
|
+
# Create and include the task worker router
|
|
784
|
+
app.include_router(create_task_worker_router(worker))
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
### Router Customization
|
|
788
|
+
|
|
789
|
+
You can customize the router with the following options:
|
|
790
|
+
|
|
791
|
+
```python
|
|
792
|
+
task_router = create_task_worker_router(
|
|
793
|
+
worker,
|
|
794
|
+
prefix="/api/v1", # Add a URL prefix to all routes
|
|
795
|
+
tags=["background-tasks"] # Custom OpenAPI documentation tags
|
|
796
|
+
)
|
|
797
|
+
```
|
|
798
|
+
|
|
799
|
+
### Available Endpoints
|
|
800
|
+
|
|
801
|
+
The router provides the following endpoints:
|
|
802
|
+
|
|
803
|
+
| Method | Endpoint | Description |
|
|
804
|
+
|--------|----------|-------------|
|
|
805
|
+
| POST | `/tasks` | Submit a new task for execution |
|
|
806
|
+
| GET | `/tasks/{task_id}` | Get status and results of a specific task |
|
|
807
|
+
| DELETE | `/tasks/{task_id}` | Cancel a running or pending task |
|
|
808
|
+
| GET | `/tasks` | List tasks with optional filtering |
|
|
809
|
+
| GET | `/tasks/types` | Get a list of all registered task types |
|
|
810
|
+
| GET | `/health` | Check the health of the task worker service |
|
|
811
|
+
|
|
812
|
+
### Example: Submitting a Task
|
|
813
|
+
|
|
814
|
+
```python
|
|
815
|
+
import httpx
|
|
816
|
+
|
|
817
|
+
async def submit_task():
|
|
818
|
+
async with httpx.AsyncClient() as client:
|
|
819
|
+
response = await client.post(
|
|
820
|
+
"http://localhost:8000/tasks",
|
|
821
|
+
json={
|
|
822
|
+
"task_type": "process_data",
|
|
823
|
+
"params": {
|
|
824
|
+
"data_id": "123",
|
|
825
|
+
"options": {"normalize": True}
|
|
826
|
+
},
|
|
827
|
+
"priority": 1
|
|
828
|
+
}
|
|
829
|
+
)
|
|
830
|
+
|
|
831
|
+
task_data = response.json()
|
|
832
|
+
task_id = task_data["id"]
|
|
833
|
+
return task_id
|
|
834
|
+
```
|
|
835
|
+
|
|
836
|
+
### Example: Checking Task Status
|
|
837
|
+
|
|
838
|
+
```python
|
|
839
|
+
async def check_task(task_id):
|
|
840
|
+
async with httpx.AsyncClient() as client:
|
|
841
|
+
response = await client.get(f"http://localhost:8000/tasks/{task_id}")
|
|
842
|
+
|
|
843
|
+
if response.status_code == 200:
|
|
844
|
+
task_data = response.json()
|
|
845
|
+
status = task_data["status"]
|
|
846
|
+
|
|
847
|
+
if status == "completed":
|
|
848
|
+
return task_data["result"]
|
|
849
|
+
elif status == "failed":
|
|
850
|
+
raise RuntimeError(f"Task failed: {task_data['error']}")
|
|
851
|
+
else:
|
|
852
|
+
return f"Task is {status} ({task_data['progress']*100:.1f}% complete)"
|
|
853
|
+
```
|
|
854
|
+
|
|
855
|
+
## License
|
|
856
|
+
|
|
857
|
+
MIT
|
|
858
|
+
|
|
859
|
+
## Contributing
|
|
860
|
+
|
|
861
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
862
|
+
|
|
863
|
+
### Build
|
|
864
|
+
|
|
865
|
+
```bash
|
|
866
|
+
git clone https://github.com/descoped/async-task-worker.git
|
|
867
|
+
cd async-task-worker
|
|
868
|
+
uv venv
|
|
869
|
+
source .venv/bin/activate
|
|
870
|
+
uv sync --all-groups
|
|
871
|
+
code .
|
|
872
|
+
```
|