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.
- async_cache/__init__.py +83 -0
- async_cache/adapters/__init__.py +11 -0
- async_cache/adapters/memory.py +122 -0
- async_cache/adapters/redis.py +182 -0
- async_cache/core.py +680 -0
- async_cache/exceptions.py +16 -0
- async_cache/key_utils.py +136 -0
- async_cache/serialization.py +230 -0
- async_task_worker/__init__.py +93 -0
- async_task_worker/adapters/__init__.py +3 -0
- async_task_worker/adapters/cache_adapter.py +206 -0
- async_task_worker/api.py +371 -0
- async_task_worker/core.py +717 -0
- async_task_worker/exceptions.py +245 -0
- async_task_worker/executor.py +204 -0
- async_task_worker/futures.py +232 -0
- async_task_worker/pool.py +343 -0
- async_task_worker/queue.py +265 -0
- async_task_worker/registry.py +96 -0
- async_task_worker/status.py +243 -0
- async_task_worker-0.3.0.dist-info/METADATA +1144 -0
- async_task_worker-0.3.0.dist-info/RECORD +24 -0
- async_task_worker-0.3.0.dist-info/WHEEL +4 -0
- async_task_worker-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Async Task Worker
|
|
3
|
+
|
|
4
|
+
Main entry point for the task worker system that integrates all components
|
|
5
|
+
and provides a simple API for users.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import logging
|
|
10
|
+
import uuid
|
|
11
|
+
import weakref
|
|
12
|
+
from datetime import datetime, timedelta
|
|
13
|
+
from typing import Any, Awaitable, Callable, Dict, List, Optional, Self, TypeVar, Tuple
|
|
14
|
+
|
|
15
|
+
from async_task_worker.adapters.cache_adapter import AsyncCacheAdapter
|
|
16
|
+
from async_task_worker.exceptions import TaskError
|
|
17
|
+
from async_task_worker.executor import TaskExecutor
|
|
18
|
+
from async_task_worker.futures import TaskFutureManager
|
|
19
|
+
from async_task_worker.pool import WorkerPool
|
|
20
|
+
from async_task_worker.queue import TaskQueue
|
|
21
|
+
from async_task_worker.status import TaskInfo, TaskStatus
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
T = TypeVar('T') # Used for generic task function return type
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AsyncTaskWorker:
|
|
29
|
+
"""
|
|
30
|
+
Worker pool for managing asynchronous background tasks.
|
|
31
|
+
|
|
32
|
+
Features:
|
|
33
|
+
- Task queuing with priorities
|
|
34
|
+
- Configurable number of worker tasks
|
|
35
|
+
- Task status tracking
|
|
36
|
+
- Task cancellation
|
|
37
|
+
- Progress reporting
|
|
38
|
+
- Result caching
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
max_workers: int = 10,
|
|
44
|
+
task_timeout: Optional[float] = None,
|
|
45
|
+
worker_poll_interval: float = 1.0,
|
|
46
|
+
cache_enabled: bool = False,
|
|
47
|
+
cache_ttl: Optional[int] = 3600, # 1 hour default
|
|
48
|
+
cache_max_size: Optional[int] = 1000,
|
|
49
|
+
cache_adapter: Optional[AsyncCacheAdapter] = None,
|
|
50
|
+
cache_cleanup_interval: int = 900, # 15 minutes default
|
|
51
|
+
max_queue_size: Optional[int] = None,
|
|
52
|
+
task_retention_days: Optional[int] = 7,
|
|
53
|
+
cleanup_interval: int = 3600 # Cleanup every hour by default
|
|
54
|
+
):
|
|
55
|
+
"""
|
|
56
|
+
Initialize the task worker.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
max_workers: Maximum number of concurrent worker tasks
|
|
60
|
+
task_timeout: Default timeout in seconds for tasks (None for no timeout)
|
|
61
|
+
worker_poll_interval: How frequently workers check for new tasks
|
|
62
|
+
cache_enabled: Whether task result caching is enabled
|
|
63
|
+
cache_ttl: Default time-to-live for cached results in seconds
|
|
64
|
+
cache_max_size: Maximum number of entries in the cache
|
|
65
|
+
cache_adapter: Custom cache adapter (default is AsyncCacheAdapter)
|
|
66
|
+
cache_cleanup_interval: Interval in seconds for cleaning up stale task ID mappings (0 to disable)
|
|
67
|
+
max_queue_size: Maximum number of items in the queue
|
|
68
|
+
task_retention_days: Days to keep completed tasks
|
|
69
|
+
cleanup_interval: Seconds between cleanup operations
|
|
70
|
+
"""
|
|
71
|
+
# Task storage and synchronization
|
|
72
|
+
self.tasks: Dict[str, TaskInfo] = {}
|
|
73
|
+
self.tasks_lock = asyncio.Lock()
|
|
74
|
+
|
|
75
|
+
# Initialize cache
|
|
76
|
+
if cache_adapter is not None:
|
|
77
|
+
# Use the provided cache adapter
|
|
78
|
+
self.cache = cache_adapter
|
|
79
|
+
else:
|
|
80
|
+
# Create a new AsyncCacheAdapter
|
|
81
|
+
logger.info("Creating new AsyncCacheAdapter for caching")
|
|
82
|
+
self.cache = AsyncCacheAdapter(
|
|
83
|
+
default_ttl=cache_ttl,
|
|
84
|
+
enabled=cache_enabled,
|
|
85
|
+
max_serialized_size=10 * 1024 * 1024,
|
|
86
|
+
validate_keys=False,
|
|
87
|
+
cleanup_interval=cache_cleanup_interval,
|
|
88
|
+
max_size=cache_max_size
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Create task queue
|
|
92
|
+
self.queue = TaskQueue(max_size=max_queue_size)
|
|
93
|
+
|
|
94
|
+
# Create task executor
|
|
95
|
+
self.task_executor = TaskExecutor(cache_manager=self.cache)
|
|
96
|
+
|
|
97
|
+
# Create future manager
|
|
98
|
+
self.future_manager = TaskFutureManager()
|
|
99
|
+
|
|
100
|
+
# Create worker pool with callbacks for task state management
|
|
101
|
+
self.worker_pool = WorkerPool(
|
|
102
|
+
task_queue=self.queue,
|
|
103
|
+
task_executor=self.task_executor,
|
|
104
|
+
max_workers=max_workers,
|
|
105
|
+
worker_poll_interval=worker_poll_interval,
|
|
106
|
+
on_task_start=self._on_task_started,
|
|
107
|
+
on_task_complete=self._on_task_completed,
|
|
108
|
+
on_task_failed=self._on_task_failed,
|
|
109
|
+
on_task_cancelled=self._on_task_cancelled
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# Configuration
|
|
113
|
+
self.default_task_timeout = task_timeout
|
|
114
|
+
self.task_retention_days = task_retention_days
|
|
115
|
+
self.cleanup_interval = cleanup_interval
|
|
116
|
+
|
|
117
|
+
# State
|
|
118
|
+
self.running = False
|
|
119
|
+
self.cleanup_task: Optional[asyncio.Task] = None
|
|
120
|
+
|
|
121
|
+
# Use a weak reference dictionary to prevent memory leaks from orphaned futures
|
|
122
|
+
self._task_futures = weakref.WeakValueDictionary()
|
|
123
|
+
|
|
124
|
+
async def __aenter__(self) -> Self:
|
|
125
|
+
"""Support async context manager protocol."""
|
|
126
|
+
await self.start()
|
|
127
|
+
return self
|
|
128
|
+
|
|
129
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
130
|
+
"""Support async context manager protocol."""
|
|
131
|
+
await self.stop()
|
|
132
|
+
|
|
133
|
+
async def start(self) -> None:
|
|
134
|
+
"""Start the worker pool and cleanup task."""
|
|
135
|
+
if self.running:
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
self.running = True
|
|
139
|
+
|
|
140
|
+
# Start worker pool
|
|
141
|
+
await self.worker_pool.start()
|
|
142
|
+
|
|
143
|
+
# Start task cleanup if retention period is set
|
|
144
|
+
if self.task_retention_days is not None:
|
|
145
|
+
self.cleanup_task = asyncio.create_task(self._cleanup_loop())
|
|
146
|
+
self.cleanup_task.set_name("task_cleanup")
|
|
147
|
+
|
|
148
|
+
# Start cache cleanup task if enabled
|
|
149
|
+
if self.cache.cleanup_interval > 0:
|
|
150
|
+
await self.cache.start_cleanup_task()
|
|
151
|
+
|
|
152
|
+
logger.info(f"Started AsyncTaskWorker with {self.worker_pool.worker_count} workers")
|
|
153
|
+
|
|
154
|
+
async def stop(self, timeout: float = 5.0) -> None:
|
|
155
|
+
"""Stop the worker pool gracefully, waiting for tasks to complete."""
|
|
156
|
+
if not self.running:
|
|
157
|
+
return
|
|
158
|
+
|
|
159
|
+
self.running = False
|
|
160
|
+
logger.info("Stopping AsyncTaskWorker...")
|
|
161
|
+
|
|
162
|
+
# List to collect errors during shutdown
|
|
163
|
+
shutdown_errors = []
|
|
164
|
+
|
|
165
|
+
# Cancel cleanup task
|
|
166
|
+
if self.cleanup_task and not self.cleanup_task.done():
|
|
167
|
+
try:
|
|
168
|
+
self.cleanup_task.cancel()
|
|
169
|
+
try:
|
|
170
|
+
await asyncio.wait_for(self.cleanup_task, timeout=1.0)
|
|
171
|
+
except asyncio.TimeoutError:
|
|
172
|
+
logger.warning("Cleanup task did not complete in time")
|
|
173
|
+
except asyncio.CancelledError:
|
|
174
|
+
logger.debug("Cleanup task cancelled")
|
|
175
|
+
except Exception as e:
|
|
176
|
+
shutdown_errors.append(f"Cleanup task error: {str(e)}")
|
|
177
|
+
logger.error(f"Error during cleanup task cancellation: {str(e)}")
|
|
178
|
+
|
|
179
|
+
# Stop cache cleanup task (must execute even if other operations fail)
|
|
180
|
+
try:
|
|
181
|
+
await self.cache.stop_cleanup_task()
|
|
182
|
+
except Exception as e:
|
|
183
|
+
shutdown_errors.append(f"Cache cleanup task error: {str(e)}")
|
|
184
|
+
logger.error(f"Error stopping cache cleanup task: {str(e)}")
|
|
185
|
+
|
|
186
|
+
# Cancel all pending futures
|
|
187
|
+
try:
|
|
188
|
+
await self.future_manager.cancel_all_futures()
|
|
189
|
+
except Exception as e:
|
|
190
|
+
shutdown_errors.append(f"Future cancellation error: {str(e)}")
|
|
191
|
+
logger.error(f"Error cancelling futures: {str(e)}")
|
|
192
|
+
|
|
193
|
+
# Stop worker pool
|
|
194
|
+
try:
|
|
195
|
+
await self.worker_pool.stop(timeout=timeout)
|
|
196
|
+
except Exception as e:
|
|
197
|
+
shutdown_errors.append(f"Worker pool error: {str(e)}")
|
|
198
|
+
logger.error(f"Error stopping worker pool: {str(e)}")
|
|
199
|
+
|
|
200
|
+
# Always clear tracking, even if other components failed to stop
|
|
201
|
+
try:
|
|
202
|
+
self.queue.clear_tracking()
|
|
203
|
+
except Exception as e:
|
|
204
|
+
shutdown_errors.append(f"Queue tracking error: {str(e)}")
|
|
205
|
+
logger.error(f"Error clearing queue tracking: {str(e)}")
|
|
206
|
+
|
|
207
|
+
# Clean task_futures to prevent memory leaks
|
|
208
|
+
self._task_futures.clear()
|
|
209
|
+
|
|
210
|
+
if shutdown_errors:
|
|
211
|
+
logger.warning(f"AsyncTaskWorker stopped with {len(shutdown_errors)} errors")
|
|
212
|
+
else:
|
|
213
|
+
logger.info("AsyncTaskWorker stopped gracefully")
|
|
214
|
+
|
|
215
|
+
async def add_task(
|
|
216
|
+
self,
|
|
217
|
+
task_func: Callable[..., Awaitable[T]],
|
|
218
|
+
*args: Any,
|
|
219
|
+
priority: int = 0,
|
|
220
|
+
task_id: Optional[str] = None,
|
|
221
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
222
|
+
timeout: Optional[int] = None,
|
|
223
|
+
use_cache: bool = True,
|
|
224
|
+
cache_ttl: Optional[int] = None,
|
|
225
|
+
**kwargs: Any
|
|
226
|
+
) -> str:
|
|
227
|
+
"""
|
|
228
|
+
Add a new task to the queue and return its ID.
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
task_func: Async function to execute
|
|
232
|
+
*args: Positional arguments to pass to the function
|
|
233
|
+
priority: Task priority (lower number = higher priority)
|
|
234
|
+
task_id: Optional custom task ID (default: auto-generated UUID)
|
|
235
|
+
metadata: Optional metadata to store with the task
|
|
236
|
+
timeout: Optional per-task timeout override
|
|
237
|
+
use_cache: Whether to use cache for this task
|
|
238
|
+
cache_ttl: Optional cache TTL override
|
|
239
|
+
**kwargs: Keyword arguments to pass to the function
|
|
240
|
+
|
|
241
|
+
Returns:
|
|
242
|
+
Task ID string
|
|
243
|
+
"""
|
|
244
|
+
if not self.running:
|
|
245
|
+
raise RuntimeError("Worker pool is not running")
|
|
246
|
+
|
|
247
|
+
# Generate or use provided task ID
|
|
248
|
+
if task_id is None:
|
|
249
|
+
task_id = str(uuid.uuid4())
|
|
250
|
+
|
|
251
|
+
# Create task info first under lock
|
|
252
|
+
task_info = TaskInfo(
|
|
253
|
+
id=task_id,
|
|
254
|
+
status=TaskStatus.PENDING,
|
|
255
|
+
created_at=datetime.now(),
|
|
256
|
+
metadata=metadata or {}
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
async with self.tasks_lock:
|
|
260
|
+
self.tasks[task_id] = task_info
|
|
261
|
+
|
|
262
|
+
# Use task-specific timeout or default
|
|
263
|
+
effective_timeout = timeout if timeout is not None else self.default_task_timeout
|
|
264
|
+
|
|
265
|
+
# Add cache options to kwargs
|
|
266
|
+
kwargs["use_cache"] = use_cache
|
|
267
|
+
if cache_ttl is not None:
|
|
268
|
+
kwargs["cache_ttl"] = cache_ttl
|
|
269
|
+
|
|
270
|
+
# Add to queue with priority - outside the lock
|
|
271
|
+
await self.queue.put(priority, task_id, task_func, args, kwargs, effective_timeout)
|
|
272
|
+
logger.info(f"Task {task_id} added to queue with priority {priority}")
|
|
273
|
+
|
|
274
|
+
return task_id
|
|
275
|
+
|
|
276
|
+
async def get_task_info(self, task_id: str) -> Optional[TaskInfo]:
|
|
277
|
+
"""
|
|
278
|
+
Get information about a specific task.
|
|
279
|
+
|
|
280
|
+
Args:
|
|
281
|
+
task_id: The task ID to look up
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
TaskInfo object or None if not found
|
|
285
|
+
"""
|
|
286
|
+
async with self.tasks_lock:
|
|
287
|
+
return self.tasks.get(task_id)
|
|
288
|
+
|
|
289
|
+
async def get_all_tasks(
|
|
290
|
+
self,
|
|
291
|
+
status: Optional[TaskStatus] = None,
|
|
292
|
+
limit: Optional[int] = None,
|
|
293
|
+
older_than: Optional[timedelta] = None
|
|
294
|
+
) -> List[TaskInfo]:
|
|
295
|
+
"""
|
|
296
|
+
Get information about tasks, with optional filtering.
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
status: Filter by task status
|
|
300
|
+
limit: Maximum number of tasks to return
|
|
301
|
+
older_than: Only return tasks created before this time delta
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
List of TaskInfo objects
|
|
305
|
+
"""
|
|
306
|
+
results = []
|
|
307
|
+
cutoff = datetime.now() - older_than if older_than else None
|
|
308
|
+
|
|
309
|
+
# Lock to prevent modifications during iteration
|
|
310
|
+
async with self.tasks_lock:
|
|
311
|
+
for task_info in self.tasks.values():
|
|
312
|
+
# Apply filters
|
|
313
|
+
if status is not None and task_info.status != status:
|
|
314
|
+
continue
|
|
315
|
+
if cutoff is not None and task_info.created_at >= cutoff:
|
|
316
|
+
continue
|
|
317
|
+
|
|
318
|
+
# Add to results
|
|
319
|
+
results.append(task_info)
|
|
320
|
+
|
|
321
|
+
# Check limit
|
|
322
|
+
if limit is not None and len(results) >= limit:
|
|
323
|
+
break
|
|
324
|
+
|
|
325
|
+
# Sort by creation time (newest first)
|
|
326
|
+
results.sort(key=lambda t: t.created_at, reverse=True)
|
|
327
|
+
|
|
328
|
+
return results
|
|
329
|
+
|
|
330
|
+
async def invalidate_cache(
|
|
331
|
+
self,
|
|
332
|
+
task_func: Callable,
|
|
333
|
+
*args: Any,
|
|
334
|
+
**kwargs: Any
|
|
335
|
+
) -> bool:
|
|
336
|
+
"""
|
|
337
|
+
Invalidate cache for a specific task function and arguments.
|
|
338
|
+
|
|
339
|
+
Args:
|
|
340
|
+
task_func: The task function
|
|
341
|
+
*args: Function arguments
|
|
342
|
+
**kwargs: Function keyword arguments
|
|
343
|
+
|
|
344
|
+
Returns:
|
|
345
|
+
True if cache entry was found and invalidated
|
|
346
|
+
"""
|
|
347
|
+
if not self.cache.enabled:
|
|
348
|
+
return False
|
|
349
|
+
|
|
350
|
+
return await self.cache.invalidate(task_func.__name__, args, kwargs)
|
|
351
|
+
|
|
352
|
+
async def clear_cache(self) -> None:
|
|
353
|
+
"""Clear all cached task results."""
|
|
354
|
+
if self.cache.enabled:
|
|
355
|
+
await self.cache.clear()
|
|
356
|
+
|
|
357
|
+
async def get_task_future(self, task_id: str) -> asyncio.Future:
|
|
358
|
+
"""
|
|
359
|
+
Get a future that will be resolved when the task completes.
|
|
360
|
+
|
|
361
|
+
Args:
|
|
362
|
+
task_id: ID of the task to track
|
|
363
|
+
|
|
364
|
+
Returns:
|
|
365
|
+
Future that resolves to the task result or raises an exception
|
|
366
|
+
|
|
367
|
+
Raises:
|
|
368
|
+
KeyError: If task_id is not found
|
|
369
|
+
"""
|
|
370
|
+
async with self.tasks_lock:
|
|
371
|
+
if task_id not in self.tasks:
|
|
372
|
+
raise KeyError(f"Task {task_id} not found")
|
|
373
|
+
|
|
374
|
+
# Check if we already have a future for this task
|
|
375
|
+
if task_id in self._task_futures:
|
|
376
|
+
return self._task_futures[task_id]
|
|
377
|
+
|
|
378
|
+
# Get the task info
|
|
379
|
+
task_info = self.tasks[task_id]
|
|
380
|
+
|
|
381
|
+
# Get or create a future for this task
|
|
382
|
+
future = await self.future_manager.get_future(task_id)
|
|
383
|
+
|
|
384
|
+
# Store in our weak dictionary
|
|
385
|
+
self._task_futures[task_id] = future
|
|
386
|
+
|
|
387
|
+
# If task is already in terminal state, resolve the future
|
|
388
|
+
if task_info.is_terminal_state():
|
|
389
|
+
await self.future_manager.complete_from_task_info(task_id, task_info)
|
|
390
|
+
|
|
391
|
+
return future
|
|
392
|
+
|
|
393
|
+
async def wait_for_tasks(self, task_ids: List[str], timeout: Optional[float] = None) -> List[T]:
|
|
394
|
+
"""
|
|
395
|
+
Wait for all specified tasks to complete.
|
|
396
|
+
|
|
397
|
+
Args:
|
|
398
|
+
task_ids: List of task IDs to wait for
|
|
399
|
+
timeout: Optional timeout in seconds
|
|
400
|
+
|
|
401
|
+
Returns:
|
|
402
|
+
List of task results in same order as task_ids
|
|
403
|
+
|
|
404
|
+
Raises:
|
|
405
|
+
TimeoutError: If the timeout is reached
|
|
406
|
+
"""
|
|
407
|
+
if not task_ids:
|
|
408
|
+
return []
|
|
409
|
+
|
|
410
|
+
# Check if any tasks are already complete and get their results directly
|
|
411
|
+
pending_task_ids = []
|
|
412
|
+
final_results = [None] * len(task_ids)
|
|
413
|
+
|
|
414
|
+
for i, task_id in enumerate(task_ids):
|
|
415
|
+
async with self.tasks_lock:
|
|
416
|
+
if self.tasks.get(task_id) and self.tasks.get(task_id).status == TaskStatus.COMPLETED:
|
|
417
|
+
# Task already completed, add result directly
|
|
418
|
+
final_results[i] = self.tasks.get(task_id).result
|
|
419
|
+
else:
|
|
420
|
+
# Task still pending, add to list for waiting
|
|
421
|
+
pending_task_ids.append((i, task_id))
|
|
422
|
+
|
|
423
|
+
# If all tasks are already complete, return results immediately
|
|
424
|
+
if not pending_task_ids:
|
|
425
|
+
return final_results
|
|
426
|
+
|
|
427
|
+
# Get futures for pending tasks
|
|
428
|
+
futures = []
|
|
429
|
+
for i, task_id in pending_task_ids:
|
|
430
|
+
future = await self.get_task_future(task_id)
|
|
431
|
+
futures.append((i, future))
|
|
432
|
+
|
|
433
|
+
# Wait for all pending futures to complete with timeout
|
|
434
|
+
try:
|
|
435
|
+
if timeout is not None:
|
|
436
|
+
async with asyncio.timeout(timeout):
|
|
437
|
+
for i, future in futures:
|
|
438
|
+
result = await future
|
|
439
|
+
final_results[i] = result
|
|
440
|
+
else:
|
|
441
|
+
for i, future in futures:
|
|
442
|
+
result = await future
|
|
443
|
+
final_results[i] = result
|
|
444
|
+
|
|
445
|
+
return final_results
|
|
446
|
+
|
|
447
|
+
except TimeoutError:
|
|
448
|
+
raise TimeoutError("Timeout waiting for tasks to complete")
|
|
449
|
+
|
|
450
|
+
async def wait_for_any_task(self, task_ids: List[str], timeout: Optional[float] = None) -> Tuple[T, str]:
|
|
451
|
+
"""
|
|
452
|
+
Wait for any of the specified tasks to complete.
|
|
453
|
+
|
|
454
|
+
Args:
|
|
455
|
+
task_ids: List of task IDs to wait for
|
|
456
|
+
timeout: Optional timeout in seconds
|
|
457
|
+
|
|
458
|
+
Returns:
|
|
459
|
+
Tuple of (result, task_id) for the first completed task
|
|
460
|
+
|
|
461
|
+
Raises:
|
|
462
|
+
TimeoutError: If the timeout is reached
|
|
463
|
+
ValueError: If no task IDs are provided
|
|
464
|
+
"""
|
|
465
|
+
if not task_ids:
|
|
466
|
+
raise ValueError("No task IDs provided")
|
|
467
|
+
|
|
468
|
+
# First check if any tasks are already complete
|
|
469
|
+
for task_id in task_ids:
|
|
470
|
+
async with self.tasks_lock:
|
|
471
|
+
if self.tasks.get(task_id) and self.tasks.get(task_id).status == TaskStatus.COMPLETED:
|
|
472
|
+
# Task already completed, return its result immediately
|
|
473
|
+
return self.tasks.get(task_id).result, task_id
|
|
474
|
+
|
|
475
|
+
# Get futures for all tasks
|
|
476
|
+
futures_map = {} # Maps Future -> task_id
|
|
477
|
+
futures = []
|
|
478
|
+
|
|
479
|
+
for task_id in task_ids:
|
|
480
|
+
future = await self.get_task_future(task_id)
|
|
481
|
+
futures.append(future)
|
|
482
|
+
futures_map[future] = task_id
|
|
483
|
+
|
|
484
|
+
# Wait for first completion
|
|
485
|
+
try:
|
|
486
|
+
if timeout is not None:
|
|
487
|
+
async with asyncio.timeout(timeout):
|
|
488
|
+
# Create a task for each future and wait for the first to complete
|
|
489
|
+
done, pending = await asyncio.wait(
|
|
490
|
+
futures,
|
|
491
|
+
return_when=asyncio.FIRST_COMPLETED
|
|
492
|
+
)
|
|
493
|
+
else:
|
|
494
|
+
done, pending = await asyncio.wait(
|
|
495
|
+
futures,
|
|
496
|
+
return_when=asyncio.FIRST_COMPLETED
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
if not done:
|
|
500
|
+
raise TimeoutError("Timeout waiting for any task to complete")
|
|
501
|
+
|
|
502
|
+
# Get the first completed future
|
|
503
|
+
completed_future = next(iter(done))
|
|
504
|
+
task_id = futures_map[completed_future]
|
|
505
|
+
result = completed_future.result()
|
|
506
|
+
|
|
507
|
+
return result, task_id
|
|
508
|
+
|
|
509
|
+
except TimeoutError:
|
|
510
|
+
raise TimeoutError("Timeout waiting for any task to complete")
|
|
511
|
+
|
|
512
|
+
async def cancel_task(self, task_id: str) -> bool:
|
|
513
|
+
"""
|
|
514
|
+
Cancel a task.
|
|
515
|
+
|
|
516
|
+
Args:
|
|
517
|
+
task_id: ID of the task to cancel
|
|
518
|
+
|
|
519
|
+
Returns:
|
|
520
|
+
True if the task was cancelled, False if not found or already completed
|
|
521
|
+
"""
|
|
522
|
+
logger.info(f"Attempting to cancel task {task_id}")
|
|
523
|
+
|
|
524
|
+
# Prepare variables for tracking cancellation state
|
|
525
|
+
task_removed = False
|
|
526
|
+
task_running = False
|
|
527
|
+
task_status = None
|
|
528
|
+
cancel_result = False
|
|
529
|
+
|
|
530
|
+
# Acquire the tasks_lock to check task state
|
|
531
|
+
async with self.tasks_lock:
|
|
532
|
+
# Check if task exists and can be cancelled
|
|
533
|
+
task_info = self.tasks.get(task_id)
|
|
534
|
+
if not task_info:
|
|
535
|
+
logger.warning(f"Task {task_id} not found for cancellation.")
|
|
536
|
+
return False
|
|
537
|
+
|
|
538
|
+
# Store the current status for decision making
|
|
539
|
+
task_status = task_info.status
|
|
540
|
+
|
|
541
|
+
# If task is already in a terminal state, we're done
|
|
542
|
+
if task_info.is_terminal_state():
|
|
543
|
+
logger.info(f"Task {task_id} is already in a terminal state ({task_status}).")
|
|
544
|
+
return False
|
|
545
|
+
|
|
546
|
+
logger.info(f"Task {task_id} is in state {task_status}")
|
|
547
|
+
|
|
548
|
+
# Track if the task is currently running
|
|
549
|
+
task_running = (task_status == TaskStatus.RUNNING)
|
|
550
|
+
|
|
551
|
+
# If task is PENDING or similar non-running state, we can cancel it directly
|
|
552
|
+
if not task_running:
|
|
553
|
+
# First try to remove from queue to prevent it from starting
|
|
554
|
+
task_removed = await self.queue.remove_task(task_id)
|
|
555
|
+
|
|
556
|
+
# Mark it as cancelled while still holding the lock
|
|
557
|
+
await task_info.mark_cancelled("Task cancelled before execution")
|
|
558
|
+
logger.info(f"Cancelled {'queued' if task_removed else 'pending'} task {task_id}")
|
|
559
|
+
|
|
560
|
+
# Notify futures (still holding the lock)
|
|
561
|
+
await self.future_manager.set_exception(
|
|
562
|
+
task_id,
|
|
563
|
+
TaskError("Task cancelled", task_id=task_id)
|
|
564
|
+
)
|
|
565
|
+
cancel_result = True
|
|
566
|
+
|
|
567
|
+
# For running tasks, special handling with the worker pool is needed
|
|
568
|
+
if task_running:
|
|
569
|
+
# Cancel the running task in the worker pool
|
|
570
|
+
worker_cancelled = await self.worker_pool.cancel_running_task(task_id)
|
|
571
|
+
|
|
572
|
+
# Now re-acquire the lock to update the task state
|
|
573
|
+
async with self.tasks_lock:
|
|
574
|
+
# Get the task info again - it might have changed
|
|
575
|
+
task_info = self.tasks.get(task_id)
|
|
576
|
+
|
|
577
|
+
# Task might have completed while we were cancelling
|
|
578
|
+
if not task_info or task_info.is_terminal_state():
|
|
579
|
+
logger.info(f"Task {task_id} completed while cancellation was in progress.")
|
|
580
|
+
cancel_result = False
|
|
581
|
+
else:
|
|
582
|
+
# Mark the task as cancelled
|
|
583
|
+
await task_info.mark_cancelled(
|
|
584
|
+
"Task execution cancelled" if worker_cancelled else "Task cancellation requested"
|
|
585
|
+
)
|
|
586
|
+
logger.info(f"Marked running task {task_id} as cancelled")
|
|
587
|
+
|
|
588
|
+
# Notify futures
|
|
589
|
+
await self.future_manager.set_exception(
|
|
590
|
+
task_id,
|
|
591
|
+
TaskError("Task cancelled", task_id=task_id)
|
|
592
|
+
)
|
|
593
|
+
cancel_result = True
|
|
594
|
+
|
|
595
|
+
return cancel_result
|
|
596
|
+
|
|
597
|
+
async def _cleanup_loop(self) -> None:
|
|
598
|
+
"""Periodically clean up old completed tasks"""
|
|
599
|
+
logger.debug("Task cleanup loop started")
|
|
600
|
+
|
|
601
|
+
while self.running:
|
|
602
|
+
try:
|
|
603
|
+
await asyncio.sleep(self.cleanup_interval)
|
|
604
|
+
await self.cleanup_old_tasks()
|
|
605
|
+
except asyncio.CancelledError:
|
|
606
|
+
logger.debug("Task cleanup loop cancelled")
|
|
607
|
+
break
|
|
608
|
+
except Exception as e:
|
|
609
|
+
logger.error(f"Error in task cleanup loop: {str(e)}", exc_info=True)
|
|
610
|
+
|
|
611
|
+
logger.debug("Task cleanup loop stopped")
|
|
612
|
+
|
|
613
|
+
# Callback methods for WorkerPool
|
|
614
|
+
async def _on_task_started(self, task_id: str, task_info: Optional[TaskInfo], _: Any) -> None:
|
|
615
|
+
"""
|
|
616
|
+
Callback when a task is started.
|
|
617
|
+
|
|
618
|
+
Args:
|
|
619
|
+
task_id: ID of the task
|
|
620
|
+
task_info: Task info from WorkerPool (not used in AsyncTaskWorker implementation,
|
|
621
|
+
which retrieves task info from its own tasks dict)
|
|
622
|
+
_: Not used
|
|
623
|
+
"""
|
|
624
|
+
async with self.tasks_lock:
|
|
625
|
+
if task_id in self.tasks:
|
|
626
|
+
await self.tasks[task_id].mark_started()
|
|
627
|
+
|
|
628
|
+
async def _on_task_completed(self, task_id: str, task_info: Optional[TaskInfo], result: Any) -> None:
|
|
629
|
+
"""
|
|
630
|
+
Callback when a task is completed.
|
|
631
|
+
|
|
632
|
+
Args:
|
|
633
|
+
task_id: ID of the task
|
|
634
|
+
task_info: Task info from WorkerPool (not used in AsyncTaskWorker implementation,
|
|
635
|
+
which retrieves task info from its own tasks dict)
|
|
636
|
+
result: Task result
|
|
637
|
+
"""
|
|
638
|
+
async with self.tasks_lock:
|
|
639
|
+
if task_id in self.tasks:
|
|
640
|
+
await self.tasks[task_id].mark_completed(result)
|
|
641
|
+
# Complete any futures waiting on this task
|
|
642
|
+
await self.future_manager.complete_from_result(task_id, result)
|
|
643
|
+
|
|
644
|
+
# noinspection PyUnusedLocal
|
|
645
|
+
async def _on_task_failed(self, task_id: str, task_info: Optional[TaskInfo], error: str) -> None:
|
|
646
|
+
"""
|
|
647
|
+
Callback when a task fails.
|
|
648
|
+
|
|
649
|
+
Args:
|
|
650
|
+
task_id: ID of the task
|
|
651
|
+
task_info: Task info from WorkerPool (not used in AsyncTaskWorker implementation,
|
|
652
|
+
which retrieves task info from its own tasks dict)
|
|
653
|
+
error: Error message
|
|
654
|
+
"""
|
|
655
|
+
async with self.tasks_lock:
|
|
656
|
+
if task_id in self.tasks:
|
|
657
|
+
await self.tasks[task_id].mark_failed(error)
|
|
658
|
+
# Set exception on any futures waiting on this task
|
|
659
|
+
await self.future_manager.set_exception(task_id, TaskError(error, task_id=task_id))
|
|
660
|
+
|
|
661
|
+
# noinspection PyUnusedLocal
|
|
662
|
+
async def _on_task_cancelled(self, task_id: str, task_info: Optional[TaskInfo], reason: str) -> None:
|
|
663
|
+
"""
|
|
664
|
+
Callback when a task is cancelled.
|
|
665
|
+
|
|
666
|
+
Args:
|
|
667
|
+
task_id: ID of the task
|
|
668
|
+
task_info: Task info from WorkerPool (not used in AsyncTaskWorker implementation,
|
|
669
|
+
which retrieves task info from its own tasks dict)
|
|
670
|
+
reason: Reason for cancellation
|
|
671
|
+
"""
|
|
672
|
+
async with self.tasks_lock:
|
|
673
|
+
if task_id in self.tasks:
|
|
674
|
+
await self.tasks[task_id].mark_cancelled(reason)
|
|
675
|
+
# Set exception on any futures waiting on this task
|
|
676
|
+
await self.future_manager.set_exception(task_id, TaskError("Task cancelled", task_id=task_id))
|
|
677
|
+
|
|
678
|
+
async def cleanup_old_tasks(self) -> int:
|
|
679
|
+
"""
|
|
680
|
+
Remove old completed, failed, or cancelled tasks.
|
|
681
|
+
|
|
682
|
+
Returns:
|
|
683
|
+
Number of tasks removed
|
|
684
|
+
"""
|
|
685
|
+
if self.task_retention_days is None:
|
|
686
|
+
return 0
|
|
687
|
+
|
|
688
|
+
cutoff_time = datetime.now() - timedelta(days=self.task_retention_days)
|
|
689
|
+
to_remove = []
|
|
690
|
+
|
|
691
|
+
async with self.tasks_lock:
|
|
692
|
+
# First identify tasks to remove
|
|
693
|
+
for task_id, task_info in self.tasks.items():
|
|
694
|
+
# Only remove tasks that are in a final state
|
|
695
|
+
if task_info.is_terminal_state():
|
|
696
|
+
# Check if the task is old enough to be removed
|
|
697
|
+
if task_info.completed_at and task_info.completed_at < cutoff_time:
|
|
698
|
+
to_remove.append(task_id)
|
|
699
|
+
|
|
700
|
+
# Then remove them and ensure all references are cleaned up
|
|
701
|
+
count = 0
|
|
702
|
+
for task_id in to_remove:
|
|
703
|
+
if task_id in self.tasks:
|
|
704
|
+
del self.tasks[task_id]
|
|
705
|
+
count += 1
|
|
706
|
+
|
|
707
|
+
# Clean up any future references
|
|
708
|
+
for task_id in to_remove:
|
|
709
|
+
# Cancel and remove any task futures without waiting
|
|
710
|
+
await self.future_manager.cancel_future(task_id)
|
|
711
|
+
|
|
712
|
+
# Also check for any lingering entries in queue tracking
|
|
713
|
+
await self.queue.clean_cancelled_tasks(to_remove)
|
|
714
|
+
|
|
715
|
+
logger.info(f"Cleaned up {count} old tasks")
|
|
716
|
+
|
|
717
|
+
return count
|