dramatiq-gcpubsub 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.
- dramatiq_gcpubsub-0.1.0/.gitignore +23 -0
- dramatiq_gcpubsub-0.1.0/LICENSE +201 -0
- dramatiq_gcpubsub-0.1.0/PKG-INFO +137 -0
- dramatiq_gcpubsub-0.1.0/README.md +111 -0
- dramatiq_gcpubsub-0.1.0/examples/README.md +51 -0
- dramatiq_gcpubsub-0.1.0/examples/__init__.py +1 -0
- dramatiq_gcpubsub-0.1.0/examples/send.py +33 -0
- dramatiq_gcpubsub-0.1.0/examples/tasks.py +39 -0
- dramatiq_gcpubsub-0.1.0/pyproject.toml +61 -0
- dramatiq_gcpubsub-0.1.0/src/dramatiq_gcpubsub/__init__.py +5 -0
- dramatiq_gcpubsub-0.1.0/src/dramatiq_gcpubsub/pubsub_broker.py +220 -0
- dramatiq_gcpubsub-0.1.0/tests/__init__.py +0 -0
- dramatiq_gcpubsub-0.1.0/tests/conftest.py +58 -0
- dramatiq_gcpubsub-0.1.0/tests/integration/__init__.py +0 -0
- dramatiq_gcpubsub-0.1.0/tests/integration/test_broker.py +65 -0
- dramatiq_gcpubsub-0.1.0/tests/unit/__init__.py +0 -0
- dramatiq_gcpubsub-0.1.0/tests/unit/test_broker.py +144 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
.eggs/
|
|
6
|
+
dist/
|
|
7
|
+
build/
|
|
8
|
+
|
|
9
|
+
# Virtual env
|
|
10
|
+
.venv/
|
|
11
|
+
venv/
|
|
12
|
+
env/
|
|
13
|
+
|
|
14
|
+
# Testing / coverage
|
|
15
|
+
.pytest_cache/
|
|
16
|
+
.coverage
|
|
17
|
+
htmlcov/
|
|
18
|
+
|
|
19
|
+
# IDE
|
|
20
|
+
.idea/
|
|
21
|
+
.vscode/
|
|
22
|
+
*.swp
|
|
23
|
+
*.swo
|
|
@@ -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 warranty 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 2026 dakaii
|
|
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/
|
|
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,137 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dramatiq-gcpubsub
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Google Cloud Pub/Sub broker for Dramatiq.
|
|
5
|
+
Project-URL: Repository, https://github.com/dakaii/dramatiq-gcpubsub
|
|
6
|
+
Project-URL: Issues, https://github.com/dakaii/dramatiq-gcpubsub/issues
|
|
7
|
+
Author: dakaii
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: dramatiq,google-cloud,pubsub
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: dramatiq
|
|
20
|
+
Requires-Dist: google-cloud-pubsub
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
23
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
24
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# dramatiq-gcpubsub
|
|
28
|
+
|
|
29
|
+
A [Dramatiq](https://dramatiq.io/) broker for [Google Cloud Pub/Sub](https://cloud.google.com/pubsub).
|
|
30
|
+
|
|
31
|
+
**Status:** alpha (`0.1.0`). APIs may change; see [limitations](#limitations-and-future-work).
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install dramatiq-gcpubsub
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
For local development of this repo:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install -e ".[dev]"
|
|
43
|
+
# or: make install
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import dramatiq
|
|
50
|
+
from dramatiq_gcpubsub import PubSubBroker
|
|
51
|
+
|
|
52
|
+
broker = PubSubBroker(project_id="your-gcp-project-id")
|
|
53
|
+
dramatiq.set_broker(broker)
|
|
54
|
+
|
|
55
|
+
@dramatiq.actor
|
|
56
|
+
def my_task(x, y):
|
|
57
|
+
return x + y
|
|
58
|
+
|
|
59
|
+
my_task.send(3, 7)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Example app (emulator)
|
|
63
|
+
|
|
64
|
+
In-repo demo under [`examples/`](examples/). Fastest path:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Terminal A: emulator + worker
|
|
68
|
+
make example
|
|
69
|
+
|
|
70
|
+
# Terminal B: enqueue sample tasks
|
|
71
|
+
make example-send
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
See [examples/README.md](examples/README.md) for non-Docker usage.
|
|
75
|
+
|
|
76
|
+
## Local development with the emulator
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
export PUBSUB_EMULATOR_HOST=localhost:8085
|
|
80
|
+
export PUBSUB_PROJECT_ID=test-project
|
|
81
|
+
dramatiq myapp.tasks
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Start the emulator:
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
make up
|
|
88
|
+
# or:
|
|
89
|
+
docker compose up -d pubsub-emulator
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Limitations and future work
|
|
93
|
+
|
|
94
|
+
- **Delayed messages** — `enqueue(..., delay=...)` is not supported yet; calling it raises `NotImplementedError`. Planned: use Pub/Sub scheduled publish (`publish_time`).
|
|
95
|
+
- **Dead-letter topic** — Subscriptions are created without a dead-letter policy. Planned: optional broker parameter to attach a dead-letter topic to subscriptions.
|
|
96
|
+
- **Publish batching** — Messages are published one at a time. Planned: optional batching for higher throughput.
|
|
97
|
+
|
|
98
|
+
## GCP permissions
|
|
99
|
+
|
|
100
|
+
For production, the service account used by your worker needs at least:
|
|
101
|
+
|
|
102
|
+
- `pubsub.topics.create`, `pubsub.topics.publish`
|
|
103
|
+
- `pubsub.subscriptions.create`, `pubsub.subscriptions.consume`, `pubsub.subscriptions.update`
|
|
104
|
+
|
|
105
|
+
Or use the predefined role `roles/pubsub.admin` for full access.
|
|
106
|
+
|
|
107
|
+
## Testing
|
|
108
|
+
|
|
109
|
+
You do **not** need a real GCP project for tests. Use the Pub/Sub emulator.
|
|
110
|
+
|
|
111
|
+
### Unit tests (no emulator)
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
make test-unit
|
|
115
|
+
# or: pytest tests/unit/ -v
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Integration tests (emulator)
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
make test
|
|
122
|
+
# or: docker compose run --rm tests
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Integration tests are skipped if `PUBSUB_EMULATOR_HOST` is not set.
|
|
126
|
+
|
|
127
|
+
### CI
|
|
128
|
+
|
|
129
|
+
GitHub Actions runs lint, unit tests on Python 3.10–3.12, and integration tests via docker compose on every push/PR. Releases re-run that suite before publishing to PyPI.
|
|
130
|
+
|
|
131
|
+
## Publishing to PyPI
|
|
132
|
+
|
|
133
|
+
See [docs/PUBLISHING.md](docs/PUBLISHING.md).
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
Apache 2.0
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# dramatiq-gcpubsub
|
|
2
|
+
|
|
3
|
+
A [Dramatiq](https://dramatiq.io/) broker for [Google Cloud Pub/Sub](https://cloud.google.com/pubsub).
|
|
4
|
+
|
|
5
|
+
**Status:** alpha (`0.1.0`). APIs may change; see [limitations](#limitations-and-future-work).
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install dramatiq-gcpubsub
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
For local development of this repo:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install -e ".[dev]"
|
|
17
|
+
# or: make install
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import dramatiq
|
|
24
|
+
from dramatiq_gcpubsub import PubSubBroker
|
|
25
|
+
|
|
26
|
+
broker = PubSubBroker(project_id="your-gcp-project-id")
|
|
27
|
+
dramatiq.set_broker(broker)
|
|
28
|
+
|
|
29
|
+
@dramatiq.actor
|
|
30
|
+
def my_task(x, y):
|
|
31
|
+
return x + y
|
|
32
|
+
|
|
33
|
+
my_task.send(3, 7)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Example app (emulator)
|
|
37
|
+
|
|
38
|
+
In-repo demo under [`examples/`](examples/). Fastest path:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
# Terminal A: emulator + worker
|
|
42
|
+
make example
|
|
43
|
+
|
|
44
|
+
# Terminal B: enqueue sample tasks
|
|
45
|
+
make example-send
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
See [examples/README.md](examples/README.md) for non-Docker usage.
|
|
49
|
+
|
|
50
|
+
## Local development with the emulator
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
export PUBSUB_EMULATOR_HOST=localhost:8085
|
|
54
|
+
export PUBSUB_PROJECT_ID=test-project
|
|
55
|
+
dramatiq myapp.tasks
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Start the emulator:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
make up
|
|
62
|
+
# or:
|
|
63
|
+
docker compose up -d pubsub-emulator
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Limitations and future work
|
|
67
|
+
|
|
68
|
+
- **Delayed messages** — `enqueue(..., delay=...)` is not supported yet; calling it raises `NotImplementedError`. Planned: use Pub/Sub scheduled publish (`publish_time`).
|
|
69
|
+
- **Dead-letter topic** — Subscriptions are created without a dead-letter policy. Planned: optional broker parameter to attach a dead-letter topic to subscriptions.
|
|
70
|
+
- **Publish batching** — Messages are published one at a time. Planned: optional batching for higher throughput.
|
|
71
|
+
|
|
72
|
+
## GCP permissions
|
|
73
|
+
|
|
74
|
+
For production, the service account used by your worker needs at least:
|
|
75
|
+
|
|
76
|
+
- `pubsub.topics.create`, `pubsub.topics.publish`
|
|
77
|
+
- `pubsub.subscriptions.create`, `pubsub.subscriptions.consume`, `pubsub.subscriptions.update`
|
|
78
|
+
|
|
79
|
+
Or use the predefined role `roles/pubsub.admin` for full access.
|
|
80
|
+
|
|
81
|
+
## Testing
|
|
82
|
+
|
|
83
|
+
You do **not** need a real GCP project for tests. Use the Pub/Sub emulator.
|
|
84
|
+
|
|
85
|
+
### Unit tests (no emulator)
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
make test-unit
|
|
89
|
+
# or: pytest tests/unit/ -v
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Integration tests (emulator)
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
make test
|
|
96
|
+
# or: docker compose run --rm tests
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Integration tests are skipped if `PUBSUB_EMULATOR_HOST` is not set.
|
|
100
|
+
|
|
101
|
+
### CI
|
|
102
|
+
|
|
103
|
+
GitHub Actions runs lint, unit tests on Python 3.10–3.12, and integration tests via docker compose on every push/PR. Releases re-run that suite before publishing to PyPI.
|
|
104
|
+
|
|
105
|
+
## Publishing to PyPI
|
|
106
|
+
|
|
107
|
+
See [docs/PUBLISHING.md](docs/PUBLISHING.md).
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Apache 2.0
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Examples
|
|
2
|
+
|
|
3
|
+
Small in-repo demo of `dramatiq-gcpubsub` against the Pub/Sub emulator.
|
|
4
|
+
|
|
5
|
+
This is meant for humans and local smoke checks. Automated coverage lives in
|
|
6
|
+
`tests/` (unit + integration). A separate external smoke-test repo can come
|
|
7
|
+
later if you want cross-release install validation (`pip install` from PyPI /
|
|
8
|
+
TestPyPI); keep library correctness tests here.
|
|
9
|
+
|
|
10
|
+
## Quick start (Docker Compose)
|
|
11
|
+
|
|
12
|
+
From the repo root:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
# Terminal A: emulator + worker
|
|
16
|
+
docker compose --profile example up --build
|
|
17
|
+
|
|
18
|
+
# Terminal B: enqueue two tasks (one-shot)
|
|
19
|
+
docker compose --profile example run --rm example-send
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
You should see `add(...)` and `hello, ...` in the worker logs.
|
|
23
|
+
|
|
24
|
+
Tear down:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
docker compose --profile example down
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Local (no compose for the app)
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# Terminal 1
|
|
34
|
+
make up
|
|
35
|
+
|
|
36
|
+
# Terminal 2
|
|
37
|
+
export PUBSUB_EMULATOR_HOST=localhost:8085 PUBSUB_PROJECT_ID=test-project
|
|
38
|
+
pip install -e ".[dev]"
|
|
39
|
+
dramatiq examples.tasks
|
|
40
|
+
|
|
41
|
+
# Terminal 3
|
|
42
|
+
export PUBSUB_EMULATOR_HOST=localhost:8085 PUBSUB_PROJECT_ID=test-project
|
|
43
|
+
python -m examples.send
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Files
|
|
47
|
+
|
|
48
|
+
| File | Role |
|
|
49
|
+
| --- | --- |
|
|
50
|
+
| `tasks.py` | Broker setup + sample actors |
|
|
51
|
+
| `send.py` | CLI to enqueue sample messages |
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Runnable examples for dramatiq-gcpubsub."""
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Enqueue example tasks. Run while a worker is consuming ``examples.tasks``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from examples.tasks import add, greet
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main() -> None:
|
|
12
|
+
parser = argparse.ArgumentParser(description="Send sample tasks to the example worker")
|
|
13
|
+
parser.add_argument("--x", type=int, default=3)
|
|
14
|
+
parser.add_argument("--y", type=int, default=7)
|
|
15
|
+
parser.add_argument("--name", default="dramatiq-gcpubsub")
|
|
16
|
+
parser.add_argument(
|
|
17
|
+
"--wait",
|
|
18
|
+
type=float,
|
|
19
|
+
default=0.0,
|
|
20
|
+
help="Seconds to sleep after enqueue (useful in compose one-shots)",
|
|
21
|
+
)
|
|
22
|
+
args = parser.parse_args()
|
|
23
|
+
|
|
24
|
+
add.send(args.x, args.y)
|
|
25
|
+
greet.send(args.name)
|
|
26
|
+
print(f"Sent add({args.x}, {args.y}) and greet({args.name!r})", flush=True)
|
|
27
|
+
|
|
28
|
+
if args.wait > 0:
|
|
29
|
+
time.sleep(args.wait)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
if __name__ == "__main__":
|
|
33
|
+
main()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Example Dramatiq actors backed by the Pub/Sub broker.
|
|
3
|
+
|
|
4
|
+
Used by the compose ``example`` profile and local smoke checks.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
import dramatiq
|
|
12
|
+
from dramatiq.middleware import AgeLimit, Callbacks, Pipelines, Retries, TimeLimit
|
|
13
|
+
|
|
14
|
+
from dramatiq_gcpubsub import PubSubBroker
|
|
15
|
+
|
|
16
|
+
PROJECT_ID = os.environ.get("PUBSUB_PROJECT_ID", "test-project")
|
|
17
|
+
|
|
18
|
+
broker = PubSubBroker(
|
|
19
|
+
project_id=PROJECT_ID,
|
|
20
|
+
middleware=[
|
|
21
|
+
AgeLimit(),
|
|
22
|
+
TimeLimit(),
|
|
23
|
+
Callbacks(),
|
|
24
|
+
Pipelines(),
|
|
25
|
+
Retries(min_backoff=1000, max_backoff=900000, max_retries=96),
|
|
26
|
+
],
|
|
27
|
+
)
|
|
28
|
+
dramatiq.set_broker(broker)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dramatiq.actor
|
|
32
|
+
def add(x: int, y: int) -> None:
|
|
33
|
+
result = x + y
|
|
34
|
+
print(f"add({x}, {y}) = {result}", flush=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dramatiq.actor
|
|
38
|
+
def greet(name: str) -> None:
|
|
39
|
+
print(f"hello, {name}", flush=True)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "dramatiq-gcpubsub"
|
|
3
|
+
description = "A Google Cloud Pub/Sub broker for Dramatiq."
|
|
4
|
+
license = "Apache-2.0"
|
|
5
|
+
keywords = ["dramatiq", "pubsub", "google-cloud"]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
authors = [{ name = "dakaii" }]
|
|
8
|
+
classifiers = [
|
|
9
|
+
"Development Status :: 3 - Alpha",
|
|
10
|
+
"License :: OSI Approved :: Apache Software License",
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Programming Language :: Python :: 3.10",
|
|
13
|
+
"Programming Language :: Python :: 3.11",
|
|
14
|
+
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Topic :: System :: Distributed Computing",
|
|
16
|
+
]
|
|
17
|
+
version = "0.1.0"
|
|
18
|
+
requires-python = ">=3.10"
|
|
19
|
+
dependencies = [
|
|
20
|
+
"dramatiq",
|
|
21
|
+
"google-cloud-pubsub",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Repository = "https://github.com/dakaii/dramatiq-gcpubsub"
|
|
26
|
+
Issues = "https://github.com/dakaii/dramatiq-gcpubsub/issues"
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
dev = [
|
|
30
|
+
"pytest",
|
|
31
|
+
"pytest-cov",
|
|
32
|
+
"ruff",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["hatchling"]
|
|
37
|
+
build-backend = "hatchling.build"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.sdist]
|
|
40
|
+
include = [
|
|
41
|
+
"/src",
|
|
42
|
+
"/tests",
|
|
43
|
+
"/examples",
|
|
44
|
+
"/LICENSE",
|
|
45
|
+
"/README.md",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.wheel]
|
|
49
|
+
packages = ["src/dramatiq_gcpubsub"]
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
testpaths = ["tests"]
|
|
53
|
+
addopts = ["-v", "--cov=src/dramatiq_gcpubsub", "--cov-report=term-missing"]
|
|
54
|
+
|
|
55
|
+
[tool.ruff]
|
|
56
|
+
src = ["src", "tests", "examples"]
|
|
57
|
+
line-length = 100
|
|
58
|
+
target-version = "py310"
|
|
59
|
+
|
|
60
|
+
[tool.ruff.lint]
|
|
61
|
+
extend-select = ["I", "UP"]
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Google Cloud Pub/Sub broker for Dramatiq."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import deque
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import dramatiq
|
|
10
|
+
from dramatiq.logging import get_logger
|
|
11
|
+
from google.api_core import exceptions as gcp_exceptions
|
|
12
|
+
from google.cloud import pubsub_v1
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _topic_id(queue_name: str) -> str:
|
|
16
|
+
return f"dramatiq-{queue_name.replace('_', '-')}"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _subscription_id(queue_name: str) -> str:
|
|
20
|
+
return f"dramatiq-{queue_name.replace('_', '-')}-sub"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PubSubMessageProxy(dramatiq.MessageProxy):
|
|
24
|
+
"""Wrapper around a Pub/Sub received message."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, ack_id: str, subscription_path: str, message: dramatiq.Message) -> None:
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self._ack_id = ack_id
|
|
29
|
+
self._subscription_path = subscription_path
|
|
30
|
+
|
|
31
|
+
def ack(self, subscriber: pubsub_v1.SubscriberClient) -> None:
|
|
32
|
+
"""Acknowledge the message."""
|
|
33
|
+
subscriber.acknowledge(
|
|
34
|
+
request={
|
|
35
|
+
"subscription": self._subscription_path,
|
|
36
|
+
"ack_ids": [self._ack_id],
|
|
37
|
+
}
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
def nack(self, subscriber: pubsub_v1.SubscriberClient) -> None:
|
|
41
|
+
"""Nack the message so it is redelivered."""
|
|
42
|
+
subscriber.modify_ack_deadline(
|
|
43
|
+
request={
|
|
44
|
+
"subscription": self._subscription_path,
|
|
45
|
+
"ack_ids": [self._ack_id],
|
|
46
|
+
"ack_deadline_seconds": 0,
|
|
47
|
+
}
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class PubSubConsumer(dramatiq.Consumer):
|
|
52
|
+
"""Consumer that pulls messages from a Pub/Sub subscription."""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
subscriber: pubsub_v1.SubscriberClient,
|
|
57
|
+
subscription_path: str,
|
|
58
|
+
prefetch: int,
|
|
59
|
+
timeout_ms: int,
|
|
60
|
+
) -> None:
|
|
61
|
+
self.logger = get_logger(__name__, type(self))
|
|
62
|
+
self._subscriber = subscriber
|
|
63
|
+
self._subscription_path = subscription_path
|
|
64
|
+
self._prefetch = max(1, min(prefetch, 100)) # Pub/Sub max is 1000, cap for sanity
|
|
65
|
+
self._timeout_ms = timeout_ms
|
|
66
|
+
self._messages: deque[PubSubMessageProxy] = deque()
|
|
67
|
+
|
|
68
|
+
def __next__(self) -> PubSubMessageProxy | None:
|
|
69
|
+
try:
|
|
70
|
+
return self._messages.popleft()
|
|
71
|
+
except IndexError:
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
request = {
|
|
75
|
+
"subscription": self._subscription_path,
|
|
76
|
+
"max_messages": self._prefetch,
|
|
77
|
+
}
|
|
78
|
+
# Use a finite timeout so pull() does not block indefinitely (e.g. in tests).
|
|
79
|
+
timeout_sec = max(1, self._timeout_ms // 1000) if self._timeout_ms else 30
|
|
80
|
+
try:
|
|
81
|
+
response = self._subscriber.pull(
|
|
82
|
+
request=request,
|
|
83
|
+
timeout=timeout_sec,
|
|
84
|
+
)
|
|
85
|
+
except Exception:
|
|
86
|
+
self.logger.exception("Pull failed")
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
for received in response.received_messages:
|
|
90
|
+
try:
|
|
91
|
+
data = received.message.data
|
|
92
|
+
if not isinstance(data, bytes):
|
|
93
|
+
data = data.encode("utf-8") if isinstance(data, str) else bytes(data)
|
|
94
|
+
decoded = dramatiq.Message.decode(data)
|
|
95
|
+
proxy = PubSubMessageProxy(
|
|
96
|
+
ack_id=received.ack_id,
|
|
97
|
+
subscription_path=self._subscription_path,
|
|
98
|
+
message=decoded,
|
|
99
|
+
)
|
|
100
|
+
self._messages.append(proxy)
|
|
101
|
+
except Exception:
|
|
102
|
+
self.logger.exception("Failed to decode message")
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
return self._messages.popleft()
|
|
106
|
+
except IndexError:
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
def ack(self, message: PubSubMessageProxy) -> None:
|
|
110
|
+
message.ack(self._subscriber)
|
|
111
|
+
|
|
112
|
+
def nack(self, message: PubSubMessageProxy) -> None:
|
|
113
|
+
message.nack(self._subscriber)
|
|
114
|
+
|
|
115
|
+
def requeue(self, messages: Iterable[PubSubMessageProxy]) -> None:
|
|
116
|
+
for msg in messages:
|
|
117
|
+
msg.nack(self._subscriber)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class PubSubBroker(dramatiq.Broker):
|
|
121
|
+
"""Dramatiq broker using Google Cloud Pub/Sub.
|
|
122
|
+
|
|
123
|
+
Uses one topic per queue (e.g. queue \"default\" -> topic \"dramatiq-default\",
|
|
124
|
+
subscription \"dramatiq-default-sub\"). Uses pull subscriptions for workers.
|
|
125
|
+
|
|
126
|
+
Parameters:
|
|
127
|
+
project_id: GCP project ID.
|
|
128
|
+
publisher_options: Optional kwargs for PublisherClient (e.g. client_options for emulator).
|
|
129
|
+
subscriber_options: Optional kwargs for SubscriberClient.
|
|
130
|
+
middleware: Optional list of Dramatiq middleware.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
def __init__(
|
|
134
|
+
self,
|
|
135
|
+
project_id: str,
|
|
136
|
+
*,
|
|
137
|
+
publisher_options: dict[str, Any] | None = None,
|
|
138
|
+
subscriber_options: dict[str, Any] | None = None,
|
|
139
|
+
middleware: list[dramatiq.Middleware] | None = None,
|
|
140
|
+
) -> None:
|
|
141
|
+
super().__init__(middleware=middleware)
|
|
142
|
+
self.project_id = project_id
|
|
143
|
+
self._publisher = pubsub_v1.PublisherClient(**(publisher_options or {}))
|
|
144
|
+
self._subscriber = pubsub_v1.SubscriberClient(**(subscriber_options or {}))
|
|
145
|
+
self.queues: dict[str, str] = {} # queue_name -> subscription_path
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def consumer_class(self) -> type[PubSubConsumer]:
|
|
149
|
+
return PubSubConsumer
|
|
150
|
+
|
|
151
|
+
def _topic_path(self, queue_name: str) -> str:
|
|
152
|
+
return self._publisher.topic_path(self.project_id, _topic_id(queue_name))
|
|
153
|
+
|
|
154
|
+
def _subscription_path(self, queue_name: str) -> str:
|
|
155
|
+
return self._subscriber.subscription_path(self.project_id, _subscription_id(queue_name))
|
|
156
|
+
|
|
157
|
+
def declare_queue(self, queue_name: str) -> None:
|
|
158
|
+
if queue_name in self.queues:
|
|
159
|
+
return
|
|
160
|
+
self.emit_before("declare_queue", queue_name)
|
|
161
|
+
topic_path = self._topic_path(queue_name)
|
|
162
|
+
subscription_path = self._subscription_path(queue_name)
|
|
163
|
+
|
|
164
|
+
try:
|
|
165
|
+
self._publisher.create_topic(request={"name": topic_path})
|
|
166
|
+
self.logger.debug("Created topic %s", topic_path)
|
|
167
|
+
except gcp_exceptions.AlreadyExists:
|
|
168
|
+
pass
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
self._subscriber.create_subscription(
|
|
172
|
+
request={
|
|
173
|
+
"name": subscription_path,
|
|
174
|
+
"topic": topic_path,
|
|
175
|
+
}
|
|
176
|
+
)
|
|
177
|
+
self.logger.debug("Created subscription %s", subscription_path)
|
|
178
|
+
except gcp_exceptions.AlreadyExists:
|
|
179
|
+
pass
|
|
180
|
+
|
|
181
|
+
self.queues[queue_name] = subscription_path
|
|
182
|
+
self.emit_after("declare_queue", queue_name)
|
|
183
|
+
|
|
184
|
+
def enqueue(self, message: dramatiq.Message, *, delay: int | None = None) -> dramatiq.Message:
|
|
185
|
+
if delay is not None and delay > 0:
|
|
186
|
+
raise NotImplementedError("Delayed messages (eta) are not yet supported")
|
|
187
|
+
queue_name = message.queue_name
|
|
188
|
+
if queue_name not in self.queues:
|
|
189
|
+
raise dramatiq.QueueNotFound(queue_name)
|
|
190
|
+
topic_path = self._topic_path(queue_name)
|
|
191
|
+
self.emit_before("enqueue", message, delay)
|
|
192
|
+
data = message.encode()
|
|
193
|
+
self._publisher.publish(topic_path, data)
|
|
194
|
+
self.logger.debug("Enqueued message %s to %s", message.message_id, queue_name)
|
|
195
|
+
self.emit_after("enqueue", message, delay)
|
|
196
|
+
return message
|
|
197
|
+
|
|
198
|
+
def consume(
|
|
199
|
+
self,
|
|
200
|
+
queue_name: str,
|
|
201
|
+
prefetch: int = 1,
|
|
202
|
+
timeout: int = 30000,
|
|
203
|
+
) -> PubSubConsumer:
|
|
204
|
+
try:
|
|
205
|
+
subscription_path = self.queues[queue_name]
|
|
206
|
+
except KeyError:
|
|
207
|
+
raise dramatiq.QueueNotFound(queue_name) from None
|
|
208
|
+
return self.consumer_class(
|
|
209
|
+
self._subscriber,
|
|
210
|
+
subscription_path,
|
|
211
|
+
prefetch,
|
|
212
|
+
timeout,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
def get_declared_queues(self) -> set[str]:
|
|
216
|
+
return set(self.queues.keys())
|
|
217
|
+
|
|
218
|
+
def close(self) -> None:
|
|
219
|
+
self._publisher.transport.close()
|
|
220
|
+
self._subscriber.transport.close()
|
|
File without changes
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Pytest fixtures for dramatiq-gcpubsub tests."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import uuid
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
|
|
7
|
+
import dramatiq
|
|
8
|
+
import pytest
|
|
9
|
+
from dramatiq.middleware import AgeLimit, Callbacks, Pipelines, Retries, TimeLimit
|
|
10
|
+
|
|
11
|
+
from dramatiq_gcpubsub import PubSubBroker
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _emulator_client_options():
|
|
15
|
+
"""Client options to connect to Pub/Sub emulator when PUBSUB_EMULATOR_HOST is set."""
|
|
16
|
+
host = os.environ.get("PUBSUB_EMULATOR_HOST")
|
|
17
|
+
if not host:
|
|
18
|
+
return {}
|
|
19
|
+
from google.api_core.client_options import ClientOptions
|
|
20
|
+
|
|
21
|
+
return {"client_options": ClientOptions(api_endpoint=host)}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@pytest.fixture
|
|
25
|
+
def broker() -> Iterator[PubSubBroker]:
|
|
26
|
+
"""Create a PubSubBroker connected to the emulator (or real GCP if env not set)."""
|
|
27
|
+
project_id = os.environ.get("PUBSUB_PROJECT_ID", "test-project")
|
|
28
|
+
client_opts = _emulator_client_options()
|
|
29
|
+
broker = PubSubBroker(
|
|
30
|
+
project_id=project_id,
|
|
31
|
+
middleware=[
|
|
32
|
+
AgeLimit(),
|
|
33
|
+
TimeLimit(),
|
|
34
|
+
Callbacks(),
|
|
35
|
+
Pipelines(),
|
|
36
|
+
Retries(min_backoff=1000, max_backoff=900000, max_retries=96),
|
|
37
|
+
],
|
|
38
|
+
publisher_options=client_opts,
|
|
39
|
+
subscriber_options=client_opts,
|
|
40
|
+
)
|
|
41
|
+
dramatiq.set_broker(broker)
|
|
42
|
+
yield broker
|
|
43
|
+
broker.close()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.fixture
|
|
47
|
+
def queue_name(broker: PubSubBroker) -> str:
|
|
48
|
+
"""Unique queue name per test."""
|
|
49
|
+
return f"queue_{uuid.uuid4().hex[:8]}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@pytest.fixture
|
|
53
|
+
def worker(broker: PubSubBroker):
|
|
54
|
+
"""Start a Dramatiq worker for the broker."""
|
|
55
|
+
worker = dramatiq.Worker(broker)
|
|
56
|
+
worker.start()
|
|
57
|
+
yield worker
|
|
58
|
+
worker.stop()
|
|
File without changes
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Integration tests for PubSubBroker (require Pub/Sub emulator)."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
import dramatiq
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@pytest.mark.skipif(
|
|
10
|
+
not __import__("os").environ.get("PUBSUB_EMULATOR_HOST"),
|
|
11
|
+
reason="PUBSUB_EMULATOR_HOST not set; run with docker compose or set env",
|
|
12
|
+
)
|
|
13
|
+
def test_can_enqueue_and_process_messages(broker, worker, queue_name):
|
|
14
|
+
db = []
|
|
15
|
+
|
|
16
|
+
@dramatiq.actor(queue_name=queue_name)
|
|
17
|
+
def do_work(x):
|
|
18
|
+
db.append(x)
|
|
19
|
+
|
|
20
|
+
do_work.send(1)
|
|
21
|
+
time.sleep(2)
|
|
22
|
+
assert db == [1]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@pytest.mark.skipif(
|
|
26
|
+
not __import__("os").environ.get("PUBSUB_EMULATOR_HOST"),
|
|
27
|
+
reason="PUBSUB_EMULATOR_HOST not set",
|
|
28
|
+
)
|
|
29
|
+
def test_can_requeue_consumed_messages(broker, queue_name):
|
|
30
|
+
@dramatiq.actor(queue_name=queue_name)
|
|
31
|
+
def do_work():
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
do_work.send()
|
|
35
|
+
time.sleep(1)
|
|
36
|
+
|
|
37
|
+
consumer = broker.consume(queue_name)
|
|
38
|
+
first_message = next(consumer)
|
|
39
|
+
assert first_message is not None
|
|
40
|
+
consumer.requeue([first_message])
|
|
41
|
+
|
|
42
|
+
second_message = next(consumer)
|
|
43
|
+
assert second_message is not None
|
|
44
|
+
assert first_message.message_id == second_message.message_id
|
|
45
|
+
consumer.ack(second_message)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@pytest.mark.skipif(
|
|
49
|
+
not __import__("os").environ.get("PUBSUB_EMULATOR_HOST"),
|
|
50
|
+
reason="PUBSUB_EMULATOR_HOST not set",
|
|
51
|
+
)
|
|
52
|
+
def test_can_ack_and_nack(broker, queue_name):
|
|
53
|
+
@dramatiq.actor(queue_name=queue_name)
|
|
54
|
+
def do_work():
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
do_work.send()
|
|
58
|
+
time.sleep(1)
|
|
59
|
+
|
|
60
|
+
consumer = broker.consume(queue_name)
|
|
61
|
+
msg = next(consumer)
|
|
62
|
+
assert msg is not None
|
|
63
|
+
consumer.ack(msg)
|
|
64
|
+
# Verify ack succeeded (message removed from subscription); we do not
|
|
65
|
+
# call next(consumer) again to avoid blocking on emulator's pull behavior.
|
|
File without changes
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Unit tests for PubSubBroker (mocked Pub/Sub)."""
|
|
2
|
+
|
|
3
|
+
from unittest.mock import MagicMock, patch
|
|
4
|
+
|
|
5
|
+
import dramatiq
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from dramatiq_gcpubsub import PubSubBroker
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@patch("dramatiq_gcpubsub.pubsub_broker.pubsub_v1")
|
|
12
|
+
def test_declare_queue_creates_topic_and_subscription(mock_pubsub_v1):
|
|
13
|
+
publisher = MagicMock()
|
|
14
|
+
publisher.topic_path.return_value = "projects/test-project/topics/dramatiq-default"
|
|
15
|
+
subscriber = MagicMock()
|
|
16
|
+
subscriber.subscription_path.return_value = (
|
|
17
|
+
"projects/test-project/subscriptions/dramatiq-default-sub"
|
|
18
|
+
)
|
|
19
|
+
mock_pubsub_v1.PublisherClient.return_value = publisher
|
|
20
|
+
mock_pubsub_v1.SubscriberClient.return_value = subscriber
|
|
21
|
+
|
|
22
|
+
broker = PubSubBroker(project_id="test-project")
|
|
23
|
+
broker.declare_queue("default")
|
|
24
|
+
|
|
25
|
+
assert "default" in broker.queues
|
|
26
|
+
publisher.create_topic.assert_called_once()
|
|
27
|
+
call = publisher.create_topic.call_args
|
|
28
|
+
assert call.kwargs["request"]["name"] == "projects/test-project/topics/dramatiq-default"
|
|
29
|
+
|
|
30
|
+
subscriber.create_subscription.assert_called_once()
|
|
31
|
+
call = subscriber.create_subscription.call_args
|
|
32
|
+
req = call.kwargs["request"]
|
|
33
|
+
assert req["name"] == "projects/test-project/subscriptions/dramatiq-default-sub"
|
|
34
|
+
assert req["topic"] == "projects/test-project/topics/dramatiq-default"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@patch("dramatiq_gcpubsub.pubsub_broker.pubsub_v1")
|
|
38
|
+
def test_declare_queue_idempotent(mock_pubsub_v1):
|
|
39
|
+
publisher = MagicMock()
|
|
40
|
+
publisher.topic_path.return_value = "projects/test-project/topics/dramatiq-default"
|
|
41
|
+
subscriber = MagicMock()
|
|
42
|
+
subscriber.subscription_path.return_value = (
|
|
43
|
+
"projects/test-project/subscriptions/dramatiq-default-sub"
|
|
44
|
+
)
|
|
45
|
+
mock_pubsub_v1.PublisherClient.return_value = publisher
|
|
46
|
+
mock_pubsub_v1.SubscriberClient.return_value = subscriber
|
|
47
|
+
|
|
48
|
+
broker = PubSubBroker(project_id="test-project")
|
|
49
|
+
broker.declare_queue("default")
|
|
50
|
+
broker.declare_queue("default")
|
|
51
|
+
|
|
52
|
+
publisher.create_topic.assert_called_once()
|
|
53
|
+
subscriber.create_subscription.assert_called_once()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@patch("dramatiq_gcpubsub.pubsub_broker.pubsub_v1")
|
|
57
|
+
def test_enqueue_publishes_encoded_message(mock_pubsub_v1):
|
|
58
|
+
publisher = MagicMock()
|
|
59
|
+
publisher.topic_path.return_value = "projects/test-project/topics/dramatiq-default"
|
|
60
|
+
subscriber = MagicMock()
|
|
61
|
+
mock_pubsub_v1.PublisherClient.return_value = publisher
|
|
62
|
+
mock_pubsub_v1.SubscriberClient.return_value = subscriber
|
|
63
|
+
|
|
64
|
+
broker = PubSubBroker(project_id="test-project")
|
|
65
|
+
broker.queues["default"] = "projects/test-project/subscriptions/dramatiq-default-sub"
|
|
66
|
+
dramatiq.set_broker(broker)
|
|
67
|
+
|
|
68
|
+
@dramatiq.actor(queue_name="default")
|
|
69
|
+
def noop():
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
message = noop.message()
|
|
73
|
+
broker.enqueue(message)
|
|
74
|
+
|
|
75
|
+
publisher.publish.assert_called_once()
|
|
76
|
+
call = publisher.publish.call_args
|
|
77
|
+
topic_path, data = call.args
|
|
78
|
+
assert topic_path == "projects/test-project/topics/dramatiq-default"
|
|
79
|
+
assert isinstance(data, bytes)
|
|
80
|
+
# Decode round-trip
|
|
81
|
+
decoded = dramatiq.Message.decode(data)
|
|
82
|
+
assert decoded.actor_name == "noop"
|
|
83
|
+
assert decoded.queue_name == "default"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@patch("dramatiq_gcpubsub.pubsub_broker.pubsub_v1")
|
|
87
|
+
def test_enqueue_raises_queue_not_found_for_undeclared_queue(mock_pubsub_v1):
|
|
88
|
+
mock_pubsub_v1.PublisherClient.return_value = MagicMock()
|
|
89
|
+
mock_pubsub_v1.SubscriberClient.return_value = MagicMock()
|
|
90
|
+
|
|
91
|
+
broker = PubSubBroker(project_id="test-project")
|
|
92
|
+
# Do not declare the queue; create message manually so declare_actor is not called
|
|
93
|
+
message = dramatiq.Message(
|
|
94
|
+
queue_name="unknown",
|
|
95
|
+
actor_name="noop",
|
|
96
|
+
args=(),
|
|
97
|
+
kwargs={},
|
|
98
|
+
options={},
|
|
99
|
+
message_id="test-id",
|
|
100
|
+
message_timestamp=0,
|
|
101
|
+
)
|
|
102
|
+
with pytest.raises(dramatiq.QueueNotFound):
|
|
103
|
+
broker.enqueue(message)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@patch("dramatiq_gcpubsub.pubsub_broker.pubsub_v1")
|
|
107
|
+
def test_enqueue_delayed_raises_not_implemented(mock_pubsub_v1):
|
|
108
|
+
mock_pubsub_v1.PublisherClient.return_value = MagicMock()
|
|
109
|
+
mock_pubsub_v1.SubscriberClient.return_value = MagicMock()
|
|
110
|
+
|
|
111
|
+
broker = PubSubBroker(project_id="test-project")
|
|
112
|
+
broker.queues["default"] = "projects/test-project/subscriptions/dramatiq-default-sub"
|
|
113
|
+
dramatiq.set_broker(broker)
|
|
114
|
+
|
|
115
|
+
@dramatiq.actor(queue_name="default")
|
|
116
|
+
def noop():
|
|
117
|
+
pass
|
|
118
|
+
|
|
119
|
+
message = noop.message()
|
|
120
|
+
with pytest.raises(NotImplementedError):
|
|
121
|
+
broker.enqueue(message, delay=5000)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@patch("dramatiq_gcpubsub.pubsub_broker.pubsub_v1")
|
|
125
|
+
def test_consume_raises_queue_not_found_for_undeclared_queue(mock_pubsub_v1):
|
|
126
|
+
mock_pubsub_v1.PublisherClient.return_value = MagicMock()
|
|
127
|
+
mock_pubsub_v1.SubscriberClient.return_value = MagicMock()
|
|
128
|
+
|
|
129
|
+
broker = PubSubBroker(project_id="test-project")
|
|
130
|
+
with pytest.raises(dramatiq.QueueNotFound):
|
|
131
|
+
broker.consume("unknown")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@patch("dramatiq_gcpubsub.pubsub_broker.pubsub_v1")
|
|
135
|
+
def test_get_declared_queues(mock_pubsub_v1):
|
|
136
|
+
mock_pubsub_v1.PublisherClient.return_value = MagicMock()
|
|
137
|
+
mock_pubsub_v1.SubscriberClient.return_value = MagicMock()
|
|
138
|
+
|
|
139
|
+
broker = PubSubBroker(project_id="test-project")
|
|
140
|
+
assert broker.get_declared_queues() == set()
|
|
141
|
+
|
|
142
|
+
broker.queues["default"] = "sub-path"
|
|
143
|
+
broker.queues["high"] = "sub-path-2"
|
|
144
|
+
assert broker.get_declared_queues() == {"default", "high"}
|