taskferry-celery 0.1.0__tar.gz
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.
- taskferry_celery-0.1.0/.gitignore +34 -0
- taskferry_celery-0.1.0/CHANGELOG.md +19 -0
- taskferry_celery-0.1.0/LICENSE +201 -0
- taskferry_celery-0.1.0/PKG-INFO +87 -0
- taskferry_celery-0.1.0/README.md +63 -0
- taskferry_celery-0.1.0/pyproject.toml +41 -0
- taskferry_celery-0.1.0/src/taskferry_celery/__init__.py +72 -0
- taskferry_celery-0.1.0/src/taskferry_celery/backend.py +278 -0
- taskferry_celery-0.1.0/src/taskferry_celery/message.py +50 -0
- taskferry_celery-0.1.0/src/taskferry_celery/py.typed +0 -0
- taskferry_celery-0.1.0/src/taskferry_celery/worker.py +121 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
.eggs/
|
|
6
|
+
|
|
7
|
+
# Build artifacts
|
|
8
|
+
dist/
|
|
9
|
+
build/
|
|
10
|
+
*.whl
|
|
11
|
+
*.tar.gz
|
|
12
|
+
|
|
13
|
+
# Environments
|
|
14
|
+
.venv/
|
|
15
|
+
.venv-*/
|
|
16
|
+
.env
|
|
17
|
+
|
|
18
|
+
# Tooling caches
|
|
19
|
+
.mypy_cache/
|
|
20
|
+
.ruff_cache/
|
|
21
|
+
.pytest_cache/
|
|
22
|
+
.coverage
|
|
23
|
+
htmlcov/
|
|
24
|
+
coverage.xml
|
|
25
|
+
node_modules/
|
|
26
|
+
|
|
27
|
+
# uv
|
|
28
|
+
uv.lock
|
|
29
|
+
|
|
30
|
+
# OS / editors
|
|
31
|
+
.DS_Store
|
|
32
|
+
.idea/
|
|
33
|
+
.vscode/
|
|
34
|
+
site/
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Changelog — taskferry-celery
|
|
2
|
+
|
|
3
|
+
Follows [Semantic Versioning](https://semver.org/); versions independently of the
|
|
4
|
+
rest of the family.
|
|
5
|
+
|
|
6
|
+
## [0.1.0]
|
|
7
|
+
|
|
8
|
+
### Added
|
|
9
|
+
|
|
10
|
+
- `CeleryTaskBackend` — sends Taskferry tasks to a Celery app via `send_task`,
|
|
11
|
+
translating `TaskSpec` (queue, priority, delay) out and Celery task state back.
|
|
12
|
+
- Honest capabilities: submit, state, cancel, delay, priority, retry.
|
|
13
|
+
`result` and `deduplication` are deliberately not advertised.
|
|
14
|
+
- Engine-owned retries via the dispatcher's `self.retry`.
|
|
15
|
+
- `register_dispatcher` + `execute_message` worker side, with an optional
|
|
16
|
+
`FunctionRegistry` import allowlist.
|
|
17
|
+
- Pure `map_state` status mapping and the shared JSON envelope.
|
|
18
|
+
- `taskferry.backends` entry point (`celery`). Contract-tested with a fake app;
|
|
19
|
+
neither Celery nor a broker is required to run the tests.
|
|
@@ -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 Derivative
|
|
95
|
+
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.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: taskferry-celery
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Celery task backend for Taskferry — enqueue Taskferry tasks onto a Celery app.
|
|
5
|
+
Project-URL: Homepage, https://github.com/xiidigital/taskferry
|
|
6
|
+
Project-URL: Documentation, https://taskferry.dev
|
|
7
|
+
Project-URL: Source, https://github.com/xiidigital/taskferry
|
|
8
|
+
Author: Taskferry authors
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: celery,queue,taskferry,tasks
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Requires-Dist: taskferry<0.3,>=0.2
|
|
21
|
+
Provides-Extra: celery
|
|
22
|
+
Requires-Dist: celery>=5.3; extra == 'celery'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# taskferry-celery
|
|
26
|
+
|
|
27
|
+
A **Celery** task backend for [Taskferry](https://taskferry.dev). Enqueue Taskferry
|
|
28
|
+
tasks onto a Celery app you already run; Taskferry supplies no worker and
|
|
29
|
+
reimplements none of Celery.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install taskferry-celery[celery]
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Submitting
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from taskferry import Taskferry
|
|
39
|
+
|
|
40
|
+
runtime = Taskferry.from_mapping(
|
|
41
|
+
{
|
|
42
|
+
"backends": {"cel": {"factory": "celery", "app": "myapp.celery:app"}},
|
|
43
|
+
"defaults": {"task": "cel"},
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
runtime.tasks.submit("myapp.tasks:refresh", 42, queue="metadata")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Executing (worker)
|
|
50
|
+
|
|
51
|
+
Register the dispatcher once, then run Celery's own worker:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from celery import Celery
|
|
55
|
+
from taskferry_celery import register_dispatcher
|
|
56
|
+
from taskferry.functions import FunctionRegistry
|
|
57
|
+
|
|
58
|
+
app = Celery("myapp", broker="redis://localhost:6379/0")
|
|
59
|
+
register_dispatcher(app, registry=FunctionRegistry(allowed_modules=["myapp"]))
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
celery -A myapp worker
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Capabilities (honest)
|
|
67
|
+
|
|
68
|
+
| Advertised | Not advertised | Why not |
|
|
69
|
+
| --- | --- | --- |
|
|
70
|
+
| submit, state, cancel, delay, priority, retry | `result` | needs a configured result backend Taskferry can't see |
|
|
71
|
+
| | `deduplication` | Celery has no native mechanism — an `idempotency_key` is rejected, not ignored |
|
|
72
|
+
|
|
73
|
+
Retries are the **engine's**: the dispatcher raises Celery's own `self.retry`, so
|
|
74
|
+
a failed task is genuinely re-queued with the requested countdown. Taskferry never
|
|
75
|
+
loops in-process pretending to retry.
|
|
76
|
+
|
|
77
|
+
`state` maps Celery's `PENDING/STARTED/SUCCESS/FAILURE/RETRY/REVOKED` onto the
|
|
78
|
+
portable states. Note Celery reports `PENDING` for both a queued task and an
|
|
79
|
+
unknown id; without a result backend the two are indistinguishable, and this
|
|
80
|
+
adapter says so rather than guessing.
|
|
81
|
+
|
|
82
|
+
Only JSON-safe arguments and a `"module:function"` name cross the wire — never a
|
|
83
|
+
pickled callable.
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
Apache-2.0.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# taskferry-celery
|
|
2
|
+
|
|
3
|
+
A **Celery** task backend for [Taskferry](https://taskferry.dev). Enqueue Taskferry
|
|
4
|
+
tasks onto a Celery app you already run; Taskferry supplies no worker and
|
|
5
|
+
reimplements none of Celery.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install taskferry-celery[celery]
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Submitting
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from taskferry import Taskferry
|
|
15
|
+
|
|
16
|
+
runtime = Taskferry.from_mapping(
|
|
17
|
+
{
|
|
18
|
+
"backends": {"cel": {"factory": "celery", "app": "myapp.celery:app"}},
|
|
19
|
+
"defaults": {"task": "cel"},
|
|
20
|
+
}
|
|
21
|
+
)
|
|
22
|
+
runtime.tasks.submit("myapp.tasks:refresh", 42, queue="metadata")
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Executing (worker)
|
|
26
|
+
|
|
27
|
+
Register the dispatcher once, then run Celery's own worker:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from celery import Celery
|
|
31
|
+
from taskferry_celery import register_dispatcher
|
|
32
|
+
from taskferry.functions import FunctionRegistry
|
|
33
|
+
|
|
34
|
+
app = Celery("myapp", broker="redis://localhost:6379/0")
|
|
35
|
+
register_dispatcher(app, registry=FunctionRegistry(allowed_modules=["myapp"]))
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
celery -A myapp worker
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Capabilities (honest)
|
|
43
|
+
|
|
44
|
+
| Advertised | Not advertised | Why not |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| submit, state, cancel, delay, priority, retry | `result` | needs a configured result backend Taskferry can't see |
|
|
47
|
+
| | `deduplication` | Celery has no native mechanism — an `idempotency_key` is rejected, not ignored |
|
|
48
|
+
|
|
49
|
+
Retries are the **engine's**: the dispatcher raises Celery's own `self.retry`, so
|
|
50
|
+
a failed task is genuinely re-queued with the requested countdown. Taskferry never
|
|
51
|
+
loops in-process pretending to retry.
|
|
52
|
+
|
|
53
|
+
`state` maps Celery's `PENDING/STARTED/SUCCESS/FAILURE/RETRY/REVOKED` onto the
|
|
54
|
+
portable states. Note Celery reports `PENDING` for both a queued task and an
|
|
55
|
+
unknown id; without a result backend the two are indistinguishable, and this
|
|
56
|
+
adapter says so rather than guessing.
|
|
57
|
+
|
|
58
|
+
Only JSON-safe arguments and a `"module:function"` name cross the wire — never a
|
|
59
|
+
pickled callable.
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
Apache-2.0.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "taskferry-celery"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Celery task backend for Taskferry — enqueue Taskferry tasks onto a Celery app."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Taskferry authors" }]
|
|
14
|
+
keywords = ["taskferry", "celery", "tasks", "queue"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: Apache Software License",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["taskferry>=0.2,<0.3"]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
celery = ["celery>=5.3"]
|
|
28
|
+
|
|
29
|
+
[project.entry-points."taskferry.backends"]
|
|
30
|
+
celery = "taskferry_celery:make_backend"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/xiidigital/taskferry"
|
|
34
|
+
Documentation = "https://taskferry.dev"
|
|
35
|
+
Source = "https://github.com/xiidigital/taskferry"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/taskferry_celery"]
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.sdist]
|
|
41
|
+
include = ["src", "README.md", "CHANGELOG.md", "LICENSE"]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Taskferry on Celery — enqueue Taskferry tasks onto a Celery app.
|
|
2
|
+
|
|
3
|
+
```mermaid
|
|
4
|
+
flowchart LR
|
|
5
|
+
APP["Application"]
|
|
6
|
+
TP["Taskferry"]
|
|
7
|
+
AD["taskferry_celery"]
|
|
8
|
+
CEL["Celery"]
|
|
9
|
+
BRK["broker (Redis / RabbitMQ)"]
|
|
10
|
+
|
|
11
|
+
APP --> TP --> AD --> CEL --> BRK
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Celery already solves the durable broker, the worker, prefetch and retries.
|
|
15
|
+
Taskferry does not reimplement any of it: this adapter translates a
|
|
16
|
+
:class:`~taskferry.specs.TaskSpec` into a Celery task and Celery's state back.
|
|
17
|
+
``taskferry`` itself never imports ``celery`` — an architectural test enforces it —
|
|
18
|
+
so Celery becomes a dependency of your deployment only when this adapter is
|
|
19
|
+
selected.
|
|
20
|
+
|
|
21
|
+
Two sides
|
|
22
|
+
---------
|
|
23
|
+
|
|
24
|
+
**Submitting** (web process, CLI, anything)::
|
|
25
|
+
|
|
26
|
+
from taskferry import Taskferry
|
|
27
|
+
|
|
28
|
+
runtime = Taskferry.from_mapping({
|
|
29
|
+
"backends": {"cel": {"factory": "celery", "app": "myapp.celery:app"}},
|
|
30
|
+
"defaults": {"task": "cel"},
|
|
31
|
+
})
|
|
32
|
+
runtime.tasks.submit("myapp.tasks:refresh", 42, queue="metadata")
|
|
33
|
+
|
|
34
|
+
**Executing** (worker process) — register the dispatcher once on your app::
|
|
35
|
+
|
|
36
|
+
from celery import Celery
|
|
37
|
+
from taskferry_celery import register_dispatcher
|
|
38
|
+
|
|
39
|
+
app = Celery("myapp", broker="redis://localhost:6379/0")
|
|
40
|
+
register_dispatcher(app)
|
|
41
|
+
|
|
42
|
+
then run Celery's own worker (``celery -A myapp worker``). Taskferry supplies no
|
|
43
|
+
worker; that is exactly the sort of thing it delegates.
|
|
44
|
+
|
|
45
|
+
What crosses the wire is the portable envelope — a ``"package.module:function"``
|
|
46
|
+
name plus JSON arguments — never a pickled callable. See :mod:`taskferry.envelope`.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
from .backend import (
|
|
52
|
+
CELERY_CAPABILITIES,
|
|
53
|
+
DEFAULT_DISPATCH_TASK,
|
|
54
|
+
CeleryTaskBackend,
|
|
55
|
+
make_backend,
|
|
56
|
+
map_state,
|
|
57
|
+
)
|
|
58
|
+
from .worker import build_message, execute_message, register_dispatcher
|
|
59
|
+
|
|
60
|
+
__version__ = "0.1.0"
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"CELERY_CAPABILITIES",
|
|
64
|
+
"DEFAULT_DISPATCH_TASK",
|
|
65
|
+
"CeleryTaskBackend",
|
|
66
|
+
"__version__",
|
|
67
|
+
"build_message",
|
|
68
|
+
"execute_message",
|
|
69
|
+
"make_backend",
|
|
70
|
+
"map_state",
|
|
71
|
+
"register_dispatcher",
|
|
72
|
+
]
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""The Celery ``TaskBackend``.
|
|
2
|
+
|
|
3
|
+
Translation, in both directions, and nothing else. A :class:`~taskferry.specs.TaskSpec`
|
|
4
|
+
becomes a Celery task sent to the ``taskferry:dispatch`` task; Celery's task state
|
|
5
|
+
is translated back to a portable :class:`~taskferry.execution.ExecutionState`.
|
|
6
|
+
|
|
7
|
+
```mermaid
|
|
8
|
+
flowchart LR
|
|
9
|
+
subgraph Taskferry
|
|
10
|
+
TS["TaskSpec<br/>queue · priority · delay · retry"]
|
|
11
|
+
EX["Execution<br/>ExecutionState"]
|
|
12
|
+
end
|
|
13
|
+
subgraph Celery
|
|
14
|
+
SEND["app.send_task('taskferry:dispatch', ...)"]
|
|
15
|
+
ST["AsyncResult.state<br/>PENDING · STARTED · SUCCESS · FAILURE · RETRY · REVOKED"]
|
|
16
|
+
end
|
|
17
|
+
TS --> SEND
|
|
18
|
+
ST --> EX
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Capabilities are advertised from what Celery genuinely does out of the box:
|
|
22
|
+
|
|
23
|
+
* ``DELAY`` — ``eta`` / ``countdown``;
|
|
24
|
+
* ``PRIORITY`` — native message priority (broker-dependent, but real);
|
|
25
|
+
* ``RETRY`` — the engine owns retries; the dispatcher turns a failure into
|
|
26
|
+
Celery's own ``self.retry`` so the task is genuinely re-queued;
|
|
27
|
+
* ``STATE`` — through ``AsyncResult``;
|
|
28
|
+
* ``CANCEL`` — ``AsyncResult.revoke``.
|
|
29
|
+
|
|
30
|
+
``RESULT`` is **not** advertised. Celery *can* store results, but only when a
|
|
31
|
+
result backend is configured, and Taskferry will not claim a capability that
|
|
32
|
+
depends on optional infrastructure it cannot see. ``DEDUPLICATION`` is not
|
|
33
|
+
advertised either: Celery has no native mechanism for it, so a spec carrying an
|
|
34
|
+
``idempotency_key`` is rejected here rather than accepted and ignored.
|
|
35
|
+
|
|
36
|
+
A note on Celery's ``PENDING``: Celery reports ``PENDING`` both for a task that is
|
|
37
|
+
genuinely queued *and* for a task id it has never heard of. Taskferry maps
|
|
38
|
+
``PENDING`` to ``QUEUED`` and documents that it cannot distinguish the two without
|
|
39
|
+
a result backend — an honest limitation, not a guess.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
from datetime import UTC, datetime
|
|
45
|
+
from typing import Any
|
|
46
|
+
|
|
47
|
+
from taskferry.capabilities import Capability, CapabilitySet
|
|
48
|
+
from taskferry.core.provider import ProviderMetadata
|
|
49
|
+
from taskferry.errors import ConfigurationError, ExecutionNotFound, SubmissionError
|
|
50
|
+
from taskferry.execution import (
|
|
51
|
+
Execution,
|
|
52
|
+
ExecutionId,
|
|
53
|
+
ExecutionKind,
|
|
54
|
+
ExecutionState,
|
|
55
|
+
new_execution_id,
|
|
56
|
+
)
|
|
57
|
+
from taskferry.ports import BaseBackend
|
|
58
|
+
from taskferry.specs import ExecutionSpec, TaskSpec
|
|
59
|
+
from taskferry.tracking import ExternalIdIndex
|
|
60
|
+
|
|
61
|
+
from .message import build_message
|
|
62
|
+
|
|
63
|
+
DEFAULT_DISPATCH_TASK = "taskferry:dispatch"
|
|
64
|
+
"""Name of the single Celery task that runs every Taskferry message."""
|
|
65
|
+
|
|
66
|
+
CELERY_CAPABILITIES = frozenset(
|
|
67
|
+
{
|
|
68
|
+
Capability.SUBMIT,
|
|
69
|
+
Capability.STATE,
|
|
70
|
+
Capability.CANCEL,
|
|
71
|
+
Capability.DELAY,
|
|
72
|
+
Capability.PRIORITY,
|
|
73
|
+
Capability.RETRY,
|
|
74
|
+
}
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
#: Celery task state -> portable state. See the ``PENDING`` note in the module
|
|
78
|
+
#: docstring. ``RETRY`` is a task waiting to be re-attempted by the engine, which
|
|
79
|
+
#: an operator sees as still running.
|
|
80
|
+
_STATE_MAP: dict[str, ExecutionState] = {
|
|
81
|
+
"PENDING": ExecutionState.QUEUED,
|
|
82
|
+
"RECEIVED": ExecutionState.QUEUED,
|
|
83
|
+
"STARTED": ExecutionState.RUNNING,
|
|
84
|
+
"RETRY": ExecutionState.RUNNING,
|
|
85
|
+
"SUCCESS": ExecutionState.SUCCEEDED,
|
|
86
|
+
"FAILURE": ExecutionState.FAILED,
|
|
87
|
+
"REVOKED": ExecutionState.CANCELLED,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def map_state(state: object) -> ExecutionState:
|
|
92
|
+
"""Map a Celery task state to a portable state. Pure, unit-testable.
|
|
93
|
+
|
|
94
|
+
An unrecognised state maps to ``UNKNOWN`` rather than to a guess — a future
|
|
95
|
+
Celery state must not make Taskferry report something false.
|
|
96
|
+
"""
|
|
97
|
+
if state is None:
|
|
98
|
+
return ExecutionState.UNKNOWN
|
|
99
|
+
return _STATE_MAP.get(str(state).upper(), ExecutionState.UNKNOWN)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _looks_like_celery_id(value: str) -> bool:
|
|
103
|
+
"""Recognise a Celery task id (a uuid4 string) copied from a dashboard."""
|
|
104
|
+
parts = value.split("-")
|
|
105
|
+
return len(parts) == 5 and all(c in "0123456789abcdef-" for c in value.lower())
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class CeleryTaskBackend(BaseBackend):
|
|
109
|
+
"""Sends Taskferry tasks to a Celery app.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
app: A ``celery.Celery`` instance, or a ``"module:attribute"`` string
|
|
113
|
+
resolved on first use so the backend is constructible before the
|
|
114
|
+
broker connection is configured.
|
|
115
|
+
dispatch_task: Name of the registered dispatcher task. Must match the name
|
|
116
|
+
passed to :func:`~taskferry_celery.register_dispatcher`.
|
|
117
|
+
name: Backend name used in metadata and errors.
|
|
118
|
+
|
|
119
|
+
Backend options, under the ``"celery"`` namespace, pass straight to
|
|
120
|
+
``send_task``::
|
|
121
|
+
|
|
122
|
+
TaskSpec(
|
|
123
|
+
task="myapp.tasks:reindex",
|
|
124
|
+
backend_options=BackendOptions({"celery": {"expires": 300}}),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
Thread-safe once constructed: a Celery ``app`` is designed to be shared and
|
|
128
|
+
this backend keeps no mutable state beyond the id index.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
*,
|
|
134
|
+
app: Any = None,
|
|
135
|
+
dispatch_task: str = DEFAULT_DISPATCH_TASK,
|
|
136
|
+
name: str = "celery",
|
|
137
|
+
tracked_ids: int = 10_000,
|
|
138
|
+
) -> None:
|
|
139
|
+
self._app = app
|
|
140
|
+
self._dispatch_task = dispatch_task
|
|
141
|
+
self._name = name
|
|
142
|
+
self._ids = ExternalIdIndex(capacity=tracked_ids, recognises=_looks_like_celery_id)
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def name(self) -> str:
|
|
146
|
+
return self._name
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def kind(self) -> ExecutionKind:
|
|
150
|
+
return ExecutionKind.TASK
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def capabilities(self) -> CapabilitySet:
|
|
154
|
+
return CapabilitySet(CELERY_CAPABILITIES, provider=self._name)
|
|
155
|
+
|
|
156
|
+
# -- the app ---------------------------------------------------------------- #
|
|
157
|
+
def app(self) -> Any:
|
|
158
|
+
"""The Celery app, resolving a dotted path on first use."""
|
|
159
|
+
if self._app is None:
|
|
160
|
+
raise ConfigurationError(
|
|
161
|
+
f"{self._name!r} needs a celery app: pass app=<Celery> or "
|
|
162
|
+
"app='myapp.celery:app' in the backend options"
|
|
163
|
+
)
|
|
164
|
+
if isinstance(self._app, str):
|
|
165
|
+
self._app = _import_attribute(self._app)
|
|
166
|
+
return self._app
|
|
167
|
+
|
|
168
|
+
# -- submission ------------------------------------------------------------- #
|
|
169
|
+
def _submit(self, spec: ExecutionSpec) -> Execution:
|
|
170
|
+
assert isinstance(spec, TaskSpec)
|
|
171
|
+
app = self.app()
|
|
172
|
+
options: dict[str, Any] = {
|
|
173
|
+
"queue": spec.queue,
|
|
174
|
+
"priority": spec.priority,
|
|
175
|
+
}
|
|
176
|
+
eta = spec.scheduled_for()
|
|
177
|
+
if eta is not None:
|
|
178
|
+
options["eta"] = eta
|
|
179
|
+
# Any celery-namespaced option passes straight through to send_task.
|
|
180
|
+
options.update(spec.options_for("celery"))
|
|
181
|
+
|
|
182
|
+
message = build_message(spec)
|
|
183
|
+
try:
|
|
184
|
+
async_result = app.send_task(
|
|
185
|
+
self._dispatch_task, kwargs={"message": message}, **options
|
|
186
|
+
)
|
|
187
|
+
except Exception as exc:
|
|
188
|
+
raise SubmissionError(
|
|
189
|
+
f"celery could not send {spec.task!r} on queue {spec.queue!r}: {exc}",
|
|
190
|
+
backend=self._name,
|
|
191
|
+
) from exc
|
|
192
|
+
|
|
193
|
+
task_id = str(getattr(async_result, "id", "") or "")
|
|
194
|
+
execution_id = new_execution_id(ExecutionKind.TASK)
|
|
195
|
+
self._ids.remember(str(execution_id), task_id)
|
|
196
|
+
return Execution(
|
|
197
|
+
id=execution_id,
|
|
198
|
+
kind=ExecutionKind.TASK,
|
|
199
|
+
backend=self._name,
|
|
200
|
+
state=ExecutionState.QUEUED,
|
|
201
|
+
name=spec.name,
|
|
202
|
+
created_at=datetime.now(UTC),
|
|
203
|
+
external_id=task_id,
|
|
204
|
+
correlation=spec.correlation,
|
|
205
|
+
provider_metadata=ProviderMetadata(
|
|
206
|
+
provider="celery",
|
|
207
|
+
provider_id=task_id,
|
|
208
|
+
resource=f"queue:{spec.queue}",
|
|
209
|
+
labels=dict(spec.labels),
|
|
210
|
+
),
|
|
211
|
+
metadata={"queue": spec.queue, "celery_task_id": task_id},
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
# -- observation ------------------------------------------------------------ #
|
|
215
|
+
def _result_handle(self, execution_id: ExecutionId) -> Any:
|
|
216
|
+
task_id = self._ids.resolve(str(execution_id))
|
|
217
|
+
if task_id is None:
|
|
218
|
+
raise ExecutionNotFound(
|
|
219
|
+
f"celery has no task {execution_id!r}; pass the celery task id when the "
|
|
220
|
+
"execution was submitted by another process",
|
|
221
|
+
backend=self._name,
|
|
222
|
+
)
|
|
223
|
+
return self.app().AsyncResult(task_id)
|
|
224
|
+
|
|
225
|
+
def _get(self, execution_id: ExecutionId) -> Execution:
|
|
226
|
+
async_result = self._result_handle(execution_id)
|
|
227
|
+
task_id = str(getattr(async_result, "id", "") or self._ids.resolve(str(execution_id)) or "")
|
|
228
|
+
return Execution(
|
|
229
|
+
id=execution_id,
|
|
230
|
+
kind=ExecutionKind.TASK,
|
|
231
|
+
backend=self._name,
|
|
232
|
+
state=map_state(getattr(async_result, "state", None)),
|
|
233
|
+
external_id=task_id,
|
|
234
|
+
provider_metadata=ProviderMetadata(provider="celery", provider_id=task_id),
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
def _cancel(self, execution_id: ExecutionId) -> Execution:
|
|
238
|
+
async_result = self._result_handle(execution_id)
|
|
239
|
+
try:
|
|
240
|
+
async_result.revoke()
|
|
241
|
+
except Exception as exc:
|
|
242
|
+
raise SubmissionError(
|
|
243
|
+
f"celery could not revoke {execution_id!r}: {exc}", backend=self._name
|
|
244
|
+
) from exc
|
|
245
|
+
return self._get(execution_id)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _import_attribute(path: str) -> Any:
|
|
249
|
+
import importlib
|
|
250
|
+
|
|
251
|
+
module_path, sep, attr = path.partition(":")
|
|
252
|
+
if not sep:
|
|
253
|
+
module_path, _, attr = path.rpartition(".")
|
|
254
|
+
if not module_path or not attr:
|
|
255
|
+
raise ConfigurationError(f"invalid app reference {path!r}; expected 'module:attribute'")
|
|
256
|
+
try:
|
|
257
|
+
return getattr(importlib.import_module(module_path), attr)
|
|
258
|
+
except (ImportError, AttributeError) as exc:
|
|
259
|
+
raise ConfigurationError(f"cannot resolve celery app {path!r}: {exc}") from exc
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def make_backend(**options: Any) -> CeleryTaskBackend:
|
|
263
|
+
"""Entry point for ``{"factory": "celery", ...}`` configuration."""
|
|
264
|
+
return CeleryTaskBackend(
|
|
265
|
+
app=options.get("app"),
|
|
266
|
+
dispatch_task=str(options.get("dispatch_task", DEFAULT_DISPATCH_TASK)),
|
|
267
|
+
name=str(options.get("name", "celery")),
|
|
268
|
+
tracked_ids=int(options.get("tracked_ids", 10_000)),
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
__all__ = [
|
|
273
|
+
"CELERY_CAPABILITIES",
|
|
274
|
+
"DEFAULT_DISPATCH_TASK",
|
|
275
|
+
"CeleryTaskBackend",
|
|
276
|
+
"make_backend",
|
|
277
|
+
"map_state",
|
|
278
|
+
]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""The wire envelope, re-exported from the core.
|
|
2
|
+
|
|
3
|
+
Every Taskferry transport carries the same JSON envelope — one function name, JSON
|
|
4
|
+
arguments, correlation, retry intent — defined once in :mod:`taskferry.envelope`
|
|
5
|
+
so Celery, Procrastinate, Cloud Tasks, SQS and the rest cannot drift apart on the
|
|
6
|
+
format a worker must understand. There is nothing Celery-specific to add, which is
|
|
7
|
+
the point; this module exists as the stable import path for the adapter's own
|
|
8
|
+
tests and docs.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from taskferry.envelope import (
|
|
14
|
+
ENVELOPE_VERSION,
|
|
15
|
+
Envelope,
|
|
16
|
+
build_envelope,
|
|
17
|
+
decode_retry,
|
|
18
|
+
encode_retry,
|
|
19
|
+
read_correlation,
|
|
20
|
+
read_envelope,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
MESSAGE_VERSION = ENVELOPE_VERSION
|
|
24
|
+
TaskferryMessage = Envelope
|
|
25
|
+
build_message = build_envelope
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def check_version(message: object) -> None:
|
|
29
|
+
"""Reject an envelope this worker does not understand, as ``ValueError``."""
|
|
30
|
+
from taskferry.errors import SerializationError
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
read_envelope(message)
|
|
34
|
+
except SerializationError as exc:
|
|
35
|
+
raise ValueError(str(exc)) from exc
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"ENVELOPE_VERSION",
|
|
40
|
+
"MESSAGE_VERSION",
|
|
41
|
+
"Envelope",
|
|
42
|
+
"TaskferryMessage",
|
|
43
|
+
"build_envelope",
|
|
44
|
+
"build_message",
|
|
45
|
+
"check_version",
|
|
46
|
+
"decode_retry",
|
|
47
|
+
"encode_retry",
|
|
48
|
+
"read_correlation",
|
|
49
|
+
"read_envelope",
|
|
50
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The worker side — one Celery task that runs every Taskferry message.
|
|
2
|
+
|
|
3
|
+
```mermaid
|
|
4
|
+
sequenceDiagram
|
|
5
|
+
participant B as broker
|
|
6
|
+
participant W as celery worker
|
|
7
|
+
participant D as taskferry:dispatch
|
|
8
|
+
participant REG as FunctionRegistry
|
|
9
|
+
participant FN as your function
|
|
10
|
+
|
|
11
|
+
B->>W: deliver task
|
|
12
|
+
W->>D: dispatch(message)
|
|
13
|
+
D->>REG: resolve "package.module:function"
|
|
14
|
+
REG-->>D: callable
|
|
15
|
+
D->>FN: call(*args, **kwargs)
|
|
16
|
+
FN-->>D: value
|
|
17
|
+
D-->>W: done
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Taskferry supplies **no worker**. You run ``celery -A myapp worker``; this module
|
|
21
|
+
only registers the function that worker calls. Reservation, concurrency, prefetch,
|
|
22
|
+
acks and shutdown are Celery's.
|
|
23
|
+
|
|
24
|
+
Security
|
|
25
|
+
--------
|
|
26
|
+
|
|
27
|
+
The dispatcher resolves a task *name* that arrived from the broker. If untrusted
|
|
28
|
+
input can reach your broker, that resolution is an arbitrary-import primitive, so
|
|
29
|
+
pass a :class:`~taskferry.functions.FunctionRegistry` with an allowlist::
|
|
30
|
+
|
|
31
|
+
registry = FunctionRegistry(allowed_modules=["myapp.tasks"])
|
|
32
|
+
register_dispatcher(app, registry=registry)
|
|
33
|
+
|
|
34
|
+
Return values
|
|
35
|
+
-------------
|
|
36
|
+
|
|
37
|
+
The dispatcher returns whatever the task returned. Celery stores it only if a
|
|
38
|
+
result backend is configured, and this adapter does not advertise ``RESULT``.
|
|
39
|
+
Write results where they belong instead of relying on the queue to keep them.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import logging
|
|
45
|
+
from typing import Any
|
|
46
|
+
|
|
47
|
+
from taskferry.envelope import execute_envelope
|
|
48
|
+
from taskferry.functions import FunctionRegistry
|
|
49
|
+
|
|
50
|
+
from .message import TaskferryMessage, build_message, check_version, decode_retry
|
|
51
|
+
|
|
52
|
+
logger = logging.getLogger("taskferry.celery")
|
|
53
|
+
|
|
54
|
+
DEFAULT_DISPATCH_TASK = "taskferry:dispatch"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def execute_message(
|
|
58
|
+
message: TaskferryMessage,
|
|
59
|
+
*,
|
|
60
|
+
registry: FunctionRegistry | None = None,
|
|
61
|
+
) -> Any:
|
|
62
|
+
"""Resolve and run one Taskferry message. Pure of Celery, so unit-testable."""
|
|
63
|
+
check_version(message)
|
|
64
|
+
return execute_envelope(message, registry=registry)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def register_dispatcher(
|
|
68
|
+
app: Any,
|
|
69
|
+
*,
|
|
70
|
+
name: str = DEFAULT_DISPATCH_TASK,
|
|
71
|
+
registry: FunctionRegistry | None = None,
|
|
72
|
+
**task_options: Any,
|
|
73
|
+
) -> Any:
|
|
74
|
+
"""Register the Taskferry dispatcher on a Celery ``app``.
|
|
75
|
+
|
|
76
|
+
Call once in the module your worker loads::
|
|
77
|
+
|
|
78
|
+
from celery import Celery
|
|
79
|
+
from taskferry_celery import register_dispatcher
|
|
80
|
+
|
|
81
|
+
app = Celery("myapp", broker="redis://localhost:6379/0")
|
|
82
|
+
register_dispatcher(app, registry=FunctionRegistry(allowed_modules=["myapp"]))
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
app: The Celery app.
|
|
86
|
+
name: Task name; must match the backend's ``dispatch_task``.
|
|
87
|
+
registry: Where task names resolve. Give it an allowlist in production.
|
|
88
|
+
task_options: Forwarded to ``@app.task`` (``max_retries``, ``acks_late``…).
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
The registered Celery task.
|
|
92
|
+
"""
|
|
93
|
+
task_options.setdefault("bind", True)
|
|
94
|
+
|
|
95
|
+
# app is typed Any: celery must not be a hard dependency of this package, so
|
|
96
|
+
# its decorator is untyped here.
|
|
97
|
+
@app.task(name=name, **task_options) # type: ignore[untyped-decorator]
|
|
98
|
+
def _taskferry_dispatch(self: Any, message: TaskferryMessage) -> Any:
|
|
99
|
+
policy = decode_retry(message)
|
|
100
|
+
try:
|
|
101
|
+
return execute_message(message, registry=registry)
|
|
102
|
+
except Exception as exc:
|
|
103
|
+
attempt = int(getattr(getattr(self, "request", None), "retries", 0) or 0) + 1
|
|
104
|
+
if policy.should_retry(exc, attempt):
|
|
105
|
+
# Celery owns the retry — a real re-queue with a real countdown —
|
|
106
|
+
# rather than this function looping and holding a worker slot.
|
|
107
|
+
# RetryOwner: exactly one layer retries, and here it is the engine.
|
|
108
|
+
delay = policy.delay_for(attempt + 1)
|
|
109
|
+
logger.info("requesting celery retry of attempt %d in %.1fs", attempt, delay)
|
|
110
|
+
raise self.retry(exc=exc, countdown=delay) from exc
|
|
111
|
+
raise
|
|
112
|
+
|
|
113
|
+
return _taskferry_dispatch
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
__all__ = [
|
|
117
|
+
"DEFAULT_DISPATCH_TASK",
|
|
118
|
+
"build_message",
|
|
119
|
+
"execute_message",
|
|
120
|
+
"register_dispatcher",
|
|
121
|
+
]
|