File size: 4,891 Bytes
383d839 16a78e2 383d839 0743ddc 383d839 0743ddc 383d839 16a78e2 0743ddc 383d839 0743ddc 383d839 0743ddc 383d839 0743ddc 383d839 16a78e2 383d839 16a78e2 383d839 d80907b 579285c 383d839 579285c 0743ddc 579285c 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 | """
YAZ Care Platform — Async Worker Process
==========================================
Runs as a separate process consuming jobs from Redis queues.
Start with::
python -m workers.worker
# or via Makefile:
make worker
Queue priority
--------------
- ``yaz:queue:high`` — urgent: security alerts, critical notifications
- ``yaz:queue:default`` — normal: emails, case events, notifications
- ``yaz:queue:low`` — background: PDF generation, analytics, exports
Retry policy
------------
- max_tries: 3 for most jobs, 1 for non-idempotent operations
- retry_delay: exponential backoff starting at 5 s
Dead-letter
-----------
Failed jobs (exhausted retries) are logged to the ``yaz:queue:dead``
sorted set in Redis and emit a CRITICAL log entry with correlation_id.
The DLQ can be inspected via::
redis-cli zrange yaz:queue:dead 0 -1 WITHSCORES
"""
from __future__ import annotations
import asyncio
import logging
import os
import sys
from datetime import UTC, datetime, timezone
from pathlib import Path
from typing import Any, Dict
# Ensure src/ is importable
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Import all job modules so their @register_job decorators fire.
# ---------------------------------------------------------------------------
from workers.jobs import ( # noqa: F401
email_jobs,
marketplace_jobs, # noqa: F401 [SPRINT-68][SP-1]
notification_jobs,
report_jobs,
surgio_jobs, # noqa: F401
)
# ---------------------------------------------------------------------------
# arq WorkerSettings
# ---------------------------------------------------------------------------
async def startup(ctx: dict[str, Any]) -> None:
"""Worker startup: share resources across job executions."""
logger.info("Worker starting up at %s", datetime.now(UTC).isoformat())
# Attach shared resources to ctx so jobs can access them.
ctx["started_at"] = datetime.now(UTC).isoformat()
async def shutdown(ctx: dict[str, Any]) -> None:
"""Worker shutdown: clean up shared resources."""
logger.info("Worker shutting down")
def _get_redis_dsn() -> str:
try:
from core.config import get_settings
settings = get_settings()
return settings.redis.url
except Exception:
return os.getenv("REDIS_URL", "redis://localhost:6379/0")
try:
import arq
class WorkerSettings:
"""arq worker configuration."""
redis_settings = arq.connections.RedisSettings.from_dsn(_get_redis_dsn())
# All coroutines that arq should be able to call
functions = [
*email_jobs.FUNCTIONS,
*report_jobs.FUNCTIONS,
*notification_jobs.FUNCTIONS,
*surgio_jobs.FUNCTIONS,
*marketplace_jobs.FUNCTIONS, # [SPRINT-68][SP-1]
]
# Queue names polled in priority order
queue_name = "yaz:queue:default"
# arq polls a single queue per worker; run 3 workers for 3 queues, or
# override via YAZ_WORKER_QUEUE env var.
queue_name = os.getenv("YAZ_WORKER_QUEUE", "yaz:queue:default")
on_startup = startup
on_shutdown = shutdown
# [SPRINT-68][SP-1] Weekly auto-payout — every Monday at 02:00 UTC
cron_jobs = [
arq.cron(
marketplace_jobs.marketplace_auto_payout,
weekday=0, # Monday
hour=2,
minute=0,
timeout=600, # 10-min max
unique=True,
),
]
max_jobs = int(os.getenv("WORKER_MAX_JOBS", "10"))
job_timeout = int(os.getenv("WORKER_JOB_TIMEOUT", "300")) # 5 min
max_tries = 3
retry_jobs = True
health_check_interval = 60
health_check_key = "yaz:worker:health"
# Dead-letter: log + push to sorted set
allow_abort_jobs = True
_WORKER_AVAILABLE = True
except ImportError:
WorkerSettings = None # type: ignore[assignment,misc]
_WORKER_AVAILABLE = False
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
if not _WORKER_AVAILABLE:
print("arq is not installed. Install it with: pip install arq")
sys.exit(1)
# Setup structured logging
try:
from core.logging_config import setup_application_logging
setup_application_logging()
except ImportError:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger.info("Starting YAZ worker (queue: %s)", WorkerSettings.queue_name)
arq.run_worker(WorkerSettings)
|