| 1 |
import warnings |
| 2 |
from typing import Any, Callable, Optional, Union, cast |
| 3 |
|
| 4 |
from django.conf import settings |
| 5 |
from django.core.exceptions import ImproperlyConfigured |
| 6 |
from django.db import connection, transaction |
| 7 |
from redis import Redis |
| 8 |
from rq.job import Job |
| 9 |
from rq.queue import Queue |
| 10 |
from rq.utils import import_attribute |
| 11 |
|
| 12 |
from . import thread_queue |
| 13 |
from .connection_utils import ( |
| 14 |
filter_connection_params, |
| 15 |
get_connection, |
| 16 |
get_redis_connection, |
| 17 |
) |
| 18 |
from .jobs import get_job_class |
| 19 |
from .settings import get_queues_list |
| 20 |
|
| 21 |
VALID_COMMIT_MODES = ('auto', 'request_finished', 'on_db_commit') |
| 22 |
|
| 23 |
|
| 24 |
def get_commit_mode() -> str: |
| 25 |
""" |
| 26 |
Returns the configured commit mode. |
| 27 |
|
| 28 |
COMMIT_MODE is preferred and supports: |
| 29 |
- "on_db_commit" (default): enqueue when the database transaction commits |
| 30 |
- "auto": enqueue immediately |
| 31 |
- "request_finished": enqueue when the request finishes (legacy behavior) |
| 32 |
|
| 33 |
If COMMIT_MODE isn't set, fall back to AUTOCOMMIT for backwards |
| 34 |
compatibility (True -> "auto", False -> "request_finished"). |
| 35 |
""" |
| 36 |
RQ = getattr(settings, 'RQ', {}) |
| 37 |
commit_mode = RQ.get('COMMIT_MODE') |
| 38 |
|
| 39 |
if not commit_mode: |
| 40 |
if 'AUTOCOMMIT' in RQ: |
| 41 |
warnings.warn('"AUTOCOMMIT" is deprecated; use "COMMIT_MODE" instead.', DeprecationWarning) |
| 42 |
return 'auto' if RQ.get('AUTOCOMMIT') else 'request_finished' |
| 43 |
return 'on_db_commit' |
| 44 |
|
| 45 |
if commit_mode in VALID_COMMIT_MODES: |
| 46 |
return commit_mode |
| 47 |
else: |
| 48 |
raise ImproperlyConfigured(f'"COMMIT_MODE" must be one of {VALID_COMMIT_MODES}.') |
| 49 |
|
| 50 |
|
| 51 |
def get_queue_class( |
| 52 |
config: Optional[dict[str, Any]] = None, |
| 53 |
queue_class: Optional[Union[str, type[Queue]]] = None, |
| 54 |
) -> type[Queue]: |
| 55 |
""" |
| 56 |
Return queue class from config or from RQ settings, otherwise return DjangoRQ. |
| 57 |
If ``queue_class`` is provided, it takes priority. |
| 58 |
|
| 59 |
The full priority list for queue class sources: |
| 60 |
1. ``queue_class`` argument |
| 61 |
2. ``QUEUE_CLASS`` in ``config`` argument |
| 62 |
3. ``QUEUE_CLASS`` in base settings (``RQ``) |
| 63 |
""" |
| 64 |
RQ = getattr(settings, 'RQ', {}) |
| 65 |
if queue_class is None: |
| 66 |
queue_class = RQ.get('QUEUE_CLASS', DjangoRQ) |
| 67 |
if config: |
| 68 |
queue_class = config.get('QUEUE_CLASS', queue_class) |
| 69 |
|
| 70 |
if isinstance(queue_class, str): |
| 71 |
queue_class = cast(type[Queue], import_attribute(queue_class)) |
| 72 |
return queue_class |
| 73 |
|
| 74 |
|
| 75 |
class DjangoRQ(Queue): |
| 76 |
""" |
| 77 |
A subclass of RQ's QUEUE that allows jobs to be stored temporarily to be |
| 78 |
enqueued later at the end of Django's request/response cycle. |
| 79 |
""" |
| 80 |
|
| 81 |
def __init__(self, *args, **kwargs): |
| 82 |
autocommit = kwargs.pop('autocommit', None) |
| 83 |
commit_mode = kwargs.pop('commit_mode', None) |
| 84 |
|
| 85 |
if commit_mode: |
| 86 |
if commit_mode not in VALID_COMMIT_MODES: |
| 87 |
raise ImproperlyConfigured(f'commit_mode must be one of {VALID_COMMIT_MODES}.') |
| 88 |
elif autocommit is not None: |
| 89 |
warnings.warn('The "autocommit" argument is deprecated; use "commit_mode" instead.', DeprecationWarning) |
| 90 |
commit_mode = 'auto' if autocommit else 'request_finished' |
| 91 |
else: |
| 92 |
commit_mode = get_commit_mode() |
| 93 |
|
| 94 |
self._commit_mode = commit_mode |
| 95 |
|
| 96 |
super().__init__(*args, **kwargs) |
| 97 |
|
| 98 |
def original_enqueue_call(self, *args, **kwargs): |
| 99 |
queue_name = kwargs.get('queue_name') or self.name |
| 100 |
kwargs['result_ttl'] = kwargs.get('result_ttl', get_result_ttl(queue_name)) |
| 101 |
|
| 102 |
return super().enqueue_call(*args, **kwargs) |
| 103 |
|
| 104 |
def enqueue_call(self, *args, **kwargs): |
| 105 |
if self._commit_mode == 'auto': |
| 106 |
return self.original_enqueue_call(*args, **kwargs) |
| 107 |
elif self._commit_mode == 'on_db_commit': |
| 108 |
if connection.in_atomic_block: |
| 109 |
transaction.on_commit(lambda: self.original_enqueue_call(*args, **kwargs)) |
| 110 |
else: |
| 111 |
return self.original_enqueue_call(*args, **kwargs) |
| 112 |
else: |
| 113 |
thread_queue.add(self, args, kwargs) |
| 114 |
|
| 115 |
|
| 116 |
def get_queue( |
| 117 |
name: str = 'default', |
| 118 |
default_timeout: Optional[int] = None, |
| 119 |
is_async: Optional[bool] = None, |
| 120 |
autocommit: Optional[bool] = None, |
| 121 |
commit_mode: Optional[str] = None, |
| 122 |
connection: Optional[Redis] = None, |
| 123 |
queue_class: Optional[Union[str, type[Queue]]] = None, |
| 124 |
job_class: Optional[Union[str, type[Job]]] = None, |
| 125 |
serializer: Any = None, |
| 126 |
**kwargs: Any, |
| 127 |
) -> Queue: |
| 128 |
""" |
| 129 |
Returns an rq Queue using parameters defined in ``RQ_QUEUES`` |
| 130 |
""" |
| 131 |
from .settings import QUEUES |
| 132 |
|
| 133 |
if kwargs.get('async') is not None: |
| 134 |
is_async = kwargs['async'] |
| 135 |
warnings.warn('The `async` keyword is deprecated. Use `is_async` instead', DeprecationWarning) |
| 136 |
|
| 137 |
# If is_async is provided, use it, otherwise, get it from the configuration |
| 138 |
if is_async is None: |
| 139 |
is_async = QUEUES[name].get('ASYNC', True) |
| 140 |
# same for job_class |
| 141 |
job_class = get_job_class(job_class) |
| 142 |
|
| 143 |
if default_timeout is None: |
| 144 |
default_timeout = QUEUES[name].get('DEFAULT_TIMEOUT') |
| 145 |
if connection is None: |
| 146 |
connection = get_connection(name) |
| 147 |
if serializer is None: |
| 148 |
serializer = QUEUES[name].get('SERIALIZER') |
| 149 |
queue_class = get_queue_class(QUEUES[name], queue_class) |
| 150 |
return queue_class( |
| 151 |
name, |
| 152 |
default_timeout=default_timeout, |
| 153 |
connection=connection, |
| 154 |
is_async=is_async, |
| 155 |
job_class=job_class, |
| 156 |
autocommit=autocommit, |
| 157 |
commit_mode=commit_mode, |
| 158 |
serializer=serializer, |
| 159 |
**kwargs, |
| 160 |
) |
| 161 |
|
| 162 |
|
| 163 |
def get_queue_by_index(index: int) -> Queue: |
| 164 |
""" |
| 165 |
Returns an rq Queue using parameters defined in ``QUEUES_LIST`` |
| 166 |
""" |
| 167 |
config = get_queues_list()[int(index)] |
| 168 |
return get_queue_class(config)( |
| 169 |
config['name'], |
| 170 |
connection=get_redis_connection(config['connection_config']), |
| 171 |
is_async=config.get('ASYNC', True), |
| 172 |
serializer=config['connection_config'].get('SERIALIZER'), |
| 173 |
) |
| 174 |
|
| 175 |
|
| 176 |
def get_scheduler_by_index(index: int) -> 'DjangoScheduler': |
| 177 |
""" |
| 178 |
Returns an rq-scheduler Scheduler using parameters defined in ``QUEUES_LIST`` |
| 179 |
""" |
| 180 |
config = get_queues_list()[int(index)] |
| 181 |
return get_scheduler(config['name']) |
| 182 |
|
| 183 |
|
| 184 |
def get_queues(*queue_names, **kwargs): |
| 185 |
""" |
| 186 |
Return queue instances from specified queue names. |
| 187 |
All instances must use the same Redis connection. |
| 188 |
""" |
| 189 |
from .settings import QUEUES |
| 190 |
|
| 191 |
if len(queue_names) <= 1: |
| 192 |
# Return "default" queue if no queue name is specified |
| 193 |
# or one queue with specified name |
| 194 |
return [get_queue(*queue_names, **kwargs)] |
| 195 |
|
| 196 |
# will return more than one queue |
| 197 |
# import job class only once for all queues |
| 198 |
kwargs['job_class'] = get_job_class(kwargs.pop('job_class', None)) |
| 199 |
|
| 200 |
queue_params = QUEUES[queue_names[0]] |
| 201 |
connection_params = filter_connection_params(queue_params) |
| 202 |
queues = [get_queue(queue_names[0], **kwargs)] |
| 203 |
|
| 204 |
# do consistency checks while building return list |
| 205 |
for name in queue_names[1:]: |
| 206 |
queue = get_queue(name, **kwargs) |
| 207 |
if type(queue) is not type(queues[0]): |
| 208 |
raise ValueError(f'Queues must have the same class."{name}" and "{queue_names[0]}" have different classes') |
| 209 |
if connection_params != filter_connection_params(QUEUES[name]): |
| 210 |
raise ValueError( |
| 211 |
f'Queues must have the same redis connection."{name}" and "{queue_names[0]}" have different connections' |
| 212 |
) |
| 213 |
queues.append(queue) |
| 214 |
|
| 215 |
return queues |
| 216 |
|
| 217 |
|
| 218 |
def enqueue(func: Callable, *args, **kwargs) -> Job: |
| 219 |
""" |
| 220 |
A convenience function to put a job in the default queue. Usage:: |
| 221 |
|
| 222 |
from django_rq import enqueue |
| 223 |
enqueue(func, *args, **kwargs) |
| 224 |
""" |
| 225 |
return get_queue().enqueue(func, *args, **kwargs) |
| 226 |
|
| 227 |
|
| 228 |
def get_result_ttl(name: str = 'default') -> Optional[int]: |
| 229 |
""" |
| 230 |
Returns the result ttl from RQ_QUEUES if found, otherwise from RQ |
| 231 |
""" |
| 232 |
from .settings import QUEUES |
| 233 |
|
| 234 |
RQ = getattr(settings, 'RQ', {}) |
| 235 |
return QUEUES[name].get('DEFAULT_RESULT_TTL', RQ.get('DEFAULT_RESULT_TTL')) |
| 236 |
|
| 237 |
|
| 238 |
""" |
| 239 |
If rq_scheduler is installed, provide a ``get_scheduler`` function that |
| 240 |
behaves like ``get_connection``, except that it returns a ``Scheduler`` |
| 241 |
instance instead of a ``Queue`` instance. |
| 242 |
""" |
| 243 |
try: |
| 244 |
from rq_scheduler import Scheduler |
| 245 |
|
| 246 |
class DjangoScheduler(Scheduler): |
| 247 |
""" |
| 248 |
Use settings ``DEFAULT_RESULT_TTL`` from ``RQ`` |
| 249 |
and ``DEFAULT_TIMEOUT`` from ``RQ_QUEUES`` if configured. |
| 250 |
""" |
| 251 |
|
| 252 |
def _create_job(self, *args, **kwargs): |
| 253 |
from .settings import QUEUES |
| 254 |
|
| 255 |
if kwargs.get('timeout') is None: |
| 256 |
queue_name = kwargs.get('queue_name') or self.queue_name |
| 257 |
kwargs['timeout'] = QUEUES[queue_name].get('DEFAULT_TIMEOUT') |
| 258 |
|
| 259 |
if kwargs.get('result_ttl') is None: |
| 260 |
kwargs['result_ttl'] = getattr(settings, 'RQ', {}).get('DEFAULT_RESULT_TTL') |
| 261 |
|
| 262 |
return super()._create_job(*args, **kwargs) |
| 263 |
|
| 264 |
def get_scheduler( |
| 265 |
name: str = 'default', |
| 266 |
queue: Optional[Queue] = None, |
| 267 |
interval: int = 60, |
| 268 |
connection: Optional[Redis] = None, |
| 269 |
) -> DjangoScheduler: |
| 270 |
""" |
| 271 |
Returns an RQ Scheduler instance using parameters defined in |
| 272 |
``RQ_QUEUES`` |
| 273 |
""" |
| 274 |
RQ = getattr(settings, 'RQ', {}) |
| 275 |
scheduler_class = RQ.get('SCHEDULER_CLASS', DjangoScheduler) |
| 276 |
|
| 277 |
if isinstance(scheduler_class, str): |
| 278 |
scheduler_class = import_attribute(scheduler_class) |
| 279 |
|
| 280 |
if connection is None: |
| 281 |
connection = get_connection(name) |
| 282 |
|
| 283 |
if queue is None: |
| 284 |
queue = get_queue(name, connection=connection) |
| 285 |
|
| 286 |
return scheduler_class( |
| 287 |
queue_name=name, interval=interval, queue=queue, job_class=queue.job_class, connection=connection |
| 288 |
) |
| 289 |
|
| 290 |
except ImportError: |
| 291 |
|
| 292 |
def get_scheduler(*args, **kwargs): # type: ignore[misc] |
| 293 |
raise ImproperlyConfigured('rq_scheduler not installed') |