async-task-worker 0.1.1__tar.gz → 0.3.0__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.3.0/CLAUDE.md +21 -0
- {async_task_worker-0.1.1 → async_task_worker-0.3.0}/PKG-INFO +329 -57
- {async_task_worker-0.1.1 → async_task_worker-0.3.0}/README.md +327 -56
- {async_task_worker-0.1.1 → async_task_worker-0.3.0}/pyproject.toml +5 -2
- async_task_worker-0.3.0/src/async_cache/__init__.py +83 -0
- async_task_worker-0.3.0/src/async_cache/adapters/__init__.py +11 -0
- async_task_worker-0.3.0/src/async_cache/adapters/memory.py +122 -0
- async_task_worker-0.3.0/src/async_cache/adapters/redis.py +182 -0
- async_task_worker-0.3.0/src/async_cache/core.py +680 -0
- async_task_worker-0.3.0/src/async_cache/exceptions.py +16 -0
- async_task_worker-0.3.0/src/async_cache/key_utils.py +136 -0
- async_task_worker-0.3.0/src/async_cache/serialization.py +230 -0
- async_task_worker-0.3.0/src/async_task_worker/__init__.py +93 -0
- async_task_worker-0.3.0/src/async_task_worker/adapters/__init__.py +3 -0
- async_task_worker-0.3.0/src/async_task_worker/adapters/cache_adapter.py +206 -0
- async_task_worker-0.3.0/src/async_task_worker/api.py +371 -0
- async_task_worker-0.3.0/src/async_task_worker/core.py +717 -0
- async_task_worker-0.3.0/src/async_task_worker/exceptions.py +245 -0
- async_task_worker-0.3.0/src/async_task_worker/executor.py +204 -0
- async_task_worker-0.3.0/src/async_task_worker/futures.py +232 -0
- async_task_worker-0.3.0/src/async_task_worker/pool.py +343 -0
- async_task_worker-0.3.0/src/async_task_worker/queue.py +265 -0
- async_task_worker-0.1.1/src/async_task_worker/task_registry.py → async_task_worker-0.3.0/src/async_task_worker/registry.py +22 -9
- async_task_worker-0.3.0/src/async_task_worker/status.py +243 -0
- {async_task_worker-0.1.1 → async_task_worker-0.3.0}/uv.lock +107 -2
- async_task_worker-0.1.1/build_hook.py +0 -6
- async_task_worker-0.1.1/src/async_task_worker/__init__.py +0 -38
- async_task_worker-0.1.1/src/async_task_worker/task_cache.py +0 -262
- async_task_worker-0.1.1/src/async_task_worker/task_worker.py +0 -633
- async_task_worker-0.1.1/src/async_task_worker/task_worker_api.py +0 -248
- {async_task_worker-0.1.1 → async_task_worker-0.3.0}/.gitignore +0 -0
- {async_task_worker-0.1.1 → async_task_worker-0.3.0}/LICENSE +0 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
+
|
|
5
|
+
## Build and Test Commands
|
|
6
|
+
- Setup environment: `uv venv && source .venv/bin/activate && uv sync --all-groups`
|
|
7
|
+
- Build: `hatch build`
|
|
8
|
+
- Run tests: `pytest`
|
|
9
|
+
- Run single test: `pytest tests/test_file.py::test_function_name`
|
|
10
|
+
- Skip integration tests: `pytest -m "not integration"` (default)
|
|
11
|
+
- Run only asyncio tests: `pytest -m asyncio`
|
|
12
|
+
|
|
13
|
+
## Code Style Guidelines
|
|
14
|
+
- Python 3.11+ with strict type annotations
|
|
15
|
+
- Imports: standard library first, third-party second, local modules third
|
|
16
|
+
- Error handling: Use structured hierarchy with `TaskError` base class
|
|
17
|
+
- Async patterns: Proper cancellation handling with try/finally and asyncio.timeout
|
|
18
|
+
- Naming: CamelCase for classes, snake_case for functions/methods, UPPER_SNAKE_CASE for constants
|
|
19
|
+
- Documentation: Docstrings with type annotations in code
|
|
20
|
+
- Testing: Use pytest fixtures with proper async teardown
|
|
21
|
+
- Clean code: maintain proper resource cleanup in all async contexts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: async-task-worker
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Async Test Worker
|
|
5
5
|
Project-URL: Homepage, https://github.com/descoped/async-task-worker
|
|
6
6
|
Project-URL: Repository, https://github.com/descoped/async-task-worker
|
|
@@ -15,6 +15,7 @@ Classifier: Programming Language :: Python :: 3.11
|
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.12
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.13
|
|
17
17
|
Requires-Python: >=3.11
|
|
18
|
+
Requires-Dist: msgpack>=1.1.0
|
|
18
19
|
Requires-Dist: pydantic>=2.11.2
|
|
19
20
|
Description-Content-Type: text/markdown
|
|
20
21
|
|
|
@@ -25,7 +26,7 @@ A robust asynchronous task worker system for Python applications with built-in c
|
|
|
25
26
|
## Installation
|
|
26
27
|
|
|
27
28
|
```bash
|
|
28
|
-
pip install async-
|
|
29
|
+
pip install async-task-worker
|
|
29
30
|
```
|
|
30
31
|
|
|
31
32
|
## Features
|
|
@@ -40,6 +41,9 @@ pip install async-async-task-worker
|
|
|
40
41
|
- **Concurrent Task Processing**: Run multiple asynchronous tasks concurrently
|
|
41
42
|
- **Status Tracking**: Monitor task status, progress, and results
|
|
42
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
|
|
43
47
|
|
|
44
48
|
## Sequence Diagrams
|
|
45
49
|
|
|
@@ -52,14 +56,25 @@ pip install async-async-task-worker
|
|
|
52
56
|
|
|
53
57
|
## How It Works
|
|
54
58
|
|
|
55
|
-
### Task Worker
|
|
59
|
+
### Task Worker Architecture
|
|
56
60
|
|
|
57
|
-
The
|
|
61
|
+
The system follows a modular, decoupled design:
|
|
58
62
|
|
|
59
|
-
1.
|
|
60
|
-
2.
|
|
61
|
-
3.
|
|
62
|
-
4.
|
|
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
|
|
63
78
|
|
|
64
79
|
```python
|
|
65
80
|
import asyncio
|
|
@@ -505,10 +520,12 @@ The task worker includes an optional caching system that stores task results to
|
|
|
505
520
|
|
|
506
521
|
#### How Caching Works
|
|
507
522
|
|
|
508
|
-
1. **Cache Key Generation**: A unique key is created for each task based on:
|
|
523
|
+
1. **Flexible Cache Key Generation**: A unique key is created for each task based on:
|
|
509
524
|
- Task function name
|
|
510
525
|
- Positional arguments
|
|
511
526
|
- Keyword arguments
|
|
527
|
+
- Optional task metadata
|
|
528
|
+
- User-defined custom key functions
|
|
512
529
|
|
|
513
530
|
2. **Lookup Process**:
|
|
514
531
|
- Before executing a task, the worker checks if the result is already in cache
|
|
@@ -528,13 +545,21 @@ The task worker includes an optional caching system that stores task results to
|
|
|
528
545
|
worker = AsyncTaskWorker(
|
|
529
546
|
cache_enabled=True, # Enable the cache
|
|
530
547
|
cache_ttl=3600, # Default time-to-live: 1 hour (in seconds)
|
|
531
|
-
cache_max_size=1000
|
|
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)
|
|
532
551
|
)
|
|
533
552
|
|
|
534
553
|
# Disable cache globally but allow per-task override
|
|
535
554
|
worker = AsyncTaskWorker(
|
|
536
555
|
cache_enabled=False # Globally disabled
|
|
537
556
|
)
|
|
557
|
+
|
|
558
|
+
# Disable automatic cleanup of stale mappings
|
|
559
|
+
worker = AsyncTaskWorker(
|
|
560
|
+
cache_enabled=True,
|
|
561
|
+
cleanup_interval=0 # Disable automatic cleanup
|
|
562
|
+
)
|
|
538
563
|
```
|
|
539
564
|
|
|
540
565
|
#### Per-Task Cache Options
|
|
@@ -546,7 +571,8 @@ task_id = await worker.add_task(
|
|
|
546
571
|
arg1,
|
|
547
572
|
arg2,
|
|
548
573
|
use_cache=True, # Enable caching for this task
|
|
549
|
-
cache_ttl=120
|
|
574
|
+
cache_ttl=120, # Custom TTL: 2 minutes
|
|
575
|
+
metadata={"version": "1.2"} # Optional metadata for key generation
|
|
550
576
|
)
|
|
551
577
|
|
|
552
578
|
# Bypass cache for a specific task even if globally enabled
|
|
@@ -556,6 +582,166 @@ task_id = await worker.add_task(
|
|
|
556
582
|
arg2,
|
|
557
583
|
use_cache=False # Disable caching for this task
|
|
558
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
|
|
559
745
|
```
|
|
560
746
|
|
|
561
747
|
### Cache Management
|
|
@@ -576,69 +762,125 @@ invalidated = await worker.invalidate_cache(task_func, arg1, arg2)
|
|
|
576
762
|
await worker.clear_cache()
|
|
577
763
|
```
|
|
578
764
|
|
|
579
|
-
###
|
|
765
|
+
### Cache Adapters
|
|
766
|
+
|
|
767
|
+
The `async_cache` package provides several cache adapters that can be used with AsyncTaskWorker:
|
|
580
768
|
|
|
581
|
-
|
|
769
|
+
1. **MemoryCacheAdapter**: In-memory LRU cache (default)
|
|
770
|
+
2. **RedisCacheAdapter**: Redis-backed distributed cache
|
|
582
771
|
|
|
583
772
|
```python
|
|
584
|
-
|
|
585
|
-
from
|
|
773
|
+
# Using Memory Adapter (default)
|
|
774
|
+
from async_cache.adapters import MemoryCacheAdapter
|
|
586
775
|
|
|
776
|
+
memory_adapter = MemoryCacheAdapter(max_size=10000)
|
|
777
|
+
cache_adapter = AsyncCacheAdapter(adapter=memory_adapter)
|
|
587
778
|
|
|
588
|
-
|
|
589
|
-
|
|
779
|
+
# Using Redis Adapter
|
|
780
|
+
from async_cache.adapters import RedisCacheAdapter
|
|
781
|
+
import redis.asyncio as redis
|
|
590
782
|
|
|
591
|
-
|
|
592
|
-
|
|
783
|
+
redis_client = redis.Redis(host='localhost', port=6379, db=0)
|
|
784
|
+
redis_adapter = RedisCacheAdapter(redis_client,
|
|
785
|
+
key_prefix="tasks:",
|
|
786
|
+
serializer="msgpack")
|
|
593
787
|
|
|
594
|
-
|
|
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
|
|
788
|
+
cache_adapter = AsyncCacheAdapter(adapter=redis_adapter)
|
|
602
789
|
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
790
|
+
# Pass to AsyncTaskWorker
|
|
791
|
+
worker = AsyncTaskWorker(
|
|
792
|
+
cache_enabled=True,
|
|
793
|
+
cache_adapter=cache_adapter
|
|
794
|
+
)
|
|
795
|
+
```
|
|
608
796
|
|
|
609
|
-
|
|
610
|
-
"""Delete a value from the cache"""
|
|
611
|
-
result = await self.redis.delete(key)
|
|
612
|
-
return result > 0
|
|
797
|
+
### Real-World Examples
|
|
613
798
|
|
|
614
|
-
|
|
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)
|
|
799
|
+
#### Version-based Cache Invalidation
|
|
621
800
|
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
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
|
+
)
|
|
625
816
|
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
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
|
+
```
|
|
629
827
|
|
|
828
|
+
#### Multi-tenant Cache Isolation
|
|
630
829
|
|
|
631
|
-
|
|
632
|
-
|
|
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
|
+
)
|
|
633
837
|
|
|
634
|
-
|
|
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
|
|
635
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
|
|
636
855
|
worker = AsyncTaskWorker(
|
|
637
|
-
|
|
638
|
-
|
|
856
|
+
cache_enabled=True,
|
|
857
|
+
cache_ttl=3600, # 1 hour cache TTL
|
|
858
|
+
cleanup_interval=900 # Clean up stale mappings every 15 minutes
|
|
639
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
|
|
640
880
|
```
|
|
641
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
|
+
|
|
642
884
|
## Advanced Usage
|
|
643
885
|
|
|
644
886
|
### Task Registry
|
|
@@ -733,13 +975,39 @@ print(f"Task failed: {info.error}") # "Value cannot be negative"
|
|
|
733
975
|
|
|
734
976
|
### AsyncTaskWorker
|
|
735
977
|
|
|
736
|
-
- `__init__(max_workers=10, task_timeout=None)`: Initialize worker pool
|
|
978
|
+
- `__init__(max_workers=10, task_timeout=None, cache_adapter=None, cache_enabled=False, cache_ttl=3600)`: Initialize worker pool
|
|
737
979
|
- `start()`: Start the worker pool
|
|
738
980
|
- `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
|
|
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
|
|
740
982
|
- `get_task_info(task_id)`: Get information about a task
|
|
741
983
|
- `get_all_tasks(status=None, limit=None, older_than=None)`: Get filtered list of tasks
|
|
742
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
|
|
743
1011
|
|
|
744
1012
|
### Task Registry
|
|
745
1013
|
|
|
@@ -748,6 +1016,10 @@ print(f"Task failed: {info.error}") # "Value cannot be negative"
|
|
|
748
1016
|
- `get_task_function(task_type)`: Get the function for a task type
|
|
749
1017
|
- `get_all_task_types()`: Get all registered task types
|
|
750
1018
|
|
|
1019
|
+
### API Router
|
|
1020
|
+
|
|
1021
|
+
- `create_task_worker_router(worker, prefix="", tags=None)`: Create a FastAPI router for task management
|
|
1022
|
+
|
|
751
1023
|
## API Router - Control API for Task Worker (optional)
|
|
752
1024
|
|
|
753
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.
|
|
@@ -763,7 +1035,7 @@ pip install fastapi
|
|
|
763
1035
|
```python
|
|
764
1036
|
from fastapi import FastAPI
|
|
765
1037
|
from contextlib import asynccontextmanager
|
|
766
|
-
from async_task_worker
|
|
1038
|
+
from async_task_worker import AsyncTaskWorker, create_task_worker_router
|
|
767
1039
|
|
|
768
1040
|
# Create task worker
|
|
769
1041
|
worker = AsyncTaskWorker(max_workers=10, cache_enabled=True)
|