popsub 0.0.0-stage → 0.2.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.
@@ -0,0 +1,224 @@
1
+ /**
2
+ * The engine behind a `Client`: it owns the WebSocket and does what every
3
+ * application would otherwise have to.
4
+ *
5
+ * It connects, logs in and authenticates, then serves the connection until
6
+ * it ends. The close code decides what happens next: reconnect with
7
+ * jittered backoff, or stop for good (`session_taken_over`,
8
+ * `unsupported_protocol`, `auth_failed`, `account_disabled`, rejected
9
+ * credentials, and `token_expired` with token credentials). After
10
+ * reconnecting it resubscribes every topic from the next `seq` it expects
11
+ * (a topic the server lists as resumed for a durable session is instead
12
+ * subscribed again from `resume` when the server holds the session's
13
+ * topics, and otherwise left to the server unless a claim on it is still
14
+ * unanswered; see below), resends confirmed publishes that never got their `published` under the
15
+ * same request id and `message_id`, and sends QoS 0 publishes and
16
+ * unsubscribes queued while disconnected.
17
+ *
18
+ * Every message is checked against the next `seq` its topic expects, so a
19
+ * retry or a replay never reaches the application twice. A duplicate the
20
+ * application acknowledged before (or any duplicate in automatic mode,
21
+ * unless its acknowledgement is held back for a full buffer) is
22
+ * acknowledged again, so a lost acknowledgement can't stall the topic.
23
+ *
24
+ * A durable session outlives the process. When a new process connects
25
+ * with the same session id, the server lists the session's topics in
26
+ * `authenticated.resumed` before the application has subscribed to
27
+ * anything. The engine must never acknowledge a message the application
28
+ * couldn't have received, so with a session id its `auth` carries
29
+ * `hold_resumed: true`. A server that honours it answers `held: true` and
30
+ * sends nothing on a resumed topic until the engine subscribes to it. Then
31
+ * nothing is unclaimed, a subscribe to a resumed topic is an ordinary
32
+ * subscribe, a pattern needs no subscribes by name, and after a reconnect
33
+ * the engine subscribes again to every tracked topic the server lists as
34
+ * resumed, with `from: "resume"`, because the server no longer does it.
35
+ *
36
+ * A server that doesn't know `hold_resumed` answers without `held` and
37
+ * sends what it kept for the resumed topics at once. A resumed topic the engine
38
+ * isn't tracking is unclaimed: its messages are dropped without an
39
+ * acknowledgement, so the server keeps them for the session. Subscribing
40
+ * to an unclaimed topic by name, or to a pattern that matches it, claims
41
+ * it. A claimed topic is tracked, but its messages are still dropped
42
+ * unacknowledged until the `subscribed` that answers the claim arrives,
43
+ * because the subscribe replays them in order from `replay_from`. A
44
+ * pattern claims a topic by sending one more `subscribe` for it by name
45
+ * with `from: "resume"`, since the server skips topics the connection
46
+ * holds when it handles the pattern itself. After a reconnect a claim
47
+ * still unanswered is sent again even when the server lists the topic as
48
+ * resumed. A topic the application never subscribes to stays unclaimed.
49
+ *
50
+ * A wildcard subscription (`orders/#`) is one pattern with one channel.
51
+ * The server announces each topic it joins for the pattern with a
52
+ * `subscribed` frame that has no id; the engine then tracks that topic
53
+ * like any other, with its own next expected `seq` and acknowledgement
54
+ * memory, owned by the pattern and feeding the pattern's channel. A
55
+ * `subscribed` or `message` for an untracked topic is matched against the
56
+ * patterns, and the oldest matching one owns it. After a reconnect the
57
+ * tracked topics are resubscribed first, then each pattern is sent again
58
+ * with `from: {"seq": 1}`, which joins only topics created meanwhile.
59
+ * Subscribing again to a pattern the engine holds replaces the
60
+ * subscription: the topics it owned move to the new channel and keep
61
+ * their next expected `seq`, because the server sends nothing again for
62
+ * topics the connection holds, and the earlier channel ends.
63
+ *
64
+ * A shared subscription (a topic read through a `group`) gets only some of
65
+ * the topic's messages, out of order, so duplicates are found with a
66
+ * bounded set of delivered `seq`s instead of a next expected one, nothing
67
+ * moves on `subscribed.replay_from` or `truncated`, and after a reconnect
68
+ * it always rejoins the group with `from: "resume"`.
69
+ *
70
+ * An `unsubscribed` frame with no id means the server ended the
71
+ * subscription; every unsubscribe the engine sends carries an id so its
72
+ * reply is never mistaken for that.
73
+ *
74
+ * The browser `WebSocket` API can't pause reading, so backpressure works in
75
+ * two steps. While a subscription's buffer holds `subscriptionBuffer`
76
+ * messages or more, automatic acknowledgements of new QoS 1 messages wait
77
+ * until the application takes them; the server's per-subscription window
78
+ * (`limits.max_inflight`) then stops sending to it, QoS 0 included. If the
79
+ * buffer still reaches `subscriptionBuffer + max_inflight` (possible with
80
+ * QoS 0 traffic, which no window paces), the engine drops the connection,
81
+ * waits until the application has taken that buffer down to half of
82
+ * `subscriptionBuffer`, reconnects, and resubscribes that topic from the
83
+ * next `seq` it expects, so the log fills the gap. Memory per subscription
84
+ * stays below `subscriptionBuffer + max_inflight` messages.
85
+ *
86
+ * Nor does the API show the server's WebSocket pings, so silence is
87
+ * detected with the protocol's own `ping` request: after `heartbeat_secs`
88
+ * with nothing from the server the engine sends `ping` with an id, and
89
+ * again after each further `heartbeat_secs` of silence. Any frame,
90
+ * including the `pong` reply, counts as hearing from the server. Once
91
+ * `idle_timeout_secs + heartbeat_secs` pass with nothing at all, the
92
+ * connection is given up and the engine reconnects.
93
+ *
94
+ * @module
95
+ */
96
+ import type { ResolvedConfig } from "./config.js";
97
+ import { Emitter } from "./events.js";
98
+ import { type ClientMessage, type CloseCode, type Encoding, type ServerMessage, type WireStartFrom } from "./protocol.js";
99
+ import { Subscription } from "./subscription.js";
100
+ /** How many QoS 0 publishes and unsubscribes are held while disconnected; the oldest go first. */
101
+ export declare const OFFLINE_LIMIT = 10000;
102
+ /** The result of a confirmed publish. */
103
+ export interface Published {
104
+ /** The message's position in the topic. */
105
+ seq: number;
106
+ /** The id it was stored under. */
107
+ messageId: string;
108
+ }
109
+ /**
110
+ * Creates a version 4 UUID, with `crypto.randomUUID` where the runtime has
111
+ * it (browsers only offer it on secure origins) and `getRandomValues`
112
+ * otherwise.
113
+ *
114
+ * @returns The UUID.
115
+ */
116
+ export declare function uuid(): string;
117
+ /** The state and the run loop behind one `Client`. */
118
+ export declare class Engine {
119
+ #private;
120
+ /** Where events go. */
121
+ readonly emitter: Emitter;
122
+ /** Settles when the first connection is up, or rejects with what stopped the client first. */
123
+ readonly ready: Promise<void>;
124
+ /** Settles when the run loop has finished and the client has stopped. */
125
+ readonly finished: Promise<void>;
126
+ /**
127
+ * Builds an engine and starts its run loop.
128
+ *
129
+ * @param config - How to connect.
130
+ */
131
+ constructor(config: ResolvedConfig);
132
+ /**
133
+ * Why the client stopped, if it has.
134
+ *
135
+ * @returns `{ code }` once stopped (the code is `null` when the
136
+ * application closed it or it ran out of attempts), `null` while running.
137
+ */
138
+ get stopped(): {
139
+ code: CloseCode | null;
140
+ } | null;
141
+ /**
142
+ * Subscribes to a topic or a wildcard pattern, replacing any earlier
143
+ * subscription to the same name. With a group it joins a shared
144
+ * subscription to the topic.
145
+ *
146
+ * Subscribing again to a topic by name starts over from `from`.
147
+ * Subscribing again to a pattern keeps the topics it owned (see
148
+ * `#replacePattern`).
149
+ *
150
+ * A topic the server held for the session, subscribed by name or matched
151
+ * by the pattern, is claimed: it is tracked with `claiming` set, so what
152
+ * the server sent on its own is dropped until the `subscribed` that
153
+ * answers the claim. A topic subscribed again while its claim is
154
+ * unanswered stays `claiming`. For a pattern each claimed topic gets its own
155
+ * subscribe by name with `from: "resume"`, sent after the pattern's.
156
+ * While disconnected nothing is sent; `#restore` sends the claims on the
157
+ * next connection.
158
+ *
159
+ * @param topic - The topic, or a pattern such as `orders/#`.
160
+ * @param from - Where replay starts.
161
+ * @param group - The shared subscription to join, or `null`.
162
+ * @returns The subscription, and a promise that settles when the server
163
+ * confirms it.
164
+ * @throws PopSubError of kind `closed` when the client has stopped.
165
+ */
166
+ subscribe(topic: string, from: WireStartFrom, group?: string | null): {
167
+ subscription: Subscription;
168
+ done: Promise<void>;
169
+ };
170
+ /**
171
+ * Unsubscribes from a topic, or from a pattern and every topic joined
172
+ * through it. While disconnected the unsubscribes are queued and the
173
+ * call succeeds at once.
174
+ *
175
+ * @param topic - The topic or pattern.
176
+ * @returns A promise that settles with the server's reply to the
177
+ * unsubscribe for `topic` itself.
178
+ */
179
+ unsubscribe(topic: string): Promise<void>;
180
+ /**
181
+ * Publishes at QoS 0. While disconnected the publish is queued.
182
+ *
183
+ * @param topic - The topic.
184
+ * @param payload - The body: text, or base64 when `encoding` says so.
185
+ * @param encoding - How `payload` encodes the body, or `null` for text.
186
+ * @throws PopSubError of kind `closed` when the client has stopped.
187
+ */
188
+ publish(topic: string, payload: string, encoding?: Encoding | null): void;
189
+ /**
190
+ * Publishes at QoS 1 under a new `message_id`, resending it after every
191
+ * reconnect until the server confirms it.
192
+ *
193
+ * @param topic - The topic.
194
+ * @param payload - The body: text, or base64 when `encoding` says so.
195
+ * @param encoding - How `payload` encodes the body, or `null` for text.
196
+ * @returns A promise that settles with the `seq` and id once stored.
197
+ */
198
+ publishConfirmed(topic: string, payload: string, encoding?: Encoding | null): Promise<Published>;
199
+ /**
200
+ * Acknowledges a message (from `Message.ack`). While disconnected it is
201
+ * only remembered, so a redelivery is acknowledged again.
202
+ *
203
+ * @param topic - The topic.
204
+ * @param seq - The message's `seq`.
205
+ */
206
+ ack(topic: string, seq: number): void;
207
+ /**
208
+ * Sends a request that is never queued while disconnected and never
209
+ * resent (the admin requests), and returns its reply.
210
+ *
211
+ * @param message - The request.
212
+ * @returns A promise that settles with the reply, rejecting with a
213
+ * `server` error for an `error` frame, or `connect` when disconnected
214
+ * or when the connection drops first.
215
+ */
216
+ request(message: ClientMessage): Promise<ServerMessage>;
217
+ /**
218
+ * Closes the connection and stops the client. Pending requests fail with
219
+ * a `closed` error.
220
+ *
221
+ * @returns A promise that settles once the client has stopped.
222
+ */
223
+ close(): Promise<void>;
224
+ }