@brokerize/client 1.11.0 → 1.12.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/README.md +45 -0
- package/dist/apiCtx.d.ts +10 -2
- package/dist/apiCtx.js +4 -4
- package/dist/authorizedApiContext.d.ts +5 -0
- package/dist/authorizedApiContext.js +11 -2
- package/dist/cjs/apiCtx.d.ts +10 -2
- package/dist/cjs/apiCtx.js +4 -4
- package/dist/cjs/authorizedApiContext.d.ts +5 -0
- package/dist/cjs/authorizedApiContext.js +10 -1
- package/dist/cjs/errors.d.ts +60 -0
- package/dist/cjs/errors.js +48 -1
- package/dist/cjs/index.d.ts +4 -4
- package/dist/cjs/index.js +4 -1
- package/dist/cjs/modelExports.d.ts +2 -0
- package/dist/cjs/modelExports.js +3 -1
- package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfo.d.ts +60 -0
- package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfo.js +51 -0
- package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfoStatus.d.ts +22 -0
- package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfoStatus.js +35 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoComplete.d.ts +7 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoComplete.js +6 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoCompleteSpecifics.d.ts +7 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoCompleteSpecifics.js +5 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoIncomplete.d.ts +7 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoIncomplete.js +6 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoIncompleteSpecifics.d.ts +7 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoIncompleteSpecifics.js +5 -0
- package/dist/cjs/swagger/models/TradeWarningReason.d.ts +1 -0
- package/dist/cjs/swagger/models/TradeWarningReason.js +1 -0
- package/dist/cjs/swagger/models/index.d.ts +2 -0
- package/dist/cjs/swagger/models/index.js +2 -0
- package/dist/cjs/websocketClient.d.ts +109 -2
- package/dist/cjs/websocketClient.js +416 -74
- package/dist/cjs/websocketTypes.d.ts +10 -0
- package/dist/client.d.ts +247 -46
- package/dist/errors.d.ts +60 -0
- package/dist/errors.js +44 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/modelExports.d.ts +2 -0
- package/dist/modelExports.js +1 -0
- package/dist/swagger/models/PortfolioOrderDetailsSyncInfo.d.ts +60 -0
- package/dist/swagger/models/PortfolioOrderDetailsSyncInfo.js +45 -0
- package/dist/swagger/models/PortfolioOrderDetailsSyncInfoStatus.d.ts +22 -0
- package/dist/swagger/models/PortfolioOrderDetailsSyncInfoStatus.js +29 -0
- package/dist/swagger/models/PortfolioSyncInfoComplete.d.ts +7 -0
- package/dist/swagger/models/PortfolioSyncInfoComplete.js +6 -0
- package/dist/swagger/models/PortfolioSyncInfoCompleteSpecifics.d.ts +7 -0
- package/dist/swagger/models/PortfolioSyncInfoCompleteSpecifics.js +5 -0
- package/dist/swagger/models/PortfolioSyncInfoIncomplete.d.ts +7 -0
- package/dist/swagger/models/PortfolioSyncInfoIncomplete.js +6 -0
- package/dist/swagger/models/PortfolioSyncInfoIncompleteSpecifics.d.ts +7 -0
- package/dist/swagger/models/PortfolioSyncInfoIncompleteSpecifics.js +5 -0
- package/dist/swagger/models/TradeWarningReason.d.ts +1 -0
- package/dist/swagger/models/TradeWarningReason.js +1 -0
- package/dist/swagger/models/index.d.ts +2 -0
- package/dist/swagger/models/index.js +2 -0
- package/dist/tsdoc-metadata.json +1 -1
- package/dist/websocketClient.d.ts +109 -2
- package/dist/websocketClient.js +416 -74
- package/dist/websocketTypes.d.ts +10 -0
- package/package.json +10 -9
package/dist/websocketClient.js
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
|
+
import { BrokerizeWebSocketError } from "./errors.js";
|
|
1
2
|
const LOG_PREFIX = "[brokerize WebSocketClient] ";
|
|
3
|
+
/**
|
|
4
|
+
* How often in a row the server may reject our token before the client gives up (see
|
|
5
|
+
* `WebSocketConnectionState`). Every attempt fetches a fresh token first, so the first retry
|
|
6
|
+
* already covers the common case of a token that expired in flight, and the remaining ones cover
|
|
7
|
+
* a backend that is briefly unable to validate it. Together with `AUTH_RETRY_INTERVAL` this spans
|
|
8
|
+
* several minutes, after which a token that is still being rejected is not going to be accepted:
|
|
9
|
+
* the session is over and retrying would only keep refreshing tokens for nobody.
|
|
10
|
+
*
|
|
11
|
+
* Until then the client stays in `reconnecting` and reports the rejection through
|
|
12
|
+
* `subscribeConnectionState`, so an application can tell the user that live updates are currently
|
|
13
|
+
* unavailable without tearing down its subscriptions.
|
|
14
|
+
*/
|
|
15
|
+
const DEFAULT_MAX_CONSECUTIVE_AUTH_FAILURES = 10;
|
|
16
|
+
/**
|
|
17
|
+
* The reconnect interval once the token has been rejected more than once. Every one of these
|
|
18
|
+
* attempts costs a token refresh, so they are spaced much wider than a plain reconnect. The first
|
|
19
|
+
* retry is deliberately not slowed down: it is the one that fixes a token that expired in flight.
|
|
20
|
+
*/
|
|
21
|
+
const AUTH_RETRY_INTERVAL = 30000;
|
|
2
22
|
export class BrokerizeWebSocketClientImpl {
|
|
3
|
-
constructor(websocketUrl, auth, createWebSocket) {
|
|
23
|
+
constructor(websocketUrl, auth, createWebSocket, options) {
|
|
24
|
+
var _a;
|
|
4
25
|
this._map = {};
|
|
5
26
|
this._authenticatedCallback = null;
|
|
6
27
|
this._disconnectTimeout = null;
|
|
@@ -9,10 +30,22 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
9
30
|
this._lastNonFatalError = null;
|
|
10
31
|
this._errorCount = 0;
|
|
11
32
|
this._apiCtx = null;
|
|
33
|
+
/**
|
|
34
|
+
* How often the server rejected our token in a row. Every retry forces a token refresh, and
|
|
35
|
+
* only `_maxConsecutiveAuthFailures` of them in a row are fatal. Reset on every successful
|
|
36
|
+
* authentication.
|
|
37
|
+
*/
|
|
38
|
+
this._authFailureCount = 0;
|
|
39
|
+
this._forceTokenRefresh = false;
|
|
40
|
+
this._destroyed = false;
|
|
41
|
+
this._connectionState = { status: "closed" };
|
|
42
|
+
this._connectionStateCallbacks = [];
|
|
12
43
|
this._url = websocketUrl;
|
|
13
44
|
this._id = 0;
|
|
14
45
|
this._socket = null;
|
|
15
46
|
this._pingIntvl = null;
|
|
47
|
+
this._maxConsecutiveAuthFailures =
|
|
48
|
+
(_a = options === null || options === void 0 ? void 0 : options.maxConsecutiveAuthFailures) !== null && _a !== void 0 ? _a : DEFAULT_MAX_CONSECUTIVE_AUTH_FAILURES;
|
|
16
49
|
this._updateReconnectInterval();
|
|
17
50
|
this._auth = auth;
|
|
18
51
|
this._createWebsocket = createWebSocket;
|
|
@@ -20,8 +53,9 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
20
53
|
_updateReconnectInterval() {
|
|
21
54
|
if (this._reconnectIntvl) {
|
|
22
55
|
clearInterval(this._reconnectIntvl);
|
|
56
|
+
this._reconnectIntvl = null;
|
|
23
57
|
}
|
|
24
|
-
if (this._fatalError) {
|
|
58
|
+
if (this._fatalError || this._destroyed) {
|
|
25
59
|
return;
|
|
26
60
|
}
|
|
27
61
|
this._reconnectIntvl = setInterval(() => {
|
|
@@ -40,17 +74,25 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
40
74
|
* Simple backoff behavior: first retry is fast (100ms), next 9 retries 1s, after that we only reconnect every 10s.
|
|
41
75
|
* Jitter is added to avoid a thundering herd when many clients reconnect simultaneously (e.g. after a server-side disconnect).
|
|
42
76
|
* The first retry uses a wider jitter window (~1s) because that's the scenario most prone to bursts of TLS handshakes.
|
|
77
|
+
*
|
|
78
|
+
* A token that keeps being rejected is retried far more slowly (`AUTH_RETRY_INTERVAL`), because
|
|
79
|
+
* every one of those attempts refreshes the token and a rejection is not something that tends to
|
|
80
|
+
* resolve within a second.
|
|
43
81
|
*/
|
|
44
82
|
_computeReconnectIntervalInMilliseconds(errorCount) {
|
|
45
83
|
if (errorCount == 0) {
|
|
46
84
|
return 100 + Math.floor(Math.random() * 1000);
|
|
47
85
|
}
|
|
48
|
-
const base =
|
|
86
|
+
const base = this._authFailureCount > 1
|
|
87
|
+
? AUTH_RETRY_INTERVAL
|
|
88
|
+
: errorCount < 10
|
|
89
|
+
? 1000
|
|
90
|
+
: 10000;
|
|
49
91
|
return base + Math.floor(Math.random() * base);
|
|
50
92
|
}
|
|
51
93
|
_shouldConnect() {
|
|
52
94
|
var _a;
|
|
53
|
-
if (this._fatalError) {
|
|
95
|
+
if (this._fatalError || this._destroyed) {
|
|
54
96
|
return false;
|
|
55
97
|
}
|
|
56
98
|
for (const k in this._map) {
|
|
@@ -60,10 +102,35 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
60
102
|
}
|
|
61
103
|
return false;
|
|
62
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* Invoke a subscriber callback. A callback that throws must not prevent the remaining
|
|
107
|
+
* subscribers from being notified, so everything is contained here.
|
|
108
|
+
*/
|
|
109
|
+
_invokeCallback(cb, err, data) {
|
|
110
|
+
try {
|
|
111
|
+
cb(err, data);
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
console.warn(LOG_PREFIX + "a subscription callback threw an error unexpectedly.", e);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
63
117
|
subscribe(cmd, callback) {
|
|
118
|
+
if (this._destroyed) {
|
|
119
|
+
const err = new BrokerizeWebSocketError({
|
|
120
|
+
msg: "the websocket client was destroyed.",
|
|
121
|
+
code: "WEBSOCKET_CONNECTION_FAILED",
|
|
122
|
+
terminal: true,
|
|
123
|
+
});
|
|
124
|
+
Promise.resolve().then(() => this._invokeCallback(callback, err, null));
|
|
125
|
+
return {
|
|
126
|
+
unsubscribe: () => { },
|
|
127
|
+
};
|
|
128
|
+
}
|
|
64
129
|
if (this._fatalError) {
|
|
65
|
-
// no more subscriptions on a websocket client that has a fatal error
|
|
66
|
-
callback
|
|
130
|
+
// no more subscriptions on a websocket client that has a fatal error. Report it
|
|
131
|
+
// asynchronously so the caller holds the Subscription before the callback runs.
|
|
132
|
+
const fatalError = this._fatalError;
|
|
133
|
+
Promise.resolve().then(() => this._invokeCallback(callback, fatalError, null));
|
|
67
134
|
return {
|
|
68
135
|
unsubscribe: () => { },
|
|
69
136
|
};
|
|
@@ -92,8 +159,13 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
92
159
|
return;
|
|
93
160
|
}
|
|
94
161
|
unsub = true;
|
|
95
|
-
|
|
96
|
-
if (
|
|
162
|
+
const entry = this._map[key];
|
|
163
|
+
if (!entry) {
|
|
164
|
+
/* the subscription was already dropped, e.g. because of a fatal error. */
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
entry.callbacks = entry.callbacks.filter((cb) => cb != wrappedCb);
|
|
168
|
+
if (entry.callbacks.length == 0) {
|
|
97
169
|
this._endSubscription(key);
|
|
98
170
|
}
|
|
99
171
|
this._startOrStopDisconnectTimeout();
|
|
@@ -108,6 +180,108 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
108
180
|
const cmd = Object.assign({ cmd: "subscribe", type: "decoupledOperationStatus", subscriptionId: null }, subscribe);
|
|
109
181
|
return this.subscribe(cmd, callback);
|
|
110
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* The current connection state. See `subscribeConnectionState`.
|
|
185
|
+
*/
|
|
186
|
+
getConnectionState() {
|
|
187
|
+
return this._connectionState;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Observe the state of the underlying websocket connection. The callback is invoked immediately
|
|
191
|
+
* with the current state and afterwards on every change.
|
|
192
|
+
*
|
|
193
|
+
* This is the only place where non-terminal errors are reported: the client recovers from them
|
|
194
|
+
* on its own, so they are not passed to the subscription callbacks, which would force
|
|
195
|
+
* applications to tear down subscriptions on every connection hiccup. Use this to show that
|
|
196
|
+
* live updates are currently unavailable.
|
|
197
|
+
*/
|
|
198
|
+
subscribeConnectionState(callback) {
|
|
199
|
+
this._connectionStateCallbacks.push(callback);
|
|
200
|
+
try {
|
|
201
|
+
callback(this._connectionState);
|
|
202
|
+
}
|
|
203
|
+
catch (e) {
|
|
204
|
+
console.warn(LOG_PREFIX + "a connection state callback threw an error unexpectedly.", e);
|
|
205
|
+
}
|
|
206
|
+
let unsub = false;
|
|
207
|
+
return {
|
|
208
|
+
unsubscribe: () => {
|
|
209
|
+
if (unsub) {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
unsub = true;
|
|
213
|
+
this._connectionStateCallbacks = this._connectionStateCallbacks.filter((cb) => cb != callback);
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Recover from a fatal error (see `WebSocketConnectionState`). The client drops the fatal error
|
|
219
|
+
* state and connects again, retrieving a fresh token. Existing subscriptions were already
|
|
220
|
+
* terminated when the fatal error occurred, so applications have to subscribe again.
|
|
221
|
+
*
|
|
222
|
+
* Calling this without a fatal error forces a reconnect of the current connection.
|
|
223
|
+
*/
|
|
224
|
+
reconnect() {
|
|
225
|
+
if (this._destroyed) {
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
this._fatalError = null;
|
|
229
|
+
this._errorCount = 0;
|
|
230
|
+
this._lastNonFatalError = null;
|
|
231
|
+
this._authFailureCount = 0;
|
|
232
|
+
this._forceTokenRefresh = true;
|
|
233
|
+
this._closeSocket();
|
|
234
|
+
this._updateReconnectInterval();
|
|
235
|
+
if (this._shouldConnect()) {
|
|
236
|
+
this._connect();
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
this._setConnectionState("closed");
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Release all resources: close the connection, drop all subscriptions and stop the reconnect and
|
|
244
|
+
* ping timers. A destroyed client cannot be revived with `reconnect()`.
|
|
245
|
+
*
|
|
246
|
+
* This is called by `AuthorizedApiContext.destroy()` for the client it created itself. A client
|
|
247
|
+
* that was passed in from outside is owned by the application and is not destroyed with the
|
|
248
|
+
* context.
|
|
249
|
+
*/
|
|
250
|
+
destroy() {
|
|
251
|
+
if (this._destroyed) {
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
this._destroyed = true;
|
|
255
|
+
if (this._reconnectIntvl) {
|
|
256
|
+
clearInterval(this._reconnectIntvl);
|
|
257
|
+
this._reconnectIntvl = null;
|
|
258
|
+
}
|
|
259
|
+
if (this._disconnectTimeout) {
|
|
260
|
+
clearTimeout(this._disconnectTimeout);
|
|
261
|
+
this._disconnectTimeout = null;
|
|
262
|
+
}
|
|
263
|
+
this._closeSocket();
|
|
264
|
+
this._map = {};
|
|
265
|
+
this._setConnectionState("closed");
|
|
266
|
+
this._connectionStateCallbacks = [];
|
|
267
|
+
}
|
|
268
|
+
_setConnectionState(status, error) {
|
|
269
|
+
if (this._connectionState.status == status &&
|
|
270
|
+
this._connectionState.error == error) {
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
this._connectionState = error ? { status, error } : { status };
|
|
274
|
+
const state = this._connectionState;
|
|
275
|
+
this._connectionStateCallbacks.slice().forEach((cb) => {
|
|
276
|
+
try {
|
|
277
|
+
cb(state);
|
|
278
|
+
}
|
|
279
|
+
catch (e) {
|
|
280
|
+
console.warn(LOG_PREFIX +
|
|
281
|
+
"a connection state callback threw an error unexpectedly.", e);
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
}
|
|
111
285
|
_startSubscription(key) {
|
|
112
286
|
var _a;
|
|
113
287
|
if (this._fatalError) {
|
|
@@ -137,7 +311,7 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
137
311
|
}; // minimal invalidate
|
|
138
312
|
console.log(LOG_PREFIX +
|
|
139
313
|
"connection was interrupted. filling in assumed invalidates that may have happened while socket was not available.");
|
|
140
|
-
callbacks.forEach((cb) => cb
|
|
314
|
+
callbacks.forEach((cb) => this._invokeCallback(cb, null, assumedInvalidate));
|
|
141
315
|
}
|
|
142
316
|
else if (cmd.type == "decoupledOperationStatus") {
|
|
143
317
|
if (this._apiCtx) {
|
|
@@ -153,7 +327,7 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
153
327
|
};
|
|
154
328
|
console.log(LOG_PREFIX +
|
|
155
329
|
"sending virtual decoupled operation status updates to subscribers due to connection interruption.");
|
|
156
|
-
callbacks.forEach((cb) => cb
|
|
330
|
+
callbacks.forEach((cb) => this._invokeCallback(cb, null, invMsg));
|
|
157
331
|
}, (err) => {
|
|
158
332
|
console.log(err, LOG_PREFIX +
|
|
159
333
|
"could not retrieve status of decoupledOperation. ignoring it.");
|
|
@@ -162,12 +336,13 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
162
336
|
}
|
|
163
337
|
}
|
|
164
338
|
_endSubscription(key) {
|
|
165
|
-
|
|
339
|
+
const entry = this._map[key];
|
|
340
|
+
if ((entry === null || entry === void 0 ? void 0 : entry.idOnSocket) != null) {
|
|
166
341
|
this._sendWs({
|
|
167
342
|
cmd: "unsubscribe",
|
|
168
|
-
subscriptionId:
|
|
169
|
-
}
|
|
170
|
-
|
|
343
|
+
subscriptionId: entry.idOnSocket,
|
|
344
|
+
});
|
|
345
|
+
entry.idOnSocket = null;
|
|
171
346
|
}
|
|
172
347
|
}
|
|
173
348
|
/**
|
|
@@ -187,11 +362,12 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
187
362
|
else if (!this._disconnectTimeout) {
|
|
188
363
|
// if there is no subscription open for 3s, disconnect from WebSocket
|
|
189
364
|
this._disconnectTimeout = setTimeout(() => {
|
|
190
|
-
|
|
365
|
+
this._disconnectTimeout = null;
|
|
191
366
|
if (!this._shouldConnect()) {
|
|
192
|
-
|
|
193
|
-
this.
|
|
194
|
-
|
|
367
|
+
this._closeSocket();
|
|
368
|
+
if (!this._fatalError) {
|
|
369
|
+
this._setConnectionState("closed");
|
|
370
|
+
}
|
|
195
371
|
}
|
|
196
372
|
}, 3000);
|
|
197
373
|
}
|
|
@@ -208,62 +384,109 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
208
384
|
console.log(LOG_PREFIX + "socket not ready, not sending message.", this._lastNonFatalError, this._fatalError);
|
|
209
385
|
}
|
|
210
386
|
}
|
|
387
|
+
/**
|
|
388
|
+
* Close the current socket, if any, and detach its handlers so that a late `close` event of an
|
|
389
|
+
* outdated socket cannot interfere with a connection established in the meantime.
|
|
390
|
+
*/
|
|
391
|
+
_closeSocket() {
|
|
392
|
+
const socket = this._socket;
|
|
393
|
+
this._socket = null;
|
|
394
|
+
this._isOpen = false;
|
|
395
|
+
this._authenticatedCallback = null;
|
|
396
|
+
if (this._pingIntvl) {
|
|
397
|
+
clearInterval(this._pingIntvl);
|
|
398
|
+
this._pingIntvl = null;
|
|
399
|
+
}
|
|
400
|
+
if (!socket) {
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
socket.onmessage = null;
|
|
404
|
+
socket.onopen = null;
|
|
405
|
+
/* keep no-op handlers: some implementations (e.g. the `ws` package) throw on unhandled error events. */
|
|
406
|
+
socket.onerror = () => { };
|
|
407
|
+
socket.onclose = () => { };
|
|
408
|
+
try {
|
|
409
|
+
socket.close();
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
console.warn(LOG_PREFIX + "closing the socket failed.", err);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
211
415
|
_connect() {
|
|
212
|
-
if (this.
|
|
213
|
-
|
|
214
|
-
|
|
416
|
+
if (this._fatalError || this._destroyed) {
|
|
417
|
+
// no more connections on a websocket client that has a fatal error or was destroyed
|
|
418
|
+
return;
|
|
215
419
|
}
|
|
216
|
-
|
|
217
|
-
|
|
420
|
+
this._closeSocket();
|
|
421
|
+
this._setConnectionState(this._errorCount > 0 ? "reconnecting" : "connecting", this._lastNonFatalError || undefined);
|
|
422
|
+
let socket;
|
|
423
|
+
try {
|
|
424
|
+
socket = this._createWebsocket(this._url);
|
|
425
|
+
}
|
|
426
|
+
catch (err) {
|
|
427
|
+
this._handleNonFatalError(new BrokerizeWebSocketError({
|
|
428
|
+
msg: "the websocket could not be created.",
|
|
429
|
+
code: "WEBSOCKET_CONNECTION_FAILED",
|
|
430
|
+
cause: err,
|
|
431
|
+
}));
|
|
218
432
|
return;
|
|
219
433
|
}
|
|
220
|
-
this.
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
entry === null || entry === void 0 ? void 0 : entry.entry.callbacks.forEach((cb) => cb(message, null));
|
|
240
|
-
}
|
|
434
|
+
this._socket = socket;
|
|
435
|
+
/* Per-socket bookkeeping: a failed connection attempt must be counted exactly once, no matter
|
|
436
|
+
whether we learn about it from an error event, from a close event or from both. */
|
|
437
|
+
let failureReported = false;
|
|
438
|
+
let authenticated = false;
|
|
439
|
+
const reportConnectionFailure = (msg, cause) => {
|
|
440
|
+
if (failureReported) {
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
failureReported = true;
|
|
444
|
+
this._handleNonFatalError(new BrokerizeWebSocketError({
|
|
445
|
+
msg,
|
|
446
|
+
code: "WEBSOCKET_CONNECTION_FAILED",
|
|
447
|
+
cause,
|
|
448
|
+
}));
|
|
449
|
+
};
|
|
450
|
+
socket.onmessage = (msg) => {
|
|
451
|
+
if (this._socket !== socket) {
|
|
452
|
+
return;
|
|
241
453
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
this._authenticatedCallback = null;
|
|
454
|
+
let message;
|
|
455
|
+
try {
|
|
456
|
+
message = JSON.parse(msg.data);
|
|
246
457
|
}
|
|
247
|
-
|
|
248
|
-
|
|
458
|
+
catch (err) {
|
|
459
|
+
this._handleNonFatalError(new BrokerizeWebSocketError({
|
|
460
|
+
msg: "a message from the server could not be parsed.",
|
|
461
|
+
code: "WEBSOCKET_PROTOCOL_ERROR",
|
|
462
|
+
cause: err,
|
|
463
|
+
}));
|
|
464
|
+
return;
|
|
249
465
|
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
this._handleFatalError(e);
|
|
256
|
-
}
|
|
257
|
-
else {
|
|
258
|
-
this._handleNonFatalError(e);
|
|
259
|
-
}
|
|
466
|
+
this._handleMessage(message);
|
|
467
|
+
};
|
|
468
|
+
socket.onerror = (ev) => {
|
|
469
|
+
if (this._socket !== socket) {
|
|
470
|
+
return;
|
|
260
471
|
}
|
|
472
|
+
/* The error event carries no usable detail; the following close event triggers the retry. */
|
|
473
|
+
reportConnectionFailure("the websocket connection failed.", ev);
|
|
261
474
|
};
|
|
262
|
-
|
|
263
|
-
|
|
475
|
+
socket.onopen = () => {
|
|
476
|
+
if (this._socket !== socket) {
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const forceRefresh = this._forceTokenRefresh;
|
|
480
|
+
this._forceTokenRefresh = false;
|
|
481
|
+
Promise.resolve(this._auth.getToken({ forceRefresh })).then((token) => {
|
|
482
|
+
if (this._socket !== socket) {
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
264
485
|
const _authCb = () => {
|
|
486
|
+
authenticated = true;
|
|
265
487
|
this._isOpen = true;
|
|
266
488
|
this._resetErrorState();
|
|
489
|
+
this._setConnectionState("open");
|
|
267
490
|
for (const k in this._map) {
|
|
268
491
|
this._startSubscription(k);
|
|
269
492
|
}
|
|
@@ -272,23 +495,54 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
272
495
|
this._sendWs({
|
|
273
496
|
cmd: "authorize",
|
|
274
497
|
idToken: token.idToken,
|
|
275
|
-
}
|
|
498
|
+
});
|
|
276
499
|
this._authenticatedCallback = _authCb;
|
|
277
500
|
}
|
|
278
501
|
else {
|
|
279
502
|
_authCb();
|
|
280
503
|
}
|
|
281
504
|
}, (err) => {
|
|
282
|
-
|
|
505
|
+
if (this._socket !== socket) {
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
/* Without a token we cannot use this connection. Report it and close, so that the
|
|
509
|
+
reconnect interval retries instead of leaving an unauthenticated socket open. */
|
|
510
|
+
failureReported = true;
|
|
511
|
+
this._handleNonFatalError(new BrokerizeWebSocketError({
|
|
512
|
+
msg: (err === null || err === void 0 ? void 0 : err.message) ||
|
|
513
|
+
"a token for the websocket connection could not be retrieved.",
|
|
514
|
+
code: "AUTH",
|
|
515
|
+
cause: err,
|
|
516
|
+
}));
|
|
517
|
+
this._closeSocket();
|
|
283
518
|
});
|
|
284
519
|
};
|
|
285
|
-
|
|
520
|
+
socket.onclose = () => {
|
|
521
|
+
if (this._socket !== socket) {
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
286
524
|
// mark all subscriptions interrupted so they can issue synthetic messages on reconnect
|
|
287
525
|
for (const k in this._map) {
|
|
288
526
|
this._map[k].interrupted = true;
|
|
289
|
-
this.
|
|
527
|
+
this._map[k].idOnSocket = null;
|
|
290
528
|
}
|
|
291
529
|
this._socket = null;
|
|
530
|
+
this._isOpen = false;
|
|
531
|
+
this._authenticatedCallback = null;
|
|
532
|
+
if (this._pingIntvl) {
|
|
533
|
+
clearInterval(this._pingIntvl);
|
|
534
|
+
this._pingIntvl = null;
|
|
535
|
+
}
|
|
536
|
+
if (!authenticated) {
|
|
537
|
+
/* the connection never became usable, so this attempt counts towards the backoff. */
|
|
538
|
+
reportConnectionFailure("the websocket connection was closed before it could be used.");
|
|
539
|
+
}
|
|
540
|
+
if (this._shouldConnect()) {
|
|
541
|
+
this._setConnectionState("reconnecting", this._lastNonFatalError || undefined);
|
|
542
|
+
}
|
|
543
|
+
else if (!this._fatalError) {
|
|
544
|
+
this._setConnectionState("closed");
|
|
545
|
+
}
|
|
292
546
|
};
|
|
293
547
|
if (this._pingIntvl)
|
|
294
548
|
clearInterval(this._pingIntvl);
|
|
@@ -308,6 +562,75 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
308
562
|
}
|
|
309
563
|
}, 30000);
|
|
310
564
|
}
|
|
565
|
+
_handleMessage(message) {
|
|
566
|
+
const subscriptionId = message
|
|
567
|
+
.subscriptionId;
|
|
568
|
+
if (subscriptionId != null) {
|
|
569
|
+
/* message concerns a subscription */
|
|
570
|
+
const entry = this._findSubscriptionEntry(subscriptionId);
|
|
571
|
+
if (message.cmd == "invalidate" ||
|
|
572
|
+
message.cmd ==
|
|
573
|
+
"updateDecoupledOperationStatus") {
|
|
574
|
+
entry === null || entry === void 0 ? void 0 : entry.entry.callbacks.forEach((cb) => this._invokeCallback(cb, null, message));
|
|
575
|
+
}
|
|
576
|
+
else if (message.error) {
|
|
577
|
+
/* error on a single subscription. Nothing retries it, so it ends this subscription. */
|
|
578
|
+
const err = toWebSocketError(message.error, true);
|
|
579
|
+
entry === null || entry === void 0 ? void 0 : entry.entry.callbacks.forEach((cb) => this._invokeCallback(cb, err, null));
|
|
580
|
+
}
|
|
581
|
+
else {
|
|
582
|
+
console.warn(LOG_PREFIX + "received an unknown subscription message.", message);
|
|
583
|
+
}
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
if (message.cmd == "authenticated") {
|
|
587
|
+
if (this._authenticatedCallback)
|
|
588
|
+
this._authenticatedCallback();
|
|
589
|
+
this._authenticatedCallback = null;
|
|
590
|
+
}
|
|
591
|
+
else if (message.cmd == "ping") {
|
|
592
|
+
// NOP
|
|
593
|
+
}
|
|
594
|
+
else if (message.error) {
|
|
595
|
+
const e = message;
|
|
596
|
+
if (isAuthenticationError(e.error)) {
|
|
597
|
+
this._handleAuthenticationFailure(e.error);
|
|
598
|
+
}
|
|
599
|
+
else {
|
|
600
|
+
this._handleNonFatalError(toWebSocketError(e.error, false));
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
else {
|
|
604
|
+
console.warn(LOG_PREFIX + "received an unknown message.", message);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* The server rejected our token. The usual cause is an id token that expired between retrieving
|
|
609
|
+
* it and the server validating it, which a fresh token fixes, so retry once before giving up on
|
|
610
|
+
* this client.
|
|
611
|
+
*/
|
|
612
|
+
_handleAuthenticationFailure(payload) {
|
|
613
|
+
this._authFailureCount++;
|
|
614
|
+
if (this._authFailureCount >= this._maxConsecutiveAuthFailures) {
|
|
615
|
+
/* the token has been rejected for several minutes: the session is gone, not expired. */
|
|
616
|
+
this._handleFatalError(toWebSocketError(payload, true));
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
/* A rejected token is worth another attempt with a fresh one: the usual cause is a token that
|
|
620
|
+
expired between retrieving it and the server validating it. The subscriptions stay alive and
|
|
621
|
+
the rejection is reported through the connection state, so nothing has to be rebuilt once we
|
|
622
|
+
are back in. */
|
|
623
|
+
this._forceTokenRefresh = true;
|
|
624
|
+
console.warn(LOG_PREFIX +
|
|
625
|
+
"authentication failed (" +
|
|
626
|
+
this._authFailureCount +
|
|
627
|
+
"/" +
|
|
628
|
+
this._maxConsecutiveAuthFailures +
|
|
629
|
+
"). retrying with a refreshed token.");
|
|
630
|
+
this._handleNonFatalError(toWebSocketError(payload, false));
|
|
631
|
+
this._closeSocket();
|
|
632
|
+
this._setConnectionState("reconnecting", this._lastNonFatalError || undefined);
|
|
633
|
+
}
|
|
311
634
|
/**
|
|
312
635
|
* Error happend when trying to connect, but it may be solved by trying a reconnect later.
|
|
313
636
|
*/
|
|
@@ -315,30 +638,35 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
315
638
|
this._errorCount++;
|
|
316
639
|
this._lastNonFatalError = e;
|
|
317
640
|
this._updateReconnectInterval();
|
|
641
|
+
if (this._shouldConnect()) {
|
|
642
|
+
this._setConnectionState("reconnecting", e);
|
|
643
|
+
}
|
|
318
644
|
}
|
|
319
645
|
/**
|
|
320
|
-
* Fatal error: this means the client is unusable from now on and must be recreated
|
|
646
|
+
* Fatal error: this means the client is unusable from now on and must be recreated or revived
|
|
647
|
+
* with `reconnect()`.
|
|
321
648
|
*/
|
|
322
649
|
_handleFatalError(e) {
|
|
323
650
|
this._fatalError = e;
|
|
324
651
|
this._updateReconnectInterval();
|
|
325
|
-
if (this._pingIntvl)
|
|
652
|
+
if (this._pingIntvl) {
|
|
326
653
|
clearInterval(this._pingIntvl);
|
|
654
|
+
this._pingIntvl = null;
|
|
655
|
+
}
|
|
656
|
+
this._closeSocket();
|
|
327
657
|
for (const key in this._map) {
|
|
328
658
|
this._notifySubscribersAboutFatalError(key);
|
|
329
659
|
}
|
|
660
|
+
/* the subscriptions are terminated, their callbacks must not be called again. */
|
|
661
|
+
this._map = {};
|
|
662
|
+
this._setConnectionState("fatal", e);
|
|
330
663
|
}
|
|
331
664
|
/**
|
|
332
665
|
* If a fatal error occurs, all registered callbacks must be called with the error parameter.
|
|
333
666
|
*/
|
|
334
667
|
_notifySubscribersAboutFatalError(key) {
|
|
335
668
|
this._map[key].callbacks.forEach((cb) => {
|
|
336
|
-
|
|
337
|
-
cb(this._fatalError, null);
|
|
338
|
-
}
|
|
339
|
-
catch (err) {
|
|
340
|
-
console.warn(LOG_PREFIX + "error in callback", err);
|
|
341
|
-
}
|
|
669
|
+
this._invokeCallback(cb, this._fatalError, null);
|
|
342
670
|
});
|
|
343
671
|
}
|
|
344
672
|
/**
|
|
@@ -347,6 +675,7 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
347
675
|
_resetErrorState() {
|
|
348
676
|
this._lastNonFatalError = null;
|
|
349
677
|
this._errorCount = 0;
|
|
678
|
+
this._authFailureCount = 0;
|
|
350
679
|
this._updateReconnectInterval();
|
|
351
680
|
}
|
|
352
681
|
_findSubscriptionEntry(subscriptionId) {
|
|
@@ -358,3 +687,16 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
358
687
|
return null;
|
|
359
688
|
}
|
|
360
689
|
}
|
|
690
|
+
function isAuthenticationError(payload) {
|
|
691
|
+
return (payload === null || payload === void 0 ? void 0 : payload.code) == "AUTH" || (payload === null || payload === void 0 ? void 0 : payload.message) == "authentication failed";
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Turn an error message received over the websocket into a proper `Error`.
|
|
695
|
+
*/
|
|
696
|
+
function toWebSocketError(payload, terminal) {
|
|
697
|
+
return new BrokerizeWebSocketError({
|
|
698
|
+
msg: (payload === null || payload === void 0 ? void 0 : payload.message) || "an unknown websocket error occurred.",
|
|
699
|
+
code: isAuthenticationError(payload) ? "AUTH" : "WEBSOCKET_ERROR",
|
|
700
|
+
terminal,
|
|
701
|
+
});
|
|
702
|
+
}
|
package/dist/websocketTypes.d.ts
CHANGED
|
@@ -57,8 +57,18 @@ export type UpdateDecoupledOperationMessage = {
|
|
|
57
57
|
subscriptionId: number;
|
|
58
58
|
status: DecoupledOperationStatus;
|
|
59
59
|
};
|
|
60
|
+
/**
|
|
61
|
+
* The error payload as it is sent over the websocket. Applications do not see this type: the
|
|
62
|
+
* websocket client converts it into a `BrokerizeWebSocketError` (the exported error class) before
|
|
63
|
+
* passing it on.
|
|
64
|
+
*/
|
|
60
65
|
export type BrokerizeWebSocketError = {
|
|
61
66
|
message: string;
|
|
67
|
+
/**
|
|
68
|
+
* A stable error code, if the server sends one. Preferred over matching `message`, which is
|
|
69
|
+
* meant to be human-readable and may change.
|
|
70
|
+
*/
|
|
71
|
+
code?: string;
|
|
62
72
|
};
|
|
63
73
|
export type WebSocketError = {
|
|
64
74
|
error: BrokerizeWebSocketError;
|