lessormq-django 0.4.10__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,27 @@
1
+ """LessorMQ for Django: a backend for Django's tasks framework (django.tasks) on
2
+ LessorMQ, the message queue over HTTP where the server decides and workers only claim,
3
+ run, ack or fail.
4
+
5
+ TASKS = {
6
+ "default": {
7
+ "BACKEND": "lessormq_django.LessorMQBackend",
8
+ "OPTIONS": {"URL": "https://mq.example.com", "API_KEY": "lmq_..."},
9
+ }
10
+ }
11
+
12
+ Run the tasks with ``manage.py lessormq_worker``.
13
+ """
14
+
15
+ from .backend import LessorMQBackend, LessorMQTaskResult
16
+ from .exceptions import LeaseExpired, MalformedTask, PermanentFailure, UnknownTask
17
+
18
+ __all__ = [
19
+ "LeaseExpired",
20
+ "LessorMQBackend",
21
+ "LessorMQTaskResult",
22
+ "MalformedTask",
23
+ "PermanentFailure",
24
+ "UnknownTask",
25
+ ]
26
+
27
+ __version__ = "0.4.10"
@@ -0,0 +1,49 @@
1
+ """A Django task as a LessorMQ message body, and back.
2
+
3
+ The body is plain JSON, so a message reads as what it is in the queue and in the
4
+ dead-letter set: ``{"task": "shop.tasks.send_invoice", "args": [1042], "kwargs": {}}``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from django.tasks import Task
12
+ from django.utils.module_loading import import_string
13
+
14
+ from .exceptions import MalformedTask, UnknownTask
15
+
16
+
17
+ def encode(task: Task[..., Any], args: list[Any], kwargs: dict[str, Any]) -> dict[str, Any]:
18
+ return {"task": task.module_path, "args": args, "kwargs": kwargs}
19
+
20
+
21
+ def decode(body: Any) -> tuple[str, list[Any], dict[str, Any]]:
22
+ """The task path, args and kwargs in a message body.
23
+
24
+ :raises MalformedTask: when the body is not a Django task
25
+ """
26
+ if not isinstance(body, dict):
27
+ raise MalformedTask("the message body is not a JSON object with a task")
28
+ path = body.get("task")
29
+ args = body.get("args", [])
30
+ kwargs = body.get("kwargs", {})
31
+ if not isinstance(path, str) or not path:
32
+ raise MalformedTask("the message body has no task path")
33
+ if not isinstance(args, list) or not isinstance(kwargs, dict):
34
+ raise MalformedTask("the args of the message are not a list, or its kwargs not an object")
35
+ return path, args, kwargs
36
+
37
+
38
+ def load(path: str) -> Task[..., Any]:
39
+ """The task a message names.
40
+
41
+ :raises UnknownTask: when this process cannot import it
42
+ """
43
+ try:
44
+ task = import_string(path)
45
+ except ImportError as e:
46
+ raise UnknownTask(f"cannot import task {path}: {e}") from e
47
+ if not isinstance(task, Task):
48
+ raise UnknownTask(f"{path} is not a task (decorate it with @task)")
49
+ return task
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class LessorMQConfig(AppConfig):
5
+ name = "lessormq_django"
6
+ verbose_name = "LessorMQ"
@@ -0,0 +1,314 @@
1
+ """The task backend: enqueue publishes to LessorMQ, and ``get_result`` reads the message
2
+ back with the same key (the publish scope may read the messages of its queues).
3
+
4
+ What happens to a task after a failure (another attempt, when, or the dead-letter set)
5
+ is decided by the queue on the server, never here: see the README, "How it behaves".
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import time
12
+ from dataclasses import replace
13
+ from datetime import datetime
14
+ from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, cast
15
+ from urllib.parse import quote
16
+
17
+ import httpx
18
+ from django.conf import settings
19
+ from django.core import checks
20
+ from django.core.exceptions import ImproperlyConfigured
21
+ from django.tasks import Task, TaskResult, TaskResultStatus
22
+ from django.tasks.backends.base import BaseTaskBackend
23
+ from django.tasks.base import TaskError
24
+ from django.tasks.exceptions import TaskResultDoesNotExist
25
+ from django.tasks.signals import task_enqueued
26
+ from django.utils import timezone
27
+ from django.utils.json import normalize_json
28
+ from lessormq import ApiError, Client, NotFoundError, RateLimitedError, ServerError, TransportError
29
+
30
+ from . import _messages
31
+ from .exceptions import LeaseExpired, MalformedTask
32
+
33
+ __all__ = ["LessorMQBackend", "LessorMQTaskResult"]
34
+
35
+ USER_AGENT = "lessormq-django/1"
36
+ _P = ParamSpec("_P")
37
+ _R = TypeVar("_R")
38
+ _QUEUE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$")
39
+ _STATUSES = {
40
+ "pending": TaskResultStatus.READY,
41
+ "processing": TaskResultStatus.RUNNING,
42
+ "completed": TaskResultStatus.SUCCESSFUL,
43
+ "failed": TaskResultStatus.FAILED,
44
+ }
45
+
46
+
47
+ if TYPE_CHECKING:
48
+ # Generic in django-stubs only.
49
+ _TaskResult = TaskResult[..., Any]
50
+ else:
51
+ _TaskResult = TaskResult
52
+
53
+
54
+ class LessorMQTaskResult(_TaskResult):
55
+ """A :class:`~django.tasks.TaskResult` from LessorMQ, which keeps no return values.
56
+
57
+ ``return_value`` of a successful result says so instead of answering ``None``, which
58
+ a task may well have returned.
59
+ """
60
+
61
+ __slots__ = ()
62
+
63
+ @property
64
+ def return_value(self) -> Any:
65
+ if self.status == TaskResultStatus.SUCCESSFUL:
66
+ raise NotImplementedError(
67
+ "LessorMQ does not keep the return values of tasks; store what a task produces yourself"
68
+ )
69
+ return TaskResult.return_value.fget(self) # type: ignore[attr-defined]
70
+
71
+
72
+ class LessorMQBackend(BaseTaskBackend):
73
+ """Runs Django tasks through LessorMQ queues::
74
+
75
+ TASKS = {
76
+ "default": {
77
+ "BACKEND": "lessormq_django.LessorMQBackend",
78
+ "QUEUES": ["default", "mail"],
79
+ "OPTIONS": {"URL": "https://mq.example.com", "API_KEY": "lmq_..."},
80
+ }
81
+ }
82
+
83
+ ``manage.py lessormq_worker`` runs the tasks. OPTIONS:
84
+
85
+ - ``URL``, ``API_KEY`` (required): the server, and a key with the publish scope (to
86
+ enqueue and read results) and the consume scope (to run a worker);
87
+ - ``QUEUE_PREFIX``: put before each Django queue name to make the LessorMQ queue;
88
+ - ``CLIENT``: keyword arguments for :class:`lessormq.Client` (``timeout``,
89
+ ``http_retries``, ``retry_delay``, ``http``).
90
+ """
91
+
92
+ supports_defer = True
93
+ supports_async_task = True
94
+ # LessorMQ hands out messages roughly in order of availability; it has no priority.
95
+ supports_priority = False
96
+ # A message is read back with the publish scope: the result is what the server has.
97
+ supports_get_result = True
98
+
99
+ def __init__(self, alias: str, params: dict[str, Any]) -> None:
100
+ super().__init__(alias, params)
101
+ self.url: str = self.options.get("URL") or ""
102
+ self.queue_prefix: str = self.options.get("QUEUE_PREFIX") or ""
103
+ self._api_key: str = self.options.get("API_KEY") or ""
104
+ self._client_options: dict[str, Any] = dict(self.options.get("CLIENT") or {})
105
+ self._client_options.setdefault("user_agent", USER_AGENT)
106
+ self._client: Client | None = None
107
+
108
+ def __repr__(self) -> str:
109
+ # Never the keys.
110
+ return f"{type(self).__name__}({self.alias!r}, {self.url!r})"
111
+
112
+ @property
113
+ def client(self) -> Client:
114
+ """The LessorMQ client of this backend, for publishing and for workers."""
115
+ if self._client is None:
116
+ if not self.url or not self._api_key:
117
+ raise ImproperlyConfigured(f"Task backend {self.alias!r} needs OPTIONS URL and API_KEY")
118
+ self._client = Client(self.url, self._api_key, **self._client_options)
119
+ return self._client
120
+
121
+ def queue_for(self, queue_name: str) -> str:
122
+ """The LessorMQ queue of a Django queue name."""
123
+ return self.queue_prefix + queue_name
124
+
125
+ def enqueue(self, task: Task[_P, _R], args: list[Any], kwargs: dict[str, Any]) -> TaskResult[_P, _R]:
126
+ self.validate_task(task)
127
+ # JSON only, as for every Django backend; a value that is not raises here, before
128
+ # anything is published.
129
+ arguments: list[Any] = normalize_json(args) # type: ignore[assignment]
130
+ keywords: dict[str, Any] = normalize_json(kwargs) # type: ignore[assignment]
131
+
132
+ available_at = None
133
+ if task.run_after is not None:
134
+ available_at = task.run_after
135
+ if timezone.is_naive(available_at):
136
+ # USE_TZ = False: Django's times are local times.
137
+ available_at = timezone.make_aware(available_at)
138
+
139
+ published = self.client.publish(
140
+ self.queue_for(task.queue_name),
141
+ _messages.encode(task, arguments, keywords),
142
+ available_at=available_at,
143
+ )
144
+ result = LessorMQTaskResult(
145
+ task=task,
146
+ id=published.id,
147
+ status=TaskResultStatus.READY,
148
+ enqueued_at=_django_time(published.created_at),
149
+ started_at=None,
150
+ last_attempted_at=None,
151
+ finished_at=None,
152
+ args=arguments,
153
+ kwargs=keywords,
154
+ backend=self.alias,
155
+ errors=[],
156
+ worker_ids=[],
157
+ )
158
+ task_enqueued.send(type(self), task_result=result)
159
+ return cast("TaskResult[_P, _R]", result)
160
+
161
+ def get_result(self, result_id: str) -> TaskResult[..., Any]:
162
+ """The task's state as the server has it: status, attempts, timestamps and the
163
+ last error.
164
+
165
+ :raises TaskResultDoesNotExist: when the message is gone (removed after the
166
+ queue's retention, discarded, deleted) or is not a Django task
167
+ """
168
+ data = self._read_message(result_id)
169
+ if data is None:
170
+ raise TaskResultDoesNotExist(result_id)
171
+ try:
172
+ path, args, kwargs = _messages.decode(data.get("body"))
173
+ except MalformedTask:
174
+ raise TaskResultDoesNotExist(result_id) from None
175
+ return self._result(data, _messages.load(path), args, kwargs)
176
+
177
+ def check(self, **kwargs: Any) -> list[checks.CheckMessage]:
178
+ errors: list[checks.CheckMessage] = []
179
+ if not self.url or not self._api_key:
180
+ errors.append(
181
+ checks.Error(
182
+ f"Task backend {self.alias!r} needs OPTIONS URL and API_KEY.",
183
+ id="lessormq_django.E001",
184
+ )
185
+ )
186
+ for name in sorted(self.queues):
187
+ if not _QUEUE_NAME.match(self.queue_for(name)):
188
+ errors.append(
189
+ checks.Error(
190
+ f"{self.queue_for(name)!r} (queue {name!r} of task backend {self.alias!r}) is not a "
191
+ "valid LessorMQ queue name: letters, digits, '.', '_' and '-', up to 200.",
192
+ id="lessormq_django.E002",
193
+ )
194
+ )
195
+ return errors
196
+
197
+ def _result(
198
+ self, data: dict[str, Any], task: Task[..., Any], args: list[Any], kwargs: dict[str, Any]
199
+ ) -> TaskResult[..., Any]:
200
+ queue = str(data.get("queue", ""))
201
+ queue_name = queue[len(self.queue_prefix):] if queue.startswith(self.queue_prefix) else queue
202
+ task = replace(task, queue_name=queue_name, backend=self.alias, run_after=None)
203
+
204
+ attempts = int(data.get("attempts") or 0)
205
+ consumer = data.get("consumer") or ""
206
+ status = str(data.get("status"))
207
+ finished = data.get("completed_at") if status == "completed" else data.get("failed_at")
208
+ last_error = data.get("last_error")
209
+ return LessorMQTaskResult(
210
+ task=task,
211
+ id=str(data["id"]),
212
+ status=_STATUSES.get(status, TaskResultStatus.READY),
213
+ enqueued_at=_django_time(data.get("created_at")),
214
+ # The server keeps the claim of the current or last attempt only.
215
+ started_at=_django_time(data.get("started_at")),
216
+ last_attempted_at=_django_time(data.get("started_at")),
217
+ finished_at=_django_time(finished),
218
+ args=args,
219
+ kwargs=kwargs,
220
+ backend=self.alias,
221
+ errors=[_task_error(last_error)] if isinstance(last_error, dict) else [],
222
+ # One entry per attempt, so ``attempts`` is the server's count. The server
223
+ # names the worker of the last claim only; earlier ones stay empty.
224
+ worker_ids=[""] * max(attempts - 1, 0) + [str(consumer)] if attempts else [],
225
+ )
226
+
227
+ def _read_message(self, message_id: str) -> dict[str, Any] | None:
228
+ """GET /v1/messages/{id} with the backend's key (its publish scope allows it): not
229
+ one of the protocol calls of lessormq.Client. Retried like those on network
230
+ errors, 5xx and 429."""
231
+ options = self._client_options
232
+ http: httpx.Client = options.get("http") or httpx.Client()
233
+ retries = int(options.get("http_retries", 3))
234
+ delay = float(options.get("retry_delay", 0.1))
235
+ url = self.url.rstrip("/") + "/v1/messages/" + quote(message_id, safe="")
236
+ headers = {
237
+ "Authorization": "Bearer " + self._api_key,
238
+ "Accept": "application/json",
239
+ "User-Agent": str(options.get("user_agent", USER_AGENT)),
240
+ }
241
+ timeout = float(options.get("timeout", 10.0))
242
+ try:
243
+ attempt = 0
244
+ while True:
245
+ attempt += 1
246
+ try:
247
+ response = http.get(url, headers=headers, timeout=timeout)
248
+ except httpx.HTTPError as e:
249
+ if attempt > retries:
250
+ raise TransportError(f"GET /v1/messages/{message_id} failed: {e!s}") from e
251
+ time.sleep(delay * attempt)
252
+ continue
253
+ if response.status_code < 400:
254
+ body: dict[str, Any] = response.json()
255
+ return body
256
+ error = ApiError.from_response(response.status_code, _json(response), _retry_after(response))
257
+ if isinstance(error, NotFoundError):
258
+ return None
259
+ if isinstance(error, (ServerError, RateLimitedError)) and attempt <= retries:
260
+ wait = error.retry_after if isinstance(error, RateLimitedError) else None
261
+ time.sleep(float(wait) if wait is not None else delay * attempt)
262
+ continue
263
+ raise error
264
+ finally:
265
+ if "http" not in options:
266
+ http.close()
267
+
268
+
269
+ def _task_error(error: dict[str, Any]) -> TaskError:
270
+ """A recorded error as Django has errors: the exception's class path and a traceback.
271
+
272
+ The server keeps the type, the message and the details a worker sent. The Python
273
+ client sends the class (``ValueError``, ``shop.errors.OutOfStock``) and where it was
274
+ raised; a lease that ran out has no type.
275
+ """
276
+ kind = error.get("type")
277
+ if not isinstance(kind, str) or not kind:
278
+ path = f"{LeaseExpired.__module__}.LeaseExpired" if error.get("expired") else "builtins.Exception"
279
+ else:
280
+ path = kind if "." in kind else "builtins." + kind
281
+ lines = ["Traceback (most recent call last):"]
282
+ details = error.get("details")
283
+ if isinstance(details, dict) and "file" in details and "line" in details:
284
+ lines.append(f' File "{details["file"]}", line {details["line"]}')
285
+ lines.append(f"{path.rsplit('.', 1)[-1]}: {error.get('message', '')}")
286
+ return TaskError(exception_class_path=path, traceback="\n".join(lines) + "\n")
287
+
288
+
289
+ def _django_time(value: Any) -> datetime | None:
290
+ """An API time as Django keeps times: aware with USE_TZ, local and naive without."""
291
+ if isinstance(value, datetime):
292
+ parsed = value
293
+ elif isinstance(value, str) and value:
294
+ parsed = datetime.fromisoformat(value)
295
+ else:
296
+ return None
297
+ if not settings.USE_TZ:
298
+ return timezone.make_naive(parsed)
299
+ return parsed
300
+
301
+
302
+ def _json(response: httpx.Response) -> Any:
303
+ try:
304
+ return response.json() if response.content else None
305
+ except ValueError:
306
+ return None
307
+
308
+
309
+ def _retry_after(response: httpx.Response) -> int | None:
310
+ value = response.headers.get("Retry-After")
311
+ try:
312
+ return int(value) if value is not None else None
313
+ except ValueError:
314
+ return None
@@ -0,0 +1,29 @@
1
+ """What the worker reports when it cannot run a message, and what a task raises to say
2
+ the input itself is unusable."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from lessormq import PermanentFailure
7
+
8
+ __all__ = ["LeaseExpired", "MalformedTask", "PermanentFailure", "UnknownTask"]
9
+
10
+
11
+ class MalformedTask(PermanentFailure):
12
+ """The message is not a Django task: no task path, or arguments of the wrong shape.
13
+
14
+ Reported as permanent, since running it again cannot help.
15
+ """
16
+
17
+
18
+ class UnknownTask(Exception):
19
+ """The task in the message cannot be imported by this worker.
20
+
21
+ Reported as an ordinary failure, not a permanent one: during a deploy a worker with
22
+ the old code can claim a task that only the new code has, and the next attempt may
23
+ land on a worker that knows it.
24
+ """
25
+
26
+
27
+ class LeaseExpired(Exception):
28
+ """Stands for an attempt that ended because its lease ran out (the worker crashed or
29
+ hung), in the errors of a result from ``get_result``. Never raised."""
File without changes
File without changes
@@ -0,0 +1,75 @@
1
+ """``manage.py lessormq_worker``: run the Django tasks of LessorMQ queues."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from argparse import ArgumentParser
6
+ from typing import Any
7
+
8
+ from django.core.management.base import BaseCommand, CommandError
9
+ from django.tasks import DEFAULT_TASK_BACKEND_ALIAS, task_backends
10
+ from django.tasks.exceptions import InvalidTaskBackend
11
+
12
+ from lessormq_django.backend import LessorMQBackend
13
+ from lessormq_django.worker import run_worker
14
+
15
+
16
+ class Command(BaseCommand):
17
+ help = (
18
+ "Run the tasks of a LessorMQ task backend's queues until SIGTERM or SIGINT. "
19
+ "Retries, backoff and the dead-letter set are the queue's settings on the server."
20
+ )
21
+
22
+ def add_arguments(self, parser: ArgumentParser) -> None:
23
+ parser.add_argument(
24
+ "--backend",
25
+ default=DEFAULT_TASK_BACKEND_ALIAS,
26
+ help="the task backend in TASKS (default: %(default)s)",
27
+ )
28
+ parser.add_argument(
29
+ "--queue",
30
+ action="append",
31
+ dest="queues",
32
+ metavar="NAME",
33
+ help="a Django queue name, repeatable (default: every queue in the backend's QUEUES)",
34
+ )
35
+ parser.add_argument("--consumer", help="the worker's name on the server (default: host:pid)")
36
+ parser.add_argument("--route", help="the path this worker runs tasks through (a VPN exit, a proxy)")
37
+ parser.add_argument(
38
+ "--wait-seconds",
39
+ type=int,
40
+ default=20,
41
+ help="long-poll wait per claim, at most 20; also the longest a stop waits (default: %(default)s)",
42
+ )
43
+ parser.add_argument("--lease-seconds", type=int, help="lease per claim (default: the queue's)")
44
+ parser.add_argument("--max-tasks", type=int, help="stop each queue's worker after this many tasks")
45
+ parser.add_argument("--max-seconds", type=float, help="stop after running this long")
46
+
47
+ def handle(self, *args: Any, **options: Any) -> None:
48
+ alias = options["backend"]
49
+ try:
50
+ backend = task_backends[alias]
51
+ except InvalidTaskBackend as e:
52
+ raise CommandError(str(e)) from e
53
+ if not isinstance(backend, LessorMQBackend):
54
+ raise CommandError(f"Task backend {alias!r} is a {type(backend).__name__}, not a LessorMQBackend")
55
+ queues = options["queues"] or sorted(backend.queues)
56
+ if not queues:
57
+ raise CommandError(f"Task backend {alias!r} allows any queue: name the queues with --queue")
58
+ unknown = [name for name in queues if backend.queues and name not in backend.queues]
59
+ if unknown:
60
+ raise CommandError(f"Not in the QUEUES of task backend {alias!r}: {', '.join(unknown)}")
61
+
62
+ self.stdout.write(
63
+ "Running tasks from " + ", ".join(f"{name} ({backend.queue_for(name)})" for name in queues)
64
+ )
65
+ handled = run_worker(
66
+ queues,
67
+ backend=alias,
68
+ consumer=options["consumer"],
69
+ route=options["route"],
70
+ wait_seconds=options["wait_seconds"],
71
+ lease_seconds=options["lease_seconds"],
72
+ max_tasks=options["max_tasks"],
73
+ max_seconds=options["max_seconds"],
74
+ )
75
+ self.stdout.write(f"Stopped after {handled} task(s)")
File without changes
@@ -0,0 +1,208 @@
1
+ """The worker: claims messages of the backend's queues and runs the Django task in each.
2
+
3
+ Built on :class:`lessormq.Worker`, which acks when the task returns, fails when it
4
+ raises (permanent for a :class:`~lessormq.PermanentFailure`) and extends the lease while
5
+ it runs. Whether and when a failed task runs again is the queue's decision.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import os
12
+ import signal
13
+ import socket
14
+ import threading
15
+ from collections.abc import Callable
16
+ from traceback import format_exception
17
+ from typing import Any
18
+
19
+ from django.db import close_old_connections, connections
20
+ from django.tasks import TaskContext, TaskResult, TaskResultStatus, task_backends
21
+ from django.tasks.base import TaskError
22
+ from django.tasks.signals import task_finished, task_started
23
+ from django.utils import timezone
24
+ from django.utils.json import normalize_json
25
+ from lessormq import Job, Message, Worker
26
+
27
+ from . import _messages
28
+ from .backend import LessorMQBackend, _django_time
29
+
30
+ __all__ = ["TaskHandler", "run_worker"]
31
+
32
+ logger = logging.getLogger("lessormq_django")
33
+
34
+
35
+ class TaskHandler:
36
+ """The handler of one queue: runs the task a message names, with Django's signals,
37
+ and closes stale database connections around it as a request would."""
38
+
39
+ def __init__(self, backend_alias: str, queue_name: str, consumer: str) -> None:
40
+ self.backend_alias = backend_alias
41
+ self.queue_name = queue_name
42
+ self.consumer = consumer
43
+
44
+ def __call__(self, message: Message, job: Job) -> None:
45
+ close_old_connections()
46
+ try:
47
+ self.run(message)
48
+ finally:
49
+ close_old_connections()
50
+
51
+ def run(self, message: Message) -> Any:
52
+ """Run the task in ``message``; returns what the task returned, raises what it
53
+ raised."""
54
+ path, args, kwargs = _messages.decode(message.body)
55
+ task = _messages.load(path).using(queue_name=self.queue_name, backend=self.backend_alias)
56
+ backend = type(task.get_backend())
57
+ now = timezone.now()
58
+ result: TaskResult[..., Any] = TaskResult(
59
+ task=task,
60
+ id=message.id,
61
+ status=TaskResultStatus.RUNNING,
62
+ enqueued_at=_django_time(message.created_at),
63
+ started_at=now,
64
+ last_attempted_at=now,
65
+ finished_at=None,
66
+ args=args,
67
+ kwargs=kwargs,
68
+ backend=self.backend_alias,
69
+ errors=[],
70
+ # One entry per attempt, so context.attempt is the server's attempt number.
71
+ # The workers of earlier attempts are not known here.
72
+ worker_ids=[""] * (message.attempt - 1) + [self.consumer],
73
+ )
74
+ task_started.send(sender=backend, task_result=result)
75
+ try:
76
+ if task.takes_context:
77
+ value = task.call(TaskContext(task_result=result), *result.args, **result.kwargs)
78
+ else:
79
+ value = task.call(*result.args, **result.kwargs)
80
+ # As in Django's own backends: a return value that is not JSON fails the task.
81
+ object.__setattr__(result, "_return_value", normalize_json(value))
82
+ except Exception as error:
83
+ object.__setattr__(result, "finished_at", timezone.now())
84
+ object.__setattr__(result, "status", TaskResultStatus.FAILED)
85
+ kind = type(error)
86
+ result.errors.append(
87
+ TaskError(
88
+ exception_class_path=f"{kind.__module__}.{kind.__qualname__}",
89
+ traceback="".join(format_exception(error)),
90
+ )
91
+ )
92
+ # Inside the except block, so receivers see the exception in sys.exc_info().
93
+ task_finished.send(sender=backend, task_result=result)
94
+ raise
95
+ object.__setattr__(result, "finished_at", timezone.now())
96
+ object.__setattr__(result, "status", TaskResultStatus.SUCCESSFUL)
97
+ task_finished.send(sender=backend, task_result=result)
98
+ return value
99
+
100
+
101
+ def run_worker(
102
+ queues: list[str],
103
+ *,
104
+ backend: str = "default",
105
+ consumer: str | None = None,
106
+ route: str | None = None,
107
+ wait_seconds: int = 20,
108
+ lease_seconds: int | None = None,
109
+ max_tasks: int | None = None,
110
+ max_seconds: float | None = None,
111
+ handle_signals: bool = True,
112
+ on_ready: Callable[[list[Worker]], None] | None = None,
113
+ ) -> int:
114
+ """Run the tasks of Django queues ``queues`` of task backend ``backend``, a thread per
115
+ queue, until SIGTERM or SIGINT (each worker finishes its current task), or until
116
+ ``max_tasks`` per queue or ``max_seconds``.
117
+
118
+ :returns: the tasks run
119
+ """
120
+ instance = task_backends[backend]
121
+ if not isinstance(instance, LessorMQBackend):
122
+ raise TypeError(f"Task backend {backend!r} is not a LessorMQBackend")
123
+ if not queues:
124
+ raise ValueError("name at least one queue")
125
+ for name in queues:
126
+ if instance.queues and name not in instance.queues:
127
+ raise ValueError(f"queue {name!r} is not one of the QUEUES of task backend {backend!r}")
128
+
129
+ client = instance.client
130
+ consumer = consumer or default_consumer()
131
+ workers = [
132
+ Worker(
133
+ client,
134
+ instance.queue_for(name),
135
+ TaskHandler(backend, name, consumer),
136
+ consumer=consumer,
137
+ route=route,
138
+ wait_seconds=wait_seconds,
139
+ lease_seconds=lease_seconds,
140
+ max_messages=max_tasks,
141
+ max_seconds=max_seconds,
142
+ # Signals reach the main thread only; it stops every worker.
143
+ handle_signals=False,
144
+ )
145
+ for name in queues
146
+ ]
147
+ counts = [0] * len(workers)
148
+ crashed: list[BaseException] = []
149
+
150
+ def work(index: int) -> None:
151
+ try:
152
+ counts[index] = workers[index].run()
153
+ except BaseException as e:
154
+ # Not one queue left unattended in a process that looks alive: stop them all,
155
+ # and fail, so whatever supervises the process starts it again.
156
+ logger.exception("The worker of queue %s stopped; stopping the others", queues[index])
157
+ crashed.append(e)
158
+ for worker in workers:
159
+ worker.stop()
160
+ finally:
161
+ connections.close_all()
162
+
163
+ threads = [
164
+ threading.Thread(target=work, args=(i,), name=f"lessormq-{name}", daemon=True)
165
+ for i, name in enumerate(queues)
166
+ ]
167
+ restore = _trap_signals(workers) if handle_signals else None
168
+ try:
169
+ for thread in threads:
170
+ thread.start()
171
+ if on_ready is not None:
172
+ on_ready(workers)
173
+ for thread in threads:
174
+ # A timeout, so a signal handler gets to run between joins.
175
+ while thread.is_alive():
176
+ thread.join(0.5)
177
+ finally:
178
+ if restore is not None:
179
+ restore()
180
+ if crashed:
181
+ raise crashed[0]
182
+ return sum(counts)
183
+
184
+
185
+ def default_consumer() -> str:
186
+ """The host and the process, as the LessorMQ clients name a worker."""
187
+ return f"{socket.gethostname()}:{os.getpid()}"
188
+
189
+
190
+ def _trap_signals(workers: list[Worker]) -> Callable[[], None] | None:
191
+ if threading.current_thread() is not threading.main_thread():
192
+ return None
193
+ stops = [s for s in (getattr(signal, "SIGTERM", None), signal.SIGINT) if s is not None]
194
+ previous = {sig: signal.getsignal(sig) for sig in stops}
195
+
196
+ def stop(*_: object) -> None:
197
+ logger.info("Stopping after the current tasks")
198
+ for worker in workers:
199
+ worker.stop()
200
+
201
+ for sig in stops:
202
+ signal.signal(sig, stop)
203
+
204
+ def restore() -> None:
205
+ for sig, handler in previous.items():
206
+ signal.signal(sig, handler)
207
+
208
+ return restore
@@ -0,0 +1,225 @@
1
+ Metadata-Version: 2.5
2
+ Name: lessormq-django
3
+ Version: 0.4.10
4
+ Summary: A Django tasks backend for LessorMQ, the message queue over HTTP where the server decides and workers only claim, run, ack or fail
5
+ Project-URL: Homepage, https://lessormq.dev
6
+ Project-URL: Documentation, https://github.com/gsid-nl/lessormq/tree/main/clients/django
7
+ Project-URL: Source, https://github.com/gsid-nl/lessormq
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: django,job-queue,lessormq,message-queue,tasks,worker
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Django :: 6.0
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: System :: Distributed Computing
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: django>=6.0
21
+ Requires-Dist: lessormq>=0.4.10
22
+ Provides-Extra: dev
23
+ Requires-Dist: django-stubs>=5.2; extra == 'dev'
24
+ Requires-Dist: mypy>=1.10; extra == 'dev'
25
+ Requires-Dist: pytest-django>=4.9; extra == 'dev'
26
+ Requires-Dist: pytest>=8; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # LessorMQ for Django
30
+
31
+ A backend for Django's tasks framework (`django.tasks`) on [LessorMQ](https://lessormq.dev),
32
+ the message queue over HTTP where the server decides and workers only claim, run, ack or
33
+ fail. `enqueue()` publishes a task to a LessorMQ queue and `manage.py lessormq_worker`
34
+ runs it. Retries, backoff and the dead-letter set are settings of the queue on the
35
+ server, not of Django or of the worker.
36
+
37
+ The package is `lessormq-django`. It needs Django 6.0 or later (the first with
38
+ `django.tasks`), and so Python 3.12 or later, and builds on `lessormq`, the
39
+ [Python client](https://github.com/gsid-nl/lessormq/tree/main/clients/python).
40
+
41
+ ## Install
42
+
43
+ ```sh
44
+ pip install lessormq-django
45
+ ```
46
+
47
+ Add the app, for its management command:
48
+
49
+ ```python
50
+ INSTALLED_APPS = [
51
+ # ...
52
+ "lessormq_django",
53
+ ]
54
+ ```
55
+
56
+ ## Configure
57
+
58
+ ```python
59
+ TASKS = {
60
+ "default": {
61
+ "BACKEND": "lessormq_django.LessorMQBackend",
62
+ "QUEUES": ["default", "mail"],
63
+ "OPTIONS": {
64
+ "URL": "https://mq.example.com",
65
+ "API_KEY": os.environ["LESSORMQ_KEY"],
66
+ "QUEUE_PREFIX": "shop-",
67
+ },
68
+ }
69
+ }
70
+ ```
71
+
72
+ | Option | Default | |
73
+ |---|---|---|
74
+ | `URL` | required | the server |
75
+ | `API_KEY` | required | a key with the `publish` scope (to enqueue and read results) and the `consume` scope (to run workers); web processes and workers may have different keys |
76
+ | `QUEUE_PREFIX` | `""` | put before each Django queue name: queue `mail` is LessorMQ queue `shop-mail` |
77
+ | `CLIENT` | `{}` | keyword arguments for `lessormq.Client`: `timeout`, `http_retries`, `retry_delay`, `http` (an `httpx.Client` of your own) |
78
+
79
+ There is no option for retries, delays or dead-lettering: set those on the queue
80
+ (`PATCH /v1/queues/{queue}`, see [queue settings](https://lessormq.dev/docs/concepts)).
81
+ `manage.py check` reports a backend without `URL` or `API_KEY`, and a queue name that
82
+ LessorMQ does not accept (letters, digits, `.`, `_` and `-`).
83
+
84
+ ## Dispatch
85
+
86
+ ```python
87
+ from django.db import transaction
88
+ from django.tasks import task
89
+ from lessormq_django import PermanentFailure
90
+
91
+
92
+ @task(queue_name="mail")
93
+ def send_invoice(invoice_id: int) -> None:
94
+ invoice = Invoice.objects.filter(pk=invoice_id).first()
95
+ if invoice is None:
96
+ raise PermanentFailure(f"no invoice {invoice_id}")
97
+ mailer.send(invoice)
98
+
99
+
100
+ result = send_invoice.enqueue(1042)
101
+ result.id # the LessorMQ message id
102
+ ```
103
+
104
+ - Arguments are JSON, as for every Django backend. The message body is plain JSON, so
105
+ it reads as what it is in the queue and in the dead-letter set:
106
+ `{"task": "shop.tasks.send_invoice", "args": [1042], "kwargs": {}}`.
107
+ - `send_invoice.using(run_after=timezone.now() + timedelta(minutes=10)).enqueue(1042)`
108
+ holds the task back: `run_after` becomes the message's `available_at`.
109
+ - Enqueue after the transaction that wrote the data commits, or a worker may run the
110
+ task before the row exists: `transaction.on_commit(lambda: send_invoice.enqueue(invoice.pk))`.
111
+ - `await send_invoice.aenqueue(1042)` from async code; async tasks (`async def`) run too.
112
+ - Every enqueue carries a dedup key the client makes up, so a publish it retries after
113
+ a network error never creates a second message.
114
+
115
+ ## Run workers
116
+
117
+ ```sh
118
+ python manage.py lessormq_worker
119
+ python manage.py lessormq_worker --queue mail --route vpn-2
120
+ ```
121
+
122
+ | Option | Default | |
123
+ |---|---|---|
124
+ | `--backend` | `default` | the task backend in `TASKS` |
125
+ | `--queue` | every queue in `QUEUES` | a Django queue name; repeat it for more |
126
+ | `--consumer` | host:pid | the worker's name in the server's list of workers |
127
+ | `--route` | none | the path this worker runs tasks through (VPN exit, proxy, account), see [routes](https://lessormq.dev/docs/concepts) |
128
+ | `--wait-seconds` | 20 | long-poll wait per claim, at most 20 |
129
+ | `--lease-seconds` | the queue's | lease per claim, and per extension |
130
+ | `--max-tasks` | none | stop each queue's worker after this many tasks |
131
+ | `--max-seconds` | none | stop after running this long |
132
+
133
+ Each queue gets a thread that runs its tasks one at a time; run more processes for more
134
+ at once. SIGTERM and SIGINT stop the worker after the tasks it is running. A claim that
135
+ is waiting finishes its wait first, so give the process a grace period of
136
+ `--wait-seconds` plus the longest task (in Kubernetes, `terminationGracePeriodSeconds`).
137
+
138
+ ## How it behaves
139
+
140
+ The worker is the Python client's `Worker`. The queue decides everything that happens
141
+ after a failure; the worker only reports it.
142
+
143
+ | Django | LessorMQ |
144
+ |---|---|
145
+ | a task returns | the message is acked |
146
+ | a task raises | the message is failed with the exception's class and message; the queue's `backoff` and `max_attempts` decide whether and when it runs again, and when it goes to the dead-letter set |
147
+ | `PermanentFailure` raised (or mixed into your exception: `class BadInput(ValueError, PermanentFailure)`) | failed as permanent; the queue's `on_permanent` decides (by default: the dead-letter set at once) |
148
+ | retries, backoff, max attempts | none in Django: the queue's settings are the only ones |
149
+ | `context.attempt` (`takes_context=True`) | the server's attempt number, counting this one |
150
+ | `run_after` | the message's `available_at` |
151
+ | `priority` | not supported: a priority other than 0 raises `InvalidTask`. LessorMQ hands out messages roughly in order of availability |
152
+ | `queue_name` | the LessorMQ queue, after `QUEUE_PREFIX` |
153
+ | timeouts | none in Django. The worker extends the lease every third of it while a task runs; a worker that dies stops extending, the lease runs out, the attempt counts and another worker gets the message |
154
+ | failed tasks | the queue's dead-letter set (status `failed`), kept for the queue's retention; inspect and replay them with the admin API |
155
+ | signals | `task_enqueued` on enqueue; `task_started` and `task_finished` for every attempt, also an attempt the queue will try again |
156
+
157
+ - A message that is not a Django task (not a JSON object with a task path, a list of
158
+ args and an object of kwargs) is failed as permanent, with type
159
+ `lessormq_django.exceptions.MalformedTask`.
160
+ - A task this worker cannot import is an ordinary failure (`UnknownTask`), not a
161
+ permanent one: during a deploy a worker with the old code can claim a task only the
162
+ new code has, and the next attempt can land on a worker that knows it.
163
+ - A return value that is not JSON fails the task, as in Django's own backends. The
164
+ value itself is not kept anywhere.
165
+ - Database connections are closed around each task when they are stale or broken, as
166
+ around a request (`CONN_MAX_AGE`).
167
+ - Delivery is at least once: a task can run twice, when its lease ran out under a slow
168
+ worker or an ack got lost. Make tasks safe to repeat.
169
+
170
+ ### Results
171
+
172
+ `get_result()` and `refresh()` read the message back with `API_KEY`: the `publish` scope
173
+ may read the messages of its queues. The result is the message as the server has it:
174
+
175
+ | `TaskResult` | from the message |
176
+ |---|---|
177
+ | `status` | `pending`: `READY`, `processing`: `RUNNING`, `completed`: `SUCCESSFUL`, `failed`: `FAILED` (the dead-letter set) |
178
+ | `attempts`, `worker_ids` | one entry per attempt; the server names the worker of the last claim only, the others are empty |
179
+ | `errors` | the last error only, with the class the worker reported and where it was raised; an attempt whose lease ran out is `lessormq_django.LeaseExpired` |
180
+ | `enqueued_at` | `created_at` |
181
+ | `started_at`, `last_attempted_at` | when the current or last attempt was claimed; none while the task waits for its next attempt |
182
+ | `finished_at` | `completed_at` or `failed_at` |
183
+ | `return_value` | LessorMQ keeps no return values: a successful result raises `NotImplementedError` (instead of answering `None`). Store what a task produces yourself |
184
+
185
+ A message that is gone (after the queue's retention, discarded, or deleted) raises
186
+ `TaskResultDoesNotExist`.
187
+
188
+ ## Moving from another queue
189
+
190
+ - From Celery: `@shared_task` becomes `@task`, `.delay()` becomes `.enqueue()`,
191
+ `apply_async(countdown=60)` becomes `.using(run_after=timezone.now() + timedelta(seconds=60)).enqueue()`.
192
+ Drop `autoretry_for`, `max_retries`, `retry_backoff` and `self.retry()`: let the task
193
+ raise, and set the queue's `max_attempts` and `backoff` to what they did.
194
+ `AsyncResult.get()` has no counterpart: a task that produces something stores it.
195
+ - From another `django.tasks` backend: change `BACKEND`, and run `lessormq_worker`
196
+ instead of that backend's worker. Retry settings of that backend move to the queue.
197
+ - Side by side: configure both backends in `TASKS` (say `"default"` the old one and
198
+ `"lessormq"` this one) and move tasks one at a time, with `@task(backend="lessormq")`
199
+ or `.using(backend="lessormq")`. Remove the old backend once its queue is empty.
200
+ - Workers on different network paths (VPN exits, proxies) pass `--route`, and the queue's
201
+ `route_policy` keeps a message away from a route it failed on.
202
+
203
+ ## Development
204
+
205
+ ```sh
206
+ cd clients/django
207
+ python3 -m venv .venv
208
+ .venv/bin/pip install -e ../python -e '.[dev]'
209
+ .venv/bin/pytest
210
+ .venv/bin/mypy
211
+ ```
212
+
213
+ The unit tests run the backend and the worker against a scripted server. The end-to-end
214
+ tests run against a real server, in a tenant of their own that they remove afterwards:
215
+ a task run and acked, a failing task back after the queue's backoff with the server's
216
+ attempt count and then in the dead-letter set, a permanent failure there at once, and
217
+ `run_after`. Without these variables they are skipped:
218
+
219
+ ```sh
220
+ LESSORMQ_URL=http://127.0.0.1:8080 LESSORMQ_OPERATOR_KEY=lmq_... .venv/bin/pytest tests/test_end_to_end.py
221
+ ```
222
+
223
+ The protocol calls are the Python client's, which passes the
224
+ [conformance suite](https://github.com/gsid-nl/lessormq/tree/main/conformance) through
225
+ `clients/python/tests/conformance_adapter.py`.
@@ -0,0 +1,14 @@
1
+ lessormq_django/__init__.py,sha256=2XmPtrQwNLMYFXiab5BVaRHuMbjiTRo0_MQ82G0xnIk,744
2
+ lessormq_django/_messages.py,sha256=hB0NeT5UTsUySiZIeyWZkWBloST809jKdT_XDFfjC8w,1715
3
+ lessormq_django/apps.py,sha256=ZCIgpcgE3NaajwxgKA1a34nmN8ZoC6DXTsWbNJlTHRs,128
4
+ lessormq_django/backend.py,sha256=V3SQ_uU72Yh8xOS0CeGXZXqVOQ1IZ34bh2NIfAFpI3c,13078
5
+ lessormq_django/exceptions.py,sha256=uNmvEFedVVrpwk-NiJnEbAHKQy2N1lhZDJpWHponCQc,991
6
+ lessormq_django/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ lessormq_django/worker.py,sha256=gcWbvhV2ILo7WHozb8CcxojE1MU-u21nrKBEyJu6wmo,7693
8
+ lessormq_django/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ lessormq_django/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ lessormq_django/management/commands/lessormq_worker.py,sha256=YG9dZ9dAEy83sfBvEIoiecfm3WQwXZAcfZRVaIAwJ7Q,3285
11
+ lessormq_django-0.4.10.dist-info/METADATA,sha256=3fieMc5ydKmtAgFCsrCbc9EU5djCdDVawr9nlG3YX00,10925
12
+ lessormq_django-0.4.10.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ lessormq_django-0.4.10.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
14
+ lessormq_django-0.4.10.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.