async-task-worker 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1144 @@
1
+ Metadata-Version: 2.4
2
+ Name: async-task-worker
3
+ Version: 0.3.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: msgpack>=1.1.0
19
+ Requires-Dist: pydantic>=2.11.2
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Async Task Worker
23
+
24
+ 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.
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ pip install async-task-worker
30
+ ```
31
+
32
+ ## Features
33
+
34
+ - **Asynchronous Execution**: Built on Python's asyncio for efficient concurrent task processing
35
+ - **Priority Queuing**: Tasks can be assigned priorities for execution order control
36
+ - **Task Tracking**: Comprehensive status monitoring and progress reporting
37
+ - **Cancellation Support**: Ability to cancel running or pending tasks
38
+ - **Result Caching**: Optional caching system with time-to-live (TTL) and size limits
39
+ - **Progress Reporting**: Built-in callback mechanism for task progress updates
40
+ - **Flexible Design**: Customizable cache adapters and task registration
41
+ - **Concurrent Task Processing**: Run multiple asynchronous tasks concurrently
42
+ - **Status Tracking**: Monitor task status, progress, and results
43
+ - **Task Registry**: Register task handlers by type
44
+ - **Worker Pool Architecture**: Decoupled worker pool implementation for improved flexibility
45
+ - **API Integration**: Ready-to-use FastAPI router for task management
46
+ - **Modular Structure**: Clean, consistent module organization with a logical structure
47
+
48
+ ## Sequence Diagrams
49
+
50
+ - [Task Registry Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Registry%20Sequence%20Diagram.mmd)
51
+ - [AsyncTaskWorker Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/AsyncTaskWorker%20Sequence%20Diagram.mmd)
52
+ - [Task Cache Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Cache%20Sequence%20Diagram.mmd)
53
+ - [Task Worker API Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Worker%20API%20Sequence%20Diagram.mmd)
54
+ - [AsyncTaskWorker Class Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/AsyncTaskWorker%20Class%20Diagram.mmd)
55
+
56
+
57
+ ## How It Works
58
+
59
+ ### Task Worker Architecture
60
+
61
+ The system follows a modular, decoupled design:
62
+
63
+ 1. **AsyncTaskWorker**: Main coordinator that integrates all components
64
+ 2. **WorkerPool**: Handles worker lifecycle and task execution processing
65
+ 3. **TaskQueue**: Manages prioritized task queuing and retrieval
66
+ 4. **TaskExecutor**: Executes individual tasks with timeout and caching
67
+ 5. **TaskRegistry**: Provides a global registry for task handlers
68
+ 6. **AsyncCacheAdapter**: Provides integration with the async_cache package for efficient result caching
69
+
70
+ The workflow proceeds as follows:
71
+
72
+ 1. When you add a task via `AsyncTaskWorker.add_task()`, it's placed in a priority queue
73
+ 2. Worker coroutines from the `WorkerPool` pick tasks from the queue based on priority
74
+ 3. The `TaskExecutor` executes the task function and captures results or errors
75
+ 4. Task status and progress are tracked in a `TaskInfo` object maintained by the `AsyncTaskWorker`
76
+ 5. Progress updates can be reported back via callbacks
77
+ 6. Results can optionally be cached for future reuse
78
+
79
+ ```python
80
+ import asyncio
81
+ from async_task_worker import AsyncTaskWorker
82
+
83
+
84
+ async def main():
85
+ # Create worker with 3 concurrent workers and 60s timeout
86
+ worker = AsyncTaskWorker(max_workers=3, task_timeout=60)
87
+ await worker.start()
88
+
89
+ try:
90
+ # Use the worker...
91
+ pass
92
+ finally:
93
+ # Graceful shutdown
94
+ await worker.stop()
95
+
96
+
97
+ asyncio.run(main())
98
+ ```
99
+
100
+ ## Quick Start
101
+
102
+ ```python
103
+ import asyncio
104
+ from async_task_worker import AsyncTaskWorker, task
105
+
106
+
107
+ # Define a task with the decorator
108
+ @task("process_data")
109
+ async def process_data(data, progress_callback=None):
110
+ total = len(data)
111
+ result = []
112
+
113
+ for i, item in enumerate(data):
114
+ # Process item
115
+ processed = item * 2
116
+ result.append(processed)
117
+
118
+ # Report progress (0.0 to 1.0)
119
+ if progress_callback:
120
+ progress_callback((i + 1) / total)
121
+
122
+ # Simulate work
123
+ await asyncio.sleep(0.1)
124
+
125
+ return result
126
+
127
+
128
+ async def main():
129
+ # Create worker with 5 concurrent workers
130
+ worker = AsyncTaskWorker(max_workers=5)
131
+
132
+ # Start the worker pool
133
+ await worker.start()
134
+
135
+ try:
136
+ # Add a task by referencing the function directly
137
+ task_id = await worker.add_task(
138
+ process_data,
139
+ [1, 2, 3, 4, 5],
140
+ priority=0
141
+ )
142
+
143
+ # Monitor task progress
144
+ while True:
145
+ info = worker.get_task_info(task_id)
146
+ print(f"Progress: {info.progress * 100:.1f}%")
147
+
148
+ if info.status not in ("pending", "running"):
149
+ break
150
+
151
+ await asyncio.sleep(0.5)
152
+
153
+ # Get task result
154
+ info = worker.get_task_info(task_id)
155
+ if info.status == "completed":
156
+ print(f"Result: {info.result}")
157
+ else:
158
+ print(f"Task failed: {info.error}")
159
+
160
+ finally:
161
+ # Stop the worker pool
162
+ await worker.stop()
163
+
164
+
165
+ if __name__ == "__main__":
166
+ asyncio.run(main())
167
+ ```
168
+
169
+ ## Detailed Documentation
170
+
171
+ ### Core Components
172
+
173
+ #### Task Registration and Execution
174
+
175
+ There are two ways to work with tasks:
176
+
177
+ 1. **Direct Function References**: Pass the function object directly to `add_task`
178
+ 2. **Task Type References**: Use the task registry with task type names
179
+
180
+ ##### Method 1: Direct Function References
181
+
182
+ ```python
183
+ # Define and register a task
184
+ @task("process_data")
185
+ async def process_data(data, progress_callback=None):
186
+ # Task implementation
187
+ return result
188
+
189
+ # Execute by passing the function directly
190
+ task_id = await worker.add_task(process_data, data)
191
+ ```
192
+
193
+ ##### Method 2: Task Type References
194
+
195
+ ```python
196
+ # Define and register a task
197
+ @task("process_data")
198
+ async def process_data(data, progress_callback=None):
199
+ # Task implementation
200
+ return result
201
+
202
+
203
+ # Get the function from the registry by task type name
204
+ from async_task_worker import get_task_function
205
+
206
+ task_func = get_task_function("process_data")
207
+
208
+ # Execute the task
209
+ task_id = await worker.add_task(task_func, data)
210
+ ```
211
+
212
+ The second method is particularly useful when:
213
+ - Tasks are registered in different modules
214
+ - You want to decouple task execution from task implementation
215
+ - You're building a dynamic system where task types are determined at runtime
216
+
217
+ ### Task Registry
218
+
219
+ The task registry provides a way to register and retrieve task functions by type:
220
+
221
+ ```python
222
+ from async_task_worker import task, get_task_function
223
+
224
+
225
+ # Register a task function using decorator
226
+ @task("process_data")
227
+ async def process_data_task(data):
228
+ # Process data
229
+ return {"processed": True}
230
+
231
+
232
+ # Get a registered task function
233
+ task_func = get_task_function("process_data")
234
+ ```
235
+
236
+ ### Task Functions and Progress Reporting
237
+
238
+ Task functions must be async and can accept a progress_callback:
239
+
240
+ ```python
241
+ from async_task_worker import task
242
+
243
+
244
+ @task("process_items")
245
+ async def process_items(items, progress_callback=None):
246
+ total = len(items)
247
+ results = []
248
+
249
+ for i, item in enumerate(items):
250
+ # Do work
251
+ result = await process_item(item)
252
+ results.append(result)
253
+
254
+ # Report progress (0.0 to 1.0)
255
+ if progress_callback:
256
+ progress_callback((i + 1) / total)
257
+
258
+ return results
259
+ ```
260
+
261
+ #### Task Worker Configuration
262
+
263
+ The `AsyncTaskWorker` class manages all aspects of task execution:
264
+
265
+ ```python
266
+ worker = AsyncTaskWorker(
267
+ max_workers=10, # Maximum number of concurrent tasks
268
+ task_timeout=None, # Default timeout for tasks in seconds (None = no timeout)
269
+ worker_poll_interval=1.0, # How frequently workers check for new tasks (seconds)
270
+ cache_enabled=False, # Whether to enable result caching
271
+ cache_ttl=3600, # Default cache TTL in seconds (1 hour)
272
+ cache_max_size=1000, # Maximum cache entries (LRU eviction)
273
+ cache_adapter=None # Custom cache adapter (defaults to in-memory)
274
+ )
275
+ ```
276
+
277
+ #### Task Registration
278
+
279
+ The `@task` decorator registers a function in the global task registry:
280
+
281
+ ```python
282
+ from async_task_worker import task
283
+
284
+
285
+ @task("unique_task_type")
286
+ async def my_task(arg1, arg2, progress_callback=None):
287
+ """
288
+ Task implementation.
289
+
290
+ Args:
291
+ arg1: First argument
292
+ arg2: Second argument
293
+ progress_callback: Optional callback for reporting progress
294
+
295
+ Returns:
296
+ The task result
297
+ """
298
+ # Initialization
299
+
300
+ # Report 50% progress
301
+ if progress_callback:
302
+ progress_callback(0.5)
303
+
304
+ # Perform task work
305
+
306
+ return result
307
+ ```
308
+
309
+ Key points about task functions:
310
+ - Must be **async** functions
311
+ - Can accept a `progress_callback` parameter for reporting progress
312
+ - Can return any result that will be stored in the task info
313
+ - Can raise exceptions which will be captured and reported
314
+
315
+ #### Task Status Lifecycle
316
+
317
+ Tasks go through the following states:
318
+ - **PENDING**: Task is queued but not yet running
319
+ - **RUNNING**: Task is currently executing
320
+ - **COMPLETED**: Task finished successfully
321
+ - **FAILED**: Task raised an exception
322
+ - **CANCELLED**: Task was explicitly cancelled
323
+
324
+ ### Adding and Executing Tasks
325
+
326
+ When you add a task to the worker:
327
+
328
+ 1. A unique task ID is generated (or you can provide one)
329
+ 2. The task is added to the queue with its priority
330
+ 3. A worker picks up the task when available
331
+ 4. You can monitor the task's status and progress
332
+ 5. When complete, you can access the result or error
333
+
334
+ ```python
335
+ # Add a task
336
+ task_id = await worker.add_task(
337
+ process_items, # Task function
338
+ ["item1", "item2", "item3"], # Args
339
+ priority=1, # Lower number = higher priority
340
+ metadata={"description": "Processing batch"} # Optional metadata
341
+ )
342
+
343
+ # Check status
344
+ task_info = worker.get_task_info(task_id)
345
+ print(f"Status: {task_info.status}, Progress: {task_info.progress:.0%}")
346
+
347
+ # Get result when complete
348
+ if task_info.status == "completed":
349
+ result = task_info.result
350
+ ```
351
+
352
+ ### Task Management
353
+
354
+ #### Adding Tasks
355
+
356
+ ```python
357
+ # Basic usage
358
+ task_id = await worker.add_task(my_task, arg1, arg2)
359
+
360
+ # With all options
361
+ task_id = await worker.add_task(
362
+ my_task, # Task function or get_task_function("task_type")
363
+ arg1, arg2, # Positional arguments passed to task
364
+ kw1=val1, kw2=val2, # Keyword arguments passed to task
365
+ priority=0, # Task priority (lower number = higher priority)
366
+ task_id="custom-id", # Custom task ID (default: auto-generated UUID)
367
+ metadata={"key": "value"}, # Custom metadata to store with task
368
+ timeout=30, # Task-specific timeout in seconds
369
+ use_cache=True, # Whether to use cache for this task
370
+ cache_ttl=60 # Custom TTL for this task's cache entry
371
+ )
372
+ ```
373
+
374
+ #### Tracking Tasks
375
+
376
+ ```python
377
+ # Get information about a specific task
378
+ info = worker.get_task_info(task_id)
379
+ print(f"Task ID: {info.id}")
380
+ print(f"Status: {info.status}") # 'pending', 'running', 'completed', 'failed', 'cancelled'
381
+ print(f"Progress: {info.progress * 100:.1f}%")
382
+ print(f"Created: {info.created_at}")
383
+ print(f"Started: {info.started_at}")
384
+ print(f"Completed: {info.completed_at}")
385
+ print(f"Result: {info.result}") # Only for completed tasks
386
+ print(f"Error: {info.error}") # Only for failed tasks
387
+ print(f"Metadata: {info.metadata}")
388
+
389
+ # Get multiple tasks with filtering
390
+ from datetime import timedelta
391
+ from async_task_worker import TaskStatus
392
+
393
+ tasks = worker.get_all_tasks(
394
+ status=TaskStatus.COMPLETED, # Filter by status
395
+ limit=10, # Maximum number to return
396
+ older_than=timedelta(hours=1) # Filter by age
397
+ )
398
+
399
+ # Tasks are sorted by creation time (newest first)
400
+ for task in tasks:
401
+ print(f"{task.id}: {task.status}")
402
+ ```
403
+
404
+ #### Task Cancellation
405
+
406
+ ```python
407
+ # Cancel a task (running or pending)
408
+ cancelled = await worker.cancel_task(task_id)
409
+
410
+ if cancelled:
411
+ print("Task was cancelled successfully")
412
+ else:
413
+ print("Task could not be cancelled (not found or already finished)")
414
+ ```
415
+
416
+ #### Waiting for Tasks
417
+
418
+ The worker provides ways to wait for task completion:
419
+
420
+ ```python
421
+ # Get a future that resolves when the task completes
422
+ future = worker.get_task_future(task_id)
423
+
424
+ try:
425
+ # Will raise exception if task fails
426
+ result = await future
427
+ print(f"Task completed with result: {result}")
428
+ except asyncio.CancelledError:
429
+ print("Task was cancelled")
430
+ except Exception as e:
431
+ print(f"Task failed: {str(e)}")
432
+
433
+ # Wait for multiple tasks
434
+ futures = worker.get_task_futures([task_id1, task_id2])
435
+ results = await asyncio.gather(*futures, return_exceptions=True)
436
+
437
+ for i, result in enumerate(results):
438
+ if isinstance(result, Exception):
439
+ print(f"Task {i} failed: {result}")
440
+ else:
441
+ print(f"Task {i} result: {result}")
442
+ ```
443
+
444
+ ### Context Manager Support
445
+
446
+ The worker can be used as an async context manager:
447
+
448
+ ```python
449
+ async def main():
450
+ async with AsyncTaskWorker(max_workers=5) as worker:
451
+ # Worker is automatically started
452
+ task_id = await worker.add_task(my_task, arg1, arg2)
453
+ # ...
454
+ # Worker is automatically stopped at the end of context
455
+ ```
456
+
457
+ ### Using AsyncTaskWorker as a Daemon
458
+
459
+ To use the worker as a headless daemon in your application:
460
+
461
+ ```python
462
+ import asyncio
463
+ import signal
464
+ from async_task_worker import AsyncTaskWorker, task
465
+
466
+ # Global worker
467
+ worker = None
468
+
469
+
470
+ @task("background_task")
471
+ async def background_task(data, progress_callback=None):
472
+ # Long-running task implementation
473
+ return {"status": "completed"}
474
+
475
+
476
+ async def start_worker():
477
+ global worker
478
+ worker = AsyncTaskWorker(max_workers=5)
479
+ await worker.start()
480
+ print("Worker started")
481
+
482
+
483
+ async def stop_worker():
484
+ if worker:
485
+ await worker.stop()
486
+ print("Worker stopped")
487
+
488
+
489
+ async def main():
490
+ # Handle signals for graceful shutdown
491
+ loop = asyncio.get_running_loop()
492
+ for sig in (signal.SIGINT, signal.SIGTERM):
493
+ loop.add_signal_handler(sig, lambda: asyncio.create_task(stop_worker()))
494
+
495
+ # Start worker
496
+ await start_worker()
497
+
498
+ # Add tasks as needed
499
+ task_id = await worker.add_task(background_task, {"key": "value"})
500
+
501
+ # Keep the daemon running
502
+ try:
503
+ while True:
504
+ await asyncio.sleep(1)
505
+ except asyncio.CancelledError:
506
+ pass
507
+ finally:
508
+ await stop_worker()
509
+
510
+
511
+ if __name__ == "__main__":
512
+ asyncio.run(main())
513
+ ```
514
+
515
+ ## Caching System
516
+
517
+ ### Caching Overview
518
+
519
+ 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.
520
+
521
+ #### How Caching Works
522
+
523
+ 1. **Flexible Cache Key Generation**: A unique key is created for each task based on:
524
+ - Task function name
525
+ - Positional arguments
526
+ - Keyword arguments
527
+ - Optional task metadata
528
+ - User-defined custom key functions
529
+
530
+ 2. **Lookup Process**:
531
+ - Before executing a task, the worker checks if the result is already in cache
532
+ - If found and not expired, the cached result is returned immediately
533
+ - If not found, the task is executed and the result is stored in cache
534
+
535
+ 3. **Eviction Policies**:
536
+ - **TTL (Time-To-Live)**: Entries can expire after a set time
537
+ - **LRU (Least Recently Used)**: When the cache size limit is reached, the least recently accessed entries are removed
538
+
539
+ ### Cache Configuration
540
+
541
+ #### Global Cache Settings
542
+
543
+ ```python
544
+ # Enable caching with default settings
545
+ worker = AsyncTaskWorker(
546
+ cache_enabled=True, # Enable the cache
547
+ cache_ttl=3600, # Default time-to-live: 1 hour (in seconds)
548
+ cache_max_size=1000, # Maximum number of entries
549
+ validate_keys=True, # Enable validation of cache keys (optional)
550
+ cleanup_interval=900 # Cleanup interval for stale mappings (15 min)
551
+ )
552
+
553
+ # Disable cache globally but allow per-task override
554
+ worker = AsyncTaskWorker(
555
+ cache_enabled=False # Globally disabled
556
+ )
557
+
558
+ # Disable automatic cleanup of stale mappings
559
+ worker = AsyncTaskWorker(
560
+ cache_enabled=True,
561
+ cleanup_interval=0 # Disable automatic cleanup
562
+ )
563
+ ```
564
+
565
+ #### Per-Task Cache Options
566
+
567
+ ```python
568
+ # Override global cache settings for specific task
569
+ task_id = await worker.add_task(
570
+ my_task,
571
+ arg1,
572
+ arg2,
573
+ use_cache=True, # Enable caching for this task
574
+ cache_ttl=120, # Custom TTL: 2 minutes
575
+ metadata={"version": "1.2"} # Optional metadata for key generation
576
+ )
577
+
578
+ # Bypass cache for a specific task even if globally enabled
579
+ task_id = await worker.add_task(
580
+ my_task,
581
+ arg1,
582
+ arg2,
583
+ use_cache=False # Disable caching for this task
584
+ )
585
+
586
+ # Use a custom cache key function
587
+ task_id = await worker.add_task(
588
+ my_task,
589
+ arg1,
590
+ arg2,
591
+ use_cache=True,
592
+ cache_key_fn=my_custom_key_function # Custom cache key generator
593
+ )
594
+ ```
595
+
596
+ ### Using the Cache Adapter
597
+
598
+ AsyncTaskWorker uses `AsyncCacheAdapter` which provides a clean integration with the `async_cache` package, enabling efficient caching with flexible key generation and storage strategies:
599
+
600
+ ```python
601
+ from async_task_worker import AsyncCacheAdapter
602
+ from async_cache.adapters import RedisCacheAdapter
603
+
604
+ # Using Redis as a cache backend
605
+ import redis.asyncio as redis
606
+
607
+ redis_client = redis.Redis(host='localhost', port=6379, db=0)
608
+ redis_adapter = RedisCacheAdapter(redis_client)
609
+
610
+ cache_adapter = AsyncCacheAdapter(
611
+ default_ttl=3600, # Default TTL: 1 hour
612
+ enabled=True, # Enable caching
613
+ max_serialized_size=5_242_880, # 5MB max serialized size
614
+ validate_keys=True, # Validate cache keys
615
+ cleanup_interval=900, # Cleanup every 15 minutes
616
+ redis_adapter=redis_adapter # Use Redis adapter
617
+ )
618
+
619
+ # Then pass to AsyncTaskWorker
620
+ worker = AsyncTaskWorker(
621
+ max_workers=5,
622
+ cache_adapter=cache_adapter,
623
+ cache_enabled=True
624
+ )
625
+ ```
626
+
627
+ ### Customizable Cache Key Generation
628
+
629
+ The caching system supports flexible, composable cache key functions for advanced caching scenarios.
630
+
631
+ #### Context Dictionary
632
+
633
+ Each cache key function receives a context dictionary containing:
634
+
635
+ ```python
636
+ context = {
637
+ "func_name": "task_function_name",
638
+ "args": (arg1, arg2, ...), # Positional arguments
639
+ "kwargs": {"key1": value1, ...}, # Keyword arguments
640
+ "entry_id": "unique-id", # Optional task/entry ID
641
+ "metadata": {"version": "1.0", ...} # Optional metadata
642
+ }
643
+ ```
644
+
645
+ #### Basic Custom Key Function
646
+
647
+ You can create a custom key function to control exactly how cache keys are generated:
648
+
649
+ ```python
650
+ def version_based_key(context):
651
+ """Generate a cache key based on function name and version."""
652
+ func = context["func_name"]
653
+ version = context.get("metadata", {}).get("version", "1.0")
654
+ return f"{func}:v{version}"
655
+
656
+ # Use the custom key function
657
+ task_id = await worker.add_task(
658
+ process_data,
659
+ dataset,
660
+ use_cache=True,
661
+ metadata={"version": "2.0"},
662
+ cache_key_fn=version_based_key
663
+ )
664
+ ```
665
+
666
+ #### Composable Cache Keys
667
+
668
+ For complex caching scenarios, you can compose multiple key functions together:
669
+
670
+ ```python
671
+ from async_cache import compose_key_functions, extract_key_component
672
+
673
+ # Create component extractors
674
+ user_id = extract_key_component("kwargs.user_id")
675
+ api_version = extract_key_component("metadata.version")
676
+ func_name = extract_key_component("func_name")
677
+
678
+ # Compose them into a single key function
679
+ composite_key = compose_key_functions(func_name, user_id, api_version)
680
+
681
+ # Use the composite key function
682
+ task_id = await worker.add_task(
683
+ get_user_data,
684
+ user_id=123,
685
+ use_cache=True,
686
+ metadata={"version": "v2"},
687
+ cache_key_fn=composite_key
688
+ )
689
+ # Will generate a key like: "get_user_data:123:v2"
690
+ ```
691
+
692
+ #### Key Component Decorator
693
+
694
+ For better readability and reuse, you can use the decorator-based approach:
695
+
696
+ ```python
697
+ from async_cache import key_component, compose_key_functions
698
+
699
+ # Create named components with decorators
700
+ @key_component("user")
701
+ def user_component(context):
702
+ return str(context["kwargs"].get("user_id", "anonymous"))
703
+
704
+ @key_component("region")
705
+ def region_component(context):
706
+ return context["kwargs"].get("region", "global")
707
+
708
+ @key_component() # Uses function name as component name
709
+ def timestamp(context):
710
+ return context.get("metadata", {}).get("timestamp", "0")
711
+
712
+ # Compose named components
713
+ composite_key = compose_key_functions(user_component, region_component, timestamp)
714
+
715
+ # Use in a task
716
+ task_id = await worker.add_task(
717
+ get_regional_data,
718
+ user_id=123,
719
+ region="eu-west",
720
+ use_cache=True,
721
+ metadata={"timestamp": "2023-04-01"},
722
+ cache_key_fn=composite_key
723
+ )
724
+ # Will generate a key like: "user:123:region:eu-west:timestamp:2023-04-01"
725
+ ```
726
+
727
+ #### Cache Utilities
728
+
729
+ ```python
730
+ # Temporarily disable the cache (context manager)
731
+ async with worker.cache._cache.temporarily_disabled():
732
+ # Cache operations in this block will be skipped
733
+ result = await worker.add_task(my_task, arg1, arg2, use_cache=True)
734
+ # The cache is actually bypassed despite use_cache=True
735
+
736
+ # Get cache key for a specific task ID
737
+ key = await worker.cache.get_cache_key_for_task("task-123")
738
+
739
+ # Invalidate cache by task ID
740
+ await worker.cache.invalidate_by_task_id("task-123")
741
+
742
+ # Control the background cleanup task
743
+ await worker.cache.start_cleanup_task() # Start periodic cleanup
744
+ await worker.cache.stop_cleanup_task() # Stop periodic cleanup
745
+ ```
746
+
747
+ ### Cache Management
748
+
749
+ ```python
750
+ # Invalidate a specific cache entry
751
+ invalidated = await worker.invalidate_cache(my_task, arg1, arg2)
752
+ if invalidated:
753
+ print("Cache entry was removed")
754
+
755
+ # Invalidate using task type name
756
+ from async_task_worker import get_task_function
757
+
758
+ task_func = get_task_function("my_task_type")
759
+ invalidated = await worker.invalidate_cache(task_func, arg1, arg2)
760
+
761
+ # Clear the entire cache
762
+ await worker.clear_cache()
763
+ ```
764
+
765
+ ### Cache Adapters
766
+
767
+ The `async_cache` package provides several cache adapters that can be used with AsyncTaskWorker:
768
+
769
+ 1. **MemoryCacheAdapter**: In-memory LRU cache (default)
770
+ 2. **RedisCacheAdapter**: Redis-backed distributed cache
771
+
772
+ ```python
773
+ # Using Memory Adapter (default)
774
+ from async_cache.adapters import MemoryCacheAdapter
775
+
776
+ memory_adapter = MemoryCacheAdapter(max_size=10000)
777
+ cache_adapter = AsyncCacheAdapter(adapter=memory_adapter)
778
+
779
+ # Using Redis Adapter
780
+ from async_cache.adapters import RedisCacheAdapter
781
+ import redis.asyncio as redis
782
+
783
+ redis_client = redis.Redis(host='localhost', port=6379, db=0)
784
+ redis_adapter = RedisCacheAdapter(redis_client,
785
+ key_prefix="tasks:",
786
+ serializer="msgpack")
787
+
788
+ cache_adapter = AsyncCacheAdapter(adapter=redis_adapter)
789
+
790
+ # Pass to AsyncTaskWorker
791
+ worker = AsyncTaskWorker(
792
+ cache_enabled=True,
793
+ cache_adapter=cache_adapter
794
+ )
795
+ ```
796
+
797
+ ### Real-World Examples
798
+
799
+ #### Version-based Cache Invalidation
800
+
801
+ ```python
802
+ # Create a cache key function that includes API version
803
+ def versioned_cache_key(context):
804
+ func = context["func_name"]
805
+ version = context.get("metadata", {}).get("api_version", "v1")
806
+ return f"{func}:{version}"
807
+
808
+ # User requests data with v1 API
809
+ task_id1 = await worker.add_task(
810
+ get_user_data,
811
+ user_id=123,
812
+ use_cache=True,
813
+ metadata={"api_version": "v1"},
814
+ cache_key_fn=versioned_cache_key
815
+ )
816
+
817
+ # Later, after API update, same data with v2 API
818
+ # Will use a different cache key, not reusing v1 cached result
819
+ task_id2 = await worker.add_task(
820
+ get_user_data,
821
+ user_id=123,
822
+ use_cache=True,
823
+ metadata={"api_version": "v2"},
824
+ cache_key_fn=versioned_cache_key
825
+ )
826
+ ```
827
+
828
+ #### Multi-tenant Cache Isolation
829
+
830
+ ```python
831
+ # Create a key function that isolates cache by tenant
832
+ tenant_key = compose_key_functions(
833
+ extract_key_component("func_name"),
834
+ extract_key_component("metadata.tenant_id"),
835
+ extract_key_component("args.0") # First arg value
836
+ )
837
+
838
+ # Different tenants share same function but get isolated cache
839
+ for tenant_id in ["tenant1", "tenant2", "tenant3"]:
840
+ task_id = await worker.add_task(
841
+ process_data,
842
+ "sample_data",
843
+ use_cache=True,
844
+ metadata={"tenant_id": tenant_id},
845
+ cache_key_fn=tenant_key
846
+ )
847
+ ```
848
+
849
+ ### Automatic Cleanup of Stale Mappings
850
+
851
+ The cache system includes an automatic cleanup mechanism to prevent memory leaks from orphaned task ID mappings when cache entries expire through TTL:
852
+
853
+ ```python
854
+ # Configure a worker with cleanup enabled
855
+ worker = AsyncTaskWorker(
856
+ cache_enabled=True,
857
+ cache_ttl=3600, # 1 hour cache TTL
858
+ cleanup_interval=900 # Clean up stale mappings every 15 minutes
859
+ )
860
+
861
+ # The sequence of events:
862
+ # 1. Add a task with caching enabled
863
+ task_id = await worker.add_task(
864
+ process_data,
865
+ dataset,
866
+ use_cache=True,
867
+ cache_ttl=60 # 1 minute TTL
868
+ )
869
+
870
+ # 2. The task_id is mapped to its cache key in task_key_map
871
+
872
+ # 3. After 1 minute, the cache entry expires due to TTL
873
+
874
+ # 4. Without cleanup, the mapping would remain in memory indefinitely
875
+
876
+ # 5. With cleanup enabled, the background task periodically checks
877
+ # all mappings and removes any where the cache entry is gone
878
+
879
+ # 6. Result: No memory leaks from expired cache entries
880
+ ```
881
+
882
+ 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.
883
+
884
+ ## Advanced Usage
885
+
886
+ ### Task Registry
887
+
888
+ The task registry provides ways to discover and lookup registered tasks:
889
+
890
+ ```python
891
+ from async_task_worker import get_task_function, get_all_task_types
892
+
893
+ # Get all registered task types
894
+ task_types = get_all_task_types()
895
+ print(f"Available tasks: {task_types}")
896
+
897
+ # Get a task function by type
898
+ task_func = get_task_function("process_data")
899
+ if task_func:
900
+ # Execute the task
901
+ task_id = await worker.add_task(task_func, data)
902
+ else:
903
+ print("Task type not found")
904
+ ```
905
+
906
+ ### Manual Task Registration
907
+
908
+ Besides the decorator, you can manually register tasks:
909
+
910
+ ```python
911
+ from async_task_worker import register_task
912
+
913
+
914
+ async def my_task(data):
915
+ # Task implementation
916
+ return result
917
+
918
+
919
+ # Register the task
920
+ register_task("custom_task", my_task)
921
+
922
+ # Later, retrieve and execute
923
+ task_func = get_task_function("custom_task")
924
+ task_id = await worker.add_task(task_func, data)
925
+ ```
926
+
927
+ ### Progress Reporting
928
+
929
+ Tasks can report progress through the `progress_callback` parameter:
930
+
931
+ ```python
932
+ @task("long_running_task")
933
+ async def long_running_task(items, progress_callback=None):
934
+ total = len(items)
935
+
936
+ for i, item in enumerate(items):
937
+ # Process item
938
+
939
+ # Report progress as a value between 0.0 and 1.0
940
+ if progress_callback:
941
+ progress_callback(i / total)
942
+
943
+ await asyncio.sleep(0.1)
944
+
945
+ # Final progress update
946
+ if progress_callback:
947
+ progress_callback(1.0)
948
+
949
+ return "Completed"
950
+ ```
951
+
952
+ The progress is stored in the task info and can be retrieved with `get_task_info()`.
953
+
954
+ ## Error Handling
955
+
956
+ The task worker captures exceptions raised by tasks:
957
+
958
+ ```python
959
+ @task("might_fail")
960
+ async def might_fail(value):
961
+ if value < 0:
962
+ raise ValueError("Value cannot be negative")
963
+ return value * 2
964
+
965
+ # Execute task that will fail
966
+ task_id = await worker.add_task(might_fail, -5)
967
+
968
+ # Check the result
969
+ info = worker.get_task_info(task_id)
970
+ assert info.status == TaskStatus.FAILED
971
+ print(f"Task failed: {info.error}") # "Value cannot be negative"
972
+ ```
973
+
974
+ ## API Reference
975
+
976
+ ### AsyncTaskWorker
977
+
978
+ - `__init__(max_workers=10, task_timeout=None, cache_adapter=None, cache_enabled=False, cache_ttl=3600)`: Initialize worker pool
979
+ - `start()`: Start the worker pool
980
+ - `stop(timeout=5.0)`: Stop the worker pool
981
+ - `add_task(task_func, *args, priority=0, task_id=None, metadata=None, use_cache=None, cache_ttl=None, cache_key_fn=None, **kwargs)`: Add a task to the queue
982
+ - `get_task_info(task_id)`: Get information about a task
983
+ - `get_all_tasks(status=None, limit=None, older_than=None)`: Get filtered list of tasks
984
+ - `cancel_task(task_id)`: Cancel a running or pending task
985
+ - `get_task_future(task_id)`: Get a future that resolves when the task completes
986
+ - `wait_for_tasks(task_ids, timeout=None)`: Wait for multiple tasks to complete
987
+ - `wait_for_any_task(task_ids, timeout=None)`: Wait for any of the specified tasks to complete
988
+ - `invalidate_cache(task_func, *args, cache_key_fn=None, **kwargs)`: Invalidate a specific cache entry
989
+ - `clear_cache()`: Clear all cache entries
990
+
991
+ ### AsyncCacheAdapter
992
+
993
+ - `__init__(default_ttl=None, enabled=True, max_serialized_size=10485760, validate_keys=False, cleanup_interval=900, max_size=1000)`: Initialize the cache adapter
994
+ - `get(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Get cached result
995
+ - `set(func_name, args, kwargs, result, ttl=None, cache_key_fn=None, task_id=None, metadata=None)`: Store result in cache
996
+ - `invalidate(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Invalidate specific cache entry
997
+ - `invalidate_by_task_id(task_id)`: Invalidate by task ID
998
+ - `clear()`: Clear the entire cache
999
+ - `start_cleanup_task()`: Start the periodic cleanup task
1000
+ - `stop_cleanup_task()`: Stop the periodic cleanup task
1001
+ - `enabled`: Property to get/set if cache is enabled
1002
+ - `default_ttl`: Property to get/set default TTL
1003
+ - `cleanup_interval`: Property to get/set cleanup interval
1004
+
1005
+ ### WorkerPool
1006
+
1007
+ - `__init__(task_queue, task_executor, max_workers=10)`: Initialize the worker pool
1008
+ - `start()`: Start the worker pool
1009
+ - `stop(timeout=5.0)`: Stop the worker pool gracefully
1010
+ - `cancel_running_task(task_id)`: Cancel a task that is currently running in a worker
1011
+
1012
+ ### Task Registry
1013
+
1014
+ - `@task(task_type)`: Decorator to register a task function
1015
+ - `register_task(task_type, task_func)`: Manually register a task function
1016
+ - `get_task_function(task_type)`: Get the function for a task type
1017
+ - `get_all_task_types()`: Get all registered task types
1018
+
1019
+ ### API Router
1020
+
1021
+ - `create_task_worker_router(worker, prefix="", tags=None)`: Create a FastAPI router for task management
1022
+
1023
+ ## API Router - Control API for Task Worker (optional)
1024
+
1025
+ 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.
1026
+
1027
+ ### Install requirement
1028
+
1029
+ ```bash
1030
+ pip install fastapi
1031
+ ```
1032
+
1033
+ ### Quick Start
1034
+
1035
+ ```python
1036
+ from fastapi import FastAPI
1037
+ from contextlib import asynccontextmanager
1038
+ from async_task_worker import AsyncTaskWorker, create_task_worker_router
1039
+
1040
+ # Create task worker
1041
+ worker = AsyncTaskWorker(max_workers=10, cache_enabled=True)
1042
+
1043
+
1044
+ # Define application lifespan
1045
+ @asynccontextmanager
1046
+ async def lifespan(app: FastAPI):
1047
+ await worker.start() # Start worker when app starts
1048
+ yield
1049
+ await worker.stop() # Stop worker when app shuts down
1050
+
1051
+
1052
+ # Create FastAPI app with lifespan
1053
+ app = FastAPI(lifespan=lifespan)
1054
+
1055
+ # Create and include the task worker router
1056
+ app.include_router(create_task_worker_router(worker))
1057
+ ```
1058
+
1059
+ ### Router Customization
1060
+
1061
+ You can customize the router with the following options:
1062
+
1063
+ ```python
1064
+ task_router = create_task_worker_router(
1065
+ worker,
1066
+ prefix="/api/v1", # Add a URL prefix to all routes
1067
+ tags=["background-tasks"] # Custom OpenAPI documentation tags
1068
+ )
1069
+ ```
1070
+
1071
+ ### Available Endpoints
1072
+
1073
+ The router provides the following endpoints:
1074
+
1075
+ | Method | Endpoint | Description |
1076
+ |--------|----------|-------------|
1077
+ | POST | `/tasks` | Submit a new task for execution |
1078
+ | GET | `/tasks/{task_id}` | Get status and results of a specific task |
1079
+ | DELETE | `/tasks/{task_id}` | Cancel a running or pending task |
1080
+ | GET | `/tasks` | List tasks with optional filtering |
1081
+ | GET | `/tasks/types` | Get a list of all registered task types |
1082
+ | GET | `/health` | Check the health of the task worker service |
1083
+
1084
+ ### Example: Submitting a Task
1085
+
1086
+ ```python
1087
+ import httpx
1088
+
1089
+ async def submit_task():
1090
+ async with httpx.AsyncClient() as client:
1091
+ response = await client.post(
1092
+ "http://localhost:8000/tasks",
1093
+ json={
1094
+ "task_type": "process_data",
1095
+ "params": {
1096
+ "data_id": "123",
1097
+ "options": {"normalize": True}
1098
+ },
1099
+ "priority": 1
1100
+ }
1101
+ )
1102
+
1103
+ task_data = response.json()
1104
+ task_id = task_data["id"]
1105
+ return task_id
1106
+ ```
1107
+
1108
+ ### Example: Checking Task Status
1109
+
1110
+ ```python
1111
+ async def check_task(task_id):
1112
+ async with httpx.AsyncClient() as client:
1113
+ response = await client.get(f"http://localhost:8000/tasks/{task_id}")
1114
+
1115
+ if response.status_code == 200:
1116
+ task_data = response.json()
1117
+ status = task_data["status"]
1118
+
1119
+ if status == "completed":
1120
+ return task_data["result"]
1121
+ elif status == "failed":
1122
+ raise RuntimeError(f"Task failed: {task_data['error']}")
1123
+ else:
1124
+ return f"Task is {status} ({task_data['progress']*100:.1f}% complete)"
1125
+ ```
1126
+
1127
+ ## License
1128
+
1129
+ MIT
1130
+
1131
+ ## Contributing
1132
+
1133
+ Contributions are welcome! Please feel free to submit a Pull Request.
1134
+
1135
+ ### Build
1136
+
1137
+ ```bash
1138
+ git clone https://github.com/descoped/async-task-worker.git
1139
+ cd async-task-worker
1140
+ uv venv
1141
+ source .venv/bin/activate
1142
+ uv sync --all-groups
1143
+ code .
1144
+ ```