popsub 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.
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
popsub-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.
popsub-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,223 @@
1
+ Metadata-Version: 2.5
2
+ Name: popsub
3
+ Version: 0.1.0
4
+ Summary: Asyncio client for the PopSub WebSocket publish/subscribe broker.
5
+ Project-URL: Homepage, https://github.com/soumyadepp/popsub
6
+ Project-URL: Repository, https://github.com/soumyadepp/popsub
7
+ Project-URL: Documentation, https://github.com/soumyadepp/popsub/tree/main/clients/python#readme
8
+ Project-URL: Issues, https://github.com/soumyadepp/popsub/issues
9
+ Author: PopSub contributors
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: asyncio,messaging,popsub,pubsub,websocket
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Communications
25
+ Classifier: Topic :: System :: Networking
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.10
28
+ Requires-Dist: websockets>=16.0
29
+ Description-Content-Type: text/markdown
30
+
31
+ # popsub (Python client)
32
+
33
+ An asyncio client for [PopSub](https://github.com/soumyadepp/popsub), a WebSocket publish/subscribe broker. It follows the behaviour every PopSub client shares (`clients/README.md` in the repository) and passes the shared scenario suite.
34
+
35
+ The client handles the protocol's bookkeeping so an application only connects, subscribes, publishes, receives and acknowledges:
36
+
37
+ - Logs in with a username and password (or takes a token) and authenticates with protocol version 1. With password credentials it logs in again when the server sends `auth_expiring`.
38
+ - Reconnects with jittered exponential backoff, and reads the close code to decide whether to: never after `auth_failed` (4001), `session_taken_over` (4003), `unsupported_protocol` (4006) or `account_disabled` (4009), and after `token_expired` (4004) only with password credentials. A rejected login on the first connection fails `connect` without retrying.
39
+ - Treats the connection as dead when nothing (pings included) arrives for `idle_timeout_secs + heartbeat_secs` from the server's `limits`.
40
+ - After reconnecting, subscribes again from `resume` to topics the server resumed for a durable session when it holds them (`held: true`) and leaves them to the server otherwise, subscribes every other topic again from `{"seq": next_expected}`, resends unconfirmed `publish_confirmed` calls with the same request id and `message_id`, and sends QoS 0 publishes held while disconnected (up to 10,000; the oldest are dropped first).
41
+ - Sends `hold_resumed: true` in `auth` whenever it has a `session_id`, so that in a new process on an existing durable session the server sends nothing on a resumed topic until the application subscribes to it. When the server answers `held: true`, that subscribe is an ordinary one and a topic the application never subscribes to has nothing in flight.
42
+ - When the server answers without `held`, neither hands over nor acknowledges messages on a resumed topic until the application subscribes to it by name or through a matching pattern, so the server keeps them. The subscribe then replays them: messages that arrive before its `subscribed` are dropped unacknowledged, and a pattern sends a `subscribe` by name from `resume` for each resumed topic it matches. A resumed topic the application never subscribes to stays unacknowledged on the server.
43
+ - Hands each `(topic, seq)` to the application once. A duplicate is acknowledged again when it was acknowledged before, or always in automatic mode.
44
+ - Stops reading the socket while a subscription's buffer is full, so the server paces delivery instead of the client buffering without bound.
45
+ - Ends a subscription and reports `Unsubscribed` when the server ends it (an `unsubscribed` frame with no id). Every unsubscribe the client sends carries an id for that reason.
46
+ - Treats a wildcard subscription (`orders/#`) as one subscription: each topic the server joins for it is tracked on its own (next expected `seq`, acknowledgements), and after a reconnect the tracked topics are resubscribed first and the pattern is sent again from `{"seq": 1}`, which joins only topics created meanwhile. Subscribing again to a held pattern replaces the subscription: its topics move to the new one with their next expected `seq`, and the earlier one ends.
47
+ - Deduplicates a shared subscription (a topic read through a `group`) with a bounded set of the 4,096 most recently delivered `seq`s, since a member gets only some messages and not in order, and rejoins the group with `resume` after a reconnect.
48
+ - Never queues or resends admin requests: a disconnect fails them with `ConnectError`, because the server may or may not have carried them out.
49
+
50
+ Delivery is what the server provides: QoS 1 is at-least-once per subscriber while connected, and across reconnects only for durable sessions whose messages are still retained. The client removes the duplicates that this produces.
51
+
52
+ ## Install
53
+
54
+ Python 3.10 or newer. The only runtime dependency is [`websockets`](https://websockets.readthedocs.io/).
55
+
56
+ ```bash
57
+ pip install popsub
58
+ ```
59
+
60
+ or `uv add popsub`. To use a version that isn't released yet, install it from a checkout: `uv add path/to/popsub/clients/python`.
61
+
62
+ ## Usage
63
+
64
+ ```python
65
+ import asyncio
66
+
67
+ from popsub import AckMode, Client, ClientConfig, PasswordCredentials, StartFrom
68
+
69
+
70
+ async def main() -> None:
71
+ config = ClientConfig(
72
+ "ws://127.0.0.1:8080",
73
+ PasswordCredentials("alice", "alice-password"),
74
+ session_id="alice-laptop",
75
+ ack_mode=AckMode.MANUAL,
76
+ )
77
+ async with await Client.connect(config) as client:
78
+ orders = await client.subscribe("orders", StartFrom.resume())
79
+ stored = await client.publish_confirmed("orders", "order 42 shipped")
80
+ print("stored as seq", stored.seq)
81
+ async for message in orders:
82
+ print(message.topic, message.seq, message.payload)
83
+ message.ack()
84
+
85
+
86
+ asyncio.run(main())
87
+ ```
88
+
89
+ Events arrive on a separate stream:
90
+
91
+ ```python
92
+ async def watch(client: Client) -> None:
93
+ async for event in client.events():
94
+ print(event.to_json())
95
+ ```
96
+
97
+ ### Binary payloads
98
+
99
+ A payload is a string. For a body that isn't text, publish bytes and read them back with `message.data`:
100
+
101
+ ```python
102
+ async def send_and_read(client: Client) -> None:
103
+ blobs = await client.subscribe("blobs", StartFrom.new())
104
+ await client.publish_bytes_confirmed("blobs", b"\x00\xff\xfe\x80")
105
+ message = await blobs.next()
106
+ if message is not None:
107
+ print(message.encoding, message.data)
108
+ ```
109
+
110
+ `publish_bytes` (QoS 0) and `publish_bytes_confirmed` (QoS 1) send the bytes as standard padded base64 in `payload` with `encoding: "base64"`, and otherwise behave like `publish` and `publish_confirmed`: held while disconnected, and resent with the same request id and `message_id`. Base64 adds about a third, and it is the encoded string that counts against the server's payload limit (`payload_too_large`).
111
+
112
+ On a received message, `payload` is the string as it arrived, `encoding` is `None` for text or `Encoding.BASE64`, and `data` is the bytes: the decoded payload for base64, otherwise the payload's UTF-8. The server checks base64 on publish and never decodes it. If a payload claims base64 and doesn't decode, the message is still delivered and `data` raises `ProtocolError`.
113
+
114
+ ### Wildcard subscriptions
115
+
116
+ A pattern uses `+` for any one level and a trailing `#` for the rest. One subscription yields the messages of every matching topic the user may read, including topics created later, each under its own topic and `seq`:
117
+
118
+ ```python
119
+ async def follow_orders(client: Client) -> None:
120
+ async with await client.subscribe("orders/#", StartFrom.new()) as orders:
121
+ async for message in orders:
122
+ print(message.topic, message.seq, message.payload)
123
+ ```
124
+
125
+ `client.unsubscribe("orders/#")`, or closing the subscription, leaves the pattern and every topic joined through it. If the server ends one of those topics (access revoked), only that topic stops and `Unsubscribed` names it.
126
+
127
+ Subscribing again to the same pattern returns a new subscription that takes over the topics already joined, each from the next `seq` it expects, so every message still arrives once. The earlier subscription ends; closing it afterwards changes nothing.
128
+
129
+ ### Shared subscriptions
130
+
131
+ Members of a group split a topic's messages: each message goes to one member. A member sees its share, not in strict `seq` order, and a message can reach a second member after the first disconnects without acknowledging it, so workers must tolerate a repeat.
132
+
133
+ ```python
134
+ async def work(client: Client) -> None:
135
+ jobs = await client.subscribe_shared("jobs", "workers", StartFrom.new())
136
+ async for message in jobs:
137
+ print("handling", message.seq, message.payload)
138
+ message.ack()
139
+ ```
140
+
141
+ `start_from` only decides where a group starts the first time it is used on a topic; after that the group's position is on the server.
142
+
143
+ ## API
144
+
145
+ Everything below is importable from `popsub`.
146
+
147
+ | Name | What it is |
148
+ |---|---|
149
+ | `await Client.connect(config)` | Connects and waits for the first authenticated connection, retrying with the reconnect policy for up to `request_timeout`. |
150
+ | `await client.subscribe(topic, start_from=StartFrom.resume())` | Returns a `Subscription`. `topic` may be a wildcard pattern. `StartFrom.resume()`, `.new()`, `.last(n)`, `.since_ms(t)` or `.seq(s)`. |
151
+ | `await client.subscribe_shared(topic, group, start_from=StartFrom.resume())` | Joins a shared subscription on an exact topic and returns a `Subscription` with this member's share. |
152
+ | `await client.unsubscribe(topic)` | Unsubscribes from a topic or pattern; its `Subscription` ends. |
153
+ | `await client.publish(topic, payload)` | QoS 0. Returns once queued; server failures arrive as `ServerErrorEvent`. |
154
+ | `await client.publish_confirmed(topic, payload)` | QoS 1 with a new UUID `message_id`. Returns `Published(seq, message_id)` once stored. |
155
+ | `await client.publish_bytes(topic, data)` | `publish` for `bytes`: sent as base64 with `encoding: "base64"`. |
156
+ | `await client.publish_bytes_confirmed(topic, data)` | `publish_confirmed` for `bytes`. Returns `Published(seq, message_id)` once stored. |
157
+ | `client.admin()` | `Admin` with `create_user`, `get_user`, `list_users`, `set_role`, `grant`, `revoke`, `set_password`, `set_enabled`, `delete_user`. They return `UserInfo` (a list for `list_users`, None for `delete_user`). The topic calls `list_topics`, `get_topic(topic)` and `purge_topic(topic)` return `TopicInfo` (`name`, `first_seq`, `last_seq`, `messages`, `subscribers`; a list for `list_topics`); a topic nothing was published to gives `ServerError` with code `topic_not_found`. |
158
+ | `client.events()` | An `EventStream`: an async iterator of events from now on, ending after the client stops. It keeps the latest 256 events for a slow reader. |
159
+ | `await client.close()` | Closes the connection and stops the client. Every task it started has finished when this returns. |
160
+ | `client.stopped`, `client.close_code` | Whether the client stopped for good, and the close code that stopped it. |
161
+ | `Subscription` | `async for message in subscription`, or `await subscription.next()` (None at the end). `subscription.close()` stops listening and unsubscribes without waiting. `replay_from` and `replay_to` come from the server's `subscribed`. |
162
+ | `Message` | `topic`, `seq`, `message_id`, `payload`, `qos`, `published_at_ms`, `encoding` (`None` for text, or `Encoding.BASE64`), `data` (the message's bytes; raises `ProtocolError` when a base64 payload doesn't decode), and `ack()`, which does something only for QoS 1 in manual mode and is safe to call twice. |
163
+
164
+ Events: `Connected(resumed)`, `Disconnected(code, reconnecting)`, `Truncated(topic, first_available)`, `Stalled(topic, seq)`, `AuthExpiring(expires_at_ms)`, `AuthRefreshed()`, `Unsubscribed(topic)` and `ServerErrorEvent(code, message)`. Each has `to_json()`.
165
+
166
+ ### Configuration
167
+
168
+ `ClientConfig(url, credentials, ...)`:
169
+
170
+ | Field | Default | Meaning |
171
+ |---|---|---|
172
+ | `url` | | `ws://` or `wss://` |
173
+ | `credentials` | | `PasswordCredentials(username, password)` or `TokenCredentials(token)` |
174
+ | `session_id` | `None` | A durable session to hold; None is ephemeral. |
175
+ | `clean_start` | `False` | Discard the session's stored subscriptions; sent on the first connection only. |
176
+ | `ack_mode` | `AckMode.AUTO` | `AUTO` acknowledges QoS 1 messages as they are handed over; `MANUAL` waits for `message.ack()`. |
177
+ | `reconnect` | `ReconnectPolicy(0.25, 30.0, None)` | `initial` and `max` ceilings in seconds, and `max_attempts` (None keeps trying). |
178
+ | `request_timeout` | `30.0` | Seconds a connect, subscribe, confirmed publish or admin call may take. |
179
+ | `subscription_buffer` | `1024` | Messages buffered per subscription before the client stops reading the socket. |
180
+ | `ssl_context` | `None` | TLS settings for `wss://`, such as a context trusting a private CA. |
181
+
182
+ ### Errors
183
+
184
+ Every failure is a `PopSubError` with a `kind`:
185
+
186
+ | Class | `kind` | Extra attributes |
187
+ |---|---|---|
188
+ | `ServerError` | `server` | `code` (such as `not_authorized`), `retry_after` |
189
+ | `ClosedError` | `closed` | `close_code` (or None) |
190
+ | `RequestTimeoutError` | `timeout` | |
191
+ | `ConnectError` | `connect` | |
192
+ | `ProtocolError` | `protocol` | |
193
+ | `ConfigError` | `config` | |
194
+
195
+ `error.is_temporary` says whether trying again later might work. Errors keep their cause in `__cause__`.
196
+
197
+ ### Logging
198
+
199
+ The client logs through the standard `logging` module under the `popsub` logger and configures no handlers. Its own log lines never include passwords, tokens or payloads. The `websockets` library logs under its own `websockets` logger, and at `DEBUG` level that includes frame contents, so keep it above `DEBUG` in production.
200
+
201
+ ## Scenario suite
202
+
203
+ The scenario driver is the internal module `popsub._driver`; it is not part of the public API. From the repository root, with the suite built (`cargo build -p popsub_scenarios`):
204
+
205
+ ```bash
206
+ target/debug/popsub-scenarios --driver "uv run --project clients/python python -m popsub._driver"
207
+ target/debug/popsub-scenarios --driver "uv run --project clients/python python -m popsub._driver" --scenario reconnect_resubscribes_without_gaps
208
+ ```
209
+
210
+ The driver logs to standard error; set `POPSUB_LOG=DEBUG` for more.
211
+
212
+ ## Development
213
+
214
+ Uses [uv](https://docs.astral.sh/uv/). From `clients/python`:
215
+
216
+ ```bash
217
+ uv sync
218
+ uv run ruff format --check . && uv run ruff check . && uv run mypy && uv run pytest
219
+ ```
220
+
221
+ That runs the formatter check, the linter, `mypy --strict` over the package and tests, and the tests. The tests cover backoff, deduplication (by next expected seq, and by the seen set for shared subscriptions), the wildcard pattern matcher, the wire types and a message's bytes, feed the engine frames directly to check how a new process claims a durable session's topics and how a repeated pattern subscribe moves its topics, and run the client against a small in-process fake server to check that resent copies are dropped and acknowledged again, that a reconnect resubscribes from the next expected seq, that byte publishes carry base64 and the encoding (also when resent) while text publishes carry none, and that `close()` leaves no task running.
222
+
223
+ `uv build` writes the wheel and source distribution to `dist/`.
popsub-0.1.0/README.md ADDED
@@ -0,0 +1,193 @@
1
+ # popsub (Python client)
2
+
3
+ An asyncio client for [PopSub](https://github.com/soumyadepp/popsub), a WebSocket publish/subscribe broker. It follows the behaviour every PopSub client shares (`clients/README.md` in the repository) and passes the shared scenario suite.
4
+
5
+ The client handles the protocol's bookkeeping so an application only connects, subscribes, publishes, receives and acknowledges:
6
+
7
+ - Logs in with a username and password (or takes a token) and authenticates with protocol version 1. With password credentials it logs in again when the server sends `auth_expiring`.
8
+ - Reconnects with jittered exponential backoff, and reads the close code to decide whether to: never after `auth_failed` (4001), `session_taken_over` (4003), `unsupported_protocol` (4006) or `account_disabled` (4009), and after `token_expired` (4004) only with password credentials. A rejected login on the first connection fails `connect` without retrying.
9
+ - Treats the connection as dead when nothing (pings included) arrives for `idle_timeout_secs + heartbeat_secs` from the server's `limits`.
10
+ - After reconnecting, subscribes again from `resume` to topics the server resumed for a durable session when it holds them (`held: true`) and leaves them to the server otherwise, subscribes every other topic again from `{"seq": next_expected}`, resends unconfirmed `publish_confirmed` calls with the same request id and `message_id`, and sends QoS 0 publishes held while disconnected (up to 10,000; the oldest are dropped first).
11
+ - Sends `hold_resumed: true` in `auth` whenever it has a `session_id`, so that in a new process on an existing durable session the server sends nothing on a resumed topic until the application subscribes to it. When the server answers `held: true`, that subscribe is an ordinary one and a topic the application never subscribes to has nothing in flight.
12
+ - When the server answers without `held`, neither hands over nor acknowledges messages on a resumed topic until the application subscribes to it by name or through a matching pattern, so the server keeps them. The subscribe then replays them: messages that arrive before its `subscribed` are dropped unacknowledged, and a pattern sends a `subscribe` by name from `resume` for each resumed topic it matches. A resumed topic the application never subscribes to stays unacknowledged on the server.
13
+ - Hands each `(topic, seq)` to the application once. A duplicate is acknowledged again when it was acknowledged before, or always in automatic mode.
14
+ - Stops reading the socket while a subscription's buffer is full, so the server paces delivery instead of the client buffering without bound.
15
+ - Ends a subscription and reports `Unsubscribed` when the server ends it (an `unsubscribed` frame with no id). Every unsubscribe the client sends carries an id for that reason.
16
+ - Treats a wildcard subscription (`orders/#`) as one subscription: each topic the server joins for it is tracked on its own (next expected `seq`, acknowledgements), and after a reconnect the tracked topics are resubscribed first and the pattern is sent again from `{"seq": 1}`, which joins only topics created meanwhile. Subscribing again to a held pattern replaces the subscription: its topics move to the new one with their next expected `seq`, and the earlier one ends.
17
+ - Deduplicates a shared subscription (a topic read through a `group`) with a bounded set of the 4,096 most recently delivered `seq`s, since a member gets only some messages and not in order, and rejoins the group with `resume` after a reconnect.
18
+ - Never queues or resends admin requests: a disconnect fails them with `ConnectError`, because the server may or may not have carried them out.
19
+
20
+ Delivery is what the server provides: QoS 1 is at-least-once per subscriber while connected, and across reconnects only for durable sessions whose messages are still retained. The client removes the duplicates that this produces.
21
+
22
+ ## Install
23
+
24
+ Python 3.10 or newer. The only runtime dependency is [`websockets`](https://websockets.readthedocs.io/).
25
+
26
+ ```bash
27
+ pip install popsub
28
+ ```
29
+
30
+ or `uv add popsub`. To use a version that isn't released yet, install it from a checkout: `uv add path/to/popsub/clients/python`.
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ import asyncio
36
+
37
+ from popsub import AckMode, Client, ClientConfig, PasswordCredentials, StartFrom
38
+
39
+
40
+ async def main() -> None:
41
+ config = ClientConfig(
42
+ "ws://127.0.0.1:8080",
43
+ PasswordCredentials("alice", "alice-password"),
44
+ session_id="alice-laptop",
45
+ ack_mode=AckMode.MANUAL,
46
+ )
47
+ async with await Client.connect(config) as client:
48
+ orders = await client.subscribe("orders", StartFrom.resume())
49
+ stored = await client.publish_confirmed("orders", "order 42 shipped")
50
+ print("stored as seq", stored.seq)
51
+ async for message in orders:
52
+ print(message.topic, message.seq, message.payload)
53
+ message.ack()
54
+
55
+
56
+ asyncio.run(main())
57
+ ```
58
+
59
+ Events arrive on a separate stream:
60
+
61
+ ```python
62
+ async def watch(client: Client) -> None:
63
+ async for event in client.events():
64
+ print(event.to_json())
65
+ ```
66
+
67
+ ### Binary payloads
68
+
69
+ A payload is a string. For a body that isn't text, publish bytes and read them back with `message.data`:
70
+
71
+ ```python
72
+ async def send_and_read(client: Client) -> None:
73
+ blobs = await client.subscribe("blobs", StartFrom.new())
74
+ await client.publish_bytes_confirmed("blobs", b"\x00\xff\xfe\x80")
75
+ message = await blobs.next()
76
+ if message is not None:
77
+ print(message.encoding, message.data)
78
+ ```
79
+
80
+ `publish_bytes` (QoS 0) and `publish_bytes_confirmed` (QoS 1) send the bytes as standard padded base64 in `payload` with `encoding: "base64"`, and otherwise behave like `publish` and `publish_confirmed`: held while disconnected, and resent with the same request id and `message_id`. Base64 adds about a third, and it is the encoded string that counts against the server's payload limit (`payload_too_large`).
81
+
82
+ On a received message, `payload` is the string as it arrived, `encoding` is `None` for text or `Encoding.BASE64`, and `data` is the bytes: the decoded payload for base64, otherwise the payload's UTF-8. The server checks base64 on publish and never decodes it. If a payload claims base64 and doesn't decode, the message is still delivered and `data` raises `ProtocolError`.
83
+
84
+ ### Wildcard subscriptions
85
+
86
+ A pattern uses `+` for any one level and a trailing `#` for the rest. One subscription yields the messages of every matching topic the user may read, including topics created later, each under its own topic and `seq`:
87
+
88
+ ```python
89
+ async def follow_orders(client: Client) -> None:
90
+ async with await client.subscribe("orders/#", StartFrom.new()) as orders:
91
+ async for message in orders:
92
+ print(message.topic, message.seq, message.payload)
93
+ ```
94
+
95
+ `client.unsubscribe("orders/#")`, or closing the subscription, leaves the pattern and every topic joined through it. If the server ends one of those topics (access revoked), only that topic stops and `Unsubscribed` names it.
96
+
97
+ Subscribing again to the same pattern returns a new subscription that takes over the topics already joined, each from the next `seq` it expects, so every message still arrives once. The earlier subscription ends; closing it afterwards changes nothing.
98
+
99
+ ### Shared subscriptions
100
+
101
+ Members of a group split a topic's messages: each message goes to one member. A member sees its share, not in strict `seq` order, and a message can reach a second member after the first disconnects without acknowledging it, so workers must tolerate a repeat.
102
+
103
+ ```python
104
+ async def work(client: Client) -> None:
105
+ jobs = await client.subscribe_shared("jobs", "workers", StartFrom.new())
106
+ async for message in jobs:
107
+ print("handling", message.seq, message.payload)
108
+ message.ack()
109
+ ```
110
+
111
+ `start_from` only decides where a group starts the first time it is used on a topic; after that the group's position is on the server.
112
+
113
+ ## API
114
+
115
+ Everything below is importable from `popsub`.
116
+
117
+ | Name | What it is |
118
+ |---|---|
119
+ | `await Client.connect(config)` | Connects and waits for the first authenticated connection, retrying with the reconnect policy for up to `request_timeout`. |
120
+ | `await client.subscribe(topic, start_from=StartFrom.resume())` | Returns a `Subscription`. `topic` may be a wildcard pattern. `StartFrom.resume()`, `.new()`, `.last(n)`, `.since_ms(t)` or `.seq(s)`. |
121
+ | `await client.subscribe_shared(topic, group, start_from=StartFrom.resume())` | Joins a shared subscription on an exact topic and returns a `Subscription` with this member's share. |
122
+ | `await client.unsubscribe(topic)` | Unsubscribes from a topic or pattern; its `Subscription` ends. |
123
+ | `await client.publish(topic, payload)` | QoS 0. Returns once queued; server failures arrive as `ServerErrorEvent`. |
124
+ | `await client.publish_confirmed(topic, payload)` | QoS 1 with a new UUID `message_id`. Returns `Published(seq, message_id)` once stored. |
125
+ | `await client.publish_bytes(topic, data)` | `publish` for `bytes`: sent as base64 with `encoding: "base64"`. |
126
+ | `await client.publish_bytes_confirmed(topic, data)` | `publish_confirmed` for `bytes`. Returns `Published(seq, message_id)` once stored. |
127
+ | `client.admin()` | `Admin` with `create_user`, `get_user`, `list_users`, `set_role`, `grant`, `revoke`, `set_password`, `set_enabled`, `delete_user`. They return `UserInfo` (a list for `list_users`, None for `delete_user`). The topic calls `list_topics`, `get_topic(topic)` and `purge_topic(topic)` return `TopicInfo` (`name`, `first_seq`, `last_seq`, `messages`, `subscribers`; a list for `list_topics`); a topic nothing was published to gives `ServerError` with code `topic_not_found`. |
128
+ | `client.events()` | An `EventStream`: an async iterator of events from now on, ending after the client stops. It keeps the latest 256 events for a slow reader. |
129
+ | `await client.close()` | Closes the connection and stops the client. Every task it started has finished when this returns. |
130
+ | `client.stopped`, `client.close_code` | Whether the client stopped for good, and the close code that stopped it. |
131
+ | `Subscription` | `async for message in subscription`, or `await subscription.next()` (None at the end). `subscription.close()` stops listening and unsubscribes without waiting. `replay_from` and `replay_to` come from the server's `subscribed`. |
132
+ | `Message` | `topic`, `seq`, `message_id`, `payload`, `qos`, `published_at_ms`, `encoding` (`None` for text, or `Encoding.BASE64`), `data` (the message's bytes; raises `ProtocolError` when a base64 payload doesn't decode), and `ack()`, which does something only for QoS 1 in manual mode and is safe to call twice. |
133
+
134
+ Events: `Connected(resumed)`, `Disconnected(code, reconnecting)`, `Truncated(topic, first_available)`, `Stalled(topic, seq)`, `AuthExpiring(expires_at_ms)`, `AuthRefreshed()`, `Unsubscribed(topic)` and `ServerErrorEvent(code, message)`. Each has `to_json()`.
135
+
136
+ ### Configuration
137
+
138
+ `ClientConfig(url, credentials, ...)`:
139
+
140
+ | Field | Default | Meaning |
141
+ |---|---|---|
142
+ | `url` | | `ws://` or `wss://` |
143
+ | `credentials` | | `PasswordCredentials(username, password)` or `TokenCredentials(token)` |
144
+ | `session_id` | `None` | A durable session to hold; None is ephemeral. |
145
+ | `clean_start` | `False` | Discard the session's stored subscriptions; sent on the first connection only. |
146
+ | `ack_mode` | `AckMode.AUTO` | `AUTO` acknowledges QoS 1 messages as they are handed over; `MANUAL` waits for `message.ack()`. |
147
+ | `reconnect` | `ReconnectPolicy(0.25, 30.0, None)` | `initial` and `max` ceilings in seconds, and `max_attempts` (None keeps trying). |
148
+ | `request_timeout` | `30.0` | Seconds a connect, subscribe, confirmed publish or admin call may take. |
149
+ | `subscription_buffer` | `1024` | Messages buffered per subscription before the client stops reading the socket. |
150
+ | `ssl_context` | `None` | TLS settings for `wss://`, such as a context trusting a private CA. |
151
+
152
+ ### Errors
153
+
154
+ Every failure is a `PopSubError` with a `kind`:
155
+
156
+ | Class | `kind` | Extra attributes |
157
+ |---|---|---|
158
+ | `ServerError` | `server` | `code` (such as `not_authorized`), `retry_after` |
159
+ | `ClosedError` | `closed` | `close_code` (or None) |
160
+ | `RequestTimeoutError` | `timeout` | |
161
+ | `ConnectError` | `connect` | |
162
+ | `ProtocolError` | `protocol` | |
163
+ | `ConfigError` | `config` | |
164
+
165
+ `error.is_temporary` says whether trying again later might work. Errors keep their cause in `__cause__`.
166
+
167
+ ### Logging
168
+
169
+ The client logs through the standard `logging` module under the `popsub` logger and configures no handlers. Its own log lines never include passwords, tokens or payloads. The `websockets` library logs under its own `websockets` logger, and at `DEBUG` level that includes frame contents, so keep it above `DEBUG` in production.
170
+
171
+ ## Scenario suite
172
+
173
+ The scenario driver is the internal module `popsub._driver`; it is not part of the public API. From the repository root, with the suite built (`cargo build -p popsub_scenarios`):
174
+
175
+ ```bash
176
+ target/debug/popsub-scenarios --driver "uv run --project clients/python python -m popsub._driver"
177
+ target/debug/popsub-scenarios --driver "uv run --project clients/python python -m popsub._driver" --scenario reconnect_resubscribes_without_gaps
178
+ ```
179
+
180
+ The driver logs to standard error; set `POPSUB_LOG=DEBUG` for more.
181
+
182
+ ## Development
183
+
184
+ Uses [uv](https://docs.astral.sh/uv/). From `clients/python`:
185
+
186
+ ```bash
187
+ uv sync
188
+ uv run ruff format --check . && uv run ruff check . && uv run mypy && uv run pytest
189
+ ```
190
+
191
+ That runs the formatter check, the linter, `mypy --strict` over the package and tests, and the tests. The tests cover backoff, deduplication (by next expected seq, and by the seen set for shared subscriptions), the wildcard pattern matcher, the wire types and a message's bytes, feed the engine frames directly to check how a new process claims a durable session's topics and how a repeated pattern subscribe moves its topics, and run the client against a small in-process fake server to check that resent copies are dropped and acknowledged again, that a reconnect resubscribes from the next expected seq, that byte publishes carry base64 and the encoding (also when resent) while text publishes carry none, and that `close()` leaves no task running.
192
+
193
+ `uv build` writes the wheel and source distribution to `dist/`.