| 1 | import asyncio |
| 2 | from typing import Any, Callable, List, TypeVar |
| 3 | |
| 4 | from utils.logger import setup_logger |
| 5 | |
| 6 | logger = setup_logger("QueueManager") |
| 7 | |
| 8 | T = TypeVar("T") |
| 9 | |
| 10 | |
| 11 | class QueueManager: |
| 12 | def __init__(self, max_workers: int = 5): |
| 13 | self.max_workers = max_workers |
| 14 | self.semaphore = asyncio.Semaphore(max_workers) |
| 15 | |
| 16 | async def process_tasks(self, tasks: List[Callable], *args, **kwargs) -> List[Any]: |
| 17 | # Failures surface as exception instances in the result list (via |
| 18 | # return_exceptions=True). Callers can filter with isinstance(r, BaseException). |
| 19 | async def _task_wrapper(task): |
| 20 | async with self.semaphore: |
| 21 | try: |
| 22 | return await task(*args, **kwargs) |
| 23 | except Exception: |
| 24 | logger.exception("Task failed") |
| 25 | raise |
| 26 | |
| 27 | return await asyncio.gather( |
| 28 | *[_task_wrapper(task) for task in tasks], return_exceptions=True |
| 29 | ) |
| 30 | |
| 31 | async def download_batch(self, download_func: Callable, items: List[Any]) -> List[Any]: |
| 32 | async def _download_wrapper(item): |
| 33 | async with self.semaphore: |
| 34 | try: |
| 35 | return await download_func(item) |
| 36 | except Exception: |
| 37 | logger.exception("Download failed for item: %r", item) |
| 38 | raise |
| 39 | |
| 40 | return await asyncio.gather( |
| 41 | *[_download_wrapper(item) for item in items], return_exceptions=True |
| 42 | ) |
| 43 |