@brokerize/client 1.11.0 → 1.12.1
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 +20 -0
- package/dist/authorizedApiContext.js +47 -5
- package/dist/cjs/apiCtx.d.ts +10 -2
- package/dist/cjs/apiCtx.js +4 -4
- package/dist/cjs/authorizedApiContext.d.ts +20 -0
- package/dist/cjs/authorizedApiContext.js +46 -4
- 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 +118 -3
- package/dist/cjs/websocketClient.js +426 -74
- package/dist/cjs/websocketTypes.d.ts +10 -0
- package/dist/client.d.ts +262 -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 +118 -3
- package/dist/websocketClient.js +426 -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,21 +336,32 @@ 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
|
/**
|
|
174
349
|
* Internal method for setting a related AuthorizedApiContext. This is used to retrieve
|
|
175
350
|
* decoupled operation status on interrupted connections.
|
|
351
|
+
*
|
|
352
|
+
* `null` detaches the current one, which a context does when it is destroyed: a destroyed
|
|
353
|
+
* context cannot perform that request, so holding on to it would be worse than holding none.
|
|
176
354
|
*/
|
|
177
355
|
_setAuthorizedApiContext(ctx) {
|
|
178
356
|
this._apiCtx = ctx;
|
|
179
357
|
}
|
|
358
|
+
/**
|
|
359
|
+
* Internal counterpart of `_setAuthorizedApiContext`, so that a context can tell whether the
|
|
360
|
+
* client is already attached to one - and whether that one is itself.
|
|
361
|
+
*/
|
|
362
|
+
_getAuthorizedApiContext() {
|
|
363
|
+
return this._apiCtx;
|
|
364
|
+
}
|
|
180
365
|
_startOrStopDisconnectTimeout() {
|
|
181
366
|
if (this._shouldConnect()) {
|
|
182
367
|
if (this._disconnectTimeout) {
|
|
@@ -187,11 +372,12 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
187
372
|
else if (!this._disconnectTimeout) {
|
|
188
373
|
// if there is no subscription open for 3s, disconnect from WebSocket
|
|
189
374
|
this._disconnectTimeout = setTimeout(() => {
|
|
190
|
-
|
|
375
|
+
this._disconnectTimeout = null;
|
|
191
376
|
if (!this._shouldConnect()) {
|
|
192
|
-
|
|
193
|
-
this.
|
|
194
|
-
|
|
377
|
+
this._closeSocket();
|
|
378
|
+
if (!this._fatalError) {
|
|
379
|
+
this._setConnectionState("closed");
|
|
380
|
+
}
|
|
195
381
|
}
|
|
196
382
|
}, 3000);
|
|
197
383
|
}
|
|
@@ -208,62 +394,109 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
208
394
|
console.log(LOG_PREFIX + "socket not ready, not sending message.", this._lastNonFatalError, this._fatalError);
|
|
209
395
|
}
|
|
210
396
|
}
|
|
397
|
+
/**
|
|
398
|
+
* Close the current socket, if any, and detach its handlers so that a late `close` event of an
|
|
399
|
+
* outdated socket cannot interfere with a connection established in the meantime.
|
|
400
|
+
*/
|
|
401
|
+
_closeSocket() {
|
|
402
|
+
const socket = this._socket;
|
|
403
|
+
this._socket = null;
|
|
404
|
+
this._isOpen = false;
|
|
405
|
+
this._authenticatedCallback = null;
|
|
406
|
+
if (this._pingIntvl) {
|
|
407
|
+
clearInterval(this._pingIntvl);
|
|
408
|
+
this._pingIntvl = null;
|
|
409
|
+
}
|
|
410
|
+
if (!socket) {
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
socket.onmessage = null;
|
|
414
|
+
socket.onopen = null;
|
|
415
|
+
/* keep no-op handlers: some implementations (e.g. the `ws` package) throw on unhandled error events. */
|
|
416
|
+
socket.onerror = () => { };
|
|
417
|
+
socket.onclose = () => { };
|
|
418
|
+
try {
|
|
419
|
+
socket.close();
|
|
420
|
+
}
|
|
421
|
+
catch (err) {
|
|
422
|
+
console.warn(LOG_PREFIX + "closing the socket failed.", err);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
211
425
|
_connect() {
|
|
212
|
-
if (this.
|
|
213
|
-
|
|
214
|
-
|
|
426
|
+
if (this._fatalError || this._destroyed) {
|
|
427
|
+
// no more connections on a websocket client that has a fatal error or was destroyed
|
|
428
|
+
return;
|
|
215
429
|
}
|
|
216
|
-
|
|
217
|
-
|
|
430
|
+
this._closeSocket();
|
|
431
|
+
this._setConnectionState(this._errorCount > 0 ? "reconnecting" : "connecting", this._lastNonFatalError || undefined);
|
|
432
|
+
let socket;
|
|
433
|
+
try {
|
|
434
|
+
socket = this._createWebsocket(this._url);
|
|
435
|
+
}
|
|
436
|
+
catch (err) {
|
|
437
|
+
this._handleNonFatalError(new BrokerizeWebSocketError({
|
|
438
|
+
msg: "the websocket could not be created.",
|
|
439
|
+
code: "WEBSOCKET_CONNECTION_FAILED",
|
|
440
|
+
cause: err,
|
|
441
|
+
}));
|
|
218
442
|
return;
|
|
219
443
|
}
|
|
220
|
-
this.
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
const entry = this._findSubscriptionEntry(message.subscriptionId);
|
|
229
|
-
entry === null || entry === void 0 ? void 0 : entry.entry.callbacks.forEach((cb) => cb(null, message));
|
|
230
|
-
}
|
|
231
|
-
else if (message.cmd ==
|
|
232
|
-
"updateDecoupledOperationStatus") {
|
|
233
|
-
const entry = this._findSubscriptionEntry(message.subscriptionId);
|
|
234
|
-
entry === null || entry === void 0 ? void 0 : entry.entry.callbacks.forEach((cb) => cb(null, message));
|
|
235
|
-
}
|
|
236
|
-
else if (message.error) {
|
|
237
|
-
/* error on subscription */
|
|
238
|
-
const entry = this._findSubscriptionEntry(message.subscriptionId);
|
|
239
|
-
entry === null || entry === void 0 ? void 0 : entry.entry.callbacks.forEach((cb) => cb(message, null));
|
|
240
|
-
}
|
|
444
|
+
this._socket = socket;
|
|
445
|
+
/* Per-socket bookkeeping: a failed connection attempt must be counted exactly once, no matter
|
|
446
|
+
whether we learn about it from an error event, from a close event or from both. */
|
|
447
|
+
let failureReported = false;
|
|
448
|
+
let authenticated = false;
|
|
449
|
+
const reportConnectionFailure = (msg, cause) => {
|
|
450
|
+
if (failureReported) {
|
|
451
|
+
return;
|
|
241
452
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
453
|
+
failureReported = true;
|
|
454
|
+
this._handleNonFatalError(new BrokerizeWebSocketError({
|
|
455
|
+
msg,
|
|
456
|
+
code: "WEBSOCKET_CONNECTION_FAILED",
|
|
457
|
+
cause,
|
|
458
|
+
}));
|
|
459
|
+
};
|
|
460
|
+
socket.onmessage = (msg) => {
|
|
461
|
+
if (this._socket !== socket) {
|
|
462
|
+
return;
|
|
246
463
|
}
|
|
247
|
-
|
|
248
|
-
|
|
464
|
+
let message;
|
|
465
|
+
try {
|
|
466
|
+
message = JSON.parse(msg.data);
|
|
249
467
|
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
468
|
+
catch (err) {
|
|
469
|
+
this._handleNonFatalError(new BrokerizeWebSocketError({
|
|
470
|
+
msg: "a message from the server could not be parsed.",
|
|
471
|
+
code: "WEBSOCKET_PROTOCOL_ERROR",
|
|
472
|
+
cause: err,
|
|
473
|
+
}));
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
this._handleMessage(message);
|
|
477
|
+
};
|
|
478
|
+
socket.onerror = (ev) => {
|
|
479
|
+
if (this._socket !== socket) {
|
|
480
|
+
return;
|
|
260
481
|
}
|
|
482
|
+
/* The error event carries no usable detail; the following close event triggers the retry. */
|
|
483
|
+
reportConnectionFailure("the websocket connection failed.", ev);
|
|
261
484
|
};
|
|
262
|
-
|
|
263
|
-
|
|
485
|
+
socket.onopen = () => {
|
|
486
|
+
if (this._socket !== socket) {
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const forceRefresh = this._forceTokenRefresh;
|
|
490
|
+
this._forceTokenRefresh = false;
|
|
491
|
+
Promise.resolve(this._auth.getToken({ forceRefresh })).then((token) => {
|
|
492
|
+
if (this._socket !== socket) {
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
264
495
|
const _authCb = () => {
|
|
496
|
+
authenticated = true;
|
|
265
497
|
this._isOpen = true;
|
|
266
498
|
this._resetErrorState();
|
|
499
|
+
this._setConnectionState("open");
|
|
267
500
|
for (const k in this._map) {
|
|
268
501
|
this._startSubscription(k);
|
|
269
502
|
}
|
|
@@ -272,23 +505,54 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
272
505
|
this._sendWs({
|
|
273
506
|
cmd: "authorize",
|
|
274
507
|
idToken: token.idToken,
|
|
275
|
-
}
|
|
508
|
+
});
|
|
276
509
|
this._authenticatedCallback = _authCb;
|
|
277
510
|
}
|
|
278
511
|
else {
|
|
279
512
|
_authCb();
|
|
280
513
|
}
|
|
281
514
|
}, (err) => {
|
|
282
|
-
|
|
515
|
+
if (this._socket !== socket) {
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
/* Without a token we cannot use this connection. Report it and close, so that the
|
|
519
|
+
reconnect interval retries instead of leaving an unauthenticated socket open. */
|
|
520
|
+
failureReported = true;
|
|
521
|
+
this._handleNonFatalError(new BrokerizeWebSocketError({
|
|
522
|
+
msg: (err === null || err === void 0 ? void 0 : err.message) ||
|
|
523
|
+
"a token for the websocket connection could not be retrieved.",
|
|
524
|
+
code: "AUTH",
|
|
525
|
+
cause: err,
|
|
526
|
+
}));
|
|
527
|
+
this._closeSocket();
|
|
283
528
|
});
|
|
284
529
|
};
|
|
285
|
-
|
|
530
|
+
socket.onclose = () => {
|
|
531
|
+
if (this._socket !== socket) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
286
534
|
// mark all subscriptions interrupted so they can issue synthetic messages on reconnect
|
|
287
535
|
for (const k in this._map) {
|
|
288
536
|
this._map[k].interrupted = true;
|
|
289
|
-
this.
|
|
537
|
+
this._map[k].idOnSocket = null;
|
|
290
538
|
}
|
|
291
539
|
this._socket = null;
|
|
540
|
+
this._isOpen = false;
|
|
541
|
+
this._authenticatedCallback = null;
|
|
542
|
+
if (this._pingIntvl) {
|
|
543
|
+
clearInterval(this._pingIntvl);
|
|
544
|
+
this._pingIntvl = null;
|
|
545
|
+
}
|
|
546
|
+
if (!authenticated) {
|
|
547
|
+
/* the connection never became usable, so this attempt counts towards the backoff. */
|
|
548
|
+
reportConnectionFailure("the websocket connection was closed before it could be used.");
|
|
549
|
+
}
|
|
550
|
+
if (this._shouldConnect()) {
|
|
551
|
+
this._setConnectionState("reconnecting", this._lastNonFatalError || undefined);
|
|
552
|
+
}
|
|
553
|
+
else if (!this._fatalError) {
|
|
554
|
+
this._setConnectionState("closed");
|
|
555
|
+
}
|
|
292
556
|
};
|
|
293
557
|
if (this._pingIntvl)
|
|
294
558
|
clearInterval(this._pingIntvl);
|
|
@@ -308,6 +572,75 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
308
572
|
}
|
|
309
573
|
}, 30000);
|
|
310
574
|
}
|
|
575
|
+
_handleMessage(message) {
|
|
576
|
+
const subscriptionId = message
|
|
577
|
+
.subscriptionId;
|
|
578
|
+
if (subscriptionId != null) {
|
|
579
|
+
/* message concerns a subscription */
|
|
580
|
+
const entry = this._findSubscriptionEntry(subscriptionId);
|
|
581
|
+
if (message.cmd == "invalidate" ||
|
|
582
|
+
message.cmd ==
|
|
583
|
+
"updateDecoupledOperationStatus") {
|
|
584
|
+
entry === null || entry === void 0 ? void 0 : entry.entry.callbacks.forEach((cb) => this._invokeCallback(cb, null, message));
|
|
585
|
+
}
|
|
586
|
+
else if (message.error) {
|
|
587
|
+
/* error on a single subscription. Nothing retries it, so it ends this subscription. */
|
|
588
|
+
const err = toWebSocketError(message.error, true);
|
|
589
|
+
entry === null || entry === void 0 ? void 0 : entry.entry.callbacks.forEach((cb) => this._invokeCallback(cb, err, null));
|
|
590
|
+
}
|
|
591
|
+
else {
|
|
592
|
+
console.warn(LOG_PREFIX + "received an unknown subscription message.", message);
|
|
593
|
+
}
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (message.cmd == "authenticated") {
|
|
597
|
+
if (this._authenticatedCallback)
|
|
598
|
+
this._authenticatedCallback();
|
|
599
|
+
this._authenticatedCallback = null;
|
|
600
|
+
}
|
|
601
|
+
else if (message.cmd == "ping") {
|
|
602
|
+
// NOP
|
|
603
|
+
}
|
|
604
|
+
else if (message.error) {
|
|
605
|
+
const e = message;
|
|
606
|
+
if (isAuthenticationError(e.error)) {
|
|
607
|
+
this._handleAuthenticationFailure(e.error);
|
|
608
|
+
}
|
|
609
|
+
else {
|
|
610
|
+
this._handleNonFatalError(toWebSocketError(e.error, false));
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
console.warn(LOG_PREFIX + "received an unknown message.", message);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* The server rejected our token. The usual cause is an id token that expired between retrieving
|
|
619
|
+
* it and the server validating it, which a fresh token fixes, so retry once before giving up on
|
|
620
|
+
* this client.
|
|
621
|
+
*/
|
|
622
|
+
_handleAuthenticationFailure(payload) {
|
|
623
|
+
this._authFailureCount++;
|
|
624
|
+
if (this._authFailureCount >= this._maxConsecutiveAuthFailures) {
|
|
625
|
+
/* the token has been rejected for several minutes: the session is gone, not expired. */
|
|
626
|
+
this._handleFatalError(toWebSocketError(payload, true));
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
/* A rejected token is worth another attempt with a fresh one: the usual cause is a token that
|
|
630
|
+
expired between retrieving it and the server validating it. The subscriptions stay alive and
|
|
631
|
+
the rejection is reported through the connection state, so nothing has to be rebuilt once we
|
|
632
|
+
are back in. */
|
|
633
|
+
this._forceTokenRefresh = true;
|
|
634
|
+
console.warn(LOG_PREFIX +
|
|
635
|
+
"authentication failed (" +
|
|
636
|
+
this._authFailureCount +
|
|
637
|
+
"/" +
|
|
638
|
+
this._maxConsecutiveAuthFailures +
|
|
639
|
+
"). retrying with a refreshed token.");
|
|
640
|
+
this._handleNonFatalError(toWebSocketError(payload, false));
|
|
641
|
+
this._closeSocket();
|
|
642
|
+
this._setConnectionState("reconnecting", this._lastNonFatalError || undefined);
|
|
643
|
+
}
|
|
311
644
|
/**
|
|
312
645
|
* Error happend when trying to connect, but it may be solved by trying a reconnect later.
|
|
313
646
|
*/
|
|
@@ -315,30 +648,35 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
315
648
|
this._errorCount++;
|
|
316
649
|
this._lastNonFatalError = e;
|
|
317
650
|
this._updateReconnectInterval();
|
|
651
|
+
if (this._shouldConnect()) {
|
|
652
|
+
this._setConnectionState("reconnecting", e);
|
|
653
|
+
}
|
|
318
654
|
}
|
|
319
655
|
/**
|
|
320
|
-
* Fatal error: this means the client is unusable from now on and must be recreated
|
|
656
|
+
* Fatal error: this means the client is unusable from now on and must be recreated or revived
|
|
657
|
+
* with `reconnect()`.
|
|
321
658
|
*/
|
|
322
659
|
_handleFatalError(e) {
|
|
323
660
|
this._fatalError = e;
|
|
324
661
|
this._updateReconnectInterval();
|
|
325
|
-
if (this._pingIntvl)
|
|
662
|
+
if (this._pingIntvl) {
|
|
326
663
|
clearInterval(this._pingIntvl);
|
|
664
|
+
this._pingIntvl = null;
|
|
665
|
+
}
|
|
666
|
+
this._closeSocket();
|
|
327
667
|
for (const key in this._map) {
|
|
328
668
|
this._notifySubscribersAboutFatalError(key);
|
|
329
669
|
}
|
|
670
|
+
/* the subscriptions are terminated, their callbacks must not be called again. */
|
|
671
|
+
this._map = {};
|
|
672
|
+
this._setConnectionState("fatal", e);
|
|
330
673
|
}
|
|
331
674
|
/**
|
|
332
675
|
* If a fatal error occurs, all registered callbacks must be called with the error parameter.
|
|
333
676
|
*/
|
|
334
677
|
_notifySubscribersAboutFatalError(key) {
|
|
335
678
|
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
|
-
}
|
|
679
|
+
this._invokeCallback(cb, this._fatalError, null);
|
|
342
680
|
});
|
|
343
681
|
}
|
|
344
682
|
/**
|
|
@@ -347,6 +685,7 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
347
685
|
_resetErrorState() {
|
|
348
686
|
this._lastNonFatalError = null;
|
|
349
687
|
this._errorCount = 0;
|
|
688
|
+
this._authFailureCount = 0;
|
|
350
689
|
this._updateReconnectInterval();
|
|
351
690
|
}
|
|
352
691
|
_findSubscriptionEntry(subscriptionId) {
|
|
@@ -358,3 +697,16 @@ export class BrokerizeWebSocketClientImpl {
|
|
|
358
697
|
return null;
|
|
359
698
|
}
|
|
360
699
|
}
|
|
700
|
+
function isAuthenticationError(payload) {
|
|
701
|
+
return (payload === null || payload === void 0 ? void 0 : payload.code) == "AUTH" || (payload === null || payload === void 0 ? void 0 : payload.message) == "authentication failed";
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Turn an error message received over the websocket into a proper `Error`.
|
|
705
|
+
*/
|
|
706
|
+
function toWebSocketError(payload, terminal) {
|
|
707
|
+
return new BrokerizeWebSocketError({
|
|
708
|
+
msg: (payload === null || payload === void 0 ? void 0 : payload.message) || "an unknown websocket error occurred.",
|
|
709
|
+
code: isAuthenticationError(payload) ? "AUTH" : "WEBSOCKET_ERROR",
|
|
710
|
+
terminal,
|
|
711
|
+
});
|
|
712
|
+
}
|