File size: 3,467 Bytes
851e5ba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | """
Job queue setup using arq (async Redis queue).
"""
import logging
from typing import Optional
from arq import create_pool
from arq.connections import RedisSettings, ArqRedis
from ..config import get_config
logger = logging.getLogger(__name__)
# Queue names
DEFAULT_QUEUE_NAME = "supoclip_tasks"
FAST_QUEUE_NAME = "supoclip_fast"
class DuplicateJobError(RuntimeError):
"""A job with the requested ``_job_id`` is already queued or running."""
def _get_redis_settings() -> RedisSettings:
config = get_config()
return RedisSettings(host=config.redis_host, port=config.redis_port, password=config.redis_password, database=0)
class JobQueue:
"""Wrapper for arq job queue operations."""
_pool: Optional[ArqRedis] = None
@classmethod
async def get_pool(cls) -> ArqRedis:
"""Get or create the Redis connection pool."""
if cls._pool is None:
config = get_config()
cls._pool = await create_pool(_get_redis_settings())
logger.info(
f"Created arq Redis pool: {config.redis_host}:{config.redis_port}"
)
return cls._pool
@classmethod
async def close_pool(cls):
"""Close the Redis connection pool."""
if cls._pool is not None:
await cls._pool.close()
cls._pool = None
logger.info("Closed arq Redis pool")
@classmethod
async def enqueue_job(cls, function_name: str, *args, **kwargs) -> str:
"""
Enqueue a job to be processed by workers.
Args:
function_name: Name of the worker function to call
*args: Positional arguments for the function
**kwargs: Keyword arguments for the function
Returns:
job_id: Unique ID for the enqueued job
"""
pool = await cls.get_pool()
queue_name = kwargs.pop("_queue_name", DEFAULT_QUEUE_NAME)
job = await pool.enqueue_job(
function_name, *args, _queue_name=queue_name, **kwargs
)
if not job:
if kwargs.get("_job_id"):
raise DuplicateJobError(f"Job {kwargs['_job_id']} already exists")
raise RuntimeError("Failed to enqueue job")
job_id = getattr(job, "job_id", None)
if not job_id:
raise RuntimeError("Failed to enqueue job: missing job ID")
logger.info(f"Enqueued job {job_id}: {function_name} on queue {queue_name}")
return str(job_id)
@classmethod
async def enqueue_processing_job(
cls, function_name: str, processing_mode: str, *args, **kwargs
) -> str:
# Keep a single queue for now; processing_mode remains available for future
# dedicated queue routing once multiple worker pools are configured.
queue_name = DEFAULT_QUEUE_NAME
return await cls.enqueue_job(
function_name, *args, _queue_name=queue_name, **kwargs
)
@classmethod
async def get_job_result(cls, job_id: str):
"""Get the result of a completed job."""
pool = await cls.get_pool()
job = await pool.job(job_id)
if job:
return await job.result()
return None
@classmethod
async def get_job_status(cls, job_id: str) -> Optional[str]:
"""Get the status of a job."""
pool = await cls.get_pool()
job = await pool.job(job_id)
if job:
return await job.status()
return None
|