Files
romm/backend/handler/rq_worker.py
renovate[bot] 3224220a1f chore(deps): update dependency rq to v3 (#5493)
* chore(deps): update dependency rq to v3

* fix: adapt the RQ worker and job types to rq 3

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix: update worker tests and task status map for rq 3

The worker tests pass the Execution to perform_job and patch the
module-level execute_failure_callback. TaskStatusItem covers the new
rate_limited and ready_to_enqueue statuses, shown as queued.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Sam Dornan <sam.dornan@athleticgreens.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-05 10:39:35 -05:00

149 lines
5.8 KiB
Python

import contextlib
import logging
import sys
from typing import TYPE_CHECKING, Any, Final, cast
import rq.scheduler
from rq import Queue, Worker, worker_registration
from rq.callbacks import execute_failure_callback
from rq.exceptions import AbandonedJobError
from rq.executions import Execution
from rq.job import Job
from tasks.tasks import report_task_failure
if TYPE_CHECKING:
from redis.client import Pipeline
from sqlalchemy import Engine, Pool
# Fragments of the lines RQ logs on every tick. The maintenance sweep and the
# scheduler heartbeat still run; only their log records are dropped.
_PERIODIC_NOISE: Final[tuple[str, ...]] = (
"cleaning registries for queue",
"scheduler sending heartbeat to",
)
# Looked up in sys.modules rather than imported, so a job that never loaded the
# ORM does not load it just to clean it up.
_DATABASE_MODULE: Final = "handler.database.base_handler"
def _database_engine() -> "Engine | None":
return cast(
"Engine | None", getattr(sys.modules.get(_DATABASE_MODULE), "sync_engine", None)
)
class _DropPeriodicNoiseFilter(logging.Filter):
"""Drops RQ's per-tick maintenance and scheduler-heartbeat log lines."""
def filter(self, record: logging.LogRecord) -> bool:
message = record.getMessage().lower()
return not any(fragment in message for fragment in _PERIODIC_NOISE)
def _silence_periodic_noise(logger: logging.Logger) -> None:
if not any(isinstance(f, _DropPeriodicNoiseFilter) for f in logger.filters):
logger.addFilter(_DropPeriodicNoiseFilter())
class RomMWorker(Worker):
"""RQ worker that reports failed tasks, closes each work horse's database
connections, silences RQ's periodic log lines, and registers again when its
registration expires."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
_silence_periodic_noise(self.log)
# --with-scheduler forks the scheduler off this process, so a filter
# added here is the only one that logger inherits.
_silence_periodic_noise(logging.getLogger(rq.scheduler.__name__))
self.push_exc_handler(report_task_failure)
self._inherited_db_pool: Pool | None = None
def heartbeat(
self, timeout: int | None = None, pipeline: "Pipeline | None" = None
) -> None:
super().heartbeat(timeout, pipeline)
# A pipelined heartbeat cannot read Redis; the next plain one catches up.
if (
pipeline is None
and self.birth_date is not None
and not self._is_registered()
):
self.log.warning(
"Worker %s: registration expired, registering again", self.name
)
self._register_again()
def _is_registered(self) -> bool:
# A suspended host lets the key lapse: either the registry sweep drops the
# worker from its sets, or the heartbeat recreates the key without queues.
if not self.connection.hexists(self.key, "queues"):
return False
registries = [self.redis_workers_keys] + [
worker_registration.WORKERS_BY_QUEUE_KEY % name
for name in self.queue_names()
]
return all(
self.connection.sismember(registry, self.key) for registry in registries
)
def _register_again(self) -> None:
# register_birth() refuses a key the heartbeat recreated, and would reset
# the birth date. The heartbeat has already set the key's TTL.
with self.connection.pipeline() as pipeline:
pipeline.hset(
self.key, mapping={**self.serialize(), "state": self.get_state()}
)
worker_registration.register(self, pipeline)
pipeline.execute()
def perform_job(self, job: Job, queue: Queue, execution: Execution) -> bool:
engine = _database_engine()
if engine is not None:
# The forked pool holds the worker's connections. Closing them, or letting
# them be garbage-collected, would end the worker's sessions.
self._inherited_db_pool = engine.pool
engine.dispose(close=False)
try:
return super().perform_job(job, queue, execution)
finally:
# RQ exits the work horse with os._exit, bypassing pool finalizers.
engine = _database_engine()
if engine is not None:
try:
engine.dispose()
except Exception:
self.log.exception("Could not close the work horse database pool")
def handle_work_horse_killed(
self, job: Job, retpid: int, ret_val: int, rusage: Any
) -> None:
# mypy's untyped_calls_exclude cannot name the receiver of a super() call.
super().handle_work_horse_killed(job, retpid, ret_val, rusage) # type: ignore[no-untyped-call]
# RQ runs neither the failure callback nor the exception handlers for a
# killed horse, only for a job whose whole worker died.
exc_info = (AbandonedJobError, AbandonedJobError(), None)
# RQ logs a callback that raises.
with contextlib.suppress(Exception):
execute_failure_callback(job, self.death_penalty_class, *exc_info)
self.handle_exception(job, *exc_info)
class PreloadingWorker(RomMWorker):
"""RomMWorker that imports the enabled scheduled tasks of its queues up front.
For a dedicated queue whose tasks run often enough that every work horse
importing its task again costs more than holding it in the parent.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
from tasks.registry import SCHEDULED_TASKS, get_task
queues = set(self.queue_names())
for name, spec in SCHEDULED_TASKS.items():
if spec.enabled and spec.queue_name in queues:
get_task(name)