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