| 1 |
import logging |
| 2 |
from collections.abc import Sequence |
| 3 |
from datetime import datetime, timezone |
| 4 |
from functools import cached_property |
| 5 |
from typing import Any, Callable, Optional, cast |
| 6 |
|
| 7 |
from redis import Redis |
| 8 |
from rq.cron import CronJob, CronScheduler |
| 9 |
from rq.utils import as_text |
| 10 |
|
| 11 |
from .connection_utils import get_connection, get_redis_connection, get_unique_connection_configs |
| 12 |
from .settings import get_queues_map |
| 13 |
|
| 14 |
# `CronJob.get_job_ids()` and the job history sorted set backing it were added in RQ 2.11 |
| 15 |
CRON_JOB_HISTORY_SUPPORTED = hasattr(CronJob, 'get_job_ids') |
| 16 |
|
| 17 |
|
| 18 |
def get_cron_job_history( |
| 19 |
cron_job: CronJob, connection: Redis, start: int = 0, end: int = -1 |
| 20 |
) -> list[tuple[str, datetime]]: |
| 21 |
""" |
| 22 |
Returns (job_id, enqueued_at) pairs for jobs spawned by `cron_job`, newest first. |
| 23 |
|
| 24 |
RQ records spawned jobs in a sorted set scored by the job's enqueue time. The history |
| 25 |
outlives the jobs themselves (entries are kept for a year, while a successful job's data |
| 26 |
is deleted once its `result_ttl` expires), so the score is the only way to tell when an |
| 27 |
already deleted job ran. |
| 28 |
|
| 29 |
`start` and `end` are zero based inclusive indexes into the newest first ordering, |
| 30 |
following `zrange` semantics (`end=-1` means the oldest entry). |
| 31 |
|
| 32 |
Returns an empty list on RQ < 2.11, which doesn't keep a job history. |
| 33 |
""" |
| 34 |
if not CRON_JOB_HISTORY_SUPPORTED: |
| 35 |
return [] |
| 36 |
|
| 37 |
entries = connection.zrange(cron_job.job_history_key, start, end, desc=True, withscores=True) |
| 38 |
return [(as_text(job_id), datetime.fromtimestamp(score, tz=timezone.utc)) for job_id, score in entries] |
| 39 |
|
| 40 |
|
| 41 |
def get_cron_job_data(cron_job: CronJob, queues_map: Optional[dict[str, int]] = None) -> dict[str, Any]: |
| 42 |
""" |
| 43 |
Returns a dict describing `cron_job` for display purposes. |
| 44 |
|
| 45 |
`queue_index` is None when the cron job's queue is not present in RQ_QUEUES, in which case |
| 46 |
the dashboard can't link to that queue's views. |
| 47 |
""" |
| 48 |
if queues_map is None: |
| 49 |
queues_map = get_queues_map() |
| 50 |
|
| 51 |
if cron_job.cron: |
| 52 |
schedule = f"Cron: {cron_job.cron}" |
| 53 |
elif cron_job.interval is not None: |
| 54 |
schedule = f"Every {cron_job.interval} seconds" |
| 55 |
else: |
| 56 |
schedule = "-" |
| 57 |
|
| 58 |
job_options = cron_job.job_options |
| 59 |
options: list[str] = [] |
| 60 |
for key in ('job_timeout', 'result_ttl', 'ttl', 'failure_ttl'): |
| 61 |
value = job_options.get(key) |
| 62 |
if value is not None: |
| 63 |
options.append(f"{key}={value}") |
| 64 |
|
| 65 |
return { |
| 66 |
# `name` identifies the job history and defaults to func_name on RQ >= 2.11. |
| 67 |
# Older versions don't have it at all. |
| 68 |
"name": getattr(cron_job, 'name', None) or cron_job.func_name, |
| 69 |
"func_name": cron_job.func_name, |
| 70 |
"queue_name": cron_job.queue_name, |
| 71 |
"queue_index": queues_map.get(cron_job.queue_name), |
| 72 |
"schedule": schedule, |
| 73 |
"latest_enqueue_time": cron_job.latest_enqueue_time, |
| 74 |
"next_enqueue_time": cron_job.next_enqueue_time, |
| 75 |
"args": cron_job.args, |
| 76 |
"kwargs": cron_job.kwargs, |
| 77 |
"meta": job_options.get('meta'), |
| 78 |
# Job options are exposed both individually, for pages that lay them out as fields, and |
| 79 |
# pre-formatted as `options`, for the cron scheduler table's single column |
| 80 |
"job_timeout": job_options.get('job_timeout'), |
| 81 |
"result_ttl": job_options.get('result_ttl'), |
| 82 |
"ttl": job_options.get('ttl'), |
| 83 |
"failure_ttl": job_options.get('failure_ttl'), |
| 84 |
"options": options, |
| 85 |
"webhooks": job_options.get('webhooks') or [], |
| 86 |
} |
| 87 |
|
| 88 |
|
| 89 |
def get_cron_job_history_count(cron_job: CronJob, connection: Redis) -> int: |
| 90 |
"""Returns the number of jobs recorded in `cron_job`'s history (0 on RQ < 2.11).""" |
| 91 |
if not CRON_JOB_HISTORY_SUPPORTED: |
| 92 |
return 0 |
| 93 |
|
| 94 |
return connection.zcard(cron_job.job_history_key) |
| 95 |
|
| 96 |
|
| 97 |
class DjangoCronScheduler(CronScheduler): |
| 98 |
""" |
| 99 |
A Django-RQ bridge for RQ's CronScheduler that integrates with django_rq's |
| 100 |
queue configuration system. |
| 101 |
|
| 102 |
Key differences from RQ's CronScheduler: |
| 103 |
- Can be initialized with or without a connection parameter |
| 104 |
- If no connection provided, connection is set dynamically when the first job is registered |
| 105 |
- Validates that all registered jobs use queues with the same Redis connection |
| 106 |
- Integrates with RQ_QUEUES configuration from Django settings |
| 107 |
""" |
| 108 |
|
| 109 |
_connection_config: Optional[dict[str, Any]] |
| 110 |
|
| 111 |
def __init__( |
| 112 |
self, |
| 113 |
connection: Optional[Redis] = None, |
| 114 |
logging_level: int = logging.INFO, |
| 115 |
name: str = '', |
| 116 |
): |
| 117 |
""" |
| 118 |
Initialize DjangoCronScheduler with optional Redis connection. |
| 119 |
|
| 120 |
If connection is not provided, it will be set when the first job is registered via register(). |
| 121 |
|
| 122 |
Args: |
| 123 |
connection: Optional Redis connection instance |
| 124 |
logging_level: Logging level for the scheduler |
| 125 |
name: Optional name for the scheduler instance |
| 126 |
""" |
| 127 |
# Call parent __init__ with the provided connection (or None) |
| 128 |
super().__init__(connection=cast(Redis, connection), logging_level=logging_level, name=name) |
| 129 |
|
| 130 |
# Track our django_rq specific state |
| 131 |
if connection is not None: |
| 132 |
self._connection_config = self._get_connection_config(connection) |
| 133 |
else: |
| 134 |
self._connection_config = None |
| 135 |
|
| 136 |
def _get_connection_config(self, connection: Redis) -> dict[str, Any]: |
| 137 |
""" |
| 138 |
Extract Redis connection configuration to compare connections. |
| 139 |
|
| 140 |
Args: |
| 141 |
connection: Redis connection instance |
| 142 |
|
| 143 |
Returns: |
| 144 |
Dictionary of connection parameters for comparison |
| 145 |
""" |
| 146 |
kwargs = connection.connection_pool.connection_kwargs |
| 147 |
|
| 148 |
# Only compare essential connection parameters that determine if |
| 149 |
# two connections are to the same Redis instance |
| 150 |
essential_params = ['host', 'port', 'db', 'username', 'password'] |
| 151 |
return {key: kwargs.get(key) for key in essential_params if key in kwargs} |
| 152 |
|
| 153 |
def register( |
| 154 |
self, |
| 155 |
func: Callable[..., Any], |
| 156 |
queue_name: str, |
| 157 |
args: Optional[tuple[Any, ...]] = None, |
| 158 |
kwargs: Optional[dict[str, Any]] = None, |
| 159 |
interval: Optional[int] = None, |
| 160 |
cron: Optional[str] = None, |
| 161 |
job_timeout: Optional[int] = None, |
| 162 |
result_ttl: int = 500, |
| 163 |
ttl: Optional[int] = None, |
| 164 |
failure_ttl: Optional[int] = None, |
| 165 |
meta: Optional[dict[str, Any]] = None, |
| 166 |
webhooks: Optional[Sequence[Any]] = None, |
| 167 |
name: str = '', |
| 168 |
): |
| 169 |
""" |
| 170 |
Register a function to be run at regular intervals. |
| 171 |
|
| 172 |
On first call, this sets the Redis connection for the scheduler. |
| 173 |
Subsequent calls validate that the queue uses the same Redis connection. |
| 174 |
|
| 175 |
Args: |
| 176 |
func: Function to be scheduled |
| 177 |
queue_name: Name of the django_rq queue (must exist in RQ_QUEUES) |
| 178 |
args: Arguments to pass to the function |
| 179 |
kwargs: Keyword arguments to pass to the function |
| 180 |
interval: Interval in seconds (mutually exclusive with cron) |
| 181 |
cron: Cron expression (mutually exclusive with interval) |
| 182 |
job_timeout: Job timeout in seconds |
| 183 |
result_ttl: How long to keep job results |
| 184 |
ttl: Job time-to-live |
| 185 |
failure_ttl: How long to keep failed job info |
| 186 |
meta: Additional job metadata |
| 187 |
webhooks: Webhooks to attach to the job (requires rq >= 2.10) |
| 188 |
name: Optional name identifying this cron job (requires rq >= 2.11). Defaults to |
| 189 |
the function's import path. Cron jobs sharing a name share a job history. |
| 190 |
|
| 191 |
Returns: |
| 192 |
CronJob instance |
| 193 |
|
| 194 |
Raises: |
| 195 |
ValueError: If queue not found or uses different Redis connection |
| 196 |
""" |
| 197 |
# Get connection for this queue |
| 198 |
connection = get_connection(queue_name) |
| 199 |
current_config = self._get_connection_config(connection) |
| 200 |
|
| 201 |
if self._connection_config: |
| 202 |
# Validate that this queue uses the same Redis connection |
| 203 |
if current_config != self._connection_config: |
| 204 |
raise ValueError( |
| 205 |
f"Queue '{queue_name}' uses a different Redis connection than previously " |
| 206 |
+ 'registered queues. All jobs in a DjangoCronScheduler instance must use ' |
| 207 |
+ 'queues with the same Redis connection.' |
| 208 |
) |
| 209 |
else: |
| 210 |
# First registration - set connection |
| 211 |
self.connection = connection |
| 212 |
self._connection_config = current_config |
| 213 |
# Clear cached_property so it recalculates with new connection |
| 214 |
if 'connection_index' in self.__dict__: |
| 215 |
del self.__dict__['connection_index'] |
| 216 |
|
| 217 |
# Now call parent register method. `webhooks` and `name` are only passed along when |
| 218 |
# set, since CronScheduler.register() only accepts them on rq >= 2.10 and >= 2.11 |
| 219 |
extra_kwargs: dict[str, Any] = {} |
| 220 |
if webhooks is not None: |
| 221 |
extra_kwargs['webhooks'] = webhooks |
| 222 |
if name: |
| 223 |
extra_kwargs['name'] = name |
| 224 |
return super().register( |
| 225 |
func=func, |
| 226 |
queue_name=queue_name, |
| 227 |
args=args, |
| 228 |
kwargs=kwargs, |
| 229 |
interval=interval, |
| 230 |
cron=cron, |
| 231 |
job_timeout=job_timeout, |
| 232 |
result_ttl=result_ttl, |
| 233 |
ttl=ttl, |
| 234 |
failure_ttl=failure_ttl, |
| 235 |
meta=meta, |
| 236 |
**extra_kwargs, |
| 237 |
) |
| 238 |
|
| 239 |
@cached_property |
| 240 |
def connection_index(self) -> int: |
| 241 |
""" |
| 242 |
Returns the index of this scheduler's Redis connection in the unique connection configs list. |
| 243 |
|
| 244 |
This allows identifying which connection the scheduler is using, which can be useful for |
| 245 |
monitoring and management purposes (e.g., identifying schedulers by connection_index). |
| 246 |
|
| 247 |
Returns: |
| 248 |
The index of the connection in get_unique_connection_configs() |
| 249 |
|
| 250 |
Raises: |
| 251 |
ValueError: If no connection has been set yet (before first register() call), |
| 252 |
or if the connection config cannot be found in unique configs |
| 253 |
""" |
| 254 |
if not self._connection_config: |
| 255 |
raise ValueError('No connection has been set for this scheduler yet.') |
| 256 |
|
| 257 |
unique_configs = get_unique_connection_configs() |
| 258 |
|
| 259 |
# Find which index matches our connection by comparing essential params |
| 260 |
for i, unique_config in enumerate(unique_configs): |
| 261 |
conn = get_redis_connection(unique_config) |
| 262 |
config = self._get_connection_config(conn) |
| 263 |
|
| 264 |
# If it matches our connection config, this is our index |
| 265 |
if config == self._connection_config: |
| 266 |
return i |
| 267 |
|
| 268 |
# This should never happen - if we have a connection_config, it must be in the list |
| 269 |
raise ValueError('Could not find matching connection config in unique configs.') |
| 270 |
|
| 271 |
def get_jobs_data(self) -> list[dict[str, Any]]: |
| 272 |
"""Returns a list of dicts describing each registered cron job for display purposes.""" |
| 273 |
queues_map = get_queues_map() |
| 274 |
return [get_cron_job_data(job, queues_map) for job in self.get_jobs()] |
| 275 |
|
| 276 |
@classmethod |
| 277 |
def all(cls, connection: Redis, cleanup: bool = True) -> list['DjangoCronScheduler']: # type: ignore[override] |
| 278 |
""" |
| 279 |
Returns all DjangoCronScheduler instances from the registry. |
| 280 |
|
| 281 |
Args: |
| 282 |
connection: Redis connection to use |
| 283 |
cleanup: If True, removes stale entries from registry before fetching schedulers |
| 284 |
|
| 285 |
Returns: |
| 286 |
List of DjangoCronScheduler instances |
| 287 |
""" |
| 288 |
return super().all(connection, cleanup) # type: ignore[return-value] |