async-task-worker 0.3.0__tar.gz → 0.3.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/CLAUDE.md +1 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/PKG-INFO +41 -11
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/README.md +40 -10
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/pyproject.toml +1 -1
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/adapters/cache_adapter.py +68 -7
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/core.py +58 -8
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/executor.py +62 -25
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/pool.py +7 -4
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/uv.lock +1 -1
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/.gitignore +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/LICENSE +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_cache/__init__.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_cache/adapters/__init__.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_cache/adapters/memory.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_cache/adapters/redis.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_cache/core.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_cache/exceptions.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_cache/key_utils.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_cache/serialization.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/__init__.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/adapters/__init__.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/api.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/exceptions.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/futures.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/queue.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/registry.py +0 -0
- {async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/status.py +0 -0
|
@@ -9,6 +9,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|
|
9
9
|
- Run single test: `pytest tests/test_file.py::test_function_name`
|
|
10
10
|
- Skip integration tests: `pytest -m "not integration"` (default)
|
|
11
11
|
- Run only asyncio tests: `pytest -m asyncio`
|
|
12
|
+
- Never perform git add. I manage git manually.
|
|
12
13
|
|
|
13
14
|
## Code Style Guidelines
|
|
14
15
|
- Python 3.11+ with strict type annotations
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: async-task-worker
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.1
|
|
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
|
|
@@ -546,8 +546,7 @@ worker = AsyncTaskWorker(
|
|
|
546
546
|
cache_enabled=True, # Enable the cache
|
|
547
547
|
cache_ttl=3600, # Default time-to-live: 1 hour (in seconds)
|
|
548
548
|
cache_max_size=1000, # Maximum number of entries
|
|
549
|
-
|
|
550
|
-
cleanup_interval=900 # Cleanup interval for stale mappings (15 min)
|
|
549
|
+
cache_cleanup_interval=900 # Cleanup interval for stale mappings (15 min)
|
|
551
550
|
)
|
|
552
551
|
|
|
553
552
|
# Disable cache globally but allow per-task override
|
|
@@ -613,7 +612,7 @@ cache_adapter = AsyncCacheAdapter(
|
|
|
613
612
|
max_serialized_size=5_242_880, # 5MB max serialized size
|
|
614
613
|
validate_keys=True, # Validate cache keys
|
|
615
614
|
cleanup_interval=900, # Cleanup every 15 minutes
|
|
616
|
-
|
|
615
|
+
adapter=redis_adapter # Use Redis adapter
|
|
617
616
|
)
|
|
618
617
|
|
|
619
618
|
# Then pass to AsyncTaskWorker
|
|
@@ -733,15 +732,24 @@ async with worker.cache._cache.temporarily_disabled():
|
|
|
733
732
|
result = await worker.add_task(my_task, arg1, arg2, use_cache=True)
|
|
734
733
|
# The cache is actually bypassed despite use_cache=True
|
|
735
734
|
|
|
736
|
-
#
|
|
737
|
-
|
|
735
|
+
# Generate a composite entry ID for consistent cache access
|
|
736
|
+
func_name = "my_func"
|
|
737
|
+
task_id = "b4fd93c8-57e3-4fea-bcc6-04be7499b28f"
|
|
738
|
+
entry_id = task_worker.cache.generate_entry_id(func_name, task_id)
|
|
738
739
|
|
|
739
|
-
#
|
|
740
|
-
await
|
|
740
|
+
# Get cached result using the composite entry ID
|
|
741
|
+
hit, result = await task_worker.cache.get_by_task_id(entry_id)
|
|
742
|
+
if hit:
|
|
743
|
+
print(f"Retrieved cached result: {result}")
|
|
744
|
+
|
|
745
|
+
# Invalidate cache by the same entry ID
|
|
746
|
+
success = await task_worker.cache.invalidate_by_task_id(entry_id)
|
|
747
|
+
if success:
|
|
748
|
+
print("Cache entry successfully invalidated")
|
|
741
749
|
|
|
742
750
|
# Control the background cleanup task
|
|
743
|
-
await
|
|
744
|
-
await
|
|
751
|
+
await task_worker.cache.start_cleanup_task() # Start periodic cleanup
|
|
752
|
+
await task_worker.cache.stop_cleanup_task() # Stop periodic cleanup
|
|
745
753
|
```
|
|
746
754
|
|
|
747
755
|
### Cache Management
|
|
@@ -772,6 +780,7 @@ The `async_cache` package provides several cache adapters that can be used with
|
|
|
772
780
|
```python
|
|
773
781
|
# Using Memory Adapter (default)
|
|
774
782
|
from async_cache.adapters import MemoryCacheAdapter
|
|
783
|
+
from async_task_worker import AsyncCacheAdapter
|
|
775
784
|
|
|
776
785
|
memory_adapter = MemoryCacheAdapter(max_size=10000)
|
|
777
786
|
cache_adapter = AsyncCacheAdapter(adapter=memory_adapter)
|
|
@@ -994,7 +1003,9 @@ print(f"Task failed: {info.error}") # "Value cannot be negative"
|
|
|
994
1003
|
- `get(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Get cached result
|
|
995
1004
|
- `set(func_name, args, kwargs, result, ttl=None, cache_key_fn=None, task_id=None, metadata=None)`: Store result in cache
|
|
996
1005
|
- `invalidate(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Invalidate specific cache entry
|
|
997
|
-
- `
|
|
1006
|
+
- `generate_entry_id(func_name, task_id)`: Generate a composite entry ID for cache operations
|
|
1007
|
+
- `get_by_task_id(task_id)`: Get cached result using only the task ID
|
|
1008
|
+
- `invalidate_by_task_id(task_id)`: Invalidate cache entry by task ID
|
|
998
1009
|
- `clear()`: Clear the entire cache
|
|
999
1010
|
- `start_cleanup_task()`: Start the periodic cleanup task
|
|
1000
1011
|
- `stop_cleanup_task()`: Stop the periodic cleanup task
|
|
@@ -1124,6 +1135,25 @@ async def check_task(task_id):
|
|
|
1124
1135
|
return f"Task is {status} ({task_data['progress']*100:.1f}% complete)"
|
|
1125
1136
|
```
|
|
1126
1137
|
|
|
1138
|
+
### Example: Reading Result from Cache by Task ID
|
|
1139
|
+
|
|
1140
|
+
```python
|
|
1141
|
+
async def get_cached_result(task_worker, func_name, task_id):
|
|
1142
|
+
# Generate the composite entry ID for cache lookup
|
|
1143
|
+
entry_id = task_worker.cache.generate_entry_id(func_name, task_id)
|
|
1144
|
+
|
|
1145
|
+
# Try to get result directly from cache using the entry_id
|
|
1146
|
+
hit, result = await task_worker.cache.get_by_task_id(entry_id)
|
|
1147
|
+
|
|
1148
|
+
if hit:
|
|
1149
|
+
print(f"Retrieved from cache: {result}")
|
|
1150
|
+
return result
|
|
1151
|
+
else:
|
|
1152
|
+
print(f"No cached result found for function {func_name}, task {task_id}")
|
|
1153
|
+
# Fall back to retrieving via task info
|
|
1154
|
+
return await handle_task_not_in_cache(task_worker, task_id)
|
|
1155
|
+
```
|
|
1156
|
+
|
|
1127
1157
|
## License
|
|
1128
1158
|
|
|
1129
1159
|
MIT
|
|
@@ -525,8 +525,7 @@ worker = AsyncTaskWorker(
|
|
|
525
525
|
cache_enabled=True, # Enable the cache
|
|
526
526
|
cache_ttl=3600, # Default time-to-live: 1 hour (in seconds)
|
|
527
527
|
cache_max_size=1000, # Maximum number of entries
|
|
528
|
-
|
|
529
|
-
cleanup_interval=900 # Cleanup interval for stale mappings (15 min)
|
|
528
|
+
cache_cleanup_interval=900 # Cleanup interval for stale mappings (15 min)
|
|
530
529
|
)
|
|
531
530
|
|
|
532
531
|
# Disable cache globally but allow per-task override
|
|
@@ -592,7 +591,7 @@ cache_adapter = AsyncCacheAdapter(
|
|
|
592
591
|
max_serialized_size=5_242_880, # 5MB max serialized size
|
|
593
592
|
validate_keys=True, # Validate cache keys
|
|
594
593
|
cleanup_interval=900, # Cleanup every 15 minutes
|
|
595
|
-
|
|
594
|
+
adapter=redis_adapter # Use Redis adapter
|
|
596
595
|
)
|
|
597
596
|
|
|
598
597
|
# Then pass to AsyncTaskWorker
|
|
@@ -712,15 +711,24 @@ async with worker.cache._cache.temporarily_disabled():
|
|
|
712
711
|
result = await worker.add_task(my_task, arg1, arg2, use_cache=True)
|
|
713
712
|
# The cache is actually bypassed despite use_cache=True
|
|
714
713
|
|
|
715
|
-
#
|
|
716
|
-
|
|
714
|
+
# Generate a composite entry ID for consistent cache access
|
|
715
|
+
func_name = "my_func"
|
|
716
|
+
task_id = "b4fd93c8-57e3-4fea-bcc6-04be7499b28f"
|
|
717
|
+
entry_id = task_worker.cache.generate_entry_id(func_name, task_id)
|
|
717
718
|
|
|
718
|
-
#
|
|
719
|
-
await
|
|
719
|
+
# Get cached result using the composite entry ID
|
|
720
|
+
hit, result = await task_worker.cache.get_by_task_id(entry_id)
|
|
721
|
+
if hit:
|
|
722
|
+
print(f"Retrieved cached result: {result}")
|
|
723
|
+
|
|
724
|
+
# Invalidate cache by the same entry ID
|
|
725
|
+
success = await task_worker.cache.invalidate_by_task_id(entry_id)
|
|
726
|
+
if success:
|
|
727
|
+
print("Cache entry successfully invalidated")
|
|
720
728
|
|
|
721
729
|
# Control the background cleanup task
|
|
722
|
-
await
|
|
723
|
-
await
|
|
730
|
+
await task_worker.cache.start_cleanup_task() # Start periodic cleanup
|
|
731
|
+
await task_worker.cache.stop_cleanup_task() # Stop periodic cleanup
|
|
724
732
|
```
|
|
725
733
|
|
|
726
734
|
### Cache Management
|
|
@@ -751,6 +759,7 @@ The `async_cache` package provides several cache adapters that can be used with
|
|
|
751
759
|
```python
|
|
752
760
|
# Using Memory Adapter (default)
|
|
753
761
|
from async_cache.adapters import MemoryCacheAdapter
|
|
762
|
+
from async_task_worker import AsyncCacheAdapter
|
|
754
763
|
|
|
755
764
|
memory_adapter = MemoryCacheAdapter(max_size=10000)
|
|
756
765
|
cache_adapter = AsyncCacheAdapter(adapter=memory_adapter)
|
|
@@ -973,7 +982,9 @@ print(f"Task failed: {info.error}") # "Value cannot be negative"
|
|
|
973
982
|
- `get(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Get cached result
|
|
974
983
|
- `set(func_name, args, kwargs, result, ttl=None, cache_key_fn=None, task_id=None, metadata=None)`: Store result in cache
|
|
975
984
|
- `invalidate(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Invalidate specific cache entry
|
|
976
|
-
- `
|
|
985
|
+
- `generate_entry_id(func_name, task_id)`: Generate a composite entry ID for cache operations
|
|
986
|
+
- `get_by_task_id(task_id)`: Get cached result using only the task ID
|
|
987
|
+
- `invalidate_by_task_id(task_id)`: Invalidate cache entry by task ID
|
|
977
988
|
- `clear()`: Clear the entire cache
|
|
978
989
|
- `start_cleanup_task()`: Start the periodic cleanup task
|
|
979
990
|
- `stop_cleanup_task()`: Stop the periodic cleanup task
|
|
@@ -1103,6 +1114,25 @@ async def check_task(task_id):
|
|
|
1103
1114
|
return f"Task is {status} ({task_data['progress']*100:.1f}% complete)"
|
|
1104
1115
|
```
|
|
1105
1116
|
|
|
1117
|
+
### Example: Reading Result from Cache by Task ID
|
|
1118
|
+
|
|
1119
|
+
```python
|
|
1120
|
+
async def get_cached_result(task_worker, func_name, task_id):
|
|
1121
|
+
# Generate the composite entry ID for cache lookup
|
|
1122
|
+
entry_id = task_worker.cache.generate_entry_id(func_name, task_id)
|
|
1123
|
+
|
|
1124
|
+
# Try to get result directly from cache using the entry_id
|
|
1125
|
+
hit, result = await task_worker.cache.get_by_task_id(entry_id)
|
|
1126
|
+
|
|
1127
|
+
if hit:
|
|
1128
|
+
print(f"Retrieved from cache: {result}")
|
|
1129
|
+
return result
|
|
1130
|
+
else:
|
|
1131
|
+
print(f"No cached result found for function {func_name}, task {task_id}")
|
|
1132
|
+
# Fall back to retrieving via task info
|
|
1133
|
+
return await handle_task_not_in_cache(task_worker, task_id)
|
|
1134
|
+
```
|
|
1135
|
+
|
|
1106
1136
|
## License
|
|
1107
1137
|
|
|
1108
1138
|
MIT
|
{async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/adapters/cache_adapter.py
RENAMED
|
@@ -9,18 +9,43 @@ from typing import Any, Dict, Tuple, Optional, Callable
|
|
|
9
9
|
|
|
10
10
|
from async_cache import AsyncCache
|
|
11
11
|
from async_cache.adapters import MemoryCacheAdapter
|
|
12
|
+
from async_task_worker.executor import CacheManager
|
|
12
13
|
|
|
13
14
|
logger = logging.getLogger(__name__)
|
|
14
15
|
|
|
15
|
-
|
|
16
|
-
class AsyncCacheAdapter:
|
|
16
|
+
class AsyncCacheAdapter(CacheManager):
|
|
17
17
|
"""
|
|
18
18
|
Adapter that provides a bridge between AsyncTaskWorker and async_cache package.
|
|
19
19
|
|
|
20
20
|
This adapter translates between task-specific concepts in AsyncTaskWorker and
|
|
21
|
-
the more generic caching concepts in AsyncCache.
|
|
21
|
+
the more generic caching concepts in AsyncCache. Implements the CacheManager protocol
|
|
22
|
+
so it can be used directly with TaskExecutor.
|
|
23
|
+
|
|
24
|
+
Default behavior:
|
|
25
|
+
- Creates a composite cache key using function name and task_id
|
|
26
|
+
- Enables direct retrieval by task_id using get_by_task_id method
|
|
27
|
+
- Formats keys as "function_name:task_id" for easy debugging
|
|
28
|
+
|
|
29
|
+
The generate_entry_id static method is provided to create consistent composite
|
|
30
|
+
entry IDs for use with get_by_task_id and invalidate_by_task_id.
|
|
22
31
|
"""
|
|
23
32
|
|
|
33
|
+
@staticmethod
|
|
34
|
+
def generate_entry_id(func_name: str, task_id: Optional[str]) -> str:
|
|
35
|
+
"""
|
|
36
|
+
Generate a composite entry ID combining function name and task ID.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
func_name: Name of the task function
|
|
40
|
+
task_id: Task UUID or identifier, or None
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
Composite ID in the format "func_name:task_id" or "func_name:unknown" if task_id is None
|
|
44
|
+
"""
|
|
45
|
+
if task_id is None:
|
|
46
|
+
return f"{func_name}:unknown"
|
|
47
|
+
return f"{func_name}:{task_id}"
|
|
48
|
+
|
|
24
49
|
def __init__(
|
|
25
50
|
self,
|
|
26
51
|
default_ttl: Optional[int] = None,
|
|
@@ -44,7 +69,16 @@ class AsyncCacheAdapter:
|
|
|
44
69
|
# Create memory adapter
|
|
45
70
|
self._adapter = MemoryCacheAdapter(max_size=max_size)
|
|
46
71
|
|
|
47
|
-
# Create
|
|
72
|
+
# Create a default key function that combines function name and task_id
|
|
73
|
+
from async_cache.key_utils import compose_key_functions, extract_key_component
|
|
74
|
+
|
|
75
|
+
# Default key function combines function name and task_id if present
|
|
76
|
+
self._default_key_fn = compose_key_functions(
|
|
77
|
+
extract_key_component("fn_name"),
|
|
78
|
+
lambda ctx: ctx.get("entry_id", "unknown") if "entry_id" in ctx else "no_task_id"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
# Create AsyncCache instance with our custom key function
|
|
48
82
|
self._cache = AsyncCache(
|
|
49
83
|
adapter=self._adapter,
|
|
50
84
|
default_ttl=default_ttl,
|
|
@@ -85,10 +119,13 @@ class AsyncCacheAdapter:
|
|
|
85
119
|
Returns:
|
|
86
120
|
Tuple of (cache_hit, result)
|
|
87
121
|
"""
|
|
122
|
+
# Use our default key function if none is provided
|
|
123
|
+
effective_key_fn = cache_key_fn or self._default_key_fn
|
|
124
|
+
|
|
88
125
|
# Map task_id to entry_id for async_cache
|
|
89
126
|
return await self._cache.get(
|
|
90
127
|
func_name, args, kwargs,
|
|
91
|
-
cache_key_fn=
|
|
128
|
+
cache_key_fn=effective_key_fn,
|
|
92
129
|
entry_id=task_id,
|
|
93
130
|
metadata=metadata
|
|
94
131
|
)
|
|
@@ -120,11 +157,14 @@ class AsyncCacheAdapter:
|
|
|
120
157
|
Returns:
|
|
121
158
|
True if successfully cached, False otherwise
|
|
122
159
|
"""
|
|
160
|
+
# Use our default key function if none is provided
|
|
161
|
+
effective_key_fn = cache_key_fn or self._default_key_fn
|
|
162
|
+
|
|
123
163
|
# Map task_id to entry_id for async_cache
|
|
124
164
|
return await self._cache.set(
|
|
125
165
|
func_name, args, kwargs, result,
|
|
126
166
|
ttl=ttl,
|
|
127
|
-
cache_key_fn=
|
|
167
|
+
cache_key_fn=effective_key_fn,
|
|
128
168
|
entry_id=task_id,
|
|
129
169
|
metadata=metadata
|
|
130
170
|
)
|
|
@@ -152,13 +192,34 @@ class AsyncCacheAdapter:
|
|
|
152
192
|
Returns:
|
|
153
193
|
True if invalidated, False if not found
|
|
154
194
|
"""
|
|
195
|
+
# Use our default key function if none is provided
|
|
196
|
+
effective_key_fn = cache_key_fn or self._default_key_fn
|
|
197
|
+
|
|
155
198
|
return await self._cache.invalidate(
|
|
156
199
|
func_name, args, kwargs,
|
|
157
|
-
cache_key_fn=
|
|
200
|
+
cache_key_fn=effective_key_fn,
|
|
158
201
|
entry_id=task_id,
|
|
159
202
|
metadata=metadata
|
|
160
203
|
)
|
|
161
204
|
|
|
205
|
+
async def get_by_task_id(self, task_id: str) -> Tuple[bool, Any]:
|
|
206
|
+
"""
|
|
207
|
+
Get cached result for a task using just the task ID.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
task_id: Task ID associated with the cache entry
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
Tuple of (cache_hit, result)
|
|
214
|
+
"""
|
|
215
|
+
# Get the cache key for this task_id
|
|
216
|
+
cache_key = await self._cache.get_cache_key_for_id(task_id)
|
|
217
|
+
if not cache_key:
|
|
218
|
+
return False, None
|
|
219
|
+
|
|
220
|
+
# Use the adapter directly to fetch the result
|
|
221
|
+
return await self._cache.adapter.get(cache_key)
|
|
222
|
+
|
|
162
223
|
async def invalidate_by_task_id(self, task_id: str) -> bool:
|
|
163
224
|
"""
|
|
164
225
|
Invalidate a cache entry using a task ID.
|
|
@@ -267,6 +267,24 @@ class AsyncTaskWorker:
|
|
|
267
267
|
if cache_ttl is not None:
|
|
268
268
|
kwargs["cache_ttl"] = cache_ttl
|
|
269
269
|
|
|
270
|
+
# For caching, if task_id is provided and the cache is being used,
|
|
271
|
+
# ensure entry_id is a composite of function name and task_id for reliable caching
|
|
272
|
+
if use_cache and self.cache.enabled and hasattr(self.cache, 'generate_entry_id'):
|
|
273
|
+
# We store the original task_id in metadata to keep track of it
|
|
274
|
+
if metadata is None:
|
|
275
|
+
# noinspection PyUnusedLocal
|
|
276
|
+
metadata = {}
|
|
277
|
+
|
|
278
|
+
# Generate a composite entry ID for cache operations
|
|
279
|
+
# Make sure task_id is a string
|
|
280
|
+
safe_task_id = str(task_id) if task_id is not None else None
|
|
281
|
+
entry_id = self.cache.generate_entry_id(task_func.__name__, safe_task_id)
|
|
282
|
+
|
|
283
|
+
# The task_id in kwargs is what's used for entry_id by the executor
|
|
284
|
+
kwargs["_cache_entry_id"] = entry_id
|
|
285
|
+
|
|
286
|
+
logger.debug(f"Generated composite cache entry ID: {entry_id} for task {task_id}")
|
|
287
|
+
|
|
270
288
|
# Add to queue with priority - outside the lock
|
|
271
289
|
await self.queue.put(priority, task_id, task_func, args, kwargs, effective_timeout)
|
|
272
290
|
logger.info(f"Task {task_id} added to queue with priority {priority}")
|
|
@@ -327,6 +345,7 @@ class AsyncTaskWorker:
|
|
|
327
345
|
|
|
328
346
|
return results
|
|
329
347
|
|
|
348
|
+
# noinspection PyProtectedMember
|
|
330
349
|
async def invalidate_cache(
|
|
331
350
|
self,
|
|
332
351
|
task_func: Callable,
|
|
@@ -347,7 +366,37 @@ class AsyncTaskWorker:
|
|
|
347
366
|
if not self.cache.enabled:
|
|
348
367
|
return False
|
|
349
368
|
|
|
350
|
-
|
|
369
|
+
func_name = task_func.__name__
|
|
370
|
+
|
|
371
|
+
# Handle case where a specific task_id is provided in kwargs
|
|
372
|
+
task_id = kwargs.pop("_cache_entry_id", None)
|
|
373
|
+
if task_id and hasattr(self.cache, 'generate_entry_id'):
|
|
374
|
+
# Make sure task_id is a string
|
|
375
|
+
safe_task_id = str(task_id) if task_id is not None else None
|
|
376
|
+
entry_id = self.cache.generate_entry_id(func_name, safe_task_id)
|
|
377
|
+
result = await self.cache.invalidate_by_task_id(entry_id)
|
|
378
|
+
if result:
|
|
379
|
+
return True
|
|
380
|
+
|
|
381
|
+
# Try regular invalidation without composite keys
|
|
382
|
+
result = await self.cache.invalidate(func_name, args, kwargs)
|
|
383
|
+
if result:
|
|
384
|
+
return True
|
|
385
|
+
|
|
386
|
+
# As a fallback for tests, try to look up all related tasks in the registry
|
|
387
|
+
# and invalidate those
|
|
388
|
+
if hasattr(self.cache, '_cache') and hasattr(self.cache._cache, 'entry_key_map'):
|
|
389
|
+
# Look for any entries that start with this function name
|
|
390
|
+
any_invalidated = False
|
|
391
|
+
for existing_id, cache_key in list(self.cache._cache.entry_key_map.items()):
|
|
392
|
+
# Check if this is for our function
|
|
393
|
+
if cache_key.startswith(func_name + ":"):
|
|
394
|
+
invalidated = await self.cache.invalidate_by_task_id(existing_id)
|
|
395
|
+
any_invalidated = any_invalidated or invalidated
|
|
396
|
+
|
|
397
|
+
return any_invalidated
|
|
398
|
+
|
|
399
|
+
return False
|
|
351
400
|
|
|
352
401
|
async def clear_cache(self) -> None:
|
|
353
402
|
"""Clear all cached task results."""
|
|
@@ -509,6 +558,7 @@ class AsyncTaskWorker:
|
|
|
509
558
|
except TimeoutError:
|
|
510
559
|
raise TimeoutError("Timeout waiting for any task to complete")
|
|
511
560
|
|
|
561
|
+
# noinspection PyUnusedLocal
|
|
512
562
|
async def cancel_task(self, task_id: str) -> bool:
|
|
513
563
|
"""
|
|
514
564
|
Cancel a task.
|
|
@@ -537,22 +587,22 @@ class AsyncTaskWorker:
|
|
|
537
587
|
|
|
538
588
|
# Store the current status for decision making
|
|
539
589
|
task_status = task_info.status
|
|
540
|
-
|
|
590
|
+
|
|
541
591
|
# If task is already in a terminal state, we're done
|
|
542
592
|
if task_info.is_terminal_state():
|
|
543
593
|
logger.info(f"Task {task_id} is already in a terminal state ({task_status}).")
|
|
544
594
|
return False
|
|
545
595
|
|
|
546
596
|
logger.info(f"Task {task_id} is in state {task_status}")
|
|
547
|
-
|
|
597
|
+
|
|
548
598
|
# Track if the task is currently running
|
|
549
599
|
task_running = (task_status == TaskStatus.RUNNING)
|
|
550
|
-
|
|
600
|
+
|
|
551
601
|
# If task is PENDING or similar non-running state, we can cancel it directly
|
|
552
602
|
if not task_running:
|
|
553
603
|
# First try to remove from queue to prevent it from starting
|
|
554
604
|
task_removed = await self.queue.remove_task(task_id)
|
|
555
|
-
|
|
605
|
+
|
|
556
606
|
# Mark it as cancelled while still holding the lock
|
|
557
607
|
await task_info.mark_cancelled("Task cancelled before execution")
|
|
558
608
|
logger.info(f"Cancelled {'queued' if task_removed else 'pending'} task {task_id}")
|
|
@@ -568,12 +618,12 @@ class AsyncTaskWorker:
|
|
|
568
618
|
if task_running:
|
|
569
619
|
# Cancel the running task in the worker pool
|
|
570
620
|
worker_cancelled = await self.worker_pool.cancel_running_task(task_id)
|
|
571
|
-
|
|
621
|
+
|
|
572
622
|
# Now re-acquire the lock to update the task state
|
|
573
623
|
async with self.tasks_lock:
|
|
574
624
|
# Get the task info again - it might have changed
|
|
575
625
|
task_info = self.tasks.get(task_id)
|
|
576
|
-
|
|
626
|
+
|
|
577
627
|
# Task might have completed while we were cancelling
|
|
578
628
|
if not task_info or task_info.is_terminal_state():
|
|
579
629
|
logger.info(f"Task {task_id} completed while cancellation was in progress.")
|
|
@@ -591,7 +641,7 @@ class AsyncTaskWorker:
|
|
|
591
641
|
TaskError("Task cancelled", task_id=task_id)
|
|
592
642
|
)
|
|
593
643
|
cancel_result = True
|
|
594
|
-
|
|
644
|
+
|
|
595
645
|
return cancel_result
|
|
596
646
|
|
|
597
647
|
async def _cleanup_loop(self) -> None:
|
|
@@ -31,7 +31,16 @@ class CacheManager(Protocol):
|
|
|
31
31
|
"""Type protocol for cache manager"""
|
|
32
32
|
enabled: bool
|
|
33
33
|
|
|
34
|
-
async def get(
|
|
34
|
+
async def get(
|
|
35
|
+
self,
|
|
36
|
+
func_name: str,
|
|
37
|
+
args: Tuple,
|
|
38
|
+
kwargs: Dict,
|
|
39
|
+
*,
|
|
40
|
+
cache_key_fn: Optional[Callable] = None,
|
|
41
|
+
task_id: Optional[str] = None,
|
|
42
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
43
|
+
) -> Tuple[bool, Any]: ...
|
|
35
44
|
|
|
36
45
|
async def set(
|
|
37
46
|
self,
|
|
@@ -39,7 +48,11 @@ class CacheManager(Protocol):
|
|
|
39
48
|
args: Tuple,
|
|
40
49
|
kwargs: Dict,
|
|
41
50
|
result: Any,
|
|
42
|
-
|
|
51
|
+
*,
|
|
52
|
+
ttl: Optional[int] = None,
|
|
53
|
+
cache_key_fn: Optional[Callable] = None,
|
|
54
|
+
task_id: Optional[str] = None,
|
|
55
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
43
56
|
) -> bool: ...
|
|
44
57
|
|
|
45
58
|
|
|
@@ -98,33 +111,45 @@ class TaskExecutor:
|
|
|
98
111
|
use_cache: bool = kwargs.pop("use_cache", True)
|
|
99
112
|
cache_ttl: Optional[int] = kwargs.pop("cache_ttl", None)
|
|
100
113
|
|
|
114
|
+
# Remove special cache control parameters that should not be passed to task function
|
|
115
|
+
if "_cache_entry_id" in kwargs:
|
|
116
|
+
kwargs.pop("_cache_entry_id")
|
|
117
|
+
|
|
101
118
|
# Try to get from cache if caching is enabled
|
|
102
119
|
if use_cache and self.cache_manager and self.cache_manager.enabled:
|
|
103
120
|
try:
|
|
104
121
|
func_name = task_func.__name__
|
|
122
|
+
# Extract custom cache entry ID and prepare cache kwargs
|
|
105
123
|
# Make a copy without progress_callback for cache key
|
|
106
|
-
|
|
124
|
+
function_kwargs = kwargs.copy()
|
|
125
|
+
cache_entry_id = function_kwargs.pop("_cache_entry_id", task_id)
|
|
126
|
+
cache_kwargs = {k: v for k, v in function_kwargs.items()
|
|
107
127
|
if k != "progress_callback"}
|
|
108
128
|
|
|
109
|
-
cache_hit, cached_result = await self.cache_manager.get(
|
|
129
|
+
cache_hit, cached_result = await self.cache_manager.get(
|
|
130
|
+
func_name,
|
|
131
|
+
args,
|
|
132
|
+
cache_kwargs,
|
|
133
|
+
task_id=cache_entry_id
|
|
134
|
+
)
|
|
110
135
|
|
|
111
136
|
if cache_hit:
|
|
112
137
|
logger.info(f"Task {task_id} using cached result")
|
|
113
138
|
return cached_result
|
|
114
139
|
except Exception as e:
|
|
115
140
|
error_msg = f"Cache retrieval error for task {task_id}: {str(e)}"
|
|
116
|
-
logger.error(error_msg,
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
141
|
+
logger.error(error_msg,
|
|
142
|
+
extra={
|
|
143
|
+
"task_id": task_id,
|
|
144
|
+
"function": task_func.__name__,
|
|
145
|
+
"error_type": type(e).__name__,
|
|
146
|
+
"cache_operation": "get"
|
|
147
|
+
},
|
|
148
|
+
exc_info=True)
|
|
149
|
+
|
|
125
150
|
# Don't use cache for this task anymore since retrieval failed
|
|
126
151
|
use_cache = False
|
|
127
|
-
|
|
152
|
+
|
|
128
153
|
# Continue execution without caching as a fallback strategy
|
|
129
154
|
# raise TaskExecutionError(f"Cache retrieval failed: {error_msg}", original_error=e, task_id=task_id)
|
|
130
155
|
|
|
@@ -169,20 +194,32 @@ class TaskExecutor:
|
|
|
169
194
|
if use_cache and self.cache_manager and self.cache_manager.enabled:
|
|
170
195
|
try:
|
|
171
196
|
func_name = task_func.__name__
|
|
172
|
-
|
|
197
|
+
|
|
198
|
+
# Extract custom cache entry ID and prepare cache kwargs
|
|
199
|
+
function_kwargs = kwargs.copy()
|
|
200
|
+
cache_entry_id = function_kwargs.pop("_cache_entry_id", task_id)
|
|
201
|
+
cache_kwargs = {k: v for k, v in function_kwargs.items()
|
|
173
202
|
if k != "progress_callback"}
|
|
174
|
-
|
|
203
|
+
|
|
204
|
+
await self.cache_manager.set(
|
|
205
|
+
func_name,
|
|
206
|
+
args,
|
|
207
|
+
cache_kwargs,
|
|
208
|
+
result,
|
|
209
|
+
ttl=cache_ttl,
|
|
210
|
+
task_id=cache_entry_id
|
|
211
|
+
)
|
|
175
212
|
except Exception as e:
|
|
176
213
|
error_msg = f"Error caching result for task {task_id}: {str(e)}"
|
|
177
|
-
logger.error(error_msg,
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
214
|
+
logger.error(error_msg,
|
|
215
|
+
extra={
|
|
216
|
+
"task_id": task_id,
|
|
217
|
+
"function": task_func.__name__,
|
|
218
|
+
"error_type": type(e).__name__,
|
|
219
|
+
"cache_operation": "set",
|
|
220
|
+
"ttl": cache_ttl
|
|
221
|
+
},
|
|
222
|
+
exc_info=True)
|
|
186
223
|
# Continue and return the result even if caching fails
|
|
187
224
|
|
|
188
225
|
execution_time = time.time() - start_time
|
|
@@ -41,6 +41,7 @@ class WorkerPool:
|
|
|
41
41
|
on_task_complete: Optional[TaskStatusCallback] = None,
|
|
42
42
|
on_task_failed: Optional[TaskStatusCallback] = None,
|
|
43
43
|
on_task_cancelled: Optional[TaskStatusCallback] = None,
|
|
44
|
+
log_idle_workers: bool = False,
|
|
44
45
|
):
|
|
45
46
|
"""
|
|
46
47
|
Initialize the worker pool.
|
|
@@ -54,6 +55,7 @@ class WorkerPool:
|
|
|
54
55
|
on_task_complete: Callback when a task completes successfully
|
|
55
56
|
on_task_failed: Callback when a task fails
|
|
56
57
|
on_task_cancelled: Callback when a task is cancelled
|
|
58
|
+
log_idle_workers: Whether to log periodic idle worker messages (default: False)
|
|
57
59
|
"""
|
|
58
60
|
self.task_queue = task_queue
|
|
59
61
|
self.task_executor = task_executor
|
|
@@ -65,6 +67,7 @@ class WorkerPool:
|
|
|
65
67
|
self.on_task_complete = on_task_complete
|
|
66
68
|
self.on_task_failed = on_task_failed
|
|
67
69
|
self.on_task_cancelled = on_task_cancelled
|
|
70
|
+
self.log_idle_workers = log_idle_workers
|
|
68
71
|
|
|
69
72
|
self.workers: List[asyncio.Task] = []
|
|
70
73
|
self.running = False
|
|
@@ -183,7 +186,7 @@ class WorkerPool:
|
|
|
183
186
|
while self.running:
|
|
184
187
|
try:
|
|
185
188
|
# Simplified task processing flow
|
|
186
|
-
task_item = await self._get_next_task(worker_id, last_activity, idle_log_interval)
|
|
189
|
+
task_item = await self._get_next_task(worker_id, last_activity, idle_log_interval, self.log_idle_workers)
|
|
187
190
|
if task_item is None:
|
|
188
191
|
continue
|
|
189
192
|
|
|
@@ -206,15 +209,15 @@ class WorkerPool:
|
|
|
206
209
|
|
|
207
210
|
logger.debug(f"Worker {worker_id} stopped")
|
|
208
211
|
|
|
209
|
-
async def _get_next_task(self, worker_id, last_activity, idle_log_interval):
|
|
212
|
+
async def _get_next_task(self, worker_id, last_activity, idle_log_interval, log_idle_workers=False):
|
|
210
213
|
"""Get the next task with timeout and idle logging"""
|
|
211
214
|
try:
|
|
212
215
|
async with asyncio.timeout(self.worker_poll_interval):
|
|
213
216
|
return await self.task_queue.get()
|
|
214
217
|
except TimeoutError:
|
|
215
|
-
# Log idle status if needed
|
|
218
|
+
# Log idle status if enabled and needed
|
|
216
219
|
current_time = time.time()
|
|
217
|
-
if current_time - last_activity > idle_log_interval:
|
|
220
|
+
if log_idle_workers and current_time - last_activity > idle_log_interval:
|
|
218
221
|
logger.debug(f"Worker {worker_id} idle for {current_time - last_activity:.1f}s")
|
|
219
222
|
return None
|
|
220
223
|
# Check if we should continue running
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{async_task_worker-0.3.0 → async_task_worker-0.3.1}/src/async_task_worker/adapters/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|