Download src/workers/queue.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 5.08 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/workers/queue.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/workers/queue.py
-
curl -L -o queue.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/workers/queue.py
5.08 kB
| """ | |
| YAZ Care Platform — Job Queue | |
| ============================== | |
| Lightweight async job queue built on Redis + arq (async Redis queue). | |
| Why arq? | |
| -------- | |
| - Zero Celery overhead; pure async Python. | |
| - Built-in retry, scheduled tasks, health checks. | |
| - Compatible with the Redis instance already required for caching. | |
| Fallback | |
| -------- | |
| If Redis is unavailable (dev / CI without Redis), jobs run **in-process** | |
| synchronously so development never breaks. | |
| Usage | |
| ----- | |
| from core.services.queue import enqueue, JobPriority | |
| await enqueue( | |
| "send_email", | |
| to="user@example.com", | |
| subject="Case submitted", | |
| correlation_id=get_correlation_id(), | |
| ) | |
| Worker startup (separate process) | |
| ---------------------------------- | |
| python -m workers.worker | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import structlog | |
| import os | |
| from enum import Enum | |
| from typing import Any, Callable, Dict, Optional | |
| logger = structlog.get_logger(__name__) | |
| # --------------------------------------------------------------------------- | |
| # Priority queues (arq supports multiple queues via queue_name) | |
| # --------------------------------------------------------------------------- | |
| class JobPriority(str, Enum): | |
| HIGH = "yaz:queue:high" | |
| DEFAULT = "yaz:queue:default" | |
| LOW = "yaz:queue:low" | |
| # --------------------------------------------------------------------------- | |
| # Redis pool (lazy-init, only if Redis is enabled / available) | |
| # --------------------------------------------------------------------------- | |
| _redis_pool: Optional[Any] = None | |
| _redis_available: bool = False | |
| async def _get_redis_pool() -> Optional[Any]: | |
| global _redis_pool, _redis_available | |
| if _redis_pool is not None: | |
| return _redis_pool | |
| try: | |
| import arq | |
| from core.config import get_settings | |
| settings = get_settings() | |
| redis_url = settings.redis.url if settings.redis.enabled else None | |
| if not redis_url: | |
| return None | |
| _redis_pool = await arq.create_pool(arq.connections.RedisSettings.from_dsn(redis_url)) | |
| _redis_available = True | |
| logger.info("Job queue: Redis pool established (%s)", redis_url) | |
| return _redis_pool | |
| except Exception as exc: | |
| logger.warning("Job queue: Redis unavailable — running in-process fallback. %s", exc) | |
| _redis_available = False | |
| return None | |
| # --------------------------------------------------------------------------- | |
| # Registry of callable jobs (name → coroutine function) | |
| # Used by the in-process fallback. | |
| # --------------------------------------------------------------------------- | |
| _JOB_REGISTRY: Dict[str, Callable] = {} | |
| def register_job(name: str) -> Callable: | |
| """Decorator to register a job coroutine under a name.""" | |
| def decorator(fn: Callable) -> Callable: | |
| _JOB_REGISTRY[name] = fn | |
| return fn | |
| return decorator | |
| # --------------------------------------------------------------------------- | |
| # Public enqueueing API | |
| # --------------------------------------------------------------------------- | |
| async def enqueue( | |
| job_name: str, | |
| *, | |
| priority: JobPriority = JobPriority.DEFAULT, | |
| _defer_by: Optional[int] = None, # seconds | |
| **kwargs: Any, | |
| ) -> Optional[str]: | |
| """ | |
| Enqueue *job_name* with **kwargs as payload. | |
| Returns | |
| ------- | |
| str | None | |
| The arq job ID, or ``None`` if running in-process fallback. | |
| """ | |
| pool = await _get_redis_pool() | |
| if pool is None: | |
| # In-process fallback: run synchronously | |
| fn = _JOB_REGISTRY.get(job_name) | |
| if fn is None: | |
| logger.error("No job registered for '%s' — cannot run in-process fallback", job_name) | |
| return None | |
| try: | |
| if asyncio.iscoroutinefunction(fn): | |
| await fn(**kwargs) | |
| else: | |
| fn(**kwargs) | |
| logger.debug("In-process job '%s' completed", job_name) | |
| except Exception as exc: | |
| logger.exception("In-process job '%s' failed: %s", job_name, exc) | |
| return None | |
| try: | |
| job = await pool.enqueue_job( | |
| job_name, | |
| _queue_name=priority.value, | |
| _defer_by=_defer_by, | |
| **kwargs, | |
| ) | |
| job_id = job.job_id if job else None | |
| logger.info( | |
| "Enqueued job", | |
| extra={ | |
| "job_name": job_name, | |
| "job_id": job_id, | |
| "priority": priority.value, | |
| "correlation_id": kwargs.get("correlation_id", ""), | |
| }, | |
| ) | |
| return job_id | |
| except Exception as exc: | |
| logger.exception("Failed to enqueue job '%s': %s", job_name, exc) | |
| return None | |
| async def close_queue() -> None: | |
| """Close the Redis pool on application shutdown.""" | |
| global _redis_pool | |
| if _redis_pool is not None: | |
| try: | |
| await _redis_pool.close() | |
| except Exception: | |
| pass | |
| _redis_pool = None | |
| __all__ = [ | |
| "JobPriority", | |
| "enqueue", | |
| "close_queue", | |
| "register_job", | |
| ] | |