popsub 0.0.0-stage → 0.1.0
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.
- package/LICENSE +201 -0
- package/README.md +196 -2
- package/dist/admin.d.ts +175 -0
- package/dist/admin.js +257 -0
- package/dist/admin.js.map +1 -0
- package/dist/backoff.d.ts +32 -0
- package/dist/backoff.js +31 -0
- package/dist/backoff.js.map +1 -0
- package/dist/base64.d.ts +24 -0
- package/dist/base64.js +104 -0
- package/dist/base64.js.map +1 -0
- package/dist/client.d.ts +250 -0
- package/dist/client.js +322 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +117 -0
- package/dist/config.js +116 -0
- package/dist/config.js.map +1 -0
- package/dist/dedup.d.ts +107 -0
- package/dist/dedup.js +150 -0
- package/dist/dedup.js.map +1 -0
- package/dist/engine.d.ts +224 -0
- package/dist/engine.js +1306 -0
- package/dist/engine.js.map +1 -0
- package/dist/errors.d.ts +80 -0
- package/dist/errors.js +90 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +111 -0
- package/dist/events.js +57 -0
- package/dist/events.js.map +1 -0
- package/dist/handshake.d.ts +91 -0
- package/dist/handshake.js +266 -0
- package/dist/handshake.js.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +33 -0
- package/dist/index.js.map +1 -0
- package/dist/pattern.d.ts +24 -0
- package/dist/pattern.js +43 -0
- package/dist/pattern.js.map +1 -0
- package/dist/protocol.d.ts +313 -0
- package/dist/protocol.js +173 -0
- package/dist/protocol.js.map +1 -0
- package/dist/subscription.d.ts +187 -0
- package/dist/subscription.js +268 -0
- package/dist/subscription.js.map +1 -0
- package/package.json +50 -4
package/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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,197 @@
|
|
|
1
|
-
#
|
|
1
|
+
# PopSub TypeScript client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A client for [PopSub](../../README.md) that runs in browsers and in Node.js 22 or later. It uses only the global `WebSocket` and has no runtime dependencies.
|
|
4
|
+
|
|
5
|
+
It does what every PopSub client does (see [`clients/README.md`](../README.md)): logs in and refreshes its token, reconnects with jittered backoff and knows from the close code when not to, resubscribes from the next `seq` it expects so nothing still in the log is missed, resends confirmed publishes under the same request id and `message_id` so the server stores them once, acknowledges QoS 1 messages, and hands each `(topic, seq)` to the application at most once. It passes the shared scenario suite.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install popsub
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
To use a version that isn't released yet, build it from a checkout and install it from this folder:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
cd clients/typescript
|
|
17
|
+
npm install
|
|
18
|
+
npm run build
|
|
19
|
+
cd /path/to/your/app
|
|
20
|
+
npm install /path/to/popsub/clients/typescript
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { Client, PopSubError } from "popsub";
|
|
27
|
+
|
|
28
|
+
const client = await Client.connect(
|
|
29
|
+
{
|
|
30
|
+
url: "ws://127.0.0.1:8080",
|
|
31
|
+
credentials: { username: "alice", password: "alice-password" },
|
|
32
|
+
sessionId: "alice-laptop",
|
|
33
|
+
},
|
|
34
|
+
(event) => {
|
|
35
|
+
if (event.type === "disconnected") {
|
|
36
|
+
console.warn("disconnected", event.code, event.reconnecting);
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
const orders = await client.subscribe("orders", "resume");
|
|
42
|
+
const stored = await client.publishConfirmed("orders", "order 42 shipped");
|
|
43
|
+
console.log("stored as seq", stored.seq);
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
for await (const message of orders) {
|
|
47
|
+
console.log(message.topic, message.seq, message.payload);
|
|
48
|
+
}
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (error instanceof PopSubError) {
|
|
51
|
+
console.error(error.kind, error.code, error.closeCode);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
await client.close();
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## API
|
|
58
|
+
|
|
59
|
+
### `Client`
|
|
60
|
+
|
|
61
|
+
| Member | What it does |
|
|
62
|
+
| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
63
|
+
| `Client.connect(config, listener?)` | Connects, logs in and authenticates, retrying with the reconnect policy for up to `requestTimeoutMs`. `listener` receives every event, including the first `connected`. Rejects with `invalid_credentials` (and other non-temporary refusals) at once, without retrying. |
|
|
64
|
+
| `subscribe(topic, from = "resume")` | Resolves with a `Subscription` once the server confirms it. `topic` is a topic name or a wildcard pattern (below). `from` is `"resume"`, `"new"`, `{ last }`, `{ sinceMs }` or `{ seq }`. Subscribing to a topic or pattern again replaces the earlier subscription. |
|
|
65
|
+
| `subscribeShared(topic, group, from = "resume")` | Joins a shared subscription to a topic (below). |
|
|
66
|
+
| `unsubscribe(topic)` | Ends the subscription to a topic, or to a pattern and every topic joined through it, and tells the server. While disconnected it is queued and resolves at once. |
|
|
67
|
+
| `publish(topic, payload)` | QoS 0. Returns at once. Up to 10,000 publishes (and unsubscribes) are held while disconnected, oldest dropped first. Server refusals arrive as `serverError` events. |
|
|
68
|
+
| `publishConfirmed(topic, payload)` | QoS 1. Resolves with `{ seq, messageId }` once stored. Resent after every reconnect until confirmed. |
|
|
69
|
+
| `publishBytes(topic, bytes)` | QoS 0 for a `Uint8Array` body that isn't text. Otherwise the same as `publish`. See [Binary payloads](#binary-payloads). |
|
|
70
|
+
| `publishBytesConfirmed(topic, bytes)` | QoS 1 for a `Uint8Array` body. Otherwise the same as `publishConfirmed`. |
|
|
71
|
+
| `admin()` | An `Admin` with the account calls `createUser`, `getUser`, `listUsers`, `setRole`, `grant`, `revoke`, `setPassword`, `setEnabled` and `deleteUser`, and the topic calls `listTopics`, `getTopic` and `purgeTopic`, which return `TopicInfo` (`name`, `firstSeq`, `lastSeq`, `messages`, `subscribers`). `getTopic` and `purgeTopic` reject with `topic_not_found` for a topic nothing was ever published to. None of these is queued or resent: while disconnected, or when the connection drops before the reply, they reject with `connect`. |
|
|
72
|
+
| `on(listener)` / `off(listener)` | Registers or removes an event listener. `on` returns a function that removes it. |
|
|
73
|
+
| `close()` | Stops the client: closes the socket, fails pending requests with `closed`, ends every subscription, clears every timer and listener. Resolves once stopped. |
|
|
74
|
+
| `stopped` | `null` while running, then `{ code }` with the close code that stopped it (or `null`). |
|
|
75
|
+
|
|
76
|
+
### Wildcard subscriptions
|
|
77
|
+
|
|
78
|
+
In a pattern a whole level may be `+` (any one level) and the last level may be `#` (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`. Order is kept within each topic, not across topics.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const orders = await client.subscribe("orders/#", "new");
|
|
82
|
+
for await (const message of orders) {
|
|
83
|
+
console.log(message.topic, message.seq, message.payload);
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Each topic the server joins for the pattern is tracked on its own (next expected `seq`, acknowledgements), so deduplication and gap-free resubscription work per topic. After a reconnect the client resubscribes those topics from where each left off and sends the pattern again, which picks up topics created while it was away from their first message. If the server ends one of the topics (an `unsubscribed` event naming it), only that topic stops. `client.unsubscribe("orders/#")`, `close()` on the subscription, or breaking out of the loop leaves the pattern and every topic joined through it.
|
|
88
|
+
|
|
89
|
+
Subscribing again to a pattern the client already holds replaces the subscription. The topics joined through it move to the new subscription and keep their next expected `seq`, so each later message arrives once, on the new subscription. The earlier subscription ends: it yields what it had already buffered and then `undefined`, and closing or dropping it doesn't unsubscribe anything.
|
|
90
|
+
|
|
91
|
+
### A durable session in a new process
|
|
92
|
+
|
|
93
|
+
A durable session (`sessionId`) outlives the process. When a new process connects with the same `sessionId`, the `connected` event lists the session's topics in `resumed` before the application has subscribed to anything. With a `sessionId` the client asks the server to hold those topics (`hold_resumed: true` in `auth`), and a server that honours it (it answers `held: true`) sends nothing on them until the client subscribes.
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
const client = await Client.connect({ url, credentials, sessionId: "alice-laptop", ackMode: "manual" });
|
|
97
|
+
const jobs = await client.subscribe("jobs", "resume");
|
|
98
|
+
const tasks = await client.subscribe("tasks/#");
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
When the topics are held, subscribing to one by name, or to a pattern that matches it, is an ordinary subscribe: `"resume"` starts one past the session's cursor, and the server joins a pattern's topic from that cursor whatever the pattern's `from`. Nothing is in flight for a topic the application never subscribes to, so it neither stalls nor is dead-lettered. After a reconnect the client subscribes again, from `"resume"`, to every topic it tracks that the server lists in `resumed`.
|
|
102
|
+
|
|
103
|
+
A server that doesn't know `hold_resumed` answers without `held` and starts sending what it kept straight away. Then, until the application subscribes to one of those topics, the client drops its messages without acknowledging them, so the server keeps them. Subscribing to the topic by name, or to a pattern that matches it, claims it: the subscribe replays the kept messages in order, and they are handed over from the `subscribed` reply on. For a pattern the client sends one more `subscribe` per claimed topic, by name with `from: "resume"`, because the server skips topics the connection already holds when it handles the pattern. A topic the application never subscribes to stays unclaimed: its messages wait on the server, where after `max_retries` the subscription stalls or the messages are dead-lettered, as for any subscriber that doesn't acknowledge. To drop a topic from the session, `unsubscribe` it.
|
|
104
|
+
|
|
105
|
+
### Shared subscriptions
|
|
106
|
+
|
|
107
|
+
Members of a group split a topic's messages: each message goes to one member. Subscribers outside the group still get everything.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
const jobs = await client.subscribeShared("jobs", "workers", "new");
|
|
111
|
+
for await (const job of jobs) {
|
|
112
|
+
await handle(job.payload);
|
|
113
|
+
job.ack();
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
That example assumes `ackMode: "manual"`; in automatic mode `ack()` does nothing. A member gets only its share, not in strict `seq` order, and a message a member never acknowledged goes to another member when it disconnects, so workers must tolerate a repeat. Within one client, repeats are dropped by remembering the last 4096 `seq`s delivered. `from` only matters the first time a group is used on a topic; after that the group's position is on the server, and the client always rejoins with `resume` after a reconnect. A group needs an exact topic, not a pattern.
|
|
118
|
+
|
|
119
|
+
### `Subscription` and `Message`
|
|
120
|
+
|
|
121
|
+
A `Subscription` is an async iterable of `Message`s in `seq` order. `next()` resolves with the next message, or `undefined` once the subscription has ended and is drained. It ends when the server ends it (access revoked), when the application unsubscribes, or when the client stops. `close()`, or breaking out of `for await`, unsubscribes and drops the messages not yet taken. `buffered` is how many messages wait.
|
|
122
|
+
|
|
123
|
+
A `Message` has `topic`, `seq`, `messageId`, `payload`, `encoding`, `qos` and `publishedAtMs`, and `bytes()` returns its body as a `Uint8Array` (see [Binary payloads](#binary-payloads)). In manual mode, `ack()` acknowledges a QoS 1 message; in automatic mode and for QoS 0 it does nothing. Acknowledging twice is harmless.
|
|
124
|
+
|
|
125
|
+
### Binary payloads
|
|
126
|
+
|
|
127
|
+
A payload is always a string. For a body that isn't text, publish a `Uint8Array`:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
client.publishBytes("frames", new Uint8Array([0x00, 0xff, 0xfe, 0x80]));
|
|
131
|
+
const stored = await client.publishBytesConfirmed("frames", bytes);
|
|
132
|
+
|
|
133
|
+
for await (const message of frames) {
|
|
134
|
+
const body = message.bytes();
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`publishBytes` and `publishBytesConfirmed` send the bytes as standard padded base64 in `payload` with `encoding: "base64"`, and otherwise behave exactly like `publish` and `publishConfirmed`: the same queue while disconnected, and the same resend under one request id and `message_id`. The server checks that the payload is base64 and carries it without decoding. Base64 adds about a third, and the server's payload limit (`max_payload_bytes`) counts the encoded string, so the largest body that fits is about three quarters of the limit.
|
|
139
|
+
|
|
140
|
+
On a received message, `payload` is the string as it arrived and `encoding` is `"base64"` for a message published as bytes or `null` for text. `bytes()` returns the decoded payload when the encoding is `base64`, and the payload's UTF-8 bytes otherwise, so it works for either kind. If a payload claims base64 and doesn't decode, the message is still delivered and `bytes()` throws a `PopSubError` of kind `protocol`. Encoding and decoding use a small strict codec in the package (padding required, no whitespace), not `Buffer`, so they work the same in browsers and Node.
|
|
141
|
+
|
|
142
|
+
### Events
|
|
143
|
+
|
|
144
|
+
`connected { resumed }`, `disconnected { code, reconnecting }`, `truncated { topic, firstAvailable }`, `stalled { topic, seq }`, `authExpiring { expiresAtMs }`, `authRefreshed`, `unsubscribed { topic }` (the server ended a subscription) and `serverError { code, message }` (an error that answers no request). A listener that throws doesn't stop the others; its error is rethrown from a microtask.
|
|
145
|
+
|
|
146
|
+
### Errors
|
|
147
|
+
|
|
148
|
+
Every failure is a `PopSubError` with `kind` (`server`, `closed`, `timeout`, `connect`, `protocol`, `config`), `code` for `server` errors (unknown codes read as `internal`), `retryAfter` for limits, `closeCode` for `closed`, and `cause` when it wraps another error. `isTemporary()` says whether retrying later might work.
|
|
149
|
+
|
|
150
|
+
### Configuration
|
|
151
|
+
|
|
152
|
+
| Field | Default | Meaning |
|
|
153
|
+
| -------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
154
|
+
| `url` | required | `ws://` or `wss://` |
|
|
155
|
+
| `credentials` | required | `{ username, password }`, or `{ token }` (a token can't be refreshed; the client stops when it expires) |
|
|
156
|
+
| `sessionId` | `null` | A durable session, 1 to 128 characters |
|
|
157
|
+
| `cleanStart` | `false` | Discard the session's stored subscriptions, on the first connection only |
|
|
158
|
+
| `ackMode` | `"auto"` | `"auto"` or `"manual"` |
|
|
159
|
+
| `reconnect` | `{ initialMs: 250, maxMs: 30000, maxAttempts: null }` | Each wait is random between zero and a ceiling that doubles from `initialMs` up to `maxMs` |
|
|
160
|
+
| `requestTimeoutMs` | `30000` | Limit for connect, subscribe, unsubscribe, confirmed publishes and admin calls |
|
|
161
|
+
| `subscriptionBuffer` | `1024` | Messages buffered per subscription before the client holds back (below) |
|
|
162
|
+
|
|
163
|
+
## How it differs from the Rust client
|
|
164
|
+
|
|
165
|
+
The browser `WebSocket` API offers no way to stop reading a socket and doesn't show WebSocket pings, so backpressure works differently than in `crates/popsub_sdk`, and silence is detected with the protocol's `ping` request, as [`clients/README.md`](../README.md) describes for clients that can't see pings.
|
|
166
|
+
|
|
167
|
+
**Backpressure.** The Rust client stops reading the socket when a subscription's buffer is full. This client can't, so:
|
|
168
|
+
|
|
169
|
+
1. While a subscription holds `subscriptionBuffer` messages or more, automatic acknowledgements of new QoS 1 messages wait until the application takes those messages. The server stops sending to a subscription whose window (`limits.max_inflight`, 100 by default) is full, QoS 0 included, so QoS 1 traffic is paced by the application. Manual mode is paced the same way by the application's own acks.
|
|
170
|
+
2. If the buffer still reaches `subscriptionBuffer + max_inflight` messages, which only QoS 0 traffic can cause since no window paces it, the client drops the connection (a `disconnected` event with `code: null` and `reconnecting: true`), waits until the application has taken that buffer down to half of `subscriptionBuffer`, reconnects, and resubscribes that topic from the next `seq` it expects, so the server's log fills the gap. Messages trimmed from the log meanwhile are reported with `truncated`.
|
|
171
|
+
|
|
172
|
+
So each subscription holds fewer than `subscriptionBuffer + max_inflight` messages. While acknowledgements are held back, the server may resend those messages after its ack timeout; the client drops them as duplicates and doesn't acknowledge them, and after `max_retries` the server reports `stalled` and pauses the topic until the held acknowledgements go out.
|
|
173
|
+
|
|
174
|
+
**Silence detection.** Browsers and Node answer the server's WebSocket pings on their own but don't report them, so a quiet topic and a dead connection look the same. As `clients/README.md` asks of such clients, after `limits.heartbeat_secs` with nothing from the server the client sends the protocol's `ping` request with an id, and again after each further `heartbeat_secs` of silence. The server answers with `pong`, which also counts as client activity for its idle timeout. Any frame resets the silence. If nothing at all arrives within `idle_timeout_secs + heartbeat_secs`, the connection is treated as dead: the client drops it (a `disconnected` event with `code: null` and `reconnecting: true`) and reconnects.
|
|
175
|
+
|
|
176
|
+
**Numbers.** `seq` values are JavaScript numbers, exact up to 2^53.
|
|
177
|
+
|
|
178
|
+
## Scenarios
|
|
179
|
+
|
|
180
|
+
From the repository root, with `popsub-scenarios` already built:
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
(cd clients/typescript && npm install && npm run build)
|
|
184
|
+
target/debug/popsub-scenarios --driver "node clients/typescript/dist/driver.js"
|
|
185
|
+
target/debug/popsub-scenarios --driver "node clients/typescript/dist/driver.js" --scenario reconnect_resubscribes_without_gaps
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
`npm run scenarios` in this folder builds and runs the whole suite. The driver (`src/driver.ts`) speaks the protocol in [`clients/DRIVER.md`](../DRIVER.md). It is built to `dist/driver.js` but isn't exported from the package and isn't included in it.
|
|
189
|
+
|
|
190
|
+
## Development
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
npm install
|
|
194
|
+
npm run check
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`npm run check` runs, in order, `typecheck` (`tsc` with `strict`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` and `noImplicitOverride`), `lint` (ESLint with typescript-eslint's strict and stylistic type-checked presets, no warnings allowed), `format:check` (Prettier) and `test` (Node's built-in test runner). The tests cover the backoff ceiling, byte payloads (the base64 codec, the frames byte and text publishes send, and `Message.bytes`), deduplication (by next expected `seq`, and by delivered `seq`s for shared subscriptions), the topic pattern matcher, close codes and configuration checks, check that a silent connection is pinged and that a `ping` left unanswered leads to a reconnect, and run a client against a small in-test WebSocket server to check how a new process claims a durable session's topics (nothing acknowledged or handed over before the application subscribes, by name or by pattern, and a claim sent again after a reconnect) and that subscribing again to a pattern moves its topics to the new subscription, and run one in a child process to check that a closed client leaves nothing that keeps Node running. `npm run format` rewrites files in place, and `npm run build` compiles to `dist/` with declaration files and source maps.
|
package/dist/admin.d.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Admin`, the account management requests, for clients logged in as an
|
|
3
|
+
* admin.
|
|
4
|
+
*
|
|
5
|
+
* Each call is one request and its reply. None is queued while the client
|
|
6
|
+
* is disconnected or resent after a reconnect, because repeating a change
|
|
7
|
+
* such as `createUser` isn't safe: a call made while disconnected fails
|
|
8
|
+
* with a `connect` error, and so does one whose connection drops before the
|
|
9
|
+
* reply, whether or not the server carried it out.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import type { Access, AdminRequest, RoleSpec, ServerMessage } from "./protocol.js";
|
|
14
|
+
/** An account, as admins see it. Never includes the password. */
|
|
15
|
+
export interface User {
|
|
16
|
+
/** The username. */
|
|
17
|
+
username: string;
|
|
18
|
+
/** What it may do. */
|
|
19
|
+
role: RoleSpec;
|
|
20
|
+
/** Whether it may log in and use topics. */
|
|
21
|
+
enabled: boolean;
|
|
22
|
+
/** When it was created, in milliseconds since the Unix epoch. */
|
|
23
|
+
createdAtMs: number;
|
|
24
|
+
}
|
|
25
|
+
/** A topic, as admins see it. */
|
|
26
|
+
export interface TopicInfo {
|
|
27
|
+
/** The topic's name. */
|
|
28
|
+
name: string;
|
|
29
|
+
/** The oldest `seq` still kept, or `lastSeq + 1` when nothing is kept. */
|
|
30
|
+
firstSeq: number;
|
|
31
|
+
/** The newest `seq` ever published. */
|
|
32
|
+
lastSeq: number;
|
|
33
|
+
/** How many records are kept now. */
|
|
34
|
+
messages: number;
|
|
35
|
+
/** How many live subscriptions it has. */
|
|
36
|
+
subscribers: number;
|
|
37
|
+
}
|
|
38
|
+
/** Sends one admin request and returns its reply. */
|
|
39
|
+
export type AdminTransport = (request: AdminRequest) => Promise<ServerMessage>;
|
|
40
|
+
/**
|
|
41
|
+
* The admin requests, from `Client.admin`. Every call rejects with a
|
|
42
|
+
* `server` error with code `forbidden` unless the client is logged in as
|
|
43
|
+
* an enabled admin, `connect` when disconnected or when the connection
|
|
44
|
+
* drops before the reply, `timeout` when no reply arrives in time, and
|
|
45
|
+
* `closed` when the client has stopped.
|
|
46
|
+
*/
|
|
47
|
+
export declare class Admin {
|
|
48
|
+
#private;
|
|
49
|
+
/**
|
|
50
|
+
* Wraps a transport. Applications get an `Admin` from `Client.admin`.
|
|
51
|
+
*
|
|
52
|
+
* @param send - Sends one request and returns its reply.
|
|
53
|
+
*/
|
|
54
|
+
constructor(send: AdminTransport);
|
|
55
|
+
/**
|
|
56
|
+
* Creates an account.
|
|
57
|
+
*
|
|
58
|
+
* @param username - Its name: 3 to 32 letters, digits, `_`, `.` or `-`.
|
|
59
|
+
* @param password - Its password, at least 8 characters.
|
|
60
|
+
* @param role - What it may do.
|
|
61
|
+
* @returns The new account.
|
|
62
|
+
* @throws PopSubError with code `user_exists`, or `bad_request` for an
|
|
63
|
+
* invalid name, password or pattern.
|
|
64
|
+
*/
|
|
65
|
+
createUser(username: string, password: string, role: RoleSpec): Promise<User>;
|
|
66
|
+
/**
|
|
67
|
+
* Reads an account.
|
|
68
|
+
*
|
|
69
|
+
* @param username - The account.
|
|
70
|
+
* @returns The account.
|
|
71
|
+
* @throws PopSubError with code `user_not_found`.
|
|
72
|
+
*/
|
|
73
|
+
getUser(username: string): Promise<User>;
|
|
74
|
+
/**
|
|
75
|
+
* Lists every account, sorted by name.
|
|
76
|
+
*
|
|
77
|
+
* @returns The accounts.
|
|
78
|
+
* @throws PopSubError of kind `protocol` when the server answers with
|
|
79
|
+
* something other than `users`.
|
|
80
|
+
*/
|
|
81
|
+
listUsers(): Promise<User[]>;
|
|
82
|
+
/**
|
|
83
|
+
* Replaces an account's role. Live subscriptions the new role doesn't
|
|
84
|
+
* allow are ended.
|
|
85
|
+
*
|
|
86
|
+
* @param username - The account.
|
|
87
|
+
* @param role - Its new role.
|
|
88
|
+
* @returns The account as it now stands.
|
|
89
|
+
* @throws PopSubError with code `user_not_found`, or `bad_request` for an
|
|
90
|
+
* invalid pattern or for demoting the last enabled admin.
|
|
91
|
+
*/
|
|
92
|
+
setRole(username: string, role: RoleSpec): Promise<User>;
|
|
93
|
+
/**
|
|
94
|
+
* Grants an account a topic pattern, replacing any grant it already has
|
|
95
|
+
* for exactly that pattern.
|
|
96
|
+
*
|
|
97
|
+
* @param username - The account.
|
|
98
|
+
* @param pattern - The topic pattern.
|
|
99
|
+
* @param access - What it allows.
|
|
100
|
+
* @returns The account as it now stands.
|
|
101
|
+
* @throws PopSubError with code `user_not_found`, or `bad_request` for an
|
|
102
|
+
* invalid pattern, an admin account, or publishing for a readonly one.
|
|
103
|
+
*/
|
|
104
|
+
grant(username: string, pattern: string, access: Access): Promise<User>;
|
|
105
|
+
/**
|
|
106
|
+
* Removes one of an account's grants. Live subscriptions no longer
|
|
107
|
+
* allowed are ended.
|
|
108
|
+
*
|
|
109
|
+
* @param username - The account.
|
|
110
|
+
* @param pattern - The pattern, exactly as granted.
|
|
111
|
+
* @returns The account as it now stands.
|
|
112
|
+
* @throws PopSubError with code `user_not_found`, or `bad_request` when
|
|
113
|
+
* the account has no such grant.
|
|
114
|
+
*/
|
|
115
|
+
revoke(username: string, pattern: string): Promise<User>;
|
|
116
|
+
/**
|
|
117
|
+
* Sets an account's password. Tokens issued before it are cancelled, and
|
|
118
|
+
* the account's connections are closed so they log in again.
|
|
119
|
+
*
|
|
120
|
+
* @param username - The account.
|
|
121
|
+
* @param password - The new password.
|
|
122
|
+
* @returns The account.
|
|
123
|
+
* @throws PopSubError with code `user_not_found`, or `bad_request` for a
|
|
124
|
+
* password that is too short or too long.
|
|
125
|
+
*/
|
|
126
|
+
setPassword(username: string, password: string): Promise<User>;
|
|
127
|
+
/**
|
|
128
|
+
* Enables or disables an account. Disabling closes its connections with
|
|
129
|
+
* `account_disabled` (4009) and refuses its logins and tokens.
|
|
130
|
+
*
|
|
131
|
+
* @param username - The account.
|
|
132
|
+
* @param enabled - Whether it may log in.
|
|
133
|
+
* @returns The account as it now stands.
|
|
134
|
+
* @throws PopSubError with code `user_not_found`, or `bad_request` for
|
|
135
|
+
* disabling the last enabled admin.
|
|
136
|
+
*/
|
|
137
|
+
setEnabled(username: string, enabled: boolean): Promise<User>;
|
|
138
|
+
/**
|
|
139
|
+
* Deletes an account and closes its connections with `account_disabled` (4009).
|
|
140
|
+
*
|
|
141
|
+
* @param username - The account.
|
|
142
|
+
* @throws PopSubError with code `user_not_found`, `bad_request` for the
|
|
143
|
+
* last enabled admin, or of kind `protocol` when the server answers
|
|
144
|
+
* with something other than `user_deleted`.
|
|
145
|
+
*/
|
|
146
|
+
deleteUser(username: string): Promise<void>;
|
|
147
|
+
/**
|
|
148
|
+
* Lists every topic that has a log, sorted by name.
|
|
149
|
+
*
|
|
150
|
+
* @returns The topics.
|
|
151
|
+
* @throws PopSubError of kind `protocol` when the server answers with
|
|
152
|
+
* something other than `topics`.
|
|
153
|
+
*/
|
|
154
|
+
listTopics(): Promise<TopicInfo[]>;
|
|
155
|
+
/**
|
|
156
|
+
* Reads a topic's bounds, record count and live subscriptions.
|
|
157
|
+
*
|
|
158
|
+
* @param topic - The topic.
|
|
159
|
+
* @returns The topic.
|
|
160
|
+
* @throws PopSubError with code `topic_not_found` when nothing was ever
|
|
161
|
+
* published to it.
|
|
162
|
+
*/
|
|
163
|
+
getTopic(topic: string): Promise<TopicInfo>;
|
|
164
|
+
/**
|
|
165
|
+
* Removes every record a topic holds. Its numbering carries on (the next
|
|
166
|
+
* publish gets `lastSeq + 1`), live subscriptions stay, and a subscriber
|
|
167
|
+
* that hadn't caught up gets `truncated`.
|
|
168
|
+
*
|
|
169
|
+
* @param topic - The topic.
|
|
170
|
+
* @returns The topic after the purge.
|
|
171
|
+
* @throws PopSubError with code `topic_not_found` when nothing was ever
|
|
172
|
+
* published to it.
|
|
173
|
+
*/
|
|
174
|
+
purgeTopic(topic: string): Promise<TopicInfo>;
|
|
175
|
+
}
|