lessormq-celery 0.4.9__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.
- lessormq_celery/__init__.py +25 -0
- lessormq_celery/checks.py +51 -0
- lessormq_celery/py.typed +0 -0
- lessormq_celery/request.py +116 -0
- lessormq_celery/task.py +120 -0
- lessormq_celery/transport.py +537 -0
- lessormq_celery-0.4.9.dist-info/METADATA +206 -0
- lessormq_celery-0.4.9.dist-info/RECORD +10 -0
- lessormq_celery-0.4.9.dist-info/WHEEL +4 -0
- lessormq_celery-0.4.9.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""LessorMQ for Celery: a kombu transport and a base task that leave retries, backoff
|
|
2
|
+
and the dead-letter set to the LessorMQ server.
|
|
3
|
+
|
|
4
|
+
import lessormq_celery
|
|
5
|
+
|
|
6
|
+
app = Celery("shop", task_cls=lessormq_celery.Task, broker="lessormq://mq.example.com")
|
|
7
|
+
app.conf.broker_transport_options = {"api_key": os.environ["LESSORMQ_KEY"]}
|
|
8
|
+
|
|
9
|
+
Importing this package registers the ``lessormq`` broker URL scheme with kombu.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from kombu.transport import TRANSPORT_ALIASES
|
|
13
|
+
|
|
14
|
+
from lessormq import PermanentFailure
|
|
15
|
+
|
|
16
|
+
from . import checks # noqa: F401 (connects the worker's startup check)
|
|
17
|
+
from .request import Request, ServerRetry
|
|
18
|
+
from .task import Task
|
|
19
|
+
from .transport import MalformedMessage, Transport
|
|
20
|
+
|
|
21
|
+
TRANSPORT_ALIASES.setdefault("lessormq", "lessormq_celery.transport:Transport")
|
|
22
|
+
|
|
23
|
+
__all__ = ["MalformedMessage", "PermanentFailure", "Request", "ServerRetry", "Task", "Transport"]
|
|
24
|
+
|
|
25
|
+
__version__ = "0.4.9"
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""The worker refuses to start on LessorMQ with a task that would decide about retries
|
|
2
|
+
itself or ack before it ran, or with a result backend that needs broadcast queues."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from celery.exceptions import ImproperlyConfigured
|
|
10
|
+
from celery.signals import worker_init
|
|
11
|
+
|
|
12
|
+
from .task import Task
|
|
13
|
+
from .transport import Transport
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger("lessormq_celery")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def problems(app: Any) -> list[str]:
|
|
19
|
+
"""What keeps ``app`` from running on LessorMQ, one line each."""
|
|
20
|
+
found = []
|
|
21
|
+
for name, task in sorted(app.tasks.items()):
|
|
22
|
+
if not isinstance(task, Task):
|
|
23
|
+
found.append(
|
|
24
|
+
f"task {name} does not derive from lessormq_celery.Task: create the app with "
|
|
25
|
+
"Celery(..., task_cls=lessormq_celery.Task), and derive a base= class from it"
|
|
26
|
+
)
|
|
27
|
+
continue
|
|
28
|
+
if not task.acks_late:
|
|
29
|
+
found.append(f"task {name} has acks_late off: it would ack its message before it runs")
|
|
30
|
+
if getattr(task, "retry_on_worker_lost", False):
|
|
31
|
+
found.append(f"task {name} has retry_on_worker_lost on: the queue decides about retries")
|
|
32
|
+
backend = str(app.conf.result_backend or "")
|
|
33
|
+
if backend.startswith("rpc"):
|
|
34
|
+
found.append("result_backend rpc:// sends results through broker queues; use another result backend")
|
|
35
|
+
return found
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@worker_init.connect(weak=False)
|
|
39
|
+
def check_worker(sender: Any = None, **kwargs: Any) -> None:
|
|
40
|
+
app = getattr(sender, "app", None)
|
|
41
|
+
if app is None or not isinstance(app.connection_for_read().transport, Transport):
|
|
42
|
+
return
|
|
43
|
+
found = problems(app)
|
|
44
|
+
if found:
|
|
45
|
+
raise ImproperlyConfigured("Not ready for LessorMQ:\n- " + "\n- ".join(found))
|
|
46
|
+
if (app.conf.worker_prefetch_multiplier or 0) > 1:
|
|
47
|
+
logger.warning(
|
|
48
|
+
"worker_prefetch_multiplier is %s: each process holds that many messages, leased and kept alive, "
|
|
49
|
+
"that idle workers cannot have; 1 is usually better on LessorMQ",
|
|
50
|
+
app.conf.worker_prefetch_multiplier,
|
|
51
|
+
)
|
lessormq_celery/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""The worker side of a delivery: tells the transport what it came to.
|
|
2
|
+
|
|
3
|
+
Celery settles a message with an ack or a reject, and acks a task that failed as well
|
|
4
|
+
(``task_acks_on_failure_or_timeout``). Only the Request, in the worker's main process,
|
|
5
|
+
sees why: the exception, a retry, a lost child process, a time limit. It tells the
|
|
6
|
+
transport, which then fails the message (the queue decides what follows), acks it, or
|
|
7
|
+
releases it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from billiard.einfo import ExceptionWithTraceback
|
|
15
|
+
from celery.exceptions import Ignore, Reject, Retry, Terminated, TimeLimitExceeded, WorkerLostError
|
|
16
|
+
from celery.utils.serialization import UnpickleableExceptionWrapper
|
|
17
|
+
from celery.worker.request import Request as CeleryRequest
|
|
18
|
+
|
|
19
|
+
from lessormq import PermanentFailure
|
|
20
|
+
|
|
21
|
+
from .transport import Outcome
|
|
22
|
+
|
|
23
|
+
__all__ = ["Request", "ServerRetry", "outcome_of"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ServerRetry(Retry):
|
|
27
|
+
"""A failed attempt that is not the last: Celery records state RETRY, and the
|
|
28
|
+
transport fails the message. When it runs again is the queue's backoff, not
|
|
29
|
+
``countdown`` or ``eta``.
|
|
30
|
+
|
|
31
|
+
Raised by :meth:`lessormq_celery.Task.retry`, and for any exception of an attempt
|
|
32
|
+
the queue will try again.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def humanize(self) -> str:
|
|
36
|
+
return "after the queue's backoff"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Request(CeleryRequest):
|
|
40
|
+
"""Celery's Request, telling the transport what each delivery came to."""
|
|
41
|
+
|
|
42
|
+
def on_accepted(self, pid: int, time_accepted: float) -> None:
|
|
43
|
+
self._tell("lessormq_running")
|
|
44
|
+
super().on_accepted(pid, time_accepted)
|
|
45
|
+
|
|
46
|
+
def on_timeout(self, soft: bool, timeout: float) -> None:
|
|
47
|
+
if not soft:
|
|
48
|
+
# The hard limit killed the child: a failed attempt, whether Celery acks or
|
|
49
|
+
# rejects it next.
|
|
50
|
+
self._tell("lessormq_outcome", Outcome.fail(TimeLimitExceeded(timeout)))
|
|
51
|
+
super().on_timeout(soft, timeout)
|
|
52
|
+
|
|
53
|
+
def on_failure(self, exc_info: Any, send_failed_event: bool = True, return_ok: bool = False) -> None:
|
|
54
|
+
outcome = outcome_of(exc_info)
|
|
55
|
+
if outcome is not None:
|
|
56
|
+
self._tell("lessormq_outcome", outcome)
|
|
57
|
+
super().on_failure(exc_info, send_failed_event, return_ok)
|
|
58
|
+
|
|
59
|
+
def acknowledge(self) -> None:
|
|
60
|
+
# An ack nothing explained is a success (or an expired task, or Ignore).
|
|
61
|
+
if not self.acknowledged:
|
|
62
|
+
self._tell("lessormq_outcome", Outcome.ack(), replace=False)
|
|
63
|
+
super().acknowledge()
|
|
64
|
+
|
|
65
|
+
def reject(self, requeue: bool = False) -> None:
|
|
66
|
+
if not self.acknowledged and requeue:
|
|
67
|
+
self._tell("lessormq_outcome", Outcome.release(), replace=False)
|
|
68
|
+
super().reject(requeue)
|
|
69
|
+
|
|
70
|
+
def _tell(self, what: str, *args: Any, **kwargs: Any) -> None:
|
|
71
|
+
message = self.message
|
|
72
|
+
method = getattr(getattr(message, "channel", None), what, None)
|
|
73
|
+
if method is not None:
|
|
74
|
+
method(message.delivery_tag, *args, **kwargs)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def outcome_of(exc_info: Any) -> Outcome | None:
|
|
78
|
+
"""What a task's exception means for its message."""
|
|
79
|
+
exc = exc_info.exception
|
|
80
|
+
if isinstance(exc, ExceptionWithTraceback):
|
|
81
|
+
exc = exc.exc
|
|
82
|
+
details = {"traceback": exc_info.traceback} if getattr(exc_info, "traceback", None) else None
|
|
83
|
+
|
|
84
|
+
if isinstance(exc, ServerRetry):
|
|
85
|
+
return _fail(exc.exc if isinstance(exc.exc, BaseException) else exc, details)
|
|
86
|
+
if isinstance(exc, Retry):
|
|
87
|
+
# Celery's own retry, kept for its built-in tasks (chord_unlock polls this way):
|
|
88
|
+
# it published the next run itself.
|
|
89
|
+
return Outcome.ack()
|
|
90
|
+
if isinstance(exc, Reject):
|
|
91
|
+
if exc.requeue:
|
|
92
|
+
return Outcome.release()
|
|
93
|
+
if isinstance(exc.reason, BaseException):
|
|
94
|
+
return _fail(exc.reason, details, permanent=True)
|
|
95
|
+
return Outcome.fail(
|
|
96
|
+
str(exc.reason or "rejected"), permanent=True, type="celery.exceptions.Reject", details=details
|
|
97
|
+
)
|
|
98
|
+
if isinstance(exc, Ignore):
|
|
99
|
+
return Outcome.ack()
|
|
100
|
+
if isinstance(exc, Terminated):
|
|
101
|
+
# Revoked with terminate: Celery leaves the message alone; so does the transport.
|
|
102
|
+
return None
|
|
103
|
+
if isinstance(exc, (SystemExit, KeyboardInterrupt)):
|
|
104
|
+
exc = WorkerLostError(f"Worker exited prematurely: {type(exc).__name__}.")
|
|
105
|
+
return _fail(exc, details)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _fail(error: BaseException, details: Any, *, permanent: bool | None = None) -> Outcome:
|
|
109
|
+
if permanent is None:
|
|
110
|
+
permanent = isinstance(error, PermanentFailure)
|
|
111
|
+
if isinstance(error, UnpickleableExceptionWrapper):
|
|
112
|
+
# The worker could not bring the exception over from the child: its class by name.
|
|
113
|
+
module, name = error.exc_module, error.exc_cls_name
|
|
114
|
+
kind = name if module == "builtins" else f"{module}.{name}"
|
|
115
|
+
return Outcome.fail(error.text or str(error), permanent=permanent, type=kind, details=details)
|
|
116
|
+
return Outcome.fail(error, permanent=permanent, details=details)
|
lessormq_celery/task.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""The base task for Celery on LessorMQ: retries are the queue's.
|
|
2
|
+
|
|
3
|
+
A failed attempt is reported to the server, which decides whether and when the task
|
|
4
|
+
runs again. So ``retry()`` publishes nothing: it raises :class:`ServerRetry`, which the
|
|
5
|
+
transport turns into a fail. Any other exception of an attempt the queue will try again
|
|
6
|
+
is a :class:`ServerRetry` too, so Celery records state RETRY and calls ``on_retry``; on
|
|
7
|
+
the last attempt (or for a permanent failure) the exception stays as it is, and Celery
|
|
8
|
+
records FAILURE.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import celery
|
|
18
|
+
from celery.exceptions import Ignore, Reject, Retry
|
|
19
|
+
|
|
20
|
+
from lessormq import PermanentFailure
|
|
21
|
+
|
|
22
|
+
from .request import ServerRetry
|
|
23
|
+
|
|
24
|
+
__all__ = ["Task"]
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger("lessormq_celery")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Task(celery.Task):
|
|
30
|
+
"""Use it as the app's task class: ``Celery("shop", task_cls=lessormq_celery.Task)``.
|
|
31
|
+
|
|
32
|
+
The worker refuses to start with a task that does not derive from it.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
# Ack (or fail) after the task ran, never before: an early ack would complete the
|
|
36
|
+
# message whatever the task does.
|
|
37
|
+
acks_late = True
|
|
38
|
+
# Celery would publish a copy after a lost child process; the server counts that
|
|
39
|
+
# attempt and decides instead.
|
|
40
|
+
retry_on_worker_lost = False
|
|
41
|
+
Request = "lessormq_celery.request:Request"
|
|
42
|
+
|
|
43
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
44
|
+
if not _from_lessormq(self.request):
|
|
45
|
+
return super().__call__(*args, **kwargs)
|
|
46
|
+
try:
|
|
47
|
+
return super().__call__(*args, **kwargs)
|
|
48
|
+
except (Retry, Ignore, Reject):
|
|
49
|
+
raise
|
|
50
|
+
except Exception as exc:
|
|
51
|
+
if isinstance(exc, PermanentFailure) or _last_attempt(self.request):
|
|
52
|
+
raise
|
|
53
|
+
raise ServerRetry(exc=exc) from exc
|
|
54
|
+
|
|
55
|
+
def retry(
|
|
56
|
+
self,
|
|
57
|
+
args: Any = None,
|
|
58
|
+
kwargs: Any = None,
|
|
59
|
+
exc: BaseException | None = None,
|
|
60
|
+
throw: bool = True,
|
|
61
|
+
eta: Any = None,
|
|
62
|
+
countdown: Any = None,
|
|
63
|
+
max_retries: int | None = None,
|
|
64
|
+
**options: Any,
|
|
65
|
+
) -> Any:
|
|
66
|
+
"""Fail this attempt; the queue decides whether and when the task runs again.
|
|
67
|
+
|
|
68
|
+
``countdown``, ``eta``, ``max_retries`` and new ``args`` or ``kwargs`` are
|
|
69
|
+
ignored: the queue's backoff and ``max_attempts`` decide, and the task runs again
|
|
70
|
+
with the arguments it was published with. Raises always, also with
|
|
71
|
+
``throw=False``, since an attempt that returns is acked and never runs again.
|
|
72
|
+
Outside a LessorMQ worker (called directly, eagerly) and for Celery's own tasks
|
|
73
|
+
(``celery.*``) it is Celery's ``retry``.
|
|
74
|
+
"""
|
|
75
|
+
request = self.request
|
|
76
|
+
if not _from_lessormq(request) or self.name.startswith("celery."):
|
|
77
|
+
return super().retry(args, kwargs, exc, throw, eta, countdown, max_retries, **options)
|
|
78
|
+
ignored = [
|
|
79
|
+
name
|
|
80
|
+
for name, value in (
|
|
81
|
+
("args", args),
|
|
82
|
+
("kwargs", kwargs),
|
|
83
|
+
("eta", eta),
|
|
84
|
+
("countdown", countdown),
|
|
85
|
+
("max_retries", max_retries),
|
|
86
|
+
)
|
|
87
|
+
if value is not None
|
|
88
|
+
] + sorted(options)
|
|
89
|
+
if (ignored or not throw) and self.name not in _warned:
|
|
90
|
+
_warned.add(self.name)
|
|
91
|
+
logger.warning(
|
|
92
|
+
"%s.retry(): %s ignored; the queue's backoff and max_attempts decide",
|
|
93
|
+
self.name,
|
|
94
|
+
", ".join(ignored + ([] if throw else ["throw=False"])),
|
|
95
|
+
)
|
|
96
|
+
if exc is None:
|
|
97
|
+
exc = sys.exc_info()[1]
|
|
98
|
+
if _last_attempt(request):
|
|
99
|
+
# The queue gives up after this attempt: Celery records FAILURE.
|
|
100
|
+
if exc is not None:
|
|
101
|
+
raise exc
|
|
102
|
+
raise self.MaxRetriesExceededError(f"{self.name}[{request.id}]: the last attempt asked for a retry")
|
|
103
|
+
raise ServerRetry(exc=exc)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# Tasks whose ignored retry() arguments were logged, once per process.
|
|
107
|
+
_warned: set[str] = set()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _from_lessormq(request: Any) -> bool:
|
|
111
|
+
"""Whether this run is a delivery of the LessorMQ transport, which puts the server's
|
|
112
|
+
attempt counts into the headers."""
|
|
113
|
+
return request is not None and not request.called_directly and request.get("lessormq_attempt") is not None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _last_attempt(request: Any) -> bool:
|
|
117
|
+
try:
|
|
118
|
+
return int(request.get("lessormq_attempt")) >= int(request.get("lessormq_max_attempts"))
|
|
119
|
+
except (TypeError, ValueError):
|
|
120
|
+
return False
|
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
"""A kombu transport on LessorMQ, for Celery.
|
|
2
|
+
|
|
3
|
+
The server decides about every message: when a failed one runs again, how often, and
|
|
4
|
+
when it goes to the dead-letter set. This transport only publishes, claims, and settles
|
|
5
|
+
each delivery with an ack, a fail or a release. Which of those a delivery comes to is
|
|
6
|
+
told by :class:`lessormq_celery.Request`, from what the task did; kombu's ack and reject
|
|
7
|
+
alone cannot say that a task failed. While the worker holds a message (running, or
|
|
8
|
+
waiting in its prefetch buffer) a thread extends the lease.
|
|
9
|
+
|
|
10
|
+
broker_url = "lessormq://mq.example.com" # HTTPS
|
|
11
|
+
broker_url = "lessormq+http://lessormq:8080" # plain HTTP, inside a cluster
|
|
12
|
+
broker_transport_options = {"api_key": os.environ["LESSORMQ_KEY"]}
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import base64
|
|
18
|
+
import binascii
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import os
|
|
22
|
+
import socket
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from datetime import datetime
|
|
27
|
+
from queue import Empty
|
|
28
|
+
from typing import Any
|
|
29
|
+
from urllib.parse import unquote, urlsplit
|
|
30
|
+
from uuid import uuid4
|
|
31
|
+
|
|
32
|
+
from kombu.transport import virtual
|
|
33
|
+
|
|
34
|
+
from lessormq import Client, Lease, LeaseLostError, LessorMQError, RateLimitedError, ServerError, TransportError
|
|
35
|
+
|
|
36
|
+
__all__ = ["Channel", "MalformedMessage", "Options", "Outcome", "Transport"]
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger("lessormq_celery")
|
|
39
|
+
|
|
40
|
+
USER_AGENT = "lessormq-celery/1"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class MalformedMessage(Exception):
|
|
44
|
+
"""A message on the queue that is not a kombu message this transport wrote.
|
|
45
|
+
|
|
46
|
+
Reported as permanent: no worker can run it.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Outcome:
|
|
52
|
+
"""What a delivery comes to: ``ack``, ``fail`` or ``release``.
|
|
53
|
+
|
|
54
|
+
For a fail, ``error`` is the exception (or a message, with ``type``), and
|
|
55
|
+
``permanent`` says the input itself is unusable. The server decides what follows.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
action: str
|
|
59
|
+
error: BaseException | str | None = None
|
|
60
|
+
permanent: bool = False
|
|
61
|
+
type: str | None = None
|
|
62
|
+
details: Any = None
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def ack() -> Outcome:
|
|
66
|
+
return Outcome("ack")
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def release() -> Outcome:
|
|
70
|
+
return Outcome("release")
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def fail(
|
|
74
|
+
error: BaseException | str, *, permanent: bool = False, type: str | None = None, details: Any = None
|
|
75
|
+
) -> Outcome:
|
|
76
|
+
return Outcome("fail", error, permanent, type, details)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Options:
|
|
81
|
+
"""The server, the key, and how the worker claims and keeps its leases. Retries are
|
|
82
|
+
the queue's business, so there is nothing about them here."""
|
|
83
|
+
|
|
84
|
+
url: str
|
|
85
|
+
api_key: str
|
|
86
|
+
wait_seconds: int = 5
|
|
87
|
+
lease_seconds: int | None = None
|
|
88
|
+
extend_every: float | None = None
|
|
89
|
+
consumer: str = ""
|
|
90
|
+
route: str | None = None
|
|
91
|
+
error_pause: float = 1.0
|
|
92
|
+
client: dict[str, Any] = field(default_factory=dict)
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def from_connection(cls, connection: Any) -> Options:
|
|
96
|
+
"""From the broker URL (``lessormq://``, ``lessormq+http://``, ``lessormq+https://``,
|
|
97
|
+
with the key as the password: ``lessormq://:KEY@host``) and the transport
|
|
98
|
+
options."""
|
|
99
|
+
raw = str(connection.hostname or "")
|
|
100
|
+
if "://" not in raw:
|
|
101
|
+
raw = "https://" + raw
|
|
102
|
+
parts = urlsplit(raw)
|
|
103
|
+
scheme = "http" if parts.scheme == "http" else "https"
|
|
104
|
+
host = parts.hostname or "localhost"
|
|
105
|
+
if ":" in host:
|
|
106
|
+
host = f"[{host}]"
|
|
107
|
+
url = f"{scheme}://{host}" + (f":{parts.port}" if parts.port else "")
|
|
108
|
+
if connection.port and not parts.port:
|
|
109
|
+
url += f":{connection.port}"
|
|
110
|
+
|
|
111
|
+
topts = dict(connection.transport_options or {})
|
|
112
|
+
api_key = topts.pop("api_key", None) or (unquote(parts.password) if parts.password else "")
|
|
113
|
+
lease_seconds = topts.pop("lease_seconds", None)
|
|
114
|
+
extend_every = topts.pop("extend_every", None)
|
|
115
|
+
client = {"user_agent": USER_AGENT}
|
|
116
|
+
for name in ("http_retries", "retry_delay", "timeout", "http"):
|
|
117
|
+
if name in topts:
|
|
118
|
+
client[name] = topts.pop(name)
|
|
119
|
+
return cls(
|
|
120
|
+
url=url,
|
|
121
|
+
api_key=str(api_key or ""),
|
|
122
|
+
wait_seconds=int(topts.pop("wait_seconds", 5)),
|
|
123
|
+
lease_seconds=int(lease_seconds) if lease_seconds is not None else None,
|
|
124
|
+
extend_every=float(extend_every) if extend_every is not None else None,
|
|
125
|
+
consumer=str(topts.pop("consumer", None) or f"{socket.gethostname()}:{os.getpid()}"),
|
|
126
|
+
route=topts.pop("route", None),
|
|
127
|
+
error_pause=float(topts.pop("error_pause", 1.0)),
|
|
128
|
+
client=client,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class _Held:
|
|
133
|
+
"""A delivery the worker holds: its lease, whether its task runs, and its outcome
|
|
134
|
+
once the Request has told it."""
|
|
135
|
+
|
|
136
|
+
def __init__(self, lease: Lease, interval: float) -> None:
|
|
137
|
+
self.lease = lease
|
|
138
|
+
self.interval = interval
|
|
139
|
+
self.next_extend = time.monotonic() + interval
|
|
140
|
+
self.running = False
|
|
141
|
+
self.lost = False
|
|
142
|
+
self.outcome: Outcome | None = None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class Channel(virtual.Channel):
|
|
146
|
+
"""Queues are LessorMQ queues; exchanges and bindings live in this process, as in
|
|
147
|
+
every virtual kombu transport."""
|
|
148
|
+
|
|
149
|
+
# No broadcast: remote control, events and broadcast queues are not carried.
|
|
150
|
+
supports_fanout = False
|
|
151
|
+
|
|
152
|
+
def __init__(self, connection: Any, **kwargs: Any) -> None:
|
|
153
|
+
super().__init__(connection, **kwargs)
|
|
154
|
+
self._transport = connection
|
|
155
|
+
self._held: dict[str, _Held] = {}
|
|
156
|
+
self._lock = threading.Lock()
|
|
157
|
+
self._keeper: threading.Thread | None = None
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def options(self) -> Options:
|
|
161
|
+
return self._transport.options # type: ignore[no-any-return]
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def lessormq(self) -> Client:
|
|
165
|
+
return self._transport.lessormq # type: ignore[no-any-return]
|
|
166
|
+
|
|
167
|
+
# What lessormq_celery.Request tells about a delivery.
|
|
168
|
+
|
|
169
|
+
def lessormq_running(self, delivery_tag: str) -> None:
|
|
170
|
+
"""The task of this delivery started: when the channel closes before it ends,
|
|
171
|
+
its message is not given back but settled when the task ends."""
|
|
172
|
+
with self._lock:
|
|
173
|
+
held = self._held.get(delivery_tag)
|
|
174
|
+
if held is not None:
|
|
175
|
+
held.running = True
|
|
176
|
+
|
|
177
|
+
def lessormq_outcome(self, delivery_tag: str, outcome: Outcome, *, replace: bool = True) -> None:
|
|
178
|
+
"""What the delivery comes to, applied when Celery acks or rejects it. With
|
|
179
|
+
``replace=False`` only when nothing was told before."""
|
|
180
|
+
with self._lock:
|
|
181
|
+
held = self._held.get(delivery_tag)
|
|
182
|
+
if held is not None and (replace or held.outcome is None):
|
|
183
|
+
held.outcome = outcome
|
|
184
|
+
|
|
185
|
+
# Publishing.
|
|
186
|
+
|
|
187
|
+
def _put(self, queue: str, message: dict[str, Any], **kwargs: Any) -> None:
|
|
188
|
+
body, headers, dedup_key, available_at = encode(message)
|
|
189
|
+
self.lessormq.publish(queue, body, headers=headers, dedup_key=dedup_key, available_at=available_at)
|
|
190
|
+
|
|
191
|
+
def _lookup(self, exchange: str, routing_key: str, default: str | None = None) -> list[str]:
|
|
192
|
+
queues: list[str] = super()._lookup(exchange, routing_key, default)
|
|
193
|
+
if not queues and exchange and routing_key and self.typeof(exchange).type == "direct":
|
|
194
|
+
# Bindings are only known in the process that declared them. A direct
|
|
195
|
+
# exchange without one for this key delivers to the queue of that name,
|
|
196
|
+
# rather than dropping the message.
|
|
197
|
+
return [routing_key]
|
|
198
|
+
return queues
|
|
199
|
+
|
|
200
|
+
# Consuming.
|
|
201
|
+
|
|
202
|
+
def _get(self, queue: str, timeout: float | None = None) -> dict[str, Any]:
|
|
203
|
+
options = self.options
|
|
204
|
+
try:
|
|
205
|
+
lease = self.lessormq.claim(
|
|
206
|
+
queue,
|
|
207
|
+
consumer=options.consumer,
|
|
208
|
+
route=options.route,
|
|
209
|
+
wait_seconds=options.wait_seconds,
|
|
210
|
+
lease_seconds=options.lease_seconds,
|
|
211
|
+
)
|
|
212
|
+
except LessorMQError as e:
|
|
213
|
+
# As the client's Worker: log, pause, claim again. The worker stays up while
|
|
214
|
+
# the server is away; leases it holds run out and the server counts them.
|
|
215
|
+
logger.error("Claim from %s failed: %s", queue, e)
|
|
216
|
+
time.sleep(options.error_pause)
|
|
217
|
+
raise Empty() from None
|
|
218
|
+
if lease is None:
|
|
219
|
+
raise Empty()
|
|
220
|
+
|
|
221
|
+
tag = uuid4().hex
|
|
222
|
+
try:
|
|
223
|
+
raw = decode(lease, tag)
|
|
224
|
+
except MalformedMessage as e:
|
|
225
|
+
logger.error("Message %s is not a kombu message; failing it as permanent", lease.message.id)
|
|
226
|
+
self._settle(_Held(lease, 0), Outcome.fail(e, permanent=True))
|
|
227
|
+
raise Empty() from None
|
|
228
|
+
self._hold(tag, lease)
|
|
229
|
+
return raw
|
|
230
|
+
|
|
231
|
+
def basic_ack(self, delivery_tag: str, multiple: bool = False) -> None:
|
|
232
|
+
held = self._take(delivery_tag)
|
|
233
|
+
if held is not None:
|
|
234
|
+
self._settle(held, held.outcome or Outcome.ack())
|
|
235
|
+
super().basic_ack(delivery_tag, multiple)
|
|
236
|
+
|
|
237
|
+
def basic_reject(self, delivery_tag: str, requeue: bool = False) -> None:
|
|
238
|
+
held = self._take(delivery_tag)
|
|
239
|
+
if held is not None:
|
|
240
|
+
default = Outcome.release() if requeue else _rejected()
|
|
241
|
+
self._settle(held, held.outcome or default)
|
|
242
|
+
# Settled above: kombu must not put the message back itself.
|
|
243
|
+
super().basic_reject(delivery_tag, requeue=False)
|
|
244
|
+
|
|
245
|
+
def _restore(self, message: Any) -> None:
|
|
246
|
+
"""kombu gives back what the worker holds when the channel closes (shutdown,
|
|
247
|
+
lost connection): a release, so the attempt does not count. A message whose task
|
|
248
|
+
is running stays held, and is settled when the task ends."""
|
|
249
|
+
tag = message.delivery_tag
|
|
250
|
+
with self._lock:
|
|
251
|
+
held = self._held.get(tag)
|
|
252
|
+
if held is None or held.running:
|
|
253
|
+
return
|
|
254
|
+
del self._held[tag]
|
|
255
|
+
self._settle(held, held.outcome or Outcome.release())
|
|
256
|
+
|
|
257
|
+
def _size(self, queue: str) -> int:
|
|
258
|
+
try:
|
|
259
|
+
return self.lessormq.stats(queue).ready
|
|
260
|
+
except LessorMQError:
|
|
261
|
+
return 0
|
|
262
|
+
|
|
263
|
+
def _purge(self, queue: str) -> int:
|
|
264
|
+
raise NotImplementedError("LessorMQ does not purge waiting messages; delete them with the admin API")
|
|
265
|
+
|
|
266
|
+
def _delete(self, queue: str, *args: Any, **kwargs: Any) -> None:
|
|
267
|
+
# A queue exists from its first message on, and stays.
|
|
268
|
+
pass
|
|
269
|
+
|
|
270
|
+
def _has_queue(self, queue: str, **kwargs: Any) -> bool:
|
|
271
|
+
return True
|
|
272
|
+
|
|
273
|
+
# Leases.
|
|
274
|
+
|
|
275
|
+
def _hold(self, tag: str, lease: Lease) -> None:
|
|
276
|
+
interval = self.options.extend_every or max(1.0, lease.seconds_left() / 3)
|
|
277
|
+
with self._lock:
|
|
278
|
+
self._held[tag] = _Held(lease, interval)
|
|
279
|
+
if self._keeper is None:
|
|
280
|
+
self._keeper = threading.Thread(target=self._keep, name="lessormq-extend", daemon=True)
|
|
281
|
+
self._keeper.start()
|
|
282
|
+
|
|
283
|
+
def _take(self, tag: str) -> _Held | None:
|
|
284
|
+
with self._lock:
|
|
285
|
+
return self._held.pop(tag, None)
|
|
286
|
+
|
|
287
|
+
def _keep(self) -> None:
|
|
288
|
+
"""Extend every held lease when it is due, until none is held."""
|
|
289
|
+
while True:
|
|
290
|
+
now = time.monotonic()
|
|
291
|
+
with self._lock:
|
|
292
|
+
if not self._held:
|
|
293
|
+
self._keeper = None
|
|
294
|
+
return
|
|
295
|
+
due = [held for held in self._held.values() if not held.lost and held.next_extend <= now]
|
|
296
|
+
for held in due:
|
|
297
|
+
try:
|
|
298
|
+
self.lessormq.extend(held.lease, self.options.lease_seconds)
|
|
299
|
+
held.next_extend = time.monotonic() + held.interval
|
|
300
|
+
except LeaseLostError:
|
|
301
|
+
held.lost = True
|
|
302
|
+
except LessorMQError as e:
|
|
303
|
+
logger.warning("Extend failed; trying again: %s", e)
|
|
304
|
+
held.next_extend = time.monotonic() + min(held.interval, 1.0)
|
|
305
|
+
time.sleep(0.2)
|
|
306
|
+
|
|
307
|
+
def _settle(self, held: _Held, outcome: Outcome) -> None:
|
|
308
|
+
"""Ack, fail or release, keeping the worker alive whatever happens: a lost lease
|
|
309
|
+
means the message is someone else's now; any other failure means the lease will
|
|
310
|
+
expire and the server will make the message available again."""
|
|
311
|
+
lease = held.lease
|
|
312
|
+
if held.lost:
|
|
313
|
+
logger.warning(
|
|
314
|
+
"Lease of %s lost before %s; the message is no longer ours", lease.message.id, outcome.action
|
|
315
|
+
)
|
|
316
|
+
return
|
|
317
|
+
try:
|
|
318
|
+
if outcome.action == "ack":
|
|
319
|
+
self.lessormq.ack(lease)
|
|
320
|
+
elif outcome.action == "release":
|
|
321
|
+
self.lessormq.release(lease)
|
|
322
|
+
else:
|
|
323
|
+
error = outcome.error if outcome.error is not None else "(no message)"
|
|
324
|
+
result = self.lessormq.fail(
|
|
325
|
+
lease, error, permanent=outcome.permanent, type=outcome.type, details=outcome.details
|
|
326
|
+
)
|
|
327
|
+
logger.info(
|
|
328
|
+
"Message %s failed (%s), attempt %d of %d: %s",
|
|
329
|
+
lease.message.id,
|
|
330
|
+
result.outcome,
|
|
331
|
+
result.attempt,
|
|
332
|
+
result.max_attempts,
|
|
333
|
+
error,
|
|
334
|
+
)
|
|
335
|
+
except LeaseLostError:
|
|
336
|
+
logger.warning(
|
|
337
|
+
"Lease of %s lost before %s; the message is no longer ours", lease.message.id, outcome.action
|
|
338
|
+
)
|
|
339
|
+
except LessorMQError as e:
|
|
340
|
+
logger.error(
|
|
341
|
+
"%s of %s failed; the lease will expire and the message come back: %s",
|
|
342
|
+
outcome.action.capitalize(),
|
|
343
|
+
lease.message.id,
|
|
344
|
+
e,
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class Transport(virtual.Transport):
|
|
349
|
+
"""kombu transport ``lessormq``, registered when :mod:`lessormq_celery` is imported."""
|
|
350
|
+
|
|
351
|
+
Channel = Channel
|
|
352
|
+
|
|
353
|
+
driver_type = "lessormq"
|
|
354
|
+
driver_name = "lessormq"
|
|
355
|
+
# The whole URL reaches the transport, which reads the scheme, host and key itself.
|
|
356
|
+
can_parse_url = True
|
|
357
|
+
# Claims wait on the server (wait_seconds); this pause only applies while the
|
|
358
|
+
# worker's prefetch buffer is full.
|
|
359
|
+
polling_interval = 0.2
|
|
360
|
+
|
|
361
|
+
implements = virtual.Transport.implements.extend(
|
|
362
|
+
asynchronous=False,
|
|
363
|
+
exchange_type=frozenset(["direct", "topic"]),
|
|
364
|
+
heartbeats=False,
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
# Celery retries a publish on these, as the client already did (with the same dedup
|
|
368
|
+
# key, so never twice).
|
|
369
|
+
connection_errors = virtual.Transport.connection_errors + ( # type: ignore[assignment]
|
|
370
|
+
TransportError,
|
|
371
|
+
ServerError,
|
|
372
|
+
RateLimitedError,
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
def __init__(self, client: Any, **kwargs: Any) -> None:
|
|
376
|
+
super().__init__(client, **kwargs)
|
|
377
|
+
self.options = Options.from_connection(client)
|
|
378
|
+
self._lessormq: Client | None = None
|
|
379
|
+
self._lessormq_lock = threading.Lock()
|
|
380
|
+
|
|
381
|
+
@property
|
|
382
|
+
def lessormq(self) -> Client:
|
|
383
|
+
"""The LessorMQ client of this connection, shared by its channels."""
|
|
384
|
+
with self._lessormq_lock:
|
|
385
|
+
if self._lessormq is None:
|
|
386
|
+
if not self.options.api_key:
|
|
387
|
+
raise ValueError(
|
|
388
|
+
"LessorMQ needs an API key: broker_transport_options['api_key'], or the URL's password "
|
|
389
|
+
"(lessormq://:KEY@host)"
|
|
390
|
+
)
|
|
391
|
+
self._lessormq = Client(self.options.url, self.options.api_key, **self.options.client)
|
|
392
|
+
return self._lessormq
|
|
393
|
+
|
|
394
|
+
def driver_version(self) -> str:
|
|
395
|
+
from lessormq import __version__
|
|
396
|
+
|
|
397
|
+
return __version__
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def encode(message: dict[str, Any]) -> tuple[dict[str, Any], dict[str, str], str | None, datetime | None]:
|
|
401
|
+
"""A kombu message as a LessorMQ message: the body, the headers, the dedup key and
|
|
402
|
+
when it becomes available.
|
|
403
|
+
|
|
404
|
+
A JSON task stays JSON in the body (``payload``), so it reads as what it is in the
|
|
405
|
+
queue and the dead-letter set; any other body is kept as base64 (``body``).
|
|
406
|
+
"""
|
|
407
|
+
properties = dict(message.get("properties") or {})
|
|
408
|
+
encoding = properties.pop("body_encoding", None)
|
|
409
|
+
properties.pop("delivery_tag", None)
|
|
410
|
+
properties.pop("delivery_info", None)
|
|
411
|
+
raw = message.get("body")
|
|
412
|
+
data: bytes
|
|
413
|
+
if encoding == "base64":
|
|
414
|
+
data = base64.b64decode(raw or b"")
|
|
415
|
+
elif isinstance(raw, str):
|
|
416
|
+
data = raw.encode(message.get("content-encoding") or "utf-8")
|
|
417
|
+
else:
|
|
418
|
+
data = bytes(raw or b"")
|
|
419
|
+
|
|
420
|
+
headers = dict(message.get("headers") or {})
|
|
421
|
+
content_type = message.get("content-type")
|
|
422
|
+
content_encoding = message.get("content-encoding")
|
|
423
|
+
body: dict[str, Any] = {
|
|
424
|
+
"content-type": content_type,
|
|
425
|
+
"content-encoding": content_encoding,
|
|
426
|
+
"headers": headers,
|
|
427
|
+
"properties": properties,
|
|
428
|
+
}
|
|
429
|
+
payload = _json(data, content_type, content_encoding, headers)
|
|
430
|
+
if payload is not _NOT_JSON:
|
|
431
|
+
body["payload"] = payload
|
|
432
|
+
else:
|
|
433
|
+
body["body"] = base64.b64encode(data).decode("ascii")
|
|
434
|
+
|
|
435
|
+
shown = {}
|
|
436
|
+
task, task_id = headers.get("task"), headers.get("id")
|
|
437
|
+
if isinstance(task, str):
|
|
438
|
+
shown["task"] = task
|
|
439
|
+
if isinstance(task_id, str):
|
|
440
|
+
shown["task_id"] = task_id
|
|
441
|
+
# One open message per task id and retry: a publish Celery repeats after an error
|
|
442
|
+
# is the same message, a retry of its own built-in tasks a new one.
|
|
443
|
+
dedup_key = f"celery-{task_id}-{headers.get('retries') or 0}" if isinstance(task_id, str) else None
|
|
444
|
+
if dedup_key is not None and len(dedup_key) > 255:
|
|
445
|
+
dedup_key = None
|
|
446
|
+
return body, shown, dedup_key, _eta(headers.get("eta"))
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def decode(lease: Lease, delivery_tag: str) -> dict[str, Any]:
|
|
450
|
+
"""A claimed LessorMQ message as the raw message kombu delivers.
|
|
451
|
+
|
|
452
|
+
The attempt counts of the server go into the headers: ``retries`` (the attempts
|
|
453
|
+
before this one, which Celery shows as ``task.request.retries``), and
|
|
454
|
+
``lessormq_attempt`` and ``lessormq_max_attempts``.
|
|
455
|
+
|
|
456
|
+
:raises MalformedMessage: when it is not a message this transport wrote
|
|
457
|
+
"""
|
|
458
|
+
message = lease.message
|
|
459
|
+
data = message.body
|
|
460
|
+
if not isinstance(data, dict) or not ("payload" in data or "body" in data):
|
|
461
|
+
raise MalformedMessage("the message body is not a kombu message")
|
|
462
|
+
headers = data.get("headers") or {}
|
|
463
|
+
properties = data.get("properties") or {}
|
|
464
|
+
if not isinstance(headers, dict) or not isinstance(properties, dict):
|
|
465
|
+
raise MalformedMessage("the headers or properties of the message are not objects")
|
|
466
|
+
if "payload" in data:
|
|
467
|
+
body = json.dumps(data["payload"]).encode("utf-8")
|
|
468
|
+
else:
|
|
469
|
+
try:
|
|
470
|
+
body = base64.b64decode(str(data["body"]), validate=True)
|
|
471
|
+
except (binascii.Error, ValueError) as e:
|
|
472
|
+
raise MalformedMessage(f"the message body is not base64: {e}") from e
|
|
473
|
+
|
|
474
|
+
try:
|
|
475
|
+
published_retries = int(headers.get("retries") or 0)
|
|
476
|
+
except (TypeError, ValueError):
|
|
477
|
+
published_retries = 0
|
|
478
|
+
headers = {
|
|
479
|
+
**headers,
|
|
480
|
+
# The attempts before this one, on top of the retries Celery counted when it
|
|
481
|
+
# published (only its own tasks, such as chord_unlock, publish their retries).
|
|
482
|
+
"retries": published_retries + max(message.attempt - 1, 0),
|
|
483
|
+
"lessormq_attempt": message.attempt,
|
|
484
|
+
"lessormq_max_attempts": message.max_attempts,
|
|
485
|
+
"lessormq_message_id": message.id,
|
|
486
|
+
}
|
|
487
|
+
return {
|
|
488
|
+
"body": base64.b64encode(body).decode("ascii"),
|
|
489
|
+
"content-type": data.get("content-type"),
|
|
490
|
+
"content-encoding": data.get("content-encoding"),
|
|
491
|
+
"headers": headers,
|
|
492
|
+
"properties": {
|
|
493
|
+
**properties,
|
|
494
|
+
"body_encoding": "base64",
|
|
495
|
+
"delivery_tag": delivery_tag,
|
|
496
|
+
"delivery_info": {
|
|
497
|
+
"exchange": "",
|
|
498
|
+
"routing_key": message.queue,
|
|
499
|
+
"redelivered": message.attempt > 1,
|
|
500
|
+
},
|
|
501
|
+
},
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
_NOT_JSON = object()
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _json(data: bytes, content_type: Any, content_encoding: Any, headers: dict[str, Any]) -> Any:
|
|
509
|
+
if content_type != "application/json" or headers.get("compression"):
|
|
510
|
+
return _NOT_JSON
|
|
511
|
+
try:
|
|
512
|
+
return json.loads(data.decode(content_encoding or "utf-8"))
|
|
513
|
+
except (UnicodeDecodeError, LookupError, ValueError):
|
|
514
|
+
return _NOT_JSON
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _eta(value: Any) -> datetime | None:
|
|
518
|
+
"""Celery's eta (from ``countdown`` or ``eta``) as the message's ``available_at``:
|
|
519
|
+
the server holds the message back, not the worker."""
|
|
520
|
+
if not isinstance(value, str) or not value:
|
|
521
|
+
return None
|
|
522
|
+
try:
|
|
523
|
+
eta = datetime.fromisoformat(value)
|
|
524
|
+
except ValueError:
|
|
525
|
+
return None
|
|
526
|
+
# A naive eta is the publisher's local time, as Celery reads it.
|
|
527
|
+
return eta if eta.tzinfo is not None else eta.astimezone()
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _rejected() -> Outcome:
|
|
531
|
+
"""A reject the Request did not explain: Celery turned the message down without
|
|
532
|
+
running it (an unknown task, an invalid message). An ordinary failure, so a worker
|
|
533
|
+
that knows the task can still get it; the worker's log says why."""
|
|
534
|
+
return Outcome.fail(
|
|
535
|
+
"the worker rejected the message without running it (unknown task or invalid message); see its log",
|
|
536
|
+
type="celery.exceptions.Reject",
|
|
537
|
+
)
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: lessormq-celery
|
|
3
|
+
Version: 0.4.9
|
|
4
|
+
Summary: Celery on LessorMQ, the message queue over HTTP where the server decides and workers only claim, run, ack or fail: a kombu transport and a base task that leave retries to the server
|
|
5
|
+
Project-URL: Homepage, https://lessormq.dev
|
|
6
|
+
Project-URL: Documentation, https://github.com/gsid-nl/lessormq/tree/main/clients/celery
|
|
7
|
+
Project-URL: Source, https://github.com/gsid-nl/lessormq
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: celery,job-queue,kombu,lessormq,message-queue,worker
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Framework :: Celery
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: celery<6,>=5.5
|
|
20
|
+
Requires-Dist: kombu<6,>=5.5
|
|
21
|
+
Requires-Dist: lessormq>=0.4.9
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
24
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# LessorMQ for Celery
|
|
28
|
+
|
|
29
|
+
Celery on [LessorMQ](https://lessormq.dev), the message queue over HTTP where the server
|
|
30
|
+
decides and workers only claim, run, ack or fail. It is a kombu transport (broker URL
|
|
31
|
+
`lessormq://`) and a base task class. Celery publishes and runs tasks as usual, but
|
|
32
|
+
retries, backoff, the number of attempts and the dead-letter set are settings of the
|
|
33
|
+
queue on the server: `retry()` and `autoretry_for` fail the attempt and leave the rest
|
|
34
|
+
to the queue, and nothing is ever republished by the worker.
|
|
35
|
+
|
|
36
|
+
The package is `lessormq-celery`, for Celery 5.5 or later on Python 3.10 or later. It
|
|
37
|
+
builds on `lessormq`, the
|
|
38
|
+
[Python client](https://github.com/gsid-nl/lessormq/tree/main/clients/python).
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pip install lessormq-celery
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Configure
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import os
|
|
50
|
+
|
|
51
|
+
import lessormq_celery # registers the lessormq:// broker URL
|
|
52
|
+
from celery import Celery
|
|
53
|
+
|
|
54
|
+
app = Celery("shop", task_cls=lessormq_celery.Task)
|
|
55
|
+
app.conf.update(
|
|
56
|
+
broker_url="lessormq://mq.example.com",
|
|
57
|
+
broker_transport_options={"api_key": os.environ["LESSORMQ_KEY"]},
|
|
58
|
+
result_backend="redis://localhost/0", # optional; any backend but rpc://
|
|
59
|
+
worker_prefetch_multiplier=1,
|
|
60
|
+
)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`lessormq://` speaks HTTPS; `lessormq+http://` plain HTTP, for a server inside the same
|
|
64
|
+
cluster. The key may also be the URL's password, `lessormq://:KEY@mq.example.com`, which
|
|
65
|
+
Celery masks in its logs. Every task must derive from `lessormq_celery.Task`, which
|
|
66
|
+
`task_cls` does for `@app.task` and `@shared_task`; a `base=` class of your own derives
|
|
67
|
+
from it too. The worker refuses to start otherwise, naming the tasks.
|
|
68
|
+
|
|
69
|
+
Transport options (`broker_transport_options`):
|
|
70
|
+
|
|
71
|
+
| Option | Default | |
|
|
72
|
+
|---|---|---|
|
|
73
|
+
| `api_key` | the URL's password | a key with the `publish` scope (to send tasks) and the `consume` scope (to run a worker) |
|
|
74
|
+
| `wait_seconds` | 5 | how long a claim waits for a message (at most 20) |
|
|
75
|
+
| `lease_seconds` | the queue's | lease per claim, and per extension |
|
|
76
|
+
| `extend_every` | a third of the lease | seconds between extensions of a held lease |
|
|
77
|
+
| `consumer` | host:pid | the worker's name in the server's list of workers |
|
|
78
|
+
| `route` | none | the path this worker runs tasks through (VPN exit, proxy, account), see [routes](https://lessormq.dev/docs/concepts) |
|
|
79
|
+
| `http_retries`, `retry_delay`, `timeout` | 3, 0.1, 10 | the HTTP client's, see the Python client |
|
|
80
|
+
|
|
81
|
+
There is no option for retries, delays or dead-lettering: set those on the queue
|
|
82
|
+
(`PATCH /v1/queues/{queue}`, see [queue settings](https://lessormq.dev/docs/concepts)).
|
|
83
|
+
A Celery queue is the LessorMQ queue of the same name (`celery` by default).
|
|
84
|
+
|
|
85
|
+
## Dispatch
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from lessormq_celery import PermanentFailure
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@app.task(bind=True)
|
|
92
|
+
def send_invoice(self, invoice_id: int) -> None:
|
|
93
|
+
invoice = Invoice.objects.filter(pk=invoice_id).first()
|
|
94
|
+
if invoice is None:
|
|
95
|
+
raise PermanentFailure(f"no invoice {invoice_id}")
|
|
96
|
+
mailer.send(invoice)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
send_invoice.delay(1042)
|
|
100
|
+
send_invoice.apply_async((1042,), countdown=600, queue="mail")
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
- Tasks with the JSON serializer (Celery's default) are stored as JSON, so a message
|
|
104
|
+
reads as what it is in the queue and the dead-letter set: `{"payload": [[1042], {},
|
|
105
|
+
{...}], "headers": {"task": "shop.tasks.send_invoice", ...}}`. Other serializers are
|
|
106
|
+
kept as base64.
|
|
107
|
+
- `countdown` and `eta` become the message's `available_at`: the server holds the task
|
|
108
|
+
back, not the worker.
|
|
109
|
+
- The task id is the message's dedup key (with its retry count): a publish Celery
|
|
110
|
+
repeats after an error is the same message, and while a task is waiting or running,
|
|
111
|
+
sending the same task id again returns it.
|
|
112
|
+
- Canvas works (chains, groups, chords). With a result backend that has no native
|
|
113
|
+
chords, `celery.chord_unlock` polls with Celery's own retry, which publishes its next
|
|
114
|
+
run; that is the one place where a retry is a new message.
|
|
115
|
+
|
|
116
|
+
## Run workers
|
|
117
|
+
|
|
118
|
+
```sh
|
|
119
|
+
celery -A shop worker -Q celery,mail --concurrency 4
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The worker is Celery's (tested with the prefork, threads and solo pools). It claims a
|
|
123
|
+
message when it has room for one (`worker_prefetch_multiplier` per process), and extends
|
|
124
|
+
the lease of every message it holds, running or waiting, from a thread. Keep the
|
|
125
|
+
prefetch multiplier at 1: a held message is leased, and no idle worker can have it.
|
|
126
|
+
|
|
127
|
+
With several queues the worker claims from each in turn, and each claim waits up to
|
|
128
|
+
`wait_seconds` on an empty queue: lower it when one worker serves many queues. On SIGTERM
|
|
129
|
+
(warm shutdown) the worker finishes the tasks it runs, acks or fails them, and gives the
|
|
130
|
+
messages it held but had not started back to the queue without counting an attempt.
|
|
131
|
+
|
|
132
|
+
## How it behaves
|
|
133
|
+
|
|
134
|
+
The queue decides everything that happens after a failure; the worker only reports it.
|
|
135
|
+
|
|
136
|
+
| Celery | LessorMQ |
|
|
137
|
+
|---|---|
|
|
138
|
+
| a task returns | the message is acked |
|
|
139
|
+
| a task raises | the message is failed with the exception's class, message and traceback; the queue's `backoff` and `max_attempts` decide whether and when it runs again, and when it goes to the dead-letter set |
|
|
140
|
+
| `PermanentFailure` raised (or mixed into your exception: `class BadInput(ValueError, PermanentFailure)`), or `Reject(requeue=False)` | failed as permanent; the queue's `on_permanent` decides (by default: the dead-letter set at once) |
|
|
141
|
+
| `self.retry()`, `autoretry_for` | the attempt fails as above. `countdown`, `eta`, `max_retries`, `retry_backoff` and new arguments are ignored (logged once per task): the task runs again with its arguments after the queue's backoff. `retry()` always raises, also with `throw=False` |
|
|
142
|
+
| `max_retries`, `default_retry_delay`, `retry_jitter` | not used: the queue's `max_attempts` and `backoff` |
|
|
143
|
+
| `self.request.retries` | the attempts before this one, from the server; `self.request.lessormq_attempt` and `lessormq_max_attempts` are the server's counts |
|
|
144
|
+
| state `RETRY` / `FAILURE` in the result backend | `RETRY` (and `on_retry`, `task_retry`) for a failed attempt the queue will try again; `FAILURE` (and `on_failure`, `task_failure`) on the last attempt and for a permanent failure. So `AsyncResult.get()` waits for the outcome of the last attempt |
|
|
145
|
+
| `acks_late` | always on: the message is settled after the task ran. The worker refuses a task with it off |
|
|
146
|
+
| `acks_on_failure_or_timeout`, `reject_on_worker_lost` | not used: a failure is a fail, whatever Celery would do with the message |
|
|
147
|
+
| a child process that dies (`WorkerLostError`), `time_limit` | a failed attempt, counted by the server |
|
|
148
|
+
| `retry_on_worker_lost` | refused: the server counts the attempt and decides |
|
|
149
|
+
| `soft_time_limit` | the task's own exception, failed as any other |
|
|
150
|
+
| `Reject(requeue=True)` | the message is released: back to the queue, the attempt not counted |
|
|
151
|
+
| `Ignore`, an expired task (`expires`) | acked |
|
|
152
|
+
| a worker killed without a warm shutdown | its leases run out; the server counts the attempts and hands the messages out again |
|
|
153
|
+
| a failed-task store | not needed: the queue's dead-letter set (status `failed`) keeps them for the queue's retention; inspect and replay them with the admin API |
|
|
154
|
+
| `priority` | ignored: LessorMQ hands out messages roughly in order of availability |
|
|
155
|
+
| remote control (`celery inspect`, `revoke`), events, Flower | not carried: LessorMQ has no broadcast. Workers and their messages are in the server's list of workers and the queue's stats |
|
|
156
|
+
| `celery purge` | not supported; delete messages with the admin API |
|
|
157
|
+
| `result_backend = "rpc://"` | refused: it needs reply queues on the broker. Any other result backend works |
|
|
158
|
+
|
|
159
|
+
- A message Celery rejects without running it (an unknown task, for one, during a
|
|
160
|
+
deploy) is an ordinary failure, so the next attempt can reach a worker that knows the
|
|
161
|
+
task. A message on the queue that this transport did not write is failed as permanent.
|
|
162
|
+
- Delivery is at least once: a task can run twice, when its lease ran out under a slow
|
|
163
|
+
worker or an ack got lost. Make tasks safe to repeat.
|
|
164
|
+
|
|
165
|
+
## Moving from another queue
|
|
166
|
+
|
|
167
|
+
- Point `broker_url` at LessorMQ, create the app with `task_cls=lessormq_celery.Task`,
|
|
168
|
+
and derive your own base task classes from it.
|
|
169
|
+
- Move the retry policy to the queue: `max_attempts` is `max_retries` plus one (Celery's
|
|
170
|
+
default is 3 retries: 4 attempts), `backoff` replaces `countdown`, `retry_backoff` and
|
|
171
|
+
`retry_jitter`. Exceptions that should never be retried become `PermanentFailure`;
|
|
172
|
+
`autoretry_for` no longer narrows what is retried, since every failure is reported and
|
|
173
|
+
the queue decides.
|
|
174
|
+
- `retry()` calls can stay; their arguments other than `exc` stop mattering.
|
|
175
|
+
- Replace `rpc://` with another result backend, and remote control (revoking, rate
|
|
176
|
+
limits at runtime) with the admin API: pause a queue, delete or replay messages.
|
|
177
|
+
- Run old and new side by side: two Celery apps (or two queues on two brokers), and
|
|
178
|
+
move task routes one at a time. Drain the old broker before you switch it off.
|
|
179
|
+
- Workers on different network paths (VPN exits, proxies) set `route`, and the queue's
|
|
180
|
+
`route_policy` keeps a message away from a route it failed on.
|
|
181
|
+
|
|
182
|
+
## Development
|
|
183
|
+
|
|
184
|
+
```sh
|
|
185
|
+
cd clients/celery
|
|
186
|
+
python3 -m venv .venv
|
|
187
|
+
.venv/bin/pip install -e ../python -e '.[dev]'
|
|
188
|
+
.venv/bin/pytest
|
|
189
|
+
.venv/bin/mypy
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The unit tests run the transport against a scripted server and the task and request
|
|
193
|
+
classes without a broker. The end-to-end tests start real Celery workers (prefork) on a
|
|
194
|
+
running server, in a tenant of their own that they remove afterwards: a task run and
|
|
195
|
+
acked, a failing task back after the queue's backoff with the server's attempt count
|
|
196
|
+
and then in the dead-letter set, `retry()` with its countdown ignored, a permanent
|
|
197
|
+
failure in the dead-letter set at once, a child process that dies, `countdown`, a warm
|
|
198
|
+
shutdown, and a chord. Without these variables they are skipped:
|
|
199
|
+
|
|
200
|
+
```sh
|
|
201
|
+
LESSORMQ_URL=http://127.0.0.1:8080 LESSORMQ_OPERATOR_KEY=lmq_... .venv/bin/pytest tests/test_end_to_end.py
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
The protocol calls are the Python client's, which passes the
|
|
205
|
+
[conformance suite](https://github.com/gsid-nl/lessormq/tree/main/conformance) through
|
|
206
|
+
`clients/python/tests/conformance_adapter.py`.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
lessormq_celery/__init__.py,sha256=daJiK4wV2hzM0TGblrV6hqVJsTHwRbnTicrZXP6iTSM,900
|
|
2
|
+
lessormq_celery/checks.py,sha256=7Zunqh8jI1lieHjhjMpGIcirjlh3NsjOYTxHmQ2709Q,2096
|
|
3
|
+
lessormq_celery/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
lessormq_celery/request.py,sha256=W7wtskxw9zAj3J_DuNgfUdqU9kvFDQFVEhsEoX2FhxQ,4902
|
|
5
|
+
lessormq_celery/task.py,sha256=Dhdhmi5H0Yi1yMgJnSGHEHUa5cVjVRYU_VvubdMdXPA,4517
|
|
6
|
+
lessormq_celery/transport.py,sha256=rvjvGJUSdilAQkxL8PWRlnKPWe6SjwZy5BinL8deuWE,21054
|
|
7
|
+
lessormq_celery-0.4.9.dist-info/METADATA,sha256=k04EfHJdsNyBvfcV9FHAhWPBrcLrWWzhal7DDNp449w,11157
|
|
8
|
+
lessormq_celery-0.4.9.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
lessormq_celery-0.4.9.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
10
|
+
lessormq_celery-0.4.9.dist-info/RECORD,,
|
|
@@ -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.
|