taskferry-procrastinate 0.2.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.
@@ -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,12 @@
1
+ # Changelog
2
+
3
+ All notable changes to `taskferry-procrastinate` are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
+ this project adheres to [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.2.0] — 2026-07-26
8
+
9
+ ### Added
10
+
11
+ - Initial release, extracted from the Django-coupled backends of `taskferry-django` 0.1
12
+ and rebuilt against the framework-agnostic Taskferry ports.
@@ -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,125 @@
1
+ Metadata-Version: 2.5
2
+ Name: taskferry-procrastinate
3
+ Version: 0.2.0
4
+ Summary: Procrastinate task backend for Taskferry — PostgreSQL-backed task execution.
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: postgresql,procrastinate,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: procrastinate
22
+ Requires-Dist: procrastinate>=2.0; extra == 'procrastinate'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # taskferry-procrastinate
26
+
27
+ Run [Taskferry](https://github.com/xiidigital/taskferry) tasks on
28
+ [Procrastinate](https://procrastinate.readthedocs.io) — a durable, PostgreSQL-backed
29
+ task engine.
30
+
31
+ ```mermaid
32
+ flowchart LR
33
+ APP["Application"]
34
+ TP["Taskferry"]
35
+ AD["taskferry-procrastinate"]
36
+ PRO["Procrastinate"]
37
+ PG["PostgreSQL"]
38
+
39
+ APP --> TP --> AD --> PRO --> PG
40
+ ```
41
+
42
+ Taskferry does not implement a queue, a worker, job reservation or retries.
43
+ Procrastinate already does all of that, correctly, on PostgreSQL. This package is
44
+ the translation layer between the two — and nothing else.
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install 'taskferry-procrastinate[procrastinate]'
50
+ ```
51
+
52
+ PostgreSQL becomes a dependency of your deployment only once you select this
53
+ backend. `taskferry` itself has no dependencies at all.
54
+
55
+ ## Submitting
56
+
57
+ ```python
58
+ from taskferry import Taskferry
59
+
60
+ runtime = Taskferry.from_mapping(
61
+ {
62
+ "backends": {"pg": {"factory": "procrastinate", "app": "myapp.tasks:app"}},
63
+ "defaults": {"task": "pg"},
64
+ }
65
+ )
66
+
67
+ runtime.tasks.submit("myapp.tasks:refresh_metadata", 42, queue="metadata")
68
+ ```
69
+
70
+ ## Executing
71
+
72
+ Register the dispatcher once, then run Procrastinate's own worker:
73
+
74
+ ```python
75
+ # myapp/tasks.py
76
+ from procrastinate import App, PsycopgConnector
77
+ from taskferry import FunctionRegistry
78
+ from taskferry_procrastinate import register_dispatcher
79
+
80
+ app = App(connector=PsycopgConnector(conninfo="postgresql://..."))
81
+
82
+ # An allowlist matters: task names arrive from the queue.
83
+ register_dispatcher(app, registry=FunctionRegistry(allowed_modules=["myapp"]))
84
+ ```
85
+
86
+ ```bash
87
+ procrastinate --app=myapp.tasks.app worker
88
+ ```
89
+
90
+ ## Capabilities
91
+
92
+ | Capability | Supported | How |
93
+ | ---------- | :-------: | --- |
94
+ | `SUBMIT` | yes | `defer()` |
95
+ | `STATE` | yes | job manager |
96
+ | `CANCEL` | yes | `cancel_job_by_id` |
97
+ | `DELAY` | yes | `schedule_at` |
98
+ | `PRIORITY` | yes | native job priority |
99
+ | `RETRY` | yes | engine-owned, via the retry signal |
100
+ | `DEDUPLICATION` | yes | `queueing_lock` |
101
+ | `RESULT` | **no** | Procrastinate stores no return values |
102
+
103
+ `RESULT` is absent because Procrastinate genuinely does not keep results.
104
+ Taskferry raises `UnsupportedCapability` rather than inventing a results table —
105
+ building queue features is precisely what this project exists not to do.
106
+
107
+ ## Backend options
108
+
109
+ ```python
110
+ TaskSpec(
111
+ task="myapp.tasks:reindex",
112
+ backend_options=BackendOptions(
113
+ {
114
+ "procrastinate": {
115
+ "lock": "reindex-42", # serialise jobs against a key
116
+ "queueing_lock": "reindex", # refuse a duplicate while one is pending
117
+ }
118
+ }
119
+ ),
120
+ )
121
+ ```
122
+
123
+ ## License
124
+
125
+ Apache-2.0.
@@ -0,0 +1,101 @@
1
+ # taskferry-procrastinate
2
+
3
+ Run [Taskferry](https://github.com/xiidigital/taskferry) tasks on
4
+ [Procrastinate](https://procrastinate.readthedocs.io) — a durable, PostgreSQL-backed
5
+ task engine.
6
+
7
+ ```mermaid
8
+ flowchart LR
9
+ APP["Application"]
10
+ TP["Taskferry"]
11
+ AD["taskferry-procrastinate"]
12
+ PRO["Procrastinate"]
13
+ PG["PostgreSQL"]
14
+
15
+ APP --> TP --> AD --> PRO --> PG
16
+ ```
17
+
18
+ Taskferry does not implement a queue, a worker, job reservation or retries.
19
+ Procrastinate already does all of that, correctly, on PostgreSQL. This package is
20
+ the translation layer between the two — and nothing else.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install 'taskferry-procrastinate[procrastinate]'
26
+ ```
27
+
28
+ PostgreSQL becomes a dependency of your deployment only once you select this
29
+ backend. `taskferry` itself has no dependencies at all.
30
+
31
+ ## Submitting
32
+
33
+ ```python
34
+ from taskferry import Taskferry
35
+
36
+ runtime = Taskferry.from_mapping(
37
+ {
38
+ "backends": {"pg": {"factory": "procrastinate", "app": "myapp.tasks:app"}},
39
+ "defaults": {"task": "pg"},
40
+ }
41
+ )
42
+
43
+ runtime.tasks.submit("myapp.tasks:refresh_metadata", 42, queue="metadata")
44
+ ```
45
+
46
+ ## Executing
47
+
48
+ Register the dispatcher once, then run Procrastinate's own worker:
49
+
50
+ ```python
51
+ # myapp/tasks.py
52
+ from procrastinate import App, PsycopgConnector
53
+ from taskferry import FunctionRegistry
54
+ from taskferry_procrastinate import register_dispatcher
55
+
56
+ app = App(connector=PsycopgConnector(conninfo="postgresql://..."))
57
+
58
+ # An allowlist matters: task names arrive from the queue.
59
+ register_dispatcher(app, registry=FunctionRegistry(allowed_modules=["myapp"]))
60
+ ```
61
+
62
+ ```bash
63
+ procrastinate --app=myapp.tasks.app worker
64
+ ```
65
+
66
+ ## Capabilities
67
+
68
+ | Capability | Supported | How |
69
+ | ---------- | :-------: | --- |
70
+ | `SUBMIT` | yes | `defer()` |
71
+ | `STATE` | yes | job manager |
72
+ | `CANCEL` | yes | `cancel_job_by_id` |
73
+ | `DELAY` | yes | `schedule_at` |
74
+ | `PRIORITY` | yes | native job priority |
75
+ | `RETRY` | yes | engine-owned, via the retry signal |
76
+ | `DEDUPLICATION` | yes | `queueing_lock` |
77
+ | `RESULT` | **no** | Procrastinate stores no return values |
78
+
79
+ `RESULT` is absent because Procrastinate genuinely does not keep results.
80
+ Taskferry raises `UnsupportedCapability` rather than inventing a results table —
81
+ building queue features is precisely what this project exists not to do.
82
+
83
+ ## Backend options
84
+
85
+ ```python
86
+ TaskSpec(
87
+ task="myapp.tasks:reindex",
88
+ backend_options=BackendOptions(
89
+ {
90
+ "procrastinate": {
91
+ "lock": "reindex-42", # serialise jobs against a key
92
+ "queueing_lock": "reindex", # refuse a duplicate while one is pending
93
+ }
94
+ }
95
+ ),
96
+ )
97
+ ```
98
+
99
+ ## License
100
+
101
+ Apache-2.0.
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "taskferry-procrastinate"
7
+ version = "0.2.0"
8
+ description = "Procrastinate task backend for Taskferry — PostgreSQL-backed task execution."
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", "procrastinate", "postgresql", "tasks"]
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
+ procrastinate = ["procrastinate>=2.0"]
28
+
29
+ [project.entry-points."taskferry.backends"]
30
+ procrastinate = "taskferry_procrastinate: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_procrastinate"]
39
+
40
+ [tool.hatch.build.targets.sdist]
41
+ include = ["src", "README.md", "CHANGELOG.md", "LICENSE"]
@@ -0,0 +1,74 @@
1
+ """Taskferry on Procrastinate — a PostgreSQL-backed task engine.
2
+
3
+ ```mermaid
4
+ flowchart LR
5
+ APP["Application"]
6
+ TP["Taskferry"]
7
+ AD["taskferry_procrastinate"]
8
+ PRO["Procrastinate"]
9
+ PG["PostgreSQL"]
10
+
11
+ APP --> TP --> AD --> PRO --> PG
12
+ ```
13
+
14
+ Procrastinate already solves the hard parts — a durable PostgreSQL queue, worker
15
+ processes, job reservation with `FOR UPDATE SKIP LOCKED`, retries, periodic
16
+ tasks. Taskferry does not reimplement any of that and does not want to. This
17
+ adapter translates a :class:`~taskferry.specs.TaskSpec` into a deferred
18
+ Procrastinate job and translates Procrastinate's states back.
19
+
20
+ PostgreSQL becomes a dependency of your deployment only when this adapter is
21
+ selected. ``taskferry`` itself never imports ``procrastinate`` or a database
22
+ driver, and an architectural test enforces that.
23
+
24
+ Two sides
25
+ ---------
26
+
27
+ **Submitting** (web process, CLI, anything)::
28
+
29
+ from taskferry import Taskferry
30
+
31
+ runtime = Taskferry.from_mapping({
32
+ "backends": {"pg": {"factory": "procrastinate", "app": "myapp.tasks:app"}},
33
+ "defaults": {"task": "pg"},
34
+ })
35
+ runtime.tasks.submit("myapp.tasks:refresh_metadata", 42, queue="metadata")
36
+
37
+ **Executing** (worker process) — register the dispatcher once on your app::
38
+
39
+ from procrastinate import App, PsycopgConnector
40
+ from taskferry_procrastinate import register_dispatcher
41
+
42
+ app = App(connector=PsycopgConnector(...))
43
+ register_dispatcher(app)
44
+
45
+ then run Procrastinate's own worker (``procrastinate worker``). Taskferry does not
46
+ supply a worker: that is exactly the sort of thing it delegates.
47
+
48
+ What crosses the wire is the portable message — a ``"package.module:function"``
49
+ name plus JSON arguments — never a pickled callable. See
50
+ :mod:`taskferry.functions`.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ from .backend import (
56
+ DEFAULT_DISPATCH_TASK,
57
+ ProcrastinateTaskBackend,
58
+ make_backend,
59
+ map_status,
60
+ )
61
+ from .worker import build_message, execute_message, register_dispatcher
62
+
63
+ __version__ = "0.2.0"
64
+
65
+ __all__ = [
66
+ "DEFAULT_DISPATCH_TASK",
67
+ "ProcrastinateTaskBackend",
68
+ "__version__",
69
+ "build_message",
70
+ "execute_message",
71
+ "make_backend",
72
+ "map_status",
73
+ "register_dispatcher",
74
+ ]
@@ -0,0 +1,336 @@
1
+ """The Procrastinate `TaskBackend`.
2
+
3
+ Translation, in both directions, and nothing else.
4
+
5
+ ```mermaid
6
+ flowchart LR
7
+ subgraph Taskferry
8
+ TS["TaskSpec<br/>queue · priority · delay · retry · idempotency_key"]
9
+ EX["Execution<br/>ExecutionState"]
10
+ end
11
+
12
+ subgraph Procrastinate
13
+ DEF["configure_task(...).defer()"]
14
+ JOB["job status<br/>todo · doing · succeeded · failed · cancelled"]
15
+ end
16
+
17
+ TS --> DEF
18
+ JOB --> EX
19
+ ```
20
+
21
+ Capabilities are advertised from what Procrastinate genuinely does:
22
+
23
+ * ``DELAY`` — ``schedule_at`` / ``schedule_in``;
24
+ * ``PRIORITY`` — native job priority;
25
+ * ``RETRY`` — the engine owns retries. The portable policy travels in the
26
+ message and the dispatcher turns a failure into Procrastinate's own retry
27
+ signal, so the job is genuinely re-queued by Procrastinate with the requested
28
+ delay. Taskferry never loops in-process pretending to retry;
29
+ * ``DEDUPLICATION`` — via ``queueing_lock``, which really does refuse a second
30
+ job while the first is pending;
31
+ * ``STATE`` — through the job manager.
32
+
33
+ ``RESULT`` is **not** advertised. Procrastinate is fire-and-forget by design: it
34
+ does not store a job's return value. Claiming otherwise here would mean inventing
35
+ a results table, which is a queue feature, and building queue features is the
36
+ thing this project exists not to do. Applications that need results write them
37
+ where they belong — the database row the task updated, an object store, a cache.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ from datetime import UTC, datetime
43
+ from typing import Any
44
+
45
+ from taskferry.capabilities import Capability, CapabilitySet
46
+ from taskferry.core.provider import ProviderMetadata
47
+ from taskferry.errors import ConfigurationError, ExecutionNotFound, SubmissionError
48
+ from taskferry.execution import (
49
+ Execution,
50
+ ExecutionId,
51
+ ExecutionKind,
52
+ ExecutionState,
53
+ new_execution_id,
54
+ )
55
+ from taskferry.ports import BaseBackend
56
+ from taskferry.specs import ExecutionSpec, TaskSpec
57
+ from taskferry.tracking import ExternalIdIndex, is_digits
58
+
59
+ from .message import build_message
60
+
61
+ DEFAULT_DISPATCH_TASK = "taskferry:dispatch"
62
+ """Name of the single Procrastinate task that runs every Taskferry message."""
63
+
64
+ PROCRASTINATE_CAPABILITIES = frozenset(
65
+ {
66
+ Capability.SUBMIT,
67
+ Capability.STATE,
68
+ Capability.CANCEL,
69
+ Capability.DELAY,
70
+ Capability.PRIORITY,
71
+ Capability.RETRY,
72
+ Capability.DEDUPLICATION,
73
+ }
74
+ )
75
+
76
+ #: Procrastinate job status -> portable state. ``aborting``/``aborted`` appear in
77
+ #: newer releases; both map to the Taskferry state that describes what an operator
78
+ #: actually sees, not the internal step.
79
+ _STATUS_MAP: dict[str, ExecutionState] = {
80
+ "todo": ExecutionState.QUEUED,
81
+ "doing": ExecutionState.RUNNING,
82
+ "succeeded": ExecutionState.SUCCEEDED,
83
+ "failed": ExecutionState.FAILED,
84
+ "cancelled": ExecutionState.CANCELLED,
85
+ "aborting": ExecutionState.RUNNING,
86
+ "aborted": ExecutionState.CANCELLED,
87
+ }
88
+
89
+
90
+ def map_status(status: object) -> ExecutionState:
91
+ """Map a Procrastinate job status to a portable state.
92
+
93
+ Pure, so it is unit-testable without a database. An unrecognised status maps
94
+ to ``UNKNOWN`` rather than to a guess — a new Procrastinate release adding a
95
+ status must not make Taskferry report something false.
96
+ """
97
+ if status is None:
98
+ return ExecutionState.UNKNOWN
99
+ key = getattr(status, "value", status)
100
+ return _STATUS_MAP.get(str(key).lower(), ExecutionState.UNKNOWN)
101
+
102
+
103
+ class ProcrastinateTaskBackend(BaseBackend):
104
+ """Defers Taskferry tasks as Procrastinate jobs.
105
+
106
+ Args:
107
+ app: A ``procrastinate.App``, or a ``"module:attribute"`` string resolved
108
+ on first use. A string keeps this backend constructible in a process
109
+ that has not yet configured its database connection.
110
+ dispatch_task: Name of the registered dispatcher task. Only change it if
111
+ you registered the dispatcher under a different name.
112
+ default_lock: ``lock`` applied when a spec does not set one. Procrastinate
113
+ serialises jobs sharing a lock, which is how you stop two workers
114
+ touching the same row.
115
+
116
+ Backend options, under the ``"procrastinate"`` namespace::
117
+
118
+ TaskSpec(
119
+ task="myapp.tasks:reindex",
120
+ backend_options=BackendOptions({"procrastinate": {
121
+ "lock": "reindex-42", # serialise against this key
122
+ "queueing_lock": "reindex", # refuse a duplicate while pending
123
+ }}),
124
+ )
125
+
126
+ Thread-safe once constructed: it holds a Procrastinate ``App``, which is
127
+ designed to be shared, and no mutable state of its own.
128
+ """
129
+
130
+ def __init__(
131
+ self,
132
+ *,
133
+ app: Any = None,
134
+ dispatch_task: str = DEFAULT_DISPATCH_TASK,
135
+ default_lock: str | None = None,
136
+ name: str = "procrastinate",
137
+ tracked_ids: int = 10_000,
138
+ ) -> None:
139
+ self._app = app
140
+ self._dispatch_task = dispatch_task
141
+ self._default_lock = default_lock
142
+ self._name = name
143
+ # Procrastinate knows nothing about Taskferry ids, so remember the
144
+ # pairing for the executions this process submitted; a bare numeric id
145
+ # from a dashboard is accepted too.
146
+ self._ids = ExternalIdIndex(capacity=tracked_ids, recognises=is_digits)
147
+
148
+ @property
149
+ def name(self) -> str:
150
+ return self._name
151
+
152
+ @property
153
+ def kind(self) -> ExecutionKind:
154
+ return ExecutionKind.TASK
155
+
156
+ @property
157
+ def capabilities(self) -> CapabilitySet:
158
+ return CapabilitySet(PROCRASTINATE_CAPABILITIES, provider=self._name)
159
+
160
+ # -- the app ---------------------------------------------------------------- #
161
+ def app(self) -> Any:
162
+ """The Procrastinate ``App``, resolving a dotted path on first use."""
163
+ if self._app is None:
164
+ raise ConfigurationError(
165
+ f"{self._name!r} needs a procrastinate App: pass app=<App> or "
166
+ "app='myapp.tasks:app' in the backend options"
167
+ )
168
+ if isinstance(self._app, str):
169
+ self._app = _import_attribute(self._app)
170
+ return self._app
171
+
172
+ # -- submission --------------------------------------------------------------- #
173
+ def _submit(self, spec: ExecutionSpec) -> Execution:
174
+ assert isinstance(spec, TaskSpec)
175
+ # Resolve the app first, outside the try below. A missing or unresolvable
176
+ # App is a ConfigurationError and must stay one — reporting it as "the
177
+ # engine refused the submission" sends whoever is debugging to look at
178
+ # PostgreSQL when the problem is a settings file.
179
+ app = self.app()
180
+ options = spec.options_for("procrastinate")
181
+ deferrer_kwargs: dict[str, Any] = {
182
+ "name": self._dispatch_task,
183
+ "queue": spec.queue,
184
+ "priority": spec.priority,
185
+ "schedule_at": spec.scheduled_for(),
186
+ }
187
+
188
+ lock = options.get("lock", self._default_lock)
189
+ if lock is not None:
190
+ deferrer_kwargs["lock"] = str(lock)
191
+
192
+ # An idempotency key maps onto queueing_lock, which is Procrastinate's
193
+ # real mechanism for "do not enqueue this twice while one is pending".
194
+ # It is honest deduplication, not an exactly-once promise.
195
+ queueing_lock = options.get("queueing_lock", spec.idempotency_key)
196
+ if queueing_lock is not None:
197
+ deferrer_kwargs["queueing_lock"] = str(queueing_lock)
198
+
199
+ for key, value in options.items():
200
+ if key not in {"lock", "queueing_lock"}:
201
+ deferrer_kwargs[key] = value
202
+
203
+ message = build_message(spec)
204
+ try:
205
+ deferrer = app.configure_task(**deferrer_kwargs)
206
+ job_id = deferrer.defer(message=message)
207
+ except Exception as exc:
208
+ raise SubmissionError(
209
+ f"procrastinate could not defer {spec.task!r} on queue {spec.queue!r}: {exc}",
210
+ backend=self._name,
211
+ ) from exc
212
+
213
+ now = datetime.now(UTC)
214
+ execution_id = new_execution_id(ExecutionKind.TASK)
215
+ self._ids.remember(str(execution_id), str(job_id))
216
+ return Execution(
217
+ id=execution_id,
218
+ kind=ExecutionKind.TASK,
219
+ backend=self._name,
220
+ state=ExecutionState.QUEUED,
221
+ name=spec.name,
222
+ created_at=now,
223
+ external_id=str(job_id),
224
+ correlation=spec.correlation,
225
+ provider_metadata=ProviderMetadata(
226
+ provider="postgres",
227
+ provider_id=str(job_id),
228
+ resource=f"queue:{spec.queue}",
229
+ labels=dict(spec.labels),
230
+ ),
231
+ metadata={"queue": spec.queue, "procrastinate_job_id": str(job_id)},
232
+ )
233
+
234
+ # -- observation ---------------------------------------------------------------- #
235
+ def _get(self, execution_id: ExecutionId) -> Execution:
236
+ """Look the job up by the Procrastinate id recorded at submission.
237
+
238
+ Taskferry ids are Taskferry's; Procrastinate never sees one. So ``get``
239
+ accepts either — a Taskferry id when this process submitted it, or the
240
+ engine's own numeric id, which is what an operator reads off a dashboard.
241
+ """
242
+ job = self._find_job(str(execution_id))
243
+ if job is None:
244
+ raise ExecutionNotFound(
245
+ f"procrastinate has no job {execution_id!r}; pass the procrastinate job id "
246
+ "when the execution was submitted by another process",
247
+ backend=self._name,
248
+ )
249
+ return self._execution_from_job(job, execution_id)
250
+
251
+ def _find_job(self, execution_id: str) -> Any:
252
+ numeric = self._ids.resolve(execution_id)
253
+ if numeric is None:
254
+ return None
255
+ manager = getattr(self.app(), "job_manager", None)
256
+ if manager is None: # pragma: no cover - very old procrastinate
257
+ raise ExecutionNotFound(
258
+ "this procrastinate App has no job_manager, so state cannot be read",
259
+ backend=self._name,
260
+ )
261
+ jobs = list(manager.list_jobs(id=int(numeric)))
262
+ return jobs[0] if jobs else None
263
+
264
+ def _execution_from_job(self, job: Any, execution_id: ExecutionId) -> Execution:
265
+ return Execution(
266
+ id=execution_id,
267
+ kind=ExecutionKind.TASK,
268
+ backend=self._name,
269
+ state=map_status(getattr(job, "status", None)),
270
+ name=str(getattr(job, "task_name", "") or ""),
271
+ external_id=str(getattr(job, "id", "")),
272
+ attempt=int(getattr(job, "attempts", 0) or 0) + 1,
273
+ provider_metadata=ProviderMetadata(
274
+ provider="postgres",
275
+ provider_id=str(getattr(job, "id", "")),
276
+ resource=f"queue:{getattr(job, 'queue_name', '')}",
277
+ ),
278
+ metadata={"queue": str(getattr(job, "queue_name", "") or "")},
279
+ )
280
+
281
+ def _cancel(self, execution_id: ExecutionId) -> Execution:
282
+ """Cancel through Procrastinate's own job manager.
283
+
284
+ A job that has already been picked up cannot be un-run; Procrastinate
285
+ reports that by refusing, and the refreshed state says what really
286
+ happened rather than claiming success.
287
+ """
288
+ numeric = self._ids.resolve(str(execution_id))
289
+ if numeric is None:
290
+ raise ExecutionNotFound(
291
+ f"{execution_id!r} was not submitted by this backend instance; pass the "
292
+ "procrastinate job id to cancel it from another process",
293
+ backend=self._name,
294
+ )
295
+ manager = self.app().job_manager
296
+ try:
297
+ manager.cancel_job_by_id(int(numeric))
298
+ except Exception as exc:
299
+ raise SubmissionError(
300
+ f"procrastinate could not cancel job {numeric}: {exc}", backend=self._name
301
+ ) from exc
302
+ return self._get(execution_id)
303
+
304
+
305
+ def _import_attribute(path: str) -> Any:
306
+ import importlib
307
+
308
+ module_path, sep, attr = path.partition(":")
309
+ if not sep:
310
+ module_path, _, attr = path.rpartition(".")
311
+ if not module_path or not attr:
312
+ raise ConfigurationError(f"invalid app reference {path!r}; expected 'module:attribute'")
313
+ try:
314
+ return getattr(importlib.import_module(module_path), attr)
315
+ except (ImportError, AttributeError) as exc:
316
+ raise ConfigurationError(f"cannot resolve procrastinate app {path!r}: {exc}") from exc
317
+
318
+
319
+ def make_backend(**options: Any) -> ProcrastinateTaskBackend:
320
+ """Entry point for ``{"factory": "procrastinate", ...}`` configuration."""
321
+ return ProcrastinateTaskBackend(
322
+ app=options.get("app"),
323
+ dispatch_task=str(options.get("dispatch_task", DEFAULT_DISPATCH_TASK)),
324
+ default_lock=options.get("default_lock"),
325
+ name=str(options.get("name", "procrastinate")),
326
+ tracked_ids=int(options.get("tracked_ids", 10_000)),
327
+ )
328
+
329
+
330
+ __all__ = [
331
+ "DEFAULT_DISPATCH_TASK",
332
+ "PROCRASTINATE_CAPABILITIES",
333
+ "ProcrastinateTaskBackend",
334
+ "make_backend",
335
+ "map_status",
336
+ ]
@@ -0,0 +1,60 @@
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. It lives in :mod:`taskferry.envelope` so
5
+ that Procrastinate, Cloud Tasks, SQS, Service Bus and Dramatiq cannot drift apart
6
+ on the format a worker has to understand.
7
+
8
+ This module stays as the import path the adapter's own tests and docs use, and as
9
+ the place to put anything genuinely Procrastinate-specific about the payload.
10
+ There is currently nothing, which is the point.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from taskferry.envelope import (
16
+ ENVELOPE_VERSION,
17
+ Envelope,
18
+ build_envelope,
19
+ decode_retry,
20
+ encode_retry,
21
+ read_correlation,
22
+ read_envelope,
23
+ )
24
+
25
+ #: Historical aliases: this adapter shipped them before the envelope moved into
26
+ #: the core. Kept so 0.2 adapter code and tests keep working.
27
+ MESSAGE_VERSION = ENVELOPE_VERSION
28
+ TaskferryMessage = Envelope
29
+ build_message = build_envelope
30
+
31
+
32
+ def check_version(message: object) -> None:
33
+ """Reject an envelope this worker does not understand.
34
+
35
+ Thin wrapper over :func:`taskferry.envelope.read_envelope` that raises
36
+ ``ValueError`` rather than ``SerializationError``, because a Procrastinate
37
+ worker treats any exception the same way and the narrower type reads better
38
+ in this adapter's own tests.
39
+ """
40
+ from taskferry.errors import SerializationError
41
+
42
+ try:
43
+ read_envelope(message)
44
+ except SerializationError as exc:
45
+ raise ValueError(str(exc)) from exc
46
+
47
+
48
+ __all__ = [
49
+ "ENVELOPE_VERSION",
50
+ "MESSAGE_VERSION",
51
+ "Envelope",
52
+ "TaskferryMessage",
53
+ "build_envelope",
54
+ "build_message",
55
+ "check_version",
56
+ "decode_retry",
57
+ "encode_retry",
58
+ "read_correlation",
59
+ "read_envelope",
60
+ ]
@@ -0,0 +1,156 @@
1
+ """The worker side — one Procrastinate task that runs every Taskferry message.
2
+
3
+ ```mermaid
4
+ sequenceDiagram
5
+ participant PG as PostgreSQL
6
+ participant W as procrastinate worker
7
+ participant D as taskferry:dispatch
8
+ participant REG as FunctionRegistry
9
+ participant FN as your function
10
+
11
+ PG->>W: reserve job
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 (discarded — see below)
17
+ D-->>W: done
18
+ W->>PG: mark succeeded
19
+ ```
20
+
21
+ Taskferry supplies **no worker**. You run ``procrastinate worker``; this module
22
+ only registers the function that worker calls. Reservation, concurrency,
23
+ shutdown, heartbeats and the listen/notify loop are Procrastinate's, and
24
+ rebuilding any of them here would be exactly the mistake this project is
25
+ organised to avoid.
26
+
27
+ Security
28
+ --------
29
+
30
+ The dispatcher resolves a task *name* that arrived from the queue. If untrusted
31
+ input can reach your queue, that resolution is an arbitrary-import primitive, so
32
+ pass a :class:`~taskferry.functions.FunctionRegistry` configured with an
33
+ allowlist::
34
+
35
+ registry = FunctionRegistry(allowed_modules=["myapp.tasks"])
36
+ register_dispatcher(app, registry=registry)
37
+
38
+ With no registry the dispatcher builds a permissive one — convenient in
39
+ development, and documented as something to tighten before production.
40
+
41
+ Return values
42
+ -------------
43
+
44
+ The dispatcher returns whatever the task returned, but Procrastinate does not
45
+ store it, and the backend does not advertise ``RESULT``. Write results where they
46
+ belong instead of expecting the queue to keep them.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import logging
52
+ from typing import Any
53
+
54
+ from taskferry.envelope import execute_envelope
55
+ from taskferry.functions import FunctionRegistry
56
+ from taskferry.retry import RetryPolicy
57
+
58
+ from .message import TaskferryMessage, build_message, check_version, decode_retry
59
+
60
+ logger = logging.getLogger("taskferry.procrastinate")
61
+
62
+ DEFAULT_DISPATCH_TASK = "taskferry:dispatch"
63
+
64
+
65
+ def execute_message(
66
+ message: TaskferryMessage,
67
+ *,
68
+ registry: FunctionRegistry | None = None,
69
+ ) -> Any:
70
+ """Resolve and run one Taskferry message. Pure of Procrastinate.
71
+
72
+ Kept independent of the engine so it can be unit-tested with a plain dict,
73
+ and reused by any other adapter that carries the same envelope.
74
+ """
75
+ check_version(message)
76
+ return execute_envelope(message, registry=registry)
77
+
78
+
79
+ def register_dispatcher(
80
+ app: Any,
81
+ *,
82
+ name: str = DEFAULT_DISPATCH_TASK,
83
+ registry: FunctionRegistry | None = None,
84
+ **task_options: Any,
85
+ ) -> Any:
86
+ """Register the Taskferry dispatcher on a Procrastinate ``App``.
87
+
88
+ Call once, at import time, in the module your worker loads::
89
+
90
+ app = App(connector=PsycopgConnector(...))
91
+ register_dispatcher(app, registry=FunctionRegistry(allowed_modules=["myapp"]))
92
+
93
+ Args:
94
+ app: The Procrastinate ``App``.
95
+ name: Task name. Must match the backend's ``dispatch_task``.
96
+ registry: Where task names resolve. Give it an allowlist in production.
97
+ task_options: Forwarded to ``@app.task`` (``pass_context``, ``retry``...).
98
+
99
+ Returns:
100
+ The registered Procrastinate task.
101
+ """
102
+ task_options.setdefault("pass_context", True)
103
+
104
+ # The App is deliberately typed Any: procrastinate must not be a hard
105
+ # dependency of this package, so its decorator is untyped here.
106
+ @app.task(name=name, **task_options) # type: ignore[untyped-decorator]
107
+ def _taskferry_dispatch(context: Any = None, *, message: TaskferryMessage) -> Any:
108
+ policy = decode_retry(message)
109
+ try:
110
+ return execute_message(message, registry=registry)
111
+ except Exception as exc:
112
+ attempt = _attempt_number(context)
113
+ if policy.should_retry(exc, attempt):
114
+ _request_engine_retry(policy, attempt, exc)
115
+ raise
116
+
117
+ return _taskferry_dispatch
118
+
119
+
120
+ def _attempt_number(context: Any) -> int:
121
+ """1-based attempt count, read from the Procrastinate job context."""
122
+ job = getattr(context, "job", None)
123
+ attempts = getattr(job, "attempts", None)
124
+ return int(attempts) + 1 if isinstance(attempts, int) else 1
125
+
126
+
127
+ def _request_engine_retry(policy: RetryPolicy, attempt: int, exc: Exception) -> None:
128
+ """Ask Procrastinate to re-queue this job, with the delay the policy asks for.
129
+
130
+ Raising Procrastinate's own retry exception means *Procrastinate* performs
131
+ the retry — a real re-queue with a real schedule — rather than this function
132
+ looping in the worker and holding a slot while it sleeps. That is the whole
133
+ point of :class:`~taskferry.retry.RetryOwner`: exactly one layer retries, and
134
+ here it is the engine.
135
+
136
+ If the installed Procrastinate does not expose the exception (very old, or a
137
+ future rename), the original error propagates and Procrastinate applies
138
+ whatever retry strategy the task was registered with. Guessing would be
139
+ worse than falling back to the engine's own default.
140
+ """
141
+ delay = policy.delay_for(attempt + 1)
142
+ try:
143
+ from procrastinate.exceptions import JobRetry
144
+ except ImportError: # pragma: no cover - depends on the installed version
145
+ logger.debug("procrastinate.exceptions.JobRetry unavailable; leaving retry to the engine")
146
+ return
147
+ logger.info("requesting retry of attempt %d in %.1fs after %s", attempt, delay, exc)
148
+ raise JobRetry(delay) from exc
149
+
150
+
151
+ __all__ = [
152
+ "DEFAULT_DISPATCH_TASK",
153
+ "build_message",
154
+ "execute_message",
155
+ "register_dispatcher",
156
+ ]