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