django-redis-tasks 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,186 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-redis-tasks
3
+ Version: 1.0.0
4
+ Summary: Django tasks backend using Redis queues
5
+ Author-email: David Nugent <davidn@uniquode.io>
6
+ License-Expression: MIT
7
+ Project-URL: Source, https://github.com/deeprave/django-redis-tasks
8
+ Project-URL: Issues, https://github.com/deeprave/django-redis-tasks/issues
9
+ Project-URL: Changelog, https://github.com/deeprave/django-redis-tasks/releases
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Programming Language :: Python :: Implementation :: CPython
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: Django :: 6.1
17
+ Requires-Python: >=3.14
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE.md
20
+ Requires-Dist: django>=6.1
21
+ Requires-Dist: django-queues[redis]<2.0.0,>=1.2.0
22
+ Dynamic: license-file
23
+
24
+ # Django Redis Tasks
25
+
26
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/deeprave/django-redis-tasks/python-test-and-build.yml?branch=main&label=tests&logo=github)](https://github.com/deeprave/django-redis-tasks/actions/workflows/python-test-and-build.yml)
27
+ [![Security](https://img.shields.io/github/actions/workflow/status/deeprave/django-redis-tasks/codeql.yml?branch=main&label=security&logo=github)](https://github.com/deeprave/django-redis-tasks/security/code-scanning)
28
+ [![Maintenance](https://img.shields.io/badge/maintenance-active-brightgreen.svg)](https://github.com/deeprave/django-redis-tasks)
29
+ [![PyPI version](https://img.shields.io/pypi/v/django-redis-tasks.svg?logo=pypi&logoColor=white)](https://pypi.org/project/django-redis-tasks/)
30
+ [![PyPI downloads](https://img.shields.io/pypi/dm/django-redis-tasks.svg?logo=pypi&logoColor=white)](https://pypi.org/project/django-redis-tasks/)
31
+ [![Python versions](https://img.shields.io/pypi/pyversions/django-redis-tasks.svg?logo=python&logoColor=white)](https://pypi.org/project/django-redis-tasks/)
32
+
33
+ This is a Redis-backed implementation of [Django's `django.tasks`](https://docs.djangoproject.com/en/6.1/topics/tasks/)
34
+ framework.
35
+
36
+ ## django-queues
37
+
38
+ Queue storage and worker execution are provided by [`django-queues`](https://pypi.org/project/django-queues/), a
39
+ generic Django queue package. `django-redis-tasks` is a thin translation layer on top of it: it maps Django's task
40
+ vocabulary (`Task`, `TaskResult`, `TaskResultStatus`) onto `django-queues`' generic queue vocabulary (`QueueEntry`,
41
+ `QueueEntryStatus`), and provides the handler function that executes queued task calls.
42
+
43
+ This package does not manage Redis connections, run a worker loop, or start anything during Django's application
44
+ startup — `django-queues` owns all of that, including its `manage.py runqueues` management command.
45
+
46
+ ## Deferred tasks
47
+
48
+ `run_after` is supported. The backend normalizes the datetime to UTC at enqueue: that UTC instant is stored on the task payload and passed to django-queues as `available_at`. Reconstruction therefore does not depend on the reader's `USE_TZ` or `TIME_ZONE`. Redis TIME decides when the entry becomes claimable; workers do not record an attempt or emit started/finished signals while the task is only waiting.
49
+
50
+ - **Aware datetimes** are converted to UTC.
51
+ - **Naive datetimes** are accepted only when `USE_TZ` is `False`; they are interpreted in Django's current timezone, then converted to UTC. When `USE_TZ` is `True`, Django rejects a naive `run_after` at enqueue. Legacy naive payload values are still normalized to UTC on read.
52
+ - A past or current `run_after` is eligible for dispatch immediately.
53
+ - A worker that has no due work waits until a deferred task becomes due; it does not busy-poll the application clock.
54
+
55
+ ## Redis runtime
56
+
57
+ django-queues 1.2.0 requires **Redis 7+** and a deployed Function library before the application or a worker starts:
58
+
59
+ ```shell
60
+ python manage.py redis_lua_lib --deploy
61
+ ```
62
+
63
+ Queue aliases must match `[A-Za-z0-9_-]`. Redis keys from django-queues before 1.2.0 are not compatible; start from empty queue keys or a new Redis logical database.
64
+
65
+ ## Installation
66
+
67
+ ```shell
68
+ uv add django-redis-tasks
69
+ ```
70
+
71
+ ## Configuration
72
+
73
+ `django_queue` must be added to `INSTALLED_APPS`. `redis_tasks` does not require
74
+ app registration today, but adding it is recommended for forward compatibility
75
+ with future Django integration points such as models, observer registrations,
76
+ templates, and static assets:
77
+
78
+ ```python
79
+ INSTALLED_APPS = [
80
+ ...
81
+ "django_queue",
82
+ "redis_tasks",
83
+ ...
84
+ ]
85
+ ```
86
+
87
+ Configuration is two settings working together: `QUEUES` (owned by `django-queues`) configures the underlying Redis
88
+ queue and registers this package's handler; `TASKS` (owned by Django) configures the task backend and points it at
89
+ that queue.
90
+
91
+ ```python
92
+ QUEUES = {
93
+ "default": {
94
+ "BACKEND": "django_queue.backends.redis.RedisAsyncPriorityQueueJson",
95
+ "LOCATION": "redis://localhost:6379/12",
96
+ "HANDLER": "redis_tasks.handlers.handle_task_entry",
97
+ "ENTRY_CLASS": "redis_tasks.entries.TaskQueueEntry",
98
+ "WORKER": "redis_tasks.worker.RedisTaskWorker",
99
+ },
100
+ }
101
+
102
+ TASKS = {
103
+ "default": {
104
+ "BACKEND": "redis_tasks.backend.RedisBackend",
105
+ "OPTIONS": {
106
+ "queue_alias": "default", # the QUEUES alias to delegate to; defaults to this TASKS alias
107
+ },
108
+ },
109
+ }
110
+ ```
111
+
112
+ A Django project may configure multiple `QUEUES`/`TASKS` alias pairs, each backed by its own Redis queue.
113
+
114
+ `TaskQueueEntry` records `worker_ids` as the ordered history of worker-process UUIDs that began dispatching a task;
115
+ `TaskResult.attempts` is the length of that list. Redis automatically recovers an entry whose worker lease expires, so a
116
+ task can execute more than once. Make handlers with side effects idempotent.
117
+
118
+ ## Running a worker
119
+
120
+ Task execution happens out-of-process, via `django-queues`' own management command:
121
+
122
+ ```shell
123
+ python manage.py runqueues
124
+ ```
125
+
126
+ This discovers every `QUEUES` alias with a `HANDLER` configured (including `redis_tasks.handlers.handle_task_entry`)
127
+ and runs its worker until the process receives a termination signal. Queue connections are initialized lazily when
128
+ their aliases are first used, but no task worker or handler execution starts in a Django web process — run `runqueues`
129
+ as a separate, standalone service.
130
+
131
+ ## Async applications
132
+
133
+ `django-redis-tasks` supports Django's native asynchronous task API. In an
134
+ ASGI view, consumer, or other coroutine, use `await task.aenqueue(...)` to
135
+ write directly through django-queues' asynchronous Redis API. Refresh an
136
+ existing result with `await result.arefresh()`. Neither operation needs this
137
+ backend to cross Django's synchronous task-backend bridge, so queue I/O stays
138
+ on the caller's event loop.
139
+
140
+ ```python
141
+ from django.http import JsonResponse
142
+
143
+
144
+ async def start_report(request):
145
+ result = await build_report.aenqueue(request.user.pk)
146
+ return JsonResponse({"task_id": result.id})
147
+
148
+
149
+ async def refresh_report(result):
150
+ await result.arefresh()
151
+ return result.status
152
+ ```
153
+
154
+ Tasks declared with `async def` are also awaited directly by this package's
155
+ handler inside django-queues' worker event loop. A synchronous task function
156
+ is still safe, but Django runs it through a thread bridge to avoid blocking
157
+ that loop.
158
+
159
+ Queue work is deliberately outside the ASGI request runtime. The separate
160
+ `runqueues` service owns task dispatch and recovery, while django-queues'
161
+ process-local queue runtime owns lifecycle-observer delivery. This lets an
162
+ application use task status and best-effort queue observers without starting
163
+ workers from views or competing with request handling for an event loop.
164
+
165
+ An entirely asynchronous application should also use async middleware, views,
166
+ task functions, and task-signal receivers. Synchronous middleware, ORM work,
167
+ task functions, and signal receivers remain supported, but Django adapts those
168
+ specific boundaries through its thread bridge.
169
+
170
+ ## Usage
171
+
172
+ A task is created using Django's `@task` decorator:
173
+
174
+ ```python
175
+ from django.tasks import task
176
+
177
+
178
+ @task()
179
+ def calculate_meaning_of_life() -> int:
180
+ return 42
181
+
182
+
183
+ @task()
184
+ async def nudge_nudge_wink_wink() -> list[str]:
185
+ return ["say", "no", "more"]
186
+ ```
@@ -0,0 +1,11 @@
1
+ django_redis_tasks-1.0.0.dist-info/licenses/LICENSE.md,sha256=6JdKP8RXcxUyxpVYAL7tQf3XPj3FqI2DJ_RiovW_QoE,1084
2
+ redis_tasks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ redis_tasks/apps.py,sha256=UNeKZG_rQbnwA8ZfNX-MmQtJrsY8VJMVdVKQv1TKtq4,129
4
+ redis_tasks/backend.py,sha256=_vH-HZQvd5dR5bVWbE1CECglEzRntBzngHTJruiU10U,12392
5
+ redis_tasks/entries.py,sha256=gCgRhmtIxGYUokY6FLbE-qwQXdoFCLz-sYWoVq-6Fyw,283
6
+ redis_tasks/handlers.py,sha256=atm_OiderqHJpYqlfJLHHlP4Pl5bVvUOgEIFzP3oAMU,1390
7
+ redis_tasks/worker.py,sha256=kkWI5hY8s8nbZIdGZUtWml6jeyPVveCd2NDOD-pOMg8,2745
8
+ django_redis_tasks-1.0.0.dist-info/METADATA,sha256=Vq4mxNFoCM_nDjErBq6b6kZ1ps1jXszr6tEzPshpX7w,8197
9
+ django_redis_tasks-1.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
10
+ django_redis_tasks-1.0.0.dist-info/top_level.txt,sha256=xqxCtg-sU358q9ABtsR_XU-16Q9sHpaJjcpAHAm3Zek,12
11
+ django_redis_tasks-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ ### Copyright (c) 2021-2026 David L Nugent
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ > The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ redis_tasks
File without changes
redis_tasks/apps.py ADDED
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class RedisTasksConfig(AppConfig):
5
+ name = "redis_tasks"
6
+ verbose_name = "Redis Tasks"
redis_tasks/backend.py ADDED
@@ -0,0 +1,326 @@
1
+ import builtins
2
+ import uuid
3
+ from datetime import UTC, datetime
4
+ from typing import Any, cast
5
+
6
+ import django_queue
7
+ from django.core.exceptions import ImproperlyConfigured
8
+ from django.tasks.backends.base import BaseTaskBackend
9
+ from django.tasks.base import Task, TaskError, TaskResult, TaskResultStatus
10
+ from django.tasks.exceptions import InvalidTask, TaskResultDoesNotExist
11
+ from django.tasks.signals import task_enqueued
12
+ from django.utils import timezone
13
+ from django.utils.json import normalize_json
14
+ from django.utils.module_loading import import_string
15
+ from django_queue.backends.base import AsyncQueue
16
+ from django_queue.backends.exceptions import QueueEntryNotFoundError
17
+ from django_queue.backends.redis.redisqueue import RedisAsyncQueue
18
+ from django_queue.clock import ClockTime
19
+ from django_queue.entries import QueueEntryStatus
20
+
21
+ from redis_tasks.entries import TaskQueueEntry
22
+
23
+ _STATUS_MAP = {
24
+ QueueEntryStatus.QUEUED: TaskResultStatus.READY,
25
+ QueueEntryStatus.RUNNING: TaskResultStatus.RUNNING,
26
+ QueueEntryStatus.SUCCEEDED: TaskResultStatus.SUCCESSFUL,
27
+ QueueEntryStatus.FAILED: TaskResultStatus.FAILED,
28
+ QueueEntryStatus.TIMEOUT: TaskResultStatus.FAILED,
29
+ QueueEntryStatus.CANCELLED: TaskResultStatus.FAILED,
30
+ }
31
+
32
+
33
+ def task_from_payload(
34
+ payload: dict[str, Any], backend_alias: str, *, allow_missing: bool = False
35
+ ) -> Task:
36
+ try:
37
+ imported = import_string(payload["func"])
38
+ except ImportError, AttributeError:
39
+ if not allow_missing:
40
+ raise
41
+ module_name, _, function_name = payload["func"].rpartition(".")
42
+
43
+ if payload.get("takes_context", False):
44
+
45
+ def unavailable_task(context: Any, *args: Any, **kwargs: Any) -> None:
46
+ raise ImportError(
47
+ f"Task function {payload['func']!r} is no longer importable"
48
+ )
49
+
50
+ else:
51
+
52
+ def unavailable_task(*args: Any, **kwargs: Any) -> None:
53
+ raise ImportError(
54
+ f"Task function {payload['func']!r} is no longer importable"
55
+ )
56
+
57
+ unavailable_task.__module__ = module_name
58
+ unavailable_task.__name__ = function_name
59
+ unavailable_task.__qualname__ = function_name
60
+ imported = unavailable_task
61
+ return _task_from_stored_fields(
62
+ func=imported.func if isinstance(imported, Task) else imported,
63
+ priority=payload.get("priority", 0),
64
+ backend=payload.get("backend", backend_alias),
65
+ queue_name=payload.get("queue_name", "default"),
66
+ takes_context=payload.get("takes_context", False),
67
+ run_after=_deserialize_run_after(payload.get("run_after")),
68
+ )
69
+
70
+
71
+ def task_result_from_entry(
72
+ task: Task, entry: TaskQueueEntry, backend_alias: str
73
+ ) -> TaskResult:
74
+ status = _STATUS_MAP[entry.status]
75
+ if entry.error is not None:
76
+ exception_name = entry.error["type"]
77
+ exception_class_path = (
78
+ f"builtins.{exception_name}"
79
+ if isinstance(getattr(builtins, exception_name, None), type)
80
+ and issubclass(getattr(builtins, exception_name), BaseException)
81
+ else "builtins.Exception"
82
+ )
83
+ errors = [
84
+ TaskError(
85
+ exception_class_path=exception_class_path,
86
+ traceback=entry.error["message"],
87
+ )
88
+ ]
89
+ elif entry.status == QueueEntryStatus.TIMEOUT:
90
+ errors = [
91
+ TaskError(
92
+ exception_class_path="builtins.TimeoutError",
93
+ traceback="Task execution timed out.",
94
+ )
95
+ ]
96
+ elif entry.status == QueueEntryStatus.CANCELLED:
97
+ errors = [
98
+ TaskError(
99
+ exception_class_path="asyncio.exceptions.CancelledError",
100
+ traceback="Task execution was cancelled.",
101
+ )
102
+ ]
103
+ else:
104
+ errors = []
105
+ result = TaskResult(
106
+ task=task,
107
+ id=str(entry.id),
108
+ status=status,
109
+ enqueued_at=entry.queued_at.to_datetime() if entry.queued_at else None,
110
+ started_at=entry.dispatched_at.to_datetime() if entry.dispatched_at else None,
111
+ finished_at=entry.finished_at.to_datetime() if entry.finished_at else None,
112
+ last_attempted_at=entry.dispatched_at.to_datetime()
113
+ if entry.dispatched_at
114
+ else None,
115
+ args=entry.payload.get("args", []),
116
+ kwargs=entry.payload.get("kwargs", {}),
117
+ backend=backend_alias,
118
+ errors=errors,
119
+ worker_ids=entry.worker_ids,
120
+ )
121
+ if status == TaskResultStatus.SUCCESSFUL:
122
+ object.__setattr__(result, "_return_value", entry.result)
123
+ return result
124
+
125
+
126
+ def task_payload(task: Task, args: list, kwargs: dict) -> dict[str, Any]:
127
+ payload = {
128
+ "func": task.module_path,
129
+ "args": normalize_json(list(args)),
130
+ "kwargs": normalize_json(kwargs),
131
+ "takes_context": task.takes_context,
132
+ "backend": task.backend,
133
+ "queue_name": task.queue_name,
134
+ "priority": task.priority,
135
+ }
136
+ if task.run_after is not None:
137
+ payload["run_after"] = _utc_datetime(task.run_after).isoformat()
138
+ return payload
139
+
140
+
141
+ def _task_from_stored_fields(
142
+ *,
143
+ func,
144
+ priority: int,
145
+ backend: str,
146
+ queue_name: str,
147
+ takes_context: bool,
148
+ run_after: datetime | None,
149
+ ) -> Task:
150
+ """Build a Task from stored payload fields.
151
+
152
+ Production reconstruction UTC-normalizes ``run_after`` in
153
+ ``_deserialize_run_after`` before this helper runs. The ``InvalidTask``
154
+ retry is defence-in-depth if a caller passes a naive datetime directly.
155
+ """
156
+ try:
157
+ return Task(
158
+ func=func,
159
+ priority=priority,
160
+ backend=backend,
161
+ queue_name=queue_name,
162
+ takes_context=takes_context,
163
+ run_after=run_after,
164
+ )
165
+ except InvalidTask:
166
+ if run_after is None or not timezone.is_naive(run_after):
167
+ raise
168
+ return Task(
169
+ func=func,
170
+ priority=priority,
171
+ backend=backend,
172
+ queue_name=queue_name,
173
+ takes_context=takes_context,
174
+ run_after=_utc_datetime(run_after),
175
+ )
176
+
177
+
178
+ def _deserialize_run_after(value: object) -> datetime | None:
179
+ if value is None:
180
+ return None
181
+ if not isinstance(value, str):
182
+ raise TypeError("run_after payload must be an ISO-8601 string")
183
+ moment = _utc_datetime(datetime.fromisoformat(value))
184
+ _clock_time_from_datetime(moment)
185
+ return moment
186
+
187
+
188
+ def _utc_datetime(value: datetime) -> datetime:
189
+ moment = value
190
+ if timezone.is_naive(moment):
191
+ moment = timezone.make_aware(moment, timezone.get_current_timezone())
192
+ return moment.astimezone(UTC)
193
+
194
+
195
+ def _clock_time_from_datetime(moment: datetime) -> ClockTime:
196
+ try:
197
+ return ClockTime.from_datetime(moment)
198
+ except ValueError as exc:
199
+ raise InvalidTask(
200
+ "run_after cannot describe an instant before the Unix epoch"
201
+ ) from exc
202
+
203
+
204
+ def _available_at_for(task: Task) -> ClockTime | None:
205
+ if task.run_after is None:
206
+ return None
207
+ return _clock_time_from_datetime(_utc_datetime(task.run_after))
208
+
209
+
210
+ def _enqueue_options(task: Task) -> dict[str, Any]:
211
+ options: dict[str, Any] = {"priority": task.priority}
212
+ available_at = _available_at_for(task)
213
+ if available_at is not None:
214
+ options["available_at"] = available_at
215
+ return options
216
+
217
+
218
+ class RedisBackend(BaseTaskBackend):
219
+ supports_async_task = True
220
+ supports_get_result = True
221
+ supports_defer = True
222
+ supports_priority = True
223
+
224
+ def __init__(self, alias: str, params: dict[str, Any]) -> None:
225
+ self._queue_alias = (params.get("OPTIONS") or {}).get("queue_alias", alias)
226
+ super().__init__(alias=alias, params=params)
227
+ if not isinstance(self._queue_alias, str) or not self._queue_alias:
228
+ raise ImproperlyConfigured(
229
+ "Redis task backend OPTIONS.queue_alias must be a non-empty string."
230
+ )
231
+ if self._queue_alias not in django_queue.queues.settings:
232
+ raise ImproperlyConfigured(
233
+ f"Redis task backend queue_alias {self._queue_alias!r} is not "
234
+ "configured in QUEUES."
235
+ )
236
+ try:
237
+ queue_backend = import_string(
238
+ django_queue.queues.settings[self._queue_alias]["BACKEND"]
239
+ )
240
+ is_redis_queue = issubclass(queue_backend, RedisAsyncQueue)
241
+ except (ImportError, AttributeError, TypeError) as exc:
242
+ raise ImproperlyConfigured(
243
+ f"Redis task backend queue_alias {self._queue_alias!r} must use a "
244
+ "RedisAsyncQueue-compatible backend."
245
+ ) from exc
246
+ if not is_redis_queue:
247
+ raise ImproperlyConfigured(
248
+ f"Redis task backend queue_alias {self._queue_alias!r} must use a "
249
+ "RedisAsyncQueue-compatible backend."
250
+ )
251
+ entry_class = django_queue.queues.settings[self._queue_alias].get("ENTRY_CLASS")
252
+ if isinstance(entry_class, str):
253
+ entry_class = import_string(entry_class)
254
+ if not isinstance(entry_class, type) or not issubclass(
255
+ entry_class, TaskQueueEntry
256
+ ):
257
+ raise ImproperlyConfigured(
258
+ f"Redis task backend queue_alias {self._queue_alias!r} must "
259
+ "configure an ENTRY_CLASS compatible with TaskQueueEntry."
260
+ )
261
+ worker_class = django_queue.queues.settings[self._queue_alias].get("WORKER")
262
+ if isinstance(worker_class, str):
263
+ worker_class = import_string(worker_class)
264
+ from redis_tasks.worker import RedisTaskWorker
265
+
266
+ if not isinstance(worker_class, type) or not issubclass(
267
+ worker_class, RedisTaskWorker
268
+ ):
269
+ raise ImproperlyConfigured(
270
+ f"Redis task backend queue_alias {self._queue_alias!r} must "
271
+ "configure a WORKER compatible with RedisTaskWorker."
272
+ )
273
+
274
+ def _resolve_queue(self) -> AsyncQueue:
275
+ return django_queue.queues[self._queue_alias]
276
+
277
+ def enqueue(self, task: Task, args: list, kwargs: dict) -> TaskResult:
278
+ self.validate_task(task)
279
+ payload = task_payload(task, args, kwargs)
280
+ queue = self._resolve_queue()
281
+ entry_id = queue.enqueue(payload, **_enqueue_options(task))
282
+ entry = queue.find(entry_id)
283
+ result = task_result_from_entry(task, cast(TaskQueueEntry, entry), self.alias)
284
+ task_enqueued.send(type(self), task_result=result)
285
+ return result
286
+
287
+ async def aenqueue(self, task: Task, args: list, kwargs: dict) -> TaskResult:
288
+ self.validate_task(task)
289
+ payload = task_payload(task, args, kwargs)
290
+ queue = self._resolve_queue()
291
+ entry_id = await queue.aenqueue(payload, **_enqueue_options(task))
292
+ entry = await queue.afind(entry_id)
293
+ result = task_result_from_entry(task, cast(TaskQueueEntry, entry), self.alias)
294
+ await task_enqueued.asend(type(self), task_result=result)
295
+ return result
296
+
297
+ def _parse_result_id(self, result_id: str) -> uuid.UUID:
298
+ try:
299
+ return uuid.UUID(result_id)
300
+ except (ValueError, AttributeError, TypeError) as exc:
301
+ raise TaskResultDoesNotExist(result_id) from exc
302
+
303
+ def _result_from_stored_entry(
304
+ self, entry: TaskQueueEntry, result_id: str
305
+ ) -> TaskResult:
306
+ try:
307
+ task = task_from_payload(entry.payload, self.alias, allow_missing=True)
308
+ except (TypeError, ValueError) as exc:
309
+ raise TaskResultDoesNotExist(result_id) from exc
310
+ return task_result_from_entry(task, entry, self.alias)
311
+
312
+ def get_result(self, result_id: str) -> TaskResult:
313
+ entry_id = self._parse_result_id(result_id)
314
+ try:
315
+ entry = self._resolve_queue().find(entry_id)
316
+ except QueueEntryNotFoundError as exc:
317
+ raise TaskResultDoesNotExist(result_id) from exc
318
+ return self._result_from_stored_entry(cast(TaskQueueEntry, entry), result_id)
319
+
320
+ async def aget_result(self, result_id: str) -> TaskResult:
321
+ entry_id = self._parse_result_id(result_id)
322
+ try:
323
+ entry = await self._resolve_queue().afind(entry_id)
324
+ except QueueEntryNotFoundError as exc:
325
+ raise TaskResultDoesNotExist(result_id) from exc
326
+ return self._result_from_stored_entry(cast(TaskQueueEntry, entry), result_id)
redis_tasks/entries.py ADDED
@@ -0,0 +1,10 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ from django_queue.entries import QueueEntry
4
+
5
+
6
+ @dataclass(frozen=True, slots=True)
7
+ class TaskQueueEntry(QueueEntry):
8
+ """A queue entry with Django task dispatch-attempt metadata."""
9
+
10
+ worker_ids: list[str] = field(default_factory=list)
@@ -0,0 +1,34 @@
1
+ import asyncio
2
+ from typing import Any, cast
3
+
4
+ from django.tasks.base import TaskContext, TaskResultStatus
5
+ from django.tasks.signals import task_started
6
+ from django.utils.json import normalize_json
7
+ from django_queue.entries import QueueEntry
8
+
9
+ from redis_tasks.backend import task_from_payload, task_result_from_entry
10
+ from redis_tasks.entries import TaskQueueEntry
11
+
12
+
13
+ async def handle_task_entry(entry: QueueEntry) -> Any:
14
+ payload = entry.payload
15
+ task = task_from_payload(payload, payload.get("backend", entry.queue))
16
+ result = task_result_from_entry(task, cast(TaskQueueEntry, entry), task.backend)
17
+ args, kwargs = payload["args"], payload["kwargs"]
18
+ backend_type = type(task.get_backend())
19
+ object.__setattr__(result, "status", TaskResultStatus.RUNNING)
20
+ await task_started.asend(backend_type, task_result=result)
21
+
22
+ async def call_task() -> Any:
23
+ if task.takes_context:
24
+ return await task.acall(TaskContext(task_result=result), *args, **kwargs)
25
+ return await task.acall(*args, **kwargs)
26
+
27
+ try:
28
+ value = await asyncio.create_task(call_task())
29
+ except asyncio.CancelledError as exc:
30
+ current_task = asyncio.current_task()
31
+ if current_task is not None and current_task.cancelling():
32
+ raise
33
+ raise RuntimeError("Task function raised asyncio.CancelledError") from exc
34
+ return normalize_json(value)
redis_tasks/worker.py ADDED
@@ -0,0 +1,71 @@
1
+ import logging
2
+ from dataclasses import replace
3
+ from typing import cast
4
+ from uuid import UUID
5
+
6
+ from django.tasks.signals import task_finished
7
+ from django_queue.backends.base import AsyncQueue
8
+ from django_queue.backends.redis.redisqueue import RedisAsyncQueue
9
+ from django_queue.backends.redis.worker import RedisAsyncQueueWorker
10
+ from django_queue.clock import MICROSECONDS_PER_SECOND
11
+ from django_queue.entries import QueueEntry, QueueEntryStatus
12
+
13
+ from redis_tasks.backend import task_from_payload, task_result_from_entry
14
+ from redis_tasks.entries import TaskQueueEntry
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class RedisTaskWorker(RedisAsyncQueueWorker):
20
+ """Persist task dispatch metadata and emit durable terminal signals."""
21
+
22
+ async def _mark_running(
23
+ self, queue: AsyncQueue, entry: QueueEntry
24
+ ) -> TaskQueueEntry | None:
25
+ redis_queue = cast(RedisAsyncQueue, queue)
26
+ queued_entry = cast(TaskQueueEntry, await redis_queue.afind(entry.id))
27
+ running_entry = replace(
28
+ queued_entry,
29
+ status=QueueEntryStatus.RUNNING,
30
+ dispatched_at=await redis_queue.clock.anow(),
31
+ worker_ids=[*queued_entry.worker_ids, str(self._worker_id)],
32
+ )
33
+ provider = self._providers[redis_queue]
34
+ if await provider.amark_running(self._worker_id, running_entry):
35
+ return running_entry
36
+ if not await redis_queue.arelease(
37
+ entry.id, self._worker_id, 1 / MICROSECONDS_PER_SECOND
38
+ ):
39
+ logger.warning("Lost claim for queue entry %s before release", entry.id)
40
+ return None
41
+
42
+ async def _settle_terminal(
43
+ self,
44
+ queue: AsyncQueue,
45
+ entry: QueueEntry,
46
+ worker_id: UUID,
47
+ status: QueueEntryStatus,
48
+ *,
49
+ result: object | None = None,
50
+ error: dict[str, str] | None = None,
51
+ ) -> QueueEntry:
52
+ """Emit ``task_finished`` only after the terminal entry is durable."""
53
+ terminal_entry = await super()._settle_terminal(
54
+ queue, entry, worker_id, status, result=result, error=error
55
+ )
56
+ if terminal_entry.status not in {
57
+ QueueEntryStatus.SUCCEEDED,
58
+ QueueEntryStatus.FAILED,
59
+ QueueEntryStatus.CANCELLED,
60
+ QueueEntryStatus.TIMEOUT,
61
+ }:
62
+ return terminal_entry
63
+
64
+ task_entry = cast(TaskQueueEntry, terminal_entry)
65
+ payload = task_entry.payload
66
+ task = task_from_payload(
67
+ payload, payload.get("backend", task_entry.queue), allow_missing=True
68
+ )
69
+ task_result = task_result_from_entry(task, task_entry, task.backend)
70
+ await task_finished.asend(type(task.get_backend()), task_result=task_result)
71
+ return terminal_entry