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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,633 @@
1
+ """
2
+ Async Task Worker
3
+
4
+ This module provides an asynchronous task worker that manages background tasks
5
+ using Python asyncio features with support for task result caching.
6
+ """
7
+
8
+ import asyncio
9
+ import inspect
10
+ import logging
11
+ import uuid
12
+ from datetime import datetime, timedelta
13
+ from enum import Enum
14
+ from typing import Any, Awaitable, Callable, Dict, List, Optional, Self, TypeVar
15
+
16
+ from pydantic import BaseModel, Field
17
+
18
+ from async_task_worker.task_cache import CacheAdapter, MemoryCacheAdapter, TaskCache
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ # Task status enum
24
+ class TaskStatus(str, Enum):
25
+ PENDING = "pending"
26
+ RUNNING = "running"
27
+ COMPLETED = "completed"
28
+ FAILED = "failed"
29
+ CANCELLED = "cancelled"
30
+
31
+
32
+ # Task info model
33
+ class TaskInfo(BaseModel):
34
+ id: str
35
+ status: TaskStatus
36
+ created_at: datetime
37
+ started_at: Optional[datetime] = None
38
+ completed_at: Optional[datetime] = None
39
+ result: Optional[Any] = None
40
+ error: Optional[str] = None
41
+ progress: float = 0.0
42
+ metadata: Dict[str, Any] = Field(default_factory=dict)
43
+
44
+ class Config:
45
+ arbitrary_types_allowed = True
46
+
47
+
48
+ # Progress callback type
49
+ ProgressCallback = Callable[[float], None]
50
+ T = TypeVar('T')
51
+
52
+
53
+ class AsyncTaskWorker:
54
+ """
55
+ Worker pool for managing asynchronous background tasks.
56
+
57
+ Features:
58
+ - Task queuing with priorities
59
+ - Configurable number of worker tasks
60
+ - Task status tracking
61
+ - Task cancellation
62
+ - Progress reporting
63
+ - Result caching
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ max_workers: int = 10,
69
+ task_timeout: Optional[int] = None,
70
+ worker_poll_interval: float = 1.0,
71
+ cache_enabled: bool = False,
72
+ cache_ttl: Optional[int] = 3600, # 1 hour default
73
+ cache_max_size: Optional[int] = 1000,
74
+ cache_adapter: Optional[CacheAdapter] = None
75
+ ):
76
+ """
77
+ Initialize the task worker.
78
+
79
+ Args:
80
+ max_workers: Maximum number of concurrent worker tasks
81
+ task_timeout: Default timeout in seconds for tasks (None for no timeout)
82
+ worker_poll_interval: How frequently workers check for new tasks
83
+ cache_enabled: Whether task result caching is enabled
84
+ cache_ttl: Default time-to-live for cached results in seconds (None for no expiry)
85
+ cache_max_size: Maximum number of entries in the cache (None for unlimited)
86
+ cache_adapter: Custom cache adapter (default is in-memory)
87
+ """
88
+ self.tasks: Dict[str, TaskInfo] = {}
89
+ self.queue: asyncio.PriorityQueue = asyncio.PriorityQueue()
90
+ self.max_workers = max_workers
91
+ self.default_task_timeout = task_timeout
92
+ self.worker_poll_interval = worker_poll_interval
93
+ self.workers: List[asyncio.Task] = []
94
+ self.running = False
95
+ self._running_tasks: Dict[str, asyncio.Task] = {}
96
+ self._progress_callbacks: Dict[str, ProgressCallback] = {}
97
+ self._completion_events: Dict[str, asyncio.Event] = {}
98
+ self._locks = {
99
+ "tasks": asyncio.Lock(),
100
+ "running_tasks": asyncio.Lock(),
101
+ "progress_callbacks": asyncio.Lock(),
102
+ "completion_events": asyncio.Lock()
103
+ }
104
+
105
+ # Set up cache
106
+ adapter = cache_adapter or MemoryCacheAdapter(max_size=cache_max_size)
107
+ self.cache = TaskCache(adapter, default_ttl=cache_ttl, enabled=cache_enabled)
108
+
109
+ async def __aenter__(self) -> Self:
110
+ """Support async context manager protocol"""
111
+ await self.start()
112
+ return self
113
+
114
+ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
115
+ """Support async context manager protocol"""
116
+ await self.stop()
117
+
118
+ async def start(self) -> None:
119
+ """Start the worker pool"""
120
+ if self.running:
121
+ return
122
+
123
+ self.running = True
124
+ # Start worker tasks
125
+ for i in range(self.max_workers):
126
+ worker = asyncio.create_task(self._worker_loop(worker_id=i))
127
+ worker.set_name(f"task_worker_{i}")
128
+ self.workers.append(worker)
129
+
130
+ logger.info(f"Started {self.max_workers} worker tasks")
131
+
132
+ async def stop(self, timeout: float = 5.0) -> None:
133
+ """
134
+ Stop the worker pool gracefully.
135
+
136
+ Args:
137
+ timeout: Maximum time to wait for tasks to complete
138
+ """
139
+ if not self.running:
140
+ return
141
+
142
+ self.running = False
143
+ logger.info("Stopping worker pool...")
144
+
145
+ # Cancel all running tasks
146
+ async with self._locks["running_tasks"]:
147
+ for task_id, task in self._running_tasks.items():
148
+ if not task.done():
149
+ logger.info(f"Cancelling task {task_id}")
150
+ task.cancel()
151
+
152
+ # Update status immediately to fix test_task_cancellation
153
+ async with self._locks["tasks"]:
154
+ if task_id in self.tasks:
155
+ self.tasks[task_id].status = TaskStatus.CANCELLED
156
+ self.tasks[task_id].completed_at = datetime.now()
157
+ self.tasks[task_id].error = "Task cancelled"
158
+
159
+ # Give workers time to process cancellations
160
+ if self.workers:
161
+ try:
162
+ await asyncio.wait_for(
163
+ asyncio.gather(*self.workers, return_exceptions=True),
164
+ timeout=timeout
165
+ )
166
+ except asyncio.TimeoutError:
167
+ logger.warning(f"Timeout waiting for workers to stop after {timeout}s")
168
+
169
+ self.workers = []
170
+
171
+ async with self._locks["running_tasks"]:
172
+ self._running_tasks = {}
173
+
174
+ logger.info("Worker pool stopped")
175
+
176
+ async def _update_progress(self, task_id: str, progress: float) -> None:
177
+ """Update task progress with proper locking"""
178
+ async with self._locks["tasks"]:
179
+ if task_id in self.tasks:
180
+ self.tasks[task_id].progress = progress
181
+
182
+ async def _worker_loop(self, worker_id: int) -> None:
183
+ """Main worker loop that processes tasks from the queue."""
184
+ logger.debug(f"Worker {worker_id} started")
185
+
186
+ while self.running:
187
+ try:
188
+ # Use a try/except block just for the queue.get operation
189
+ try:
190
+ priority, task_id, task_func, task_args, task_kwargs, timeout = await asyncio.wait_for(
191
+ self.queue.get(), timeout=self.worker_poll_interval
192
+ )
193
+
194
+ logger.info(f"Worker {worker_id} processing task {task_id} (priority: {priority})")
195
+
196
+ # Update task status
197
+ async with self._locks["tasks"]:
198
+ if task_id not in self.tasks:
199
+ logger.warning(f"Task {task_id} not found in tasks dictionary")
200
+ self.queue.task_done()
201
+ continue
202
+
203
+ self.tasks[task_id].status = TaskStatus.RUNNING
204
+ self.tasks[task_id].started_at = datetime.now()
205
+
206
+ # Use the per-task timeout if provided
207
+ await self._execute_task(task_id, task_func, task_args, task_kwargs, timeout)
208
+
209
+ # Mark task as done in queue
210
+ self.queue.task_done()
211
+
212
+ except asyncio.TimeoutError:
213
+ # No task received, continue loop
214
+ continue
215
+
216
+ except asyncio.CancelledError:
217
+ # Worker is being cancelled
218
+ logger.debug(f"Worker {worker_id} cancelled")
219
+ break
220
+
221
+ except Exception as e:
222
+ # Log unexpected exceptions but continue processing
223
+ logger.error(f"Unexpected error in worker {worker_id}: {str(e)}", exc_info=True)
224
+
225
+ logger.debug(f"Worker {worker_id} stopped")
226
+
227
+ async def _execute_task(
228
+ self,
229
+ task_id: str,
230
+ task_func: Callable,
231
+ task_args: tuple,
232
+ task_kwargs: dict,
233
+ timeout: Optional[int] = None
234
+ ) -> Any:
235
+ """Execute a task with the specified timeout."""
236
+
237
+ # Extract cache options from kwargs if present
238
+ use_cache = task_kwargs.pop("use_cache", True)
239
+ cache_ttl = task_kwargs.pop("cache_ttl", None)
240
+
241
+ # Try to get from cache if caching is enabled
242
+ if use_cache and self.cache.enabled:
243
+ func_name = task_func.__name__
244
+ # Make a copy without progress_callback for cache key
245
+ cache_kwargs = {k: v for k, v in task_kwargs.items()
246
+ if k != "progress_callback"}
247
+
248
+ cache_hit, cached_result = await self.cache.get(func_name, task_args, cache_kwargs)
249
+
250
+ if cache_hit:
251
+ logger.info(f"Task {task_id} using cached result")
252
+
253
+ # Update task with cached result
254
+ async with self._locks["tasks"]:
255
+ if task_id in self.tasks: # Guard against race conditions
256
+ self.tasks[task_id].status = TaskStatus.COMPLETED
257
+ self.tasks[task_id].completed_at = datetime.now()
258
+ self.tasks[task_id].result = cached_result
259
+ self.tasks[task_id].progress = 1.0
260
+
261
+ return cached_result
262
+
263
+ # Create progress callback
264
+ def update_progress(progress: float) -> None:
265
+ asyncio.create_task(self._update_progress(task_id, progress))
266
+
267
+ # Create a copy of kwargs to avoid modifying the original
268
+ task_kwargs_copy = task_kwargs.copy()
269
+
270
+ # Check if the function can accept progress_callback
271
+ try:
272
+ # Get the signature and check if it has **kwargs or explicit progress_callback
273
+ sig = inspect.signature(task_func)
274
+ has_progress_param = "progress_callback" in sig.parameters
275
+ has_kwargs = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values())
276
+
277
+ # Only add if the function can accept it
278
+ if has_progress_param or has_kwargs:
279
+ task_kwargs_copy["progress_callback"] = update_progress
280
+ except (ValueError, TypeError):
281
+ # If we can't inspect the function, don't add the callback
282
+ pass
283
+
284
+ # Create the task coroutine
285
+ task_coroutine = task_func(*task_args, **task_kwargs_copy)
286
+
287
+ # Apply timeout if configured
288
+ if timeout is not None:
289
+ task_coroutine = asyncio.wait_for(task_coroutine, timeout=timeout)
290
+
291
+ # Execute the task
292
+ execution_task = asyncio.create_task(task_coroutine)
293
+
294
+ async with self._locks["running_tasks"]:
295
+ self._running_tasks[task_id] = execution_task
296
+
297
+ try:
298
+ # Wait for task to complete
299
+ result = await execution_task
300
+
301
+ # Update task with success
302
+ async with self._locks["tasks"]:
303
+ if task_id in self.tasks: # Guard against race conditions
304
+ self.tasks[task_id].status = TaskStatus.COMPLETED
305
+ self.tasks[task_id].completed_at = datetime.now()
306
+ self.tasks[task_id].result = result
307
+ self.tasks[task_id].progress = 1.0
308
+
309
+ logger.info(f"Task {task_id} completed successfully")
310
+
311
+ # Store in cache if caching is enabled
312
+ if use_cache and self.cache.enabled:
313
+ # Get function name and kwargs without progress_callback
314
+ func_name = task_func.__name__
315
+ cache_kwargs = {k: v for k, v in task_kwargs.items()
316
+ if k != "progress_callback"}
317
+
318
+ # Store in cache
319
+ await self.cache.set(func_name, task_args, cache_kwargs, result, cache_ttl)
320
+
321
+ return result
322
+
323
+ except asyncio.CancelledError:
324
+ # Task was cancelled
325
+ async with self._locks["tasks"]:
326
+ if task_id in self.tasks:
327
+ self.tasks[task_id].status = TaskStatus.CANCELLED
328
+ self.tasks[task_id].completed_at = datetime.now()
329
+ self.tasks[task_id].error = "Task cancelled"
330
+
331
+ logger.info(f"Task {task_id} was cancelled")
332
+ raise
333
+
334
+ except asyncio.TimeoutError:
335
+ # Task timed out
336
+ async with self._locks["tasks"]:
337
+ if task_id in self.tasks:
338
+ self.tasks[task_id].status = TaskStatus.FAILED
339
+ self.tasks[task_id].completed_at = datetime.now()
340
+ self.tasks[task_id].error = f"Task timed out after {timeout}s"
341
+
342
+ logger.error(f"Task {task_id} timed out")
343
+ raise
344
+
345
+ except Exception as e:
346
+ # Task failed with an exception
347
+ async with self._locks["tasks"]:
348
+ if task_id in self.tasks:
349
+ self.tasks[task_id].status = TaskStatus.FAILED
350
+ self.tasks[task_id].completed_at = datetime.now()
351
+ self.tasks[task_id].error = str(e)
352
+
353
+ logger.error(f"Task {task_id} failed: {str(e)}", exc_info=True)
354
+ raise
355
+
356
+ finally:
357
+ # Clean up
358
+ async with self._locks["running_tasks"]:
359
+ if task_id in self._running_tasks:
360
+ del self._running_tasks[task_id]
361
+
362
+ async with self._locks["progress_callbacks"]:
363
+ if task_id in self._progress_callbacks:
364
+ del self._progress_callbacks[task_id]
365
+
366
+ # Signal completion for any waiting futures
367
+ async with self._locks["completion_events"]:
368
+ if task_id in self._completion_events:
369
+ self._completion_events[task_id].set()
370
+
371
+ async def add_task(
372
+ self,
373
+ task_func: Callable[..., Awaitable[T]],
374
+ *args: Any,
375
+ priority: int = 0,
376
+ task_id: Optional[str] = None,
377
+ metadata: Optional[Dict[str, Any]] = None,
378
+ timeout: Optional[int] = None,
379
+ use_cache: bool = True,
380
+ cache_ttl: Optional[int] = None,
381
+ **kwargs: Any
382
+ ) -> str:
383
+ """
384
+ Add a new task to the queue and return its ID.
385
+
386
+ Args:
387
+ task_func: Async function to execute
388
+ *args: Positional arguments to pass to the function
389
+ priority: Task priority (lower number = higher priority)
390
+ task_id: Optional custom task ID (default: auto-generated UUID)
391
+ metadata: Optional metadata to store with the task
392
+ timeout: Optional per-task timeout override (uses default if None)
393
+ use_cache: Whether to use cache for this task
394
+ cache_ttl: Optional cache TTL override
395
+ **kwargs: Keyword arguments to pass to the function
396
+
397
+ Returns:
398
+ Task ID string
399
+ """
400
+ if not self.running:
401
+ raise RuntimeError("Worker pool is not running")
402
+
403
+ # Generate or use provided task ID
404
+ if task_id is None:
405
+ task_id = str(uuid.uuid4())
406
+
407
+ # Create task info
408
+ async with self._locks["tasks"]:
409
+ self.tasks[task_id] = TaskInfo(
410
+ id=task_id,
411
+ status=TaskStatus.PENDING,
412
+ created_at=datetime.now(),
413
+ metadata=metadata or {}
414
+ )
415
+
416
+ # Use task-specific timeout or default
417
+ effective_timeout = timeout if timeout is not None else self.default_task_timeout
418
+
419
+ # Add cache options to kwargs
420
+ kwargs["use_cache"] = use_cache
421
+ if cache_ttl is not None:
422
+ kwargs["cache_ttl"] = cache_ttl
423
+
424
+ # Add to queue with priority
425
+ await self.queue.put((priority, task_id, task_func, args, kwargs, effective_timeout))
426
+ logger.info(f"Task {task_id} added to queue with priority {priority}")
427
+
428
+ return task_id
429
+
430
+ def get_task_info(self, task_id: str) -> Optional[TaskInfo]:
431
+ """
432
+ Get information about a specific task.
433
+
434
+ Args:
435
+ task_id: The task ID to look up
436
+
437
+ Returns:
438
+ TaskInfo object or None if not found
439
+ """
440
+ # No need for lock here as we're just reading
441
+ return self.tasks.get(task_id)
442
+
443
+ def get_all_tasks(
444
+ self,
445
+ status: Optional[TaskStatus] = None,
446
+ limit: Optional[int] = None,
447
+ older_than: Optional[timedelta] = None
448
+ ) -> List[TaskInfo]:
449
+ """
450
+ Get information about tasks, with optional filtering.
451
+
452
+ Args:
453
+ status: Filter by task status
454
+ limit: Maximum number of tasks to return
455
+ older_than: Only return tasks created before this time delta
456
+
457
+ Returns:
458
+ List of TaskInfo objects
459
+ """
460
+ # Make a copy of tasks to avoid mutation during iteration
461
+ tasks = list(self.tasks.values())
462
+
463
+ # Apply status filter
464
+ if status is not None:
465
+ tasks = [t for t in tasks if t.status == status]
466
+
467
+ # Apply age filter
468
+ if older_than is not None:
469
+ cutoff = datetime.now() - older_than
470
+ tasks = [t for t in tasks if t.created_at < cutoff]
471
+
472
+ # Sort by creation time (newest first)
473
+ tasks.sort(key=lambda t: t.created_at, reverse=True)
474
+
475
+ # Apply limit
476
+ if limit is not None:
477
+ tasks = tasks[:limit]
478
+
479
+ return tasks
480
+
481
+ async def cancel_task(self, task_id: str) -> bool:
482
+ """
483
+ Cancel a running or pending task.
484
+
485
+ Args:
486
+ task_id: ID of the task to cancel
487
+
488
+ Returns:
489
+ True if the task was cancelled, False if not found or already completed
490
+ """
491
+ # Check if task exists and get task info
492
+ async with self._locks["tasks"]:
493
+ if task_id not in self.tasks:
494
+ return False
495
+
496
+ task_info = self.tasks[task_id]
497
+
498
+ # Can't cancel completed tasks
499
+ if task_info.status in (TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED):
500
+ return False
501
+
502
+ # If task is running, cancel it
503
+ async with self._locks["running_tasks"]:
504
+ running_task = self._running_tasks.get(task_id)
505
+
506
+ if running_task and not running_task.done():
507
+ running_task.cancel()
508
+ # Update task status immediately
509
+ async with self._locks["tasks"]:
510
+ task_info.status = TaskStatus.CANCELLED
511
+ task_info.completed_at = datetime.now()
512
+ task_info.error = "Task cancelled"
513
+ logger.info(f"Cancelled running task {task_id}")
514
+ return True
515
+
516
+ # Task is pending, mark as cancelled
517
+ async with self._locks["tasks"]:
518
+ task_info.status = TaskStatus.CANCELLED
519
+ task_info.completed_at = datetime.now()
520
+ task_info.error = "Task cancelled before execution"
521
+ logger.info(f"Cancelled pending task {task_id}")
522
+ return True
523
+
524
+ async def invalidate_cache(
525
+ self,
526
+ task_func: Callable,
527
+ *args: Any,
528
+ **kwargs: Any
529
+ ) -> bool:
530
+ """
531
+ Invalidate cache for a specific task function and arguments.
532
+
533
+ Args:
534
+ task_func: The task function
535
+ *args: Function arguments
536
+ **kwargs: Function keyword arguments
537
+
538
+ Returns:
539
+ True if cache entry was found and invalidated
540
+ """
541
+ if not self.cache.enabled:
542
+ return False
543
+
544
+ return await self.cache.invalidate(task_func.__name__, args, kwargs)
545
+
546
+ async def clear_cache(self) -> None:
547
+ """Clear all cached task results."""
548
+ if self.cache.enabled:
549
+ await self.cache.clear()
550
+
551
+ def get_task_future(self, task_id: str) -> asyncio.Future:
552
+ """
553
+ Get a future that will be resolved when the task completes.
554
+
555
+ Args:
556
+ task_id: ID of the task to track
557
+
558
+ Returns:
559
+ Future that resolves to the task result or raises an exception
560
+
561
+ Raises:
562
+ KeyError: If task_id is not found
563
+ """
564
+ if task_id not in self.tasks:
565
+ raise KeyError(f"Task {task_id} not found")
566
+
567
+ # Create future for the result
568
+ future = asyncio.Future()
569
+ task_info = self.tasks[task_id]
570
+
571
+ # If already complete, return pre-resolved future
572
+ if task_info.status == TaskStatus.COMPLETED:
573
+ future.set_result(task_info.result)
574
+ elif task_info.status == TaskStatus.FAILED:
575
+ future.set_exception(RuntimeError(f"Task failed: {task_info.error}"))
576
+ elif task_info.status == TaskStatus.CANCELLED:
577
+ future.set_exception(asyncio.CancelledError(f"Task was cancelled: {task_info.error}"))
578
+ else:
579
+ # Create event and register monitoring task
580
+ event = asyncio.Event()
581
+ asyncio.create_task(self._wait_for_completion(task_id, future, event))
582
+ asyncio.create_task(self._register_completion_event(task_id, event))
583
+
584
+ return future
585
+
586
+ def get_task_futures(self, task_ids: List[str]) -> List[asyncio.Future]:
587
+ """
588
+ Get futures for multiple tasks at once.
589
+
590
+ Args:
591
+ task_ids: List of task IDs to monitor
592
+
593
+ Returns:
594
+ List of futures that will resolve to task results
595
+
596
+ Raises:
597
+ KeyError: If any task_id is not found
598
+ """
599
+ return [self.get_task_future(task_id) for task_id in task_ids]
600
+
601
+ async def _register_completion_event(self, task_id: str, event: asyncio.Event) -> None:
602
+ """Register a completion event for a task"""
603
+ async with self._locks["completion_events"]:
604
+ self._completion_events[task_id] = event
605
+
606
+ async def _wait_for_completion(self, task_id: str, future: asyncio.Future, event: asyncio.Event) -> None:
607
+ """Wait for task completion using an event"""
608
+ try:
609
+ # Wait for the event to be set
610
+ await event.wait()
611
+
612
+ # Get final task info
613
+ task_info = self.get_task_info(task_id)
614
+
615
+ # Handle the result based on status
616
+ if task_info is None:
617
+ future.set_exception(RuntimeError(f"Task {task_id} was removed"))
618
+ elif task_info.status == TaskStatus.COMPLETED:
619
+ future.set_result(task_info.result)
620
+ elif task_info.status == TaskStatus.FAILED:
621
+ future.set_exception(RuntimeError(f"Task failed: {task_info.error}"))
622
+ elif task_info.status == TaskStatus.CANCELLED:
623
+ future.set_exception(asyncio.CancelledError(f"Task was cancelled: {task_info.error}"))
624
+ else:
625
+ future.set_exception(RuntimeError(f"Task in unexpected state: {task_info.status}"))
626
+ except Exception as e:
627
+ if not future.done():
628
+ future.set_exception(e)
629
+ finally:
630
+ # Clean up the event
631
+ async with self._locks["completion_events"]:
632
+ if task_id in self._completion_events:
633
+ del self._completion_events[task_id]