zigmq 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.
- zigmq-0.1.0/LICENSE +201 -0
- zigmq-0.1.0/PKG-INFO +120 -0
- zigmq-0.1.0/README.md +97 -0
- zigmq-0.1.0/pyproject.toml +36 -0
- zigmq-0.1.0/setup.cfg +4 -0
- zigmq-0.1.0/src/zigmq/__init__.py +28 -0
- zigmq-0.1.0/src/zigmq/client.py +452 -0
- zigmq-0.1.0/src/zigmq/errors.py +31 -0
- zigmq-0.1.0/src/zigmq/models.py +20 -0
- zigmq-0.1.0/src/zigmq.egg-info/PKG-INFO +120 -0
- zigmq-0.1.0/src/zigmq.egg-info/SOURCES.txt +12 -0
- zigmq-0.1.0/src/zigmq.egg-info/dependency_links.txt +1 -0
- zigmq-0.1.0/src/zigmq.egg-info/top_level.txt +1 -0
- zigmq-0.1.0/tests/test_client.py +130 -0
zigmq-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
zigmq-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: zigmq
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A tiny, pythonic SDK for the ZigMQ text protocol.
|
|
5
|
+
Author: reasonz
|
|
6
|
+
Project-URL: Homepage, https://github.com/reasonz/zigMQ-python-SDK
|
|
7
|
+
Project-URL: Repository, https://github.com/reasonz/zigMQ-python-SDK
|
|
8
|
+
Keywords: zigmq,queue,pubsub,messaging
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Communications
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# zigMQ Python SDK
|
|
25
|
+
|
|
26
|
+
`zigmq` is a tiny, pythonic SDK for the [ZigMQ](https://github.com/reasonz/zigMQ) text protocol.
|
|
27
|
+
|
|
28
|
+
By default, the SDK connects to `127.0.0.1:8388`.
|
|
29
|
+
|
|
30
|
+
The goal of this SDK is deliberately narrow:
|
|
31
|
+
|
|
32
|
+
- one small sync client for queue/admin commands
|
|
33
|
+
- one dedicated subscriber client for pub/sub delivery
|
|
34
|
+
- no dependency, no ORM-style abstraction, no magic reconnect layer
|
|
35
|
+
- protocol-compatible with the current ZigMQ server behavior
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install zigmq
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Local development:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
cd zigMQ-python-SDK
|
|
47
|
+
pip install -e .
|
|
48
|
+
python -m unittest -v
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Quick Start
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from zigmq import Client
|
|
55
|
+
|
|
56
|
+
with Client() as mq:
|
|
57
|
+
mq.send("jobs", "hello world")
|
|
58
|
+
print(mq.recv("jobs"))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Pub/Sub:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from zigmq import Client, Subscriber
|
|
65
|
+
|
|
66
|
+
with Subscriber() as sub:
|
|
67
|
+
sub.subscribe("news")
|
|
68
|
+
|
|
69
|
+
with Client() as mq:
|
|
70
|
+
delivered = mq.publish("news", "shipped")
|
|
71
|
+
print(delivered)
|
|
72
|
+
|
|
73
|
+
event = sub.get()
|
|
74
|
+
print(event.topic, event.message)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## API
|
|
78
|
+
|
|
79
|
+
### `Client`
|
|
80
|
+
|
|
81
|
+
- `ping() -> str`
|
|
82
|
+
- `info() -> Info`
|
|
83
|
+
- `send(queue, message) -> None`
|
|
84
|
+
- `recv(queue) -> str`
|
|
85
|
+
- `recv_bytes(queue) -> bytes`
|
|
86
|
+
- `peek(queue) -> str`
|
|
87
|
+
- `peek_bytes(queue) -> bytes`
|
|
88
|
+
- `queue_length(queue) -> int`
|
|
89
|
+
- `create_queue(queue) -> None`
|
|
90
|
+
- `list_queues() -> list[str]`
|
|
91
|
+
- `publish(topic, message) -> int`
|
|
92
|
+
- `list_topics() -> dict[str, int]`
|
|
93
|
+
- `subscriber(*topics) -> Subscriber`
|
|
94
|
+
|
|
95
|
+
Short protocol-style aliases are also available: `mq`, `len`, `queues`, `pub`, `topics`.
|
|
96
|
+
|
|
97
|
+
### `Subscriber`
|
|
98
|
+
|
|
99
|
+
- `subscribe(*topics) -> None`
|
|
100
|
+
- `unsubscribe(*topics) -> None`
|
|
101
|
+
- `get(timeout=None) -> Event`
|
|
102
|
+
- iteration support: `for event in sub: ...`
|
|
103
|
+
|
|
104
|
+
## Design Notes
|
|
105
|
+
|
|
106
|
+
- This SDK is text-first, because ZigMQ itself is a line-based text protocol.
|
|
107
|
+
- The default connection target is `127.0.0.1:8388`.
|
|
108
|
+
- Queue/topic names cannot contain whitespace or line breaks.
|
|
109
|
+
- Message bodies can contain spaces, but cannot contain `\\r` or `\\n`.
|
|
110
|
+
- `queues`, `topics`, and `info` follow the current ZigMQ server behavior and are parsed from multi-line responses.
|
|
111
|
+
|
|
112
|
+
## Publish To PyPI
|
|
113
|
+
|
|
114
|
+
Update `version` in [pyproject.toml](./pyproject.toml), then:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
cd zigMQ-python-SDK
|
|
118
|
+
python -m build
|
|
119
|
+
twine upload dist/*
|
|
120
|
+
```
|
zigmq-0.1.0/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# zigMQ Python SDK
|
|
2
|
+
|
|
3
|
+
`zigmq` is a tiny, pythonic SDK for the [ZigMQ](https://github.com/reasonz/zigMQ) text protocol.
|
|
4
|
+
|
|
5
|
+
By default, the SDK connects to `127.0.0.1:8388`.
|
|
6
|
+
|
|
7
|
+
The goal of this SDK is deliberately narrow:
|
|
8
|
+
|
|
9
|
+
- one small sync client for queue/admin commands
|
|
10
|
+
- one dedicated subscriber client for pub/sub delivery
|
|
11
|
+
- no dependency, no ORM-style abstraction, no magic reconnect layer
|
|
12
|
+
- protocol-compatible with the current ZigMQ server behavior
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install zigmq
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Local development:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
cd zigMQ-python-SDK
|
|
24
|
+
pip install -e .
|
|
25
|
+
python -m unittest -v
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Quick Start
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from zigmq import Client
|
|
32
|
+
|
|
33
|
+
with Client() as mq:
|
|
34
|
+
mq.send("jobs", "hello world")
|
|
35
|
+
print(mq.recv("jobs"))
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Pub/Sub:
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from zigmq import Client, Subscriber
|
|
42
|
+
|
|
43
|
+
with Subscriber() as sub:
|
|
44
|
+
sub.subscribe("news")
|
|
45
|
+
|
|
46
|
+
with Client() as mq:
|
|
47
|
+
delivered = mq.publish("news", "shipped")
|
|
48
|
+
print(delivered)
|
|
49
|
+
|
|
50
|
+
event = sub.get()
|
|
51
|
+
print(event.topic, event.message)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## API
|
|
55
|
+
|
|
56
|
+
### `Client`
|
|
57
|
+
|
|
58
|
+
- `ping() -> str`
|
|
59
|
+
- `info() -> Info`
|
|
60
|
+
- `send(queue, message) -> None`
|
|
61
|
+
- `recv(queue) -> str`
|
|
62
|
+
- `recv_bytes(queue) -> bytes`
|
|
63
|
+
- `peek(queue) -> str`
|
|
64
|
+
- `peek_bytes(queue) -> bytes`
|
|
65
|
+
- `queue_length(queue) -> int`
|
|
66
|
+
- `create_queue(queue) -> None`
|
|
67
|
+
- `list_queues() -> list[str]`
|
|
68
|
+
- `publish(topic, message) -> int`
|
|
69
|
+
- `list_topics() -> dict[str, int]`
|
|
70
|
+
- `subscriber(*topics) -> Subscriber`
|
|
71
|
+
|
|
72
|
+
Short protocol-style aliases are also available: `mq`, `len`, `queues`, `pub`, `topics`.
|
|
73
|
+
|
|
74
|
+
### `Subscriber`
|
|
75
|
+
|
|
76
|
+
- `subscribe(*topics) -> None`
|
|
77
|
+
- `unsubscribe(*topics) -> None`
|
|
78
|
+
- `get(timeout=None) -> Event`
|
|
79
|
+
- iteration support: `for event in sub: ...`
|
|
80
|
+
|
|
81
|
+
## Design Notes
|
|
82
|
+
|
|
83
|
+
- This SDK is text-first, because ZigMQ itself is a line-based text protocol.
|
|
84
|
+
- The default connection target is `127.0.0.1:8388`.
|
|
85
|
+
- Queue/topic names cannot contain whitespace or line breaks.
|
|
86
|
+
- Message bodies can contain spaces, but cannot contain `\\r` or `\\n`.
|
|
87
|
+
- `queues`, `topics`, and `info` follow the current ZigMQ server behavior and are parsed from multi-line responses.
|
|
88
|
+
|
|
89
|
+
## Publish To PyPI
|
|
90
|
+
|
|
91
|
+
Update `version` in [pyproject.toml](./pyproject.toml), then:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
cd zigMQ-python-SDK
|
|
95
|
+
python -m build
|
|
96
|
+
twine upload dist/*
|
|
97
|
+
```
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "zigmq"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A tiny, pythonic SDK for the ZigMQ text protocol."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
authors = [
|
|
12
|
+
{ name = "reasonz" },
|
|
13
|
+
]
|
|
14
|
+
keywords = ["zigmq", "queue", "pubsub", "messaging"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Programming Language :: Python :: 3.9",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Topic :: Communications",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/reasonz/zigMQ-python-SDK"
|
|
30
|
+
Repository = "https://github.com/reasonz/zigMQ-python-SDK"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools]
|
|
33
|
+
package-dir = {"" = "src"}
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.packages.find]
|
|
36
|
+
where = ["src"]
|
zigmq-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from .client import Client, Subscriber
|
|
2
|
+
from .errors import (
|
|
3
|
+
ConnectionClosedError,
|
|
4
|
+
EmptyError,
|
|
5
|
+
ProtocolError,
|
|
6
|
+
QueueFullError,
|
|
7
|
+
QueueNotFoundError,
|
|
8
|
+
ServerError,
|
|
9
|
+
TimeoutError,
|
|
10
|
+
ZigMQError,
|
|
11
|
+
)
|
|
12
|
+
from .models import Event, Info
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"Client",
|
|
16
|
+
"ConnectionClosedError",
|
|
17
|
+
"EmptyError",
|
|
18
|
+
"Event",
|
|
19
|
+
"Info",
|
|
20
|
+
"ProtocolError",
|
|
21
|
+
"QueueFullError",
|
|
22
|
+
"QueueNotFoundError",
|
|
23
|
+
"ServerError",
|
|
24
|
+
"Subscriber",
|
|
25
|
+
"TimeoutError",
|
|
26
|
+
"ZigMQError",
|
|
27
|
+
]
|
|
28
|
+
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import socket
|
|
4
|
+
import time
|
|
5
|
+
from collections import deque
|
|
6
|
+
from typing import Deque, Iterator
|
|
7
|
+
|
|
8
|
+
from .errors import (
|
|
9
|
+
ConnectionClosedError,
|
|
10
|
+
EmptyError,
|
|
11
|
+
ProtocolError,
|
|
12
|
+
QueueFullError,
|
|
13
|
+
QueueNotFoundError,
|
|
14
|
+
ServerError,
|
|
15
|
+
TimeoutError,
|
|
16
|
+
)
|
|
17
|
+
from .models import Event, Info
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class _SocketProtocol:
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
host: str,
|
|
24
|
+
port: int,
|
|
25
|
+
*,
|
|
26
|
+
timeout: float = 1.0,
|
|
27
|
+
idle_timeout: float = 0.08,
|
|
28
|
+
encoding: str = "utf-8",
|
|
29
|
+
) -> None:
|
|
30
|
+
self.host = host
|
|
31
|
+
self.port = port
|
|
32
|
+
self.timeout = timeout
|
|
33
|
+
self.idle_timeout = idle_timeout
|
|
34
|
+
self.encoding = encoding
|
|
35
|
+
self.sock = socket.create_connection((host, port), timeout=timeout)
|
|
36
|
+
self.sock.settimeout(timeout)
|
|
37
|
+
self._buffer = bytearray()
|
|
38
|
+
|
|
39
|
+
def close(self) -> None:
|
|
40
|
+
try:
|
|
41
|
+
self.sock.close()
|
|
42
|
+
except OSError:
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
def _send_command(self, op: str, name: str | None = None, body: str | bytes | None = None) -> None:
|
|
46
|
+
parts = [_encode_name(op)]
|
|
47
|
+
if name is not None:
|
|
48
|
+
parts.append(_encode_name(name))
|
|
49
|
+
payload = b" ".join(parts)
|
|
50
|
+
if body is not None:
|
|
51
|
+
payload += b" " + _encode_body(body, self.encoding)
|
|
52
|
+
self.sock.sendall(payload + b"\r\n")
|
|
53
|
+
|
|
54
|
+
def _read_line(self, timeout: float | None = None) -> bytes:
|
|
55
|
+
timeout = self.timeout if timeout is None else timeout
|
|
56
|
+
self.sock.settimeout(timeout)
|
|
57
|
+
|
|
58
|
+
while True:
|
|
59
|
+
index = self._buffer.find(b"\r\n")
|
|
60
|
+
if index != -1:
|
|
61
|
+
line = bytes(self._buffer[:index])
|
|
62
|
+
del self._buffer[: index + 2]
|
|
63
|
+
return line
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
chunk = self.sock.recv(4096)
|
|
67
|
+
except socket.timeout as exc:
|
|
68
|
+
raise TimeoutError("timed out waiting for server response") from exc
|
|
69
|
+
|
|
70
|
+
if not chunk:
|
|
71
|
+
raise ConnectionClosedError("server closed the connection")
|
|
72
|
+
|
|
73
|
+
self._buffer.extend(chunk)
|
|
74
|
+
|
|
75
|
+
def _read_exact(self, size: int) -> bytes:
|
|
76
|
+
while len(self._buffer) < size:
|
|
77
|
+
try:
|
|
78
|
+
chunk = self.sock.recv(4096)
|
|
79
|
+
except socket.timeout as exc:
|
|
80
|
+
raise TimeoutError("timed out waiting for server response") from exc
|
|
81
|
+
|
|
82
|
+
if not chunk:
|
|
83
|
+
raise ConnectionClosedError("server closed the connection")
|
|
84
|
+
|
|
85
|
+
self._buffer.extend(chunk)
|
|
86
|
+
|
|
87
|
+
data = bytes(self._buffer[:size])
|
|
88
|
+
del self._buffer[:size]
|
|
89
|
+
return data
|
|
90
|
+
|
|
91
|
+
def _read_one(self, timeout: float | None = None) -> tuple[str, object]:
|
|
92
|
+
line = self._read_line(timeout=timeout)
|
|
93
|
+
if not line:
|
|
94
|
+
raise ProtocolError("empty server response")
|
|
95
|
+
|
|
96
|
+
prefix = line[:1]
|
|
97
|
+
payload = line[1:]
|
|
98
|
+
|
|
99
|
+
if prefix == b"$":
|
|
100
|
+
try:
|
|
101
|
+
length = int(payload.decode("ascii"))
|
|
102
|
+
except ValueError as exc:
|
|
103
|
+
raise ProtocolError(f"invalid bulk header: {line!r}") from exc
|
|
104
|
+
|
|
105
|
+
body = self._read_exact(length)
|
|
106
|
+
trailer = self._read_exact(2)
|
|
107
|
+
if trailer != b"\r\n":
|
|
108
|
+
raise ProtocolError("bulk response missing CRLF trailer")
|
|
109
|
+
return ("bulk", body)
|
|
110
|
+
|
|
111
|
+
if prefix == b"-":
|
|
112
|
+
message = _decode_text(payload, self.encoding)
|
|
113
|
+
if message.startswith("ERR "):
|
|
114
|
+
message = message[4:]
|
|
115
|
+
return ("error", message)
|
|
116
|
+
|
|
117
|
+
if prefix == b"+":
|
|
118
|
+
if b":" in payload and not payload.startswith(b"OK ") and not payload.startswith(b"ZigMQ "):
|
|
119
|
+
topic, _, body = payload.partition(b":")
|
|
120
|
+
return (
|
|
121
|
+
"event",
|
|
122
|
+
Event(
|
|
123
|
+
topic=_decode_text(topic, self.encoding),
|
|
124
|
+
message=_decode_text(body, self.encoding),
|
|
125
|
+
data=bytes(body),
|
|
126
|
+
),
|
|
127
|
+
)
|
|
128
|
+
return ("status", _decode_text(payload, self.encoding))
|
|
129
|
+
|
|
130
|
+
raise ProtocolError(f"unknown response prefix: {line!r}")
|
|
131
|
+
|
|
132
|
+
def _read_until_idle(self) -> bytes:
|
|
133
|
+
chunks: list[bytes] = []
|
|
134
|
+
|
|
135
|
+
if self._buffer:
|
|
136
|
+
chunks.append(bytes(self._buffer))
|
|
137
|
+
self._buffer.clear()
|
|
138
|
+
|
|
139
|
+
deadline = time.monotonic() + self.timeout
|
|
140
|
+
while not chunks:
|
|
141
|
+
if time.monotonic() > deadline:
|
|
142
|
+
raise TimeoutError("timed out waiting for server response")
|
|
143
|
+
|
|
144
|
+
try:
|
|
145
|
+
chunk = self.sock.recv(4096)
|
|
146
|
+
except socket.timeout:
|
|
147
|
+
continue
|
|
148
|
+
|
|
149
|
+
if not chunk:
|
|
150
|
+
raise ConnectionClosedError("server closed the connection")
|
|
151
|
+
|
|
152
|
+
chunks.append(chunk)
|
|
153
|
+
|
|
154
|
+
self.sock.settimeout(self.idle_timeout)
|
|
155
|
+
while True:
|
|
156
|
+
try:
|
|
157
|
+
chunk = self.sock.recv(4096)
|
|
158
|
+
except socket.timeout:
|
|
159
|
+
break
|
|
160
|
+
|
|
161
|
+
if not chunk:
|
|
162
|
+
break
|
|
163
|
+
|
|
164
|
+
chunks.append(chunk)
|
|
165
|
+
|
|
166
|
+
self.sock.settimeout(self.timeout)
|
|
167
|
+
return b"".join(chunks)
|
|
168
|
+
|
|
169
|
+
def _request_status(self, op: str, name: str | None = None, body: str | bytes | None = None) -> str:
|
|
170
|
+
self._send_command(op, name, body)
|
|
171
|
+
kind, value = self._read_one()
|
|
172
|
+
if kind == "error":
|
|
173
|
+
_raise_server_error(str(value))
|
|
174
|
+
if kind != "status":
|
|
175
|
+
raise ProtocolError(f"expected status response, got {kind}")
|
|
176
|
+
return str(value)
|
|
177
|
+
|
|
178
|
+
def _request_bulk(self, op: str, name: str) -> bytes:
|
|
179
|
+
self._send_command(op, name)
|
|
180
|
+
kind, value = self._read_one()
|
|
181
|
+
if kind == "error":
|
|
182
|
+
_raise_server_error(str(value))
|
|
183
|
+
if kind != "bulk":
|
|
184
|
+
raise ProtocolError(f"expected bulk response, got {kind}")
|
|
185
|
+
return bytes(value)
|
|
186
|
+
|
|
187
|
+
def _request_multiline(self, op: str) -> bytes:
|
|
188
|
+
self._send_command(op)
|
|
189
|
+
return self._read_until_idle()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class Client:
|
|
193
|
+
def __init__(
|
|
194
|
+
self,
|
|
195
|
+
host: str = "127.0.0.1",
|
|
196
|
+
port: int = 8388,
|
|
197
|
+
*,
|
|
198
|
+
timeout: float = 1.0,
|
|
199
|
+
idle_timeout: float = 0.08,
|
|
200
|
+
encoding: str = "utf-8",
|
|
201
|
+
) -> None:
|
|
202
|
+
self._conn = _SocketProtocol(
|
|
203
|
+
host,
|
|
204
|
+
port,
|
|
205
|
+
timeout=timeout,
|
|
206
|
+
idle_timeout=idle_timeout,
|
|
207
|
+
encoding=encoding,
|
|
208
|
+
)
|
|
209
|
+
self.host = host
|
|
210
|
+
self.port = port
|
|
211
|
+
self.timeout = timeout
|
|
212
|
+
self.idle_timeout = idle_timeout
|
|
213
|
+
self.encoding = encoding
|
|
214
|
+
|
|
215
|
+
def close(self) -> None:
|
|
216
|
+
self._conn.close()
|
|
217
|
+
|
|
218
|
+
def __enter__(self) -> Client:
|
|
219
|
+
return self
|
|
220
|
+
|
|
221
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
222
|
+
self.close()
|
|
223
|
+
|
|
224
|
+
def ping(self) -> str:
|
|
225
|
+
status = self._conn._request_status("ping")
|
|
226
|
+
if status != "PONG":
|
|
227
|
+
raise ProtocolError(f"unexpected ping response: {status!r}")
|
|
228
|
+
return status
|
|
229
|
+
|
|
230
|
+
def info(self) -> Info:
|
|
231
|
+
raw = self._conn._request_multiline("info")
|
|
232
|
+
lines = _parse_listing_lines(raw)
|
|
233
|
+
if not lines or not lines[0].startswith("ZigMQ "):
|
|
234
|
+
raise ProtocolError(f"invalid info response: {raw!r}")
|
|
235
|
+
|
|
236
|
+
fields = {}
|
|
237
|
+
for line in lines[1:]:
|
|
238
|
+
key, sep, value = line.partition(":")
|
|
239
|
+
if sep != ":":
|
|
240
|
+
raise ProtocolError(f"invalid info field: {line!r}")
|
|
241
|
+
fields[key] = value
|
|
242
|
+
|
|
243
|
+
return Info(
|
|
244
|
+
banner=lines[0],
|
|
245
|
+
version=lines[0].split(" ", 1)[1],
|
|
246
|
+
queues=int(fields["queues"]),
|
|
247
|
+
topics=int(fields["topics"]),
|
|
248
|
+
initial_capacity=int(fields["initial_capacity"]),
|
|
249
|
+
max_capacity=int(fields["max_capacity"]),
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
def send(self, queue: str, message: str | bytes) -> None:
|
|
253
|
+
status = self._conn._request_status("send", queue, message)
|
|
254
|
+
if status != "OK":
|
|
255
|
+
raise ProtocolError(f"unexpected send response: {status!r}")
|
|
256
|
+
|
|
257
|
+
def recv_bytes(self, queue: str) -> bytes:
|
|
258
|
+
return self._conn._request_bulk("recv", queue)
|
|
259
|
+
|
|
260
|
+
def recv(self, queue: str) -> str:
|
|
261
|
+
return _decode_text(self.recv_bytes(queue), self.encoding)
|
|
262
|
+
|
|
263
|
+
def peek_bytes(self, queue: str) -> bytes:
|
|
264
|
+
return self._conn._request_bulk("peek", queue)
|
|
265
|
+
|
|
266
|
+
def peek(self, queue: str) -> str:
|
|
267
|
+
return _decode_text(self.peek_bytes(queue), self.encoding)
|
|
268
|
+
|
|
269
|
+
def queue_length(self, queue: str) -> int:
|
|
270
|
+
status = self._conn._request_status("len", queue)
|
|
271
|
+
try:
|
|
272
|
+
return int(status)
|
|
273
|
+
except ValueError as exc:
|
|
274
|
+
raise ProtocolError(f"invalid len response: {status!r}") from exc
|
|
275
|
+
|
|
276
|
+
def len(self, queue: str) -> int:
|
|
277
|
+
return self.queue_length(queue)
|
|
278
|
+
|
|
279
|
+
def create_queue(self, queue: str) -> None:
|
|
280
|
+
status = self._conn._request_status("mq", queue)
|
|
281
|
+
if status != "OK":
|
|
282
|
+
raise ProtocolError(f"unexpected mq response: {status!r}")
|
|
283
|
+
|
|
284
|
+
def mq(self, queue: str) -> None:
|
|
285
|
+
self.create_queue(queue)
|
|
286
|
+
|
|
287
|
+
def list_queues(self) -> list[str]:
|
|
288
|
+
return _parse_listing_lines(self._conn._request_multiline("queues"))
|
|
289
|
+
|
|
290
|
+
def queues(self) -> list[str]:
|
|
291
|
+
return self.list_queues()
|
|
292
|
+
|
|
293
|
+
def publish(self, topic: str, message: str | bytes) -> int:
|
|
294
|
+
status = self._conn._request_status("pub", topic, message)
|
|
295
|
+
if not status.startswith("OK "):
|
|
296
|
+
raise ProtocolError(f"unexpected pub response: {status!r}")
|
|
297
|
+
try:
|
|
298
|
+
return int(status.split(" ", 1)[1])
|
|
299
|
+
except ValueError as exc:
|
|
300
|
+
raise ProtocolError(f"invalid pub response: {status!r}") from exc
|
|
301
|
+
|
|
302
|
+
def pub(self, topic: str, message: str | bytes) -> int:
|
|
303
|
+
return self.publish(topic, message)
|
|
304
|
+
|
|
305
|
+
def list_topics(self) -> dict[str, int]:
|
|
306
|
+
items = _parse_listing_lines(self._conn._request_multiline("topics"))
|
|
307
|
+
result: dict[str, int] = {}
|
|
308
|
+
for item in items:
|
|
309
|
+
name, left, count = item.rpartition("(")
|
|
310
|
+
if not left or not count.endswith(")"):
|
|
311
|
+
raise ProtocolError(f"invalid topic listing item: {item!r}")
|
|
312
|
+
result[name] = int(count[:-1])
|
|
313
|
+
return result
|
|
314
|
+
|
|
315
|
+
def topics(self) -> dict[str, int]:
|
|
316
|
+
return self.list_topics()
|
|
317
|
+
|
|
318
|
+
def subscriber(self, *topics: str) -> Subscriber:
|
|
319
|
+
sub = Subscriber(
|
|
320
|
+
self.host,
|
|
321
|
+
self.port,
|
|
322
|
+
timeout=self.timeout,
|
|
323
|
+
idle_timeout=self.idle_timeout,
|
|
324
|
+
encoding=self.encoding,
|
|
325
|
+
)
|
|
326
|
+
if topics:
|
|
327
|
+
sub.subscribe(*topics)
|
|
328
|
+
return sub
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class Subscriber:
|
|
332
|
+
def __init__(
|
|
333
|
+
self,
|
|
334
|
+
host: str = "127.0.0.1",
|
|
335
|
+
port: int = 8388,
|
|
336
|
+
*,
|
|
337
|
+
timeout: float = 1.0,
|
|
338
|
+
idle_timeout: float = 0.08,
|
|
339
|
+
encoding: str = "utf-8",
|
|
340
|
+
) -> None:
|
|
341
|
+
self._conn = _SocketProtocol(
|
|
342
|
+
host,
|
|
343
|
+
port,
|
|
344
|
+
timeout=timeout,
|
|
345
|
+
idle_timeout=idle_timeout,
|
|
346
|
+
encoding=encoding,
|
|
347
|
+
)
|
|
348
|
+
self._events: Deque[Event] = deque()
|
|
349
|
+
|
|
350
|
+
def close(self) -> None:
|
|
351
|
+
self._conn.close()
|
|
352
|
+
|
|
353
|
+
def __enter__(self) -> Subscriber:
|
|
354
|
+
return self
|
|
355
|
+
|
|
356
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
357
|
+
self.close()
|
|
358
|
+
|
|
359
|
+
def __iter__(self) -> Iterator[Event]:
|
|
360
|
+
while True:
|
|
361
|
+
yield self.get()
|
|
362
|
+
|
|
363
|
+
def _request_status(self, op: str, topic: str | None = None) -> str:
|
|
364
|
+
self._conn._send_command(op, topic)
|
|
365
|
+
while True:
|
|
366
|
+
kind, value = self._conn._read_one()
|
|
367
|
+
if kind == "event":
|
|
368
|
+
self._events.append(value) # type: ignore[arg-type]
|
|
369
|
+
continue
|
|
370
|
+
if kind == "error":
|
|
371
|
+
_raise_server_error(str(value))
|
|
372
|
+
if kind != "status":
|
|
373
|
+
raise ProtocolError(f"expected status response, got {kind}")
|
|
374
|
+
return str(value)
|
|
375
|
+
|
|
376
|
+
def subscribe(self, *topics: str) -> None:
|
|
377
|
+
for topic in topics:
|
|
378
|
+
status = self._request_status("sub", topic)
|
|
379
|
+
if status != "OK":
|
|
380
|
+
raise ProtocolError(f"unexpected sub response: {status!r}")
|
|
381
|
+
|
|
382
|
+
def sub(self, *topics: str) -> None:
|
|
383
|
+
self.subscribe(*topics)
|
|
384
|
+
|
|
385
|
+
def unsubscribe(self, *topics: str) -> None:
|
|
386
|
+
if not topics:
|
|
387
|
+
status = self._request_status("unsub")
|
|
388
|
+
if status != "OK":
|
|
389
|
+
raise ProtocolError(f"unexpected unsub response: {status!r}")
|
|
390
|
+
return
|
|
391
|
+
|
|
392
|
+
for topic in topics:
|
|
393
|
+
status = self._request_status("unsub", topic)
|
|
394
|
+
if status != "OK":
|
|
395
|
+
raise ProtocolError(f"unexpected unsub response: {status!r}")
|
|
396
|
+
|
|
397
|
+
def unsub(self, *topics: str) -> None:
|
|
398
|
+
self.unsubscribe(*topics)
|
|
399
|
+
|
|
400
|
+
def get(self, timeout: float | None = None) -> Event:
|
|
401
|
+
if self._events:
|
|
402
|
+
return self._events.popleft()
|
|
403
|
+
|
|
404
|
+
while True:
|
|
405
|
+
kind, value = self._conn._read_one(timeout=timeout)
|
|
406
|
+
if kind == "event":
|
|
407
|
+
return value # type: ignore[return-value]
|
|
408
|
+
if kind == "error":
|
|
409
|
+
_raise_server_error(str(value))
|
|
410
|
+
raise ProtocolError(f"expected event response, got {kind}")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _encode_name(value: str) -> bytes:
|
|
414
|
+
encoded = value.encode("utf-8")
|
|
415
|
+
if not encoded:
|
|
416
|
+
raise ValueError("queue/topic names cannot be empty")
|
|
417
|
+
if any(byte in encoded for byte in b" \t\r\n"):
|
|
418
|
+
raise ValueError("queue/topic names cannot contain whitespace or line breaks")
|
|
419
|
+
return encoded
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _encode_body(value: str | bytes, encoding: str) -> bytes:
|
|
423
|
+
encoded = value.encode(encoding) if isinstance(value, str) else bytes(value)
|
|
424
|
+
if b"\r" in encoded or b"\n" in encoded:
|
|
425
|
+
raise ValueError("message bodies cannot contain CR or LF")
|
|
426
|
+
return encoded
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _decode_text(value: bytes, encoding: str) -> str:
|
|
430
|
+
return value.decode(encoding)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _parse_listing_lines(raw: bytes) -> list[str]:
|
|
434
|
+
text = raw.decode("utf-8")
|
|
435
|
+
if not text.startswith("+"):
|
|
436
|
+
raise ProtocolError(f"invalid listing response: {text!r}")
|
|
437
|
+
|
|
438
|
+
body = text[1:]
|
|
439
|
+
if body == "\r\n":
|
|
440
|
+
return []
|
|
441
|
+
|
|
442
|
+
return [line for line in body.rstrip("\r\n").split("\r\n") if line]
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _raise_server_error(message: str) -> None:
|
|
446
|
+
mapping = {
|
|
447
|
+
"empty": EmptyError,
|
|
448
|
+
"queue not found": QueueNotFoundError,
|
|
449
|
+
"queue full": QueueFullError,
|
|
450
|
+
}
|
|
451
|
+
exc_type = mapping.get(message, ServerError)
|
|
452
|
+
raise exc_type(message)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
class ZigMQError(Exception):
|
|
2
|
+
"""Base exception for the ZigMQ SDK."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ProtocolError(ZigMQError):
|
|
6
|
+
"""Raised when the server response does not match the ZigMQ protocol."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ServerError(ZigMQError):
|
|
10
|
+
"""Raised when the server returns `-ERR`."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class QueueNotFoundError(ServerError):
|
|
14
|
+
"""Raised when a queue does not exist."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class EmptyError(ServerError):
|
|
18
|
+
"""Raised when a queue exists but has no available messages."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class QueueFullError(ServerError):
|
|
22
|
+
"""Raised when a queue is full and cannot grow anymore."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TimeoutError(ZigMQError):
|
|
26
|
+
"""Raised when the client times out waiting for a response."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ConnectionClosedError(ZigMQError):
|
|
30
|
+
"""Raised when the server closes the connection."""
|
|
31
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class Info:
|
|
8
|
+
banner: str
|
|
9
|
+
version: str
|
|
10
|
+
queues: int
|
|
11
|
+
topics: int
|
|
12
|
+
initial_capacity: int
|
|
13
|
+
max_capacity: int
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Event:
|
|
18
|
+
topic: str
|
|
19
|
+
message: str
|
|
20
|
+
data: bytes
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: zigmq
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A tiny, pythonic SDK for the ZigMQ text protocol.
|
|
5
|
+
Author: reasonz
|
|
6
|
+
Project-URL: Homepage, https://github.com/reasonz/zigMQ-python-SDK
|
|
7
|
+
Project-URL: Repository, https://github.com/reasonz/zigMQ-python-SDK
|
|
8
|
+
Keywords: zigmq,queue,pubsub,messaging
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Communications
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# zigMQ Python SDK
|
|
25
|
+
|
|
26
|
+
`zigmq` is a tiny, pythonic SDK for the [ZigMQ](https://github.com/reasonz/zigMQ) text protocol.
|
|
27
|
+
|
|
28
|
+
By default, the SDK connects to `127.0.0.1:8388`.
|
|
29
|
+
|
|
30
|
+
The goal of this SDK is deliberately narrow:
|
|
31
|
+
|
|
32
|
+
- one small sync client for queue/admin commands
|
|
33
|
+
- one dedicated subscriber client for pub/sub delivery
|
|
34
|
+
- no dependency, no ORM-style abstraction, no magic reconnect layer
|
|
35
|
+
- protocol-compatible with the current ZigMQ server behavior
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install zigmq
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Local development:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
cd zigMQ-python-SDK
|
|
47
|
+
pip install -e .
|
|
48
|
+
python -m unittest -v
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Quick Start
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from zigmq import Client
|
|
55
|
+
|
|
56
|
+
with Client() as mq:
|
|
57
|
+
mq.send("jobs", "hello world")
|
|
58
|
+
print(mq.recv("jobs"))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Pub/Sub:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from zigmq import Client, Subscriber
|
|
65
|
+
|
|
66
|
+
with Subscriber() as sub:
|
|
67
|
+
sub.subscribe("news")
|
|
68
|
+
|
|
69
|
+
with Client() as mq:
|
|
70
|
+
delivered = mq.publish("news", "shipped")
|
|
71
|
+
print(delivered)
|
|
72
|
+
|
|
73
|
+
event = sub.get()
|
|
74
|
+
print(event.topic, event.message)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## API
|
|
78
|
+
|
|
79
|
+
### `Client`
|
|
80
|
+
|
|
81
|
+
- `ping() -> str`
|
|
82
|
+
- `info() -> Info`
|
|
83
|
+
- `send(queue, message) -> None`
|
|
84
|
+
- `recv(queue) -> str`
|
|
85
|
+
- `recv_bytes(queue) -> bytes`
|
|
86
|
+
- `peek(queue) -> str`
|
|
87
|
+
- `peek_bytes(queue) -> bytes`
|
|
88
|
+
- `queue_length(queue) -> int`
|
|
89
|
+
- `create_queue(queue) -> None`
|
|
90
|
+
- `list_queues() -> list[str]`
|
|
91
|
+
- `publish(topic, message) -> int`
|
|
92
|
+
- `list_topics() -> dict[str, int]`
|
|
93
|
+
- `subscriber(*topics) -> Subscriber`
|
|
94
|
+
|
|
95
|
+
Short protocol-style aliases are also available: `mq`, `len`, `queues`, `pub`, `topics`.
|
|
96
|
+
|
|
97
|
+
### `Subscriber`
|
|
98
|
+
|
|
99
|
+
- `subscribe(*topics) -> None`
|
|
100
|
+
- `unsubscribe(*topics) -> None`
|
|
101
|
+
- `get(timeout=None) -> Event`
|
|
102
|
+
- iteration support: `for event in sub: ...`
|
|
103
|
+
|
|
104
|
+
## Design Notes
|
|
105
|
+
|
|
106
|
+
- This SDK is text-first, because ZigMQ itself is a line-based text protocol.
|
|
107
|
+
- The default connection target is `127.0.0.1:8388`.
|
|
108
|
+
- Queue/topic names cannot contain whitespace or line breaks.
|
|
109
|
+
- Message bodies can contain spaces, but cannot contain `\\r` or `\\n`.
|
|
110
|
+
- `queues`, `topics`, and `info` follow the current ZigMQ server behavior and are parsed from multi-line responses.
|
|
111
|
+
|
|
112
|
+
## Publish To PyPI
|
|
113
|
+
|
|
114
|
+
Update `version` in [pyproject.toml](./pyproject.toml), then:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
cd zigMQ-python-SDK
|
|
118
|
+
python -m build
|
|
119
|
+
twine upload dist/*
|
|
120
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/zigmq/__init__.py
|
|
5
|
+
src/zigmq/client.py
|
|
6
|
+
src/zigmq/errors.py
|
|
7
|
+
src/zigmq/models.py
|
|
8
|
+
src/zigmq.egg-info/PKG-INFO
|
|
9
|
+
src/zigmq.egg-info/SOURCES.txt
|
|
10
|
+
src/zigmq.egg-info/dependency_links.txt
|
|
11
|
+
src/zigmq.egg-info/top_level.txt
|
|
12
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
zigmq
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import signal
|
|
5
|
+
import socket
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
import unittest
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
PROJECT_DIR = Path(__file__).resolve().parents[1]
|
|
14
|
+
WORKSPACE_ROOT = PROJECT_DIR.parent
|
|
15
|
+
SERVER_REPO = WORKSPACE_ROOT / "zigMQ"
|
|
16
|
+
SERVER_VERSION = (SERVER_REPO / "VERSION").read_text(encoding="utf-8").strip()
|
|
17
|
+
sys.path.insert(0, str(PROJECT_DIR / "src"))
|
|
18
|
+
|
|
19
|
+
from zigmq import Client, EmptyError, QueueNotFoundError, Subscriber # noqa: E402
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _find_server_exe() -> Path:
|
|
23
|
+
candidates = [
|
|
24
|
+
SERVER_REPO / "zig-out" / "bin" / "zigmq",
|
|
25
|
+
SERVER_REPO / "dist" / "release" / f"zigmq-v{SERVER_VERSION}-macos-aarch64" / "zigmq",
|
|
26
|
+
SERVER_REPO / "dist" / "release" / f"zigmq-v{SERVER_VERSION}-linux-x86_64" / "zigmq",
|
|
27
|
+
]
|
|
28
|
+
for candidate in candidates:
|
|
29
|
+
if candidate.exists():
|
|
30
|
+
return candidate
|
|
31
|
+
raise FileNotFoundError("could not find a ZigMQ executable for tests")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _free_port() -> int:
|
|
35
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
36
|
+
sock.bind(("127.0.0.1", 0))
|
|
37
|
+
return int(sock.getsockname()[1])
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@contextlib.contextmanager
|
|
41
|
+
def running_server(*extra_args: str):
|
|
42
|
+
exe = _find_server_exe()
|
|
43
|
+
port = _free_port()
|
|
44
|
+
command = [str(exe), "--port", str(port), *extra_args]
|
|
45
|
+
process = subprocess.Popen(
|
|
46
|
+
command,
|
|
47
|
+
stdout=subprocess.PIPE,
|
|
48
|
+
stderr=subprocess.PIPE,
|
|
49
|
+
text=True,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
deadline = time.monotonic() + 5.0
|
|
53
|
+
while time.monotonic() < deadline:
|
|
54
|
+
if process.poll() is not None:
|
|
55
|
+
stdout, stderr = process.communicate(timeout=0.2)
|
|
56
|
+
raise RuntimeError(
|
|
57
|
+
f"server exited during startup\ncommand: {' '.join(command)}\nstdout:\n{stdout}\nstderr:\n{stderr}"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
probe = socket.create_connection(("127.0.0.1", port), timeout=0.2)
|
|
62
|
+
except OSError:
|
|
63
|
+
time.sleep(0.05)
|
|
64
|
+
continue
|
|
65
|
+
|
|
66
|
+
probe.close()
|
|
67
|
+
break
|
|
68
|
+
else:
|
|
69
|
+
process.kill()
|
|
70
|
+
stdout, stderr = process.communicate(timeout=0.2)
|
|
71
|
+
raise RuntimeError(
|
|
72
|
+
f"server did not start\ncommand: {' '.join(command)}\nstdout:\n{stdout}\nstderr:\n{stderr}"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
yield port
|
|
77
|
+
finally:
|
|
78
|
+
if process.poll() is None:
|
|
79
|
+
with contextlib.suppress(ProcessLookupError):
|
|
80
|
+
process.send_signal(signal.SIGINT)
|
|
81
|
+
try:
|
|
82
|
+
process.communicate(timeout=2.0)
|
|
83
|
+
except subprocess.TimeoutExpired:
|
|
84
|
+
process.kill()
|
|
85
|
+
process.communicate(timeout=2.0)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ClientTests(unittest.TestCase):
|
|
89
|
+
def test_queue_roundtrip_and_info(self) -> None:
|
|
90
|
+
with running_server("--capacity", "2", "--max-capacity", "4") as port:
|
|
91
|
+
with Client(port=port) as mq:
|
|
92
|
+
self.assertEqual(mq.ping(), "PONG")
|
|
93
|
+
|
|
94
|
+
info = mq.info()
|
|
95
|
+
self.assertEqual(info.initial_capacity, 2)
|
|
96
|
+
self.assertEqual(info.max_capacity, 4)
|
|
97
|
+
|
|
98
|
+
mq.send("jobs", "hello world")
|
|
99
|
+
self.assertEqual(mq.queue_length("jobs"), 1)
|
|
100
|
+
self.assertEqual(mq.peek("jobs"), "hello world")
|
|
101
|
+
self.assertEqual(mq.recv("jobs"), "hello world")
|
|
102
|
+
self.assertIn("jobs", mq.list_queues())
|
|
103
|
+
|
|
104
|
+
def test_error_mapping(self) -> None:
|
|
105
|
+
with running_server("--capacity", "2", "--max-capacity", "4") as port:
|
|
106
|
+
with Client(port=port) as mq:
|
|
107
|
+
with self.assertRaises(QueueNotFoundError):
|
|
108
|
+
mq.recv("missing")
|
|
109
|
+
|
|
110
|
+
mq.create_queue("jobs")
|
|
111
|
+
with self.assertRaises(EmptyError):
|
|
112
|
+
mq.recv("jobs")
|
|
113
|
+
|
|
114
|
+
def test_topics_and_publish(self) -> None:
|
|
115
|
+
with running_server("--capacity", "2", "--max-capacity", "4") as port:
|
|
116
|
+
with Subscriber(port=port) as sub:
|
|
117
|
+
sub.subscribe("news")
|
|
118
|
+
|
|
119
|
+
with Client(port=port) as mq:
|
|
120
|
+
self.assertEqual(mq.publish("news", "shipped"), 1)
|
|
121
|
+
self.assertEqual(mq.list_topics(), {"news": 1})
|
|
122
|
+
|
|
123
|
+
event = sub.get(timeout=1.0)
|
|
124
|
+
self.assertEqual(event.topic, "news")
|
|
125
|
+
self.assertEqual(event.message, "shipped")
|
|
126
|
+
self.assertEqual(event.data, b"shipped")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
if __name__ == "__main__":
|
|
130
|
+
unittest.main()
|