Spaces:
Paused

File size: 5,076 Bytes
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a78e2
383d839
 
 
579285c
383d839
 
 
 
579285c
383d839
 
 
 
 
16a78e2
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a78e2
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a78e2
383d839
 
 
16a78e2
383d839
 
 
 
 
 
 
16a78e2
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
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",
]