@genesislcap/foundation-comms 15.83.0 → 15.84.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 (49) hide show
  1. package/dist/dts/connect/connect.d.ts +22 -10
  2. package/dist/dts/connect/connect.d.ts.map +1 -1
  3. package/dist/dts/connect/connect.errors.d.ts +120 -0
  4. package/dist/dts/connect/connect.errors.d.ts.map +1 -0
  5. package/dist/dts/connect/connect.types.d.ts +27 -0
  6. package/dist/dts/connect/connect.types.d.ts.map +1 -1
  7. package/dist/dts/connect/errorCodes.d.ts +6 -0
  8. package/dist/dts/connect/errorCodes.d.ts.map +1 -0
  9. package/dist/dts/connect/http.connect.d.ts +14 -5
  10. package/dist/dts/connect/http.connect.d.ts.map +1 -1
  11. package/dist/dts/connect/http.d.ts +1 -0
  12. package/dist/dts/connect/http.d.ts.map +1 -1
  13. package/dist/dts/connect/httpTransport.d.ts +12 -6
  14. package/dist/dts/connect/httpTransport.d.ts.map +1 -1
  15. package/dist/dts/connect/index.d.ts +1 -0
  16. package/dist/dts/connect/index.d.ts.map +1 -1
  17. package/dist/dts/connect/message.d.ts +18 -1
  18. package/dist/dts/connect/message.d.ts.map +1 -1
  19. package/dist/dts/connect/networkFailure.d.ts +7 -0
  20. package/dist/dts/connect/networkFailure.d.ts.map +1 -0
  21. package/dist/dts/connect/reconnectStrategy.d.ts +2 -1
  22. package/dist/dts/connect/reconnectStrategy.d.ts.map +1 -1
  23. package/dist/dts/connect/requestLifecycle.d.ts +23 -0
  24. package/dist/dts/connect/requestLifecycle.d.ts.map +1 -0
  25. package/dist/dts/connect/socket.d.ts +14 -3
  26. package/dist/dts/connect/socket.d.ts.map +1 -1
  27. package/dist/dts/connect/socket.types.d.ts +5 -0
  28. package/dist/dts/connect/socket.types.d.ts.map +1 -1
  29. package/dist/dts/datasource/datasource.d.ts +6 -0
  30. package/dist/dts/datasource/datasource.d.ts.map +1 -1
  31. package/dist/dts/utils/error-code.d.ts +2 -1
  32. package/dist/dts/utils/error-code.d.ts.map +1 -1
  33. package/dist/esm/connect/connect.errors.js +192 -0
  34. package/dist/esm/connect/connect.js +56 -28
  35. package/dist/esm/connect/errorCodes.js +20 -0
  36. package/dist/esm/connect/http.connect.js +166 -74
  37. package/dist/esm/connect/http.js +22 -9
  38. package/dist/esm/connect/httpTransport.js +35 -12
  39. package/dist/esm/connect/index.js +1 -0
  40. package/dist/esm/connect/message.js +6 -1
  41. package/dist/esm/connect/networkFailure.js +12 -0
  42. package/dist/esm/connect/reconnectStrategy.js +4 -3
  43. package/dist/esm/connect/requestLifecycle.js +96 -0
  44. package/dist/esm/connect/socket.js +74 -37
  45. package/dist/esm/datasource/datasource.js +75 -22
  46. package/dist/esm/utils/error-code.js +6 -2
  47. package/dist/foundation-comms.api.json +1573 -35
  48. package/dist/foundation-comms.d.ts +244 -24
  49. package/package.json +12 -12
@@ -11,10 +11,13 @@ import { MetaCache } from '../metadata';
11
11
  import { Session } from '../session';
12
12
  import { logger } from '../utils';
13
13
  import { withErrorCode } from '../utils/error-code';
14
+ import { ConnectNackError, ConnectTransportError } from './connect.errors';
14
15
  import { ConnectConfig } from './connect.types';
16
+ import { normaliseErrorCodes } from './errorCodes';
15
17
  import { Http } from './http';
16
18
  import { EventMessageType, MessageBuilder, MessageType, } from './message';
17
19
  import { exponentialScheduler, linearScheduler, MAX_RECONNECT_ATTEMPTS, retryInterval, SocketReconnectStrategy, } from './reconnectStrategy';
20
+ import { abortedBeforeSend, isRejectedNack, settleWithin } from './requestLifecycle';
18
21
  import { resourceNameOf, ScdbStreamDecoder } from './scdbStreamDecoder';
19
22
  import { onOtherTabReauthComplete, SessionRefreshResult, tryRefreshSession, waitForOtherTabReauth, } from './sessionRefresh';
20
23
  import { SocketStatus } from './socket.status';
@@ -175,12 +178,13 @@ let DefaultSocket = class DefaultSocket {
175
178
  var _a, _b, _c, _d;
176
179
  logger.info(`${this.isReconnecting ? 'Reconnecting' : 'Connecting'} to ${this.url}`);
177
180
  this.status.isConnecting = !this.isReconnecting;
181
+ this.rejectPendingRequests();
178
182
  const cleanMessages = !this.isReconnecting || !((_a = this.reconnectOptions) === null || _a === void 0 ? void 0 : _a.reconnectStreams);
179
183
  if (cleanMessages) {
180
184
  this.cleanMessages();
181
185
  }
182
186
  (_b = this.socketSubscription) === null || _b === void 0 ? void 0 : _b.unsubscribe();
183
- this.websocket = new WebSocketSubject({
187
+ const websocket = new WebSocketSubject({
184
188
  url: this.url,
185
189
  openObserver: {
186
190
  next: () => {
@@ -193,9 +197,16 @@ let DefaultSocket = class DefaultSocket {
193
197
  },
194
198
  closeObserver: {
195
199
  next: (closeEvent) => {
196
- this.status.onClose(closeEvent);
197
- if (this.isDisconnectedByServer) {
198
- logger.info(`WebSocket connection was closed due an error - Code: ${closeEvent.code} ${closeEvent.reason ? ' | Reason: ' + closeEvent.reason : ''}`);
200
+ // A replaced socket closes late; its close must not touch its successor's state.
201
+ if (this.websocket === websocket) {
202
+ this.status.onClose(closeEvent);
203
+ this.rejectPendingRequests(new ConnectTransportError('WebSocket connection closed before a reply arrived', {
204
+ closeCode: closeEvent === null || closeEvent === void 0 ? void 0 : closeEvent.code,
205
+ closeReason: closeEvent === null || closeEvent === void 0 ? void 0 : closeEvent.reason,
206
+ }));
207
+ if (this.isDisconnectedByServer) {
208
+ logger.info(`WebSocket connection was closed due an error - Code: ${closeEvent.code} ${closeEvent.reason ? ' | Reason: ' + closeEvent.reason : ''}`);
209
+ }
199
210
  }
200
211
  resolve(this.isConnected);
201
212
  },
@@ -203,8 +214,10 @@ let DefaultSocket = class DefaultSocket {
203
214
  serializer: (object) => this.serializer.serialize(object),
204
215
  deserializer: (event) => this.serializer.deserialize(event),
205
216
  });
217
+ this.websocket = websocket;
206
218
  const onNextMessage = (receivedMessage) => __awaiter(this, void 0, void 0, function* () {
207
219
  var _a;
220
+ normaliseErrorCodes(receivedMessage);
208
221
  const responseMessageReceivedLog = `Response Message received for SourceRef: ${receivedMessage.SOURCE_REF} | MessageType: ${receivedMessage.MESSAGE_TYPE}`;
209
222
  this.logMessageTypeFlow(receivedMessage.MESSAGE_TYPE, logger.info, responseMessageReceivedLog);
210
223
  const { SOURCE_REF, MESSAGE_TYPE } = receivedMessage;
@@ -217,7 +230,7 @@ let DefaultSocket = class DefaultSocket {
217
230
  }
218
231
  return;
219
232
  }
220
- let nacked = false;
233
+ const nacked = isRejectedNack(receivedMessage);
221
234
  switch (receivedMessage.MESSAGE_TYPE) {
222
235
  case EventMessageType.EVENT_LOGIN_AUTH_ACK: {
223
236
  this.applyServerHeartbeatInterval(receivedMessage.DETAILS);
@@ -241,11 +254,6 @@ let DefaultSocket = class DefaultSocket {
241
254
  }
242
255
  break;
243
256
  }
244
- case MessageType.MSG_NACK:
245
- case MessageType.LOGON_NACK: {
246
- nacked = true;
247
- break;
248
- }
249
257
  }
250
258
  // A binary payload lazily warms the WASM fast-path (covers per-datasource opt-ins too).
251
259
  if ((receivedMessage === null || receivedMessage === void 0 ? void 0 : receivedMessage.ENCODING) === 'SCDB_V1')
@@ -263,19 +271,13 @@ let DefaultSocket = class DefaultSocket {
263
271
  { CODE: 'SCDB_DECODE_FAILED', TEXT: String((_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error) },
264
272
  ],
265
273
  };
266
- messageHandler.onReceivedError.call(this, {
267
- receivedMessage: nack,
268
- sentMessage: messageHandler.sentMessage,
269
- });
274
+ messageHandler.onReceivedError.call(this, new ConnectNackError(nack, messageHandler.sentMessage));
270
275
  this.removeMessageHandler(SOURCE_REF);
271
276
  this.wsMessages.next(nack);
272
277
  return;
273
278
  }
274
279
  if (nacked) {
275
- messageHandler.onReceivedError.call(this, {
276
- receivedMessage,
277
- sentMessage: messageHandler.sentMessage,
278
- });
280
+ messageHandler.onReceivedError.call(this, new ConnectNackError(receivedMessage, messageHandler.sentMessage));
279
281
  }
280
282
  else {
281
283
  messageHandler.onReceivedMessage.call(this, receivedMessage);
@@ -372,6 +374,7 @@ let DefaultSocket = class DefaultSocket {
372
374
  if (this.heartbeatTicker) {
373
375
  this.heartbeatTicker.stop();
374
376
  }
377
+ const intervalInMillisecocnds = (_b = (_a = this.connectOptions) === null || _a === void 0 ? void 0 : _a.heartbeatInterval) !== null && _b !== void 0 ? _b : this.heartbeatInterval;
375
378
  const sendHeartbeat = () => __awaiter(this, void 0, void 0, function* () {
376
379
  var _a, _b, _c;
377
380
  if (!this.isConnected)
@@ -380,11 +383,18 @@ let DefaultSocket = class DefaultSocket {
380
383
  if ((_b = this.connectOptions) === null || _b === void 0 ? void 0 : _b.heartbeatPingCallback) {
381
384
  this.connectOptions.heartbeatPingCallback(ping);
382
385
  }
383
- const pong = yield this.send(ping);
386
+ let pong;
387
+ try {
388
+ pong = yield this.send(ping, true, { timeout: intervalInMillisecocnds });
389
+ }
390
+ catch (error) {
391
+ logger.debug('Heartbeat ping got no pong: ', error);
392
+ return;
393
+ }
384
394
  // when heartbeat runs before user logs in (connected to websocket but
385
395
  // not authenticated) we don't extend session as it doesn't exist yet
386
396
  if (this.user.isAuthenticated && !pong.IS_AUTHENTICATED) {
387
- this.handleExpiredSession();
397
+ this.handleExpiredSession().catch((error) => logger.debug('Could not refresh the expired session: ', error));
388
398
  }
389
399
  if ((_c = this.connectOptions) === null || _c === void 0 ? void 0 : _c.heartbeatPongCallback) {
390
400
  this.connectOptions.heartbeatPongCallback(pong);
@@ -392,8 +402,7 @@ let DefaultSocket = class DefaultSocket {
392
402
  this.heartbeatIsEnabled =
393
403
  pong.MESSAGE_TYPE === MessageType.HEARTBEAT_PONG && pong.SOURCE_REF === ping.SOURCE_REF;
394
404
  });
395
- if ((_b = (_a = this.connectOptions) === null || _a === void 0 ? void 0 : _a.enableHeartbeat) !== null && _b !== void 0 ? _b : this.heartbeatIsEnabled) {
396
- const intervalInMillisecocnds = (_d = (_c = this.connectOptions) === null || _c === void 0 ? void 0 : _c.heartbeatInterval) !== null && _d !== void 0 ? _d : this.heartbeatInterval;
405
+ if ((_d = (_c = this.connectOptions) === null || _c === void 0 ? void 0 : _c.enableHeartbeat) !== null && _d !== void 0 ? _d : this.heartbeatIsEnabled) {
397
406
  this.heartbeatTicker = new Ticker(intervalInMillisecocnds);
398
407
  this.heartbeatTicker.start(() => {
399
408
  if (this.websocket && this.isConnected) {
@@ -486,34 +495,48 @@ let DefaultSocket = class DefaultSocket {
486
495
  this.cleanMessages();
487
496
  }
488
497
  cleanMessages() {
498
+ this.rejectPendingRequests();
489
499
  this.wsMessages && this.wsMessages.complete();
490
500
  this.wsMessages = new SocketSubject();
491
501
  this.wsMessageHandlers = new Map();
492
502
  this.scdbDecoder.clear();
493
503
  }
494
- send(message, needsHandling = true) {
504
+ // Stream handlers are kept: they are re-sent on reconnect.
505
+ rejectPendingRequests(error = new ConnectTransportError('WebSocket connection closed before a reply arrived')) {
506
+ var _a;
507
+ (_a = this.wsMessageHandlers) === null || _a === void 0 ? void 0 : _a.forEach((handler, sourceRef) => {
508
+ if (handler.isSubscription)
509
+ return;
510
+ this.wsMessageHandlers.delete(sourceRef);
511
+ handler.onReceivedError.call(this, error);
512
+ });
513
+ }
514
+ send(message, needsHandling = true, options) {
515
+ var _a, _b;
516
+ const aborted = abortedBeforeSend(options === null || options === void 0 ? void 0 : options.signal);
517
+ if (aborted) {
518
+ return aborted;
519
+ }
495
520
  if (!this.isConnected) {
496
- return Promise.reject(new Error('WebSocket connection is closed'));
521
+ return Promise.reject(new ConnectTransportError('WebSocket connection is closed'));
497
522
  }
498
523
  const sendingMessasgeLog = `Sending Message for SourceRef: ${message.SOURCE_REF} | MessageType: ${message.MESSAGE_TYPE}`;
499
524
  this.logMessageTypeFlow(message.MESSAGE_TYPE, logger.info, sendingMessasgeLog);
500
525
  this.scdbDecoder.prepareRequest(message);
501
- return new Promise((resolve, reject) => {
502
- const onMessage = (msg) => {
503
- resolve(msg);
504
- };
505
- const onError = (err) => {
506
- reject(err);
507
- };
526
+ const reply = new Promise((resolve, reject) => {
508
527
  if (needsHandling) {
509
- this.setMessageHandler(message, onMessage, onError);
528
+ this.setMessageHandler(message, resolve, reject);
510
529
  }
511
530
  this.websocket.next(message);
512
531
  });
532
+ if (!needsHandling) {
533
+ return reply;
534
+ }
535
+ return settleWithin(reply, { timeout: (_a = options === null || options === void 0 ? void 0 : options.timeout) !== null && _a !== void 0 ? _a : (_b = this.connectOptions) === null || _b === void 0 ? void 0 : _b.requestTimeout, signal: options === null || options === void 0 ? void 0 : options.signal }, () => this.removeMessageHandler(message.SOURCE_REF));
513
536
  }
514
537
  sendForStream(message, onMessage, onError, onComplete) {
515
538
  if (!this.isConnected) {
516
- return throwError(() => new Error('WebSocket connection is closed'));
539
+ return throwError(() => new ConnectTransportError('WebSocket connection is closed'));
517
540
  }
518
541
  const sendingMessageLog = `Sending Message (stream) for SourceRef: ${message.SOURCE_REF} | MessageType: ${message.MESSAGE_TYPE}`;
519
542
  this.logMessageTypeFlow(message.MESSAGE_TYPE, logger.info, sendingMessageLog);
@@ -523,8 +546,18 @@ let DefaultSocket = class DefaultSocket {
523
546
  * We need to queue these outgoing messages to allow the consumers to subscribe in time. We should review the entire
524
547
  * setup with late subscribers in mind, as we can't say when they will actually subscribe. The impact is grids and
525
548
  * other components remaining stuck on Loading screens, as they miss the first `onMessage` reply.
549
+ *
550
+ * A stream torn down before its turn (subscribed and unsubscribed in one task) sends neither message: its
551
+ * DATA_LOGOFF would reach the server ahead of the DATA_LOGON, which would then open a subscription nothing handles.
526
552
  */
527
- DOM.queueUpdate(() => this.websocket.next(message));
553
+ let logonSent = false;
554
+ let tornDown = false;
555
+ DOM.queueUpdate(() => {
556
+ if (tornDown)
557
+ return;
558
+ logonSent = true;
559
+ this.websocket.next(message);
560
+ });
528
561
  /**
529
562
  * @privateRemarks
530
563
  * Running the data logoff from here makes more sense given the network monitor actor is optionally added.
@@ -544,8 +577,11 @@ let DefaultSocket = class DefaultSocket {
544
577
  },
545
578
  });
546
579
  return () => {
580
+ tornDown = true;
547
581
  messagesSubscription.unsubscribe();
548
- this.sendDataLogoff(message.SOURCE_REF);
582
+ if (logonSent) {
583
+ this.sendDataLogoff(message.SOURCE_REF);
584
+ }
549
585
  this.removeMessageHandler(message.SOURCE_REF);
550
586
  onComplete && onComplete();
551
587
  };
@@ -553,7 +589,7 @@ let DefaultSocket = class DefaultSocket {
553
589
  }
554
590
  sendForStreamWithoutTeardown(message, onMessage, onError) {
555
591
  if (!this.isConnected) {
556
- return throwError(() => new Error('WebSocket connection is closed'));
592
+ return throwError(() => new ConnectTransportError('WebSocket connection is closed'));
557
593
  }
558
594
  const sendingMessageLog = `Sending Message (stream) for SourceRef: ${message.SOURCE_REF} | MessageType: ${message.MESSAGE_TYPE}`;
559
595
  this.logMessageTypeFlow(message.MESSAGE_TYPE, logger.info, sendingMessageLog);
@@ -568,7 +604,8 @@ let DefaultSocket = class DefaultSocket {
568
604
  this.wsMessageHandlers.set(message.SOURCE_REF, new SocketMessageHandler(message, onMessage, onError, isSubscription));
569
605
  }
570
606
  sendDataLogoff(sourceRef) {
571
- this.send(this.messageBuilder.createDataLogoffMessage(sourceRef), false);
607
+ // Nothing awaits a logoff, and a closed socket has no server subscription left to end.
608
+ this.send(this.messageBuilder.createDataLogoffMessage(sourceRef), false).catch((error) => logger.debug(`DATA_LOGOFF not sent for SourceRef: ${sourceRef}`, error));
572
609
  }
573
610
  removeMessageHandler(sourceRef) {
574
611
  this.wsMessageHandlers.delete(sourceRef);
@@ -51,6 +51,9 @@ let DefaultDatasource = class DefaultDatasource {
51
51
  this.loadMoreCount = 0;
52
52
  this.readOnly = true;
53
53
  this._allParams = null;
54
+ // Counts init() and destroy() calls, so an init() or metadata fetch still waiting on the server
55
+ // when a later one runs can tell, and stop.
56
+ this.generation = 0;
54
57
  this.pollTrigger$ = new Subject();
55
58
  }
56
59
  triggerPoll() {
@@ -70,31 +73,61 @@ let DefaultDatasource = class DefaultDatasource {
70
73
  }
71
74
  init(options_1) {
72
75
  return __awaiter(this, arguments, void 0, function* (options, fetchMeta = this.fetchMetadataRequired, startStream = this.startStreamRequired) {
76
+ // The latest init() wins: one still waiting on the server stops, and takes this one's result.
77
+ const generation = (this.generation += 1);
78
+ const result = this.initialise(generation, options, fetchMeta, startStream).catch((error) => {
79
+ if (generation === this.generation)
80
+ throw error;
81
+ // A request that failed once this was superseded is not its failure any more: a socket that
82
+ // closes rejects every request still waiting for a reply.
83
+ logger.debug(`${options === null || options === void 0 ? void 0 : options.resourceName} datasource initialisation failed after it was superseded:`, error);
84
+ return this.interruptedInit(options === null || options === void 0 ? void 0 : options.resourceName);
85
+ });
86
+ this.latestInit = { generation, result };
87
+ return result;
88
+ });
89
+ }
90
+ initialise(generation, options, fetchMeta, startStream) {
91
+ return __awaiter(this, void 0, void 0, function* () {
73
92
  this.fetchMetadataRequired = fetchMeta;
74
93
  this.options = Object.assign(Object.assign({}, this.config.options), options);
75
94
  // Invalidate parameter cache when options change
76
95
  this.invalidateCache();
77
- const resourceName = this.options.resourceName;
96
+ // A destroy() or another init() may run while this waits on the server (an element leaving the
97
+ // document, a grid restarting or reloading): destroy() clears the options, init() replaces
98
+ // them. Read the name once, and stop once either has run, rather than go on to send requests
99
+ // and a DATA_LOGON with no resource name, or with another init()'s options.
100
+ const { resourceName } = this.options;
101
+ const superseded = () => generation !== this.generation;
78
102
  const connected = this.connect.isConnected || (yield this.connect.connect());
103
+ if (superseded())
104
+ return this.interruptedInit(resourceName);
79
105
  if (!connected) {
80
106
  logger.error(`Unable to connect to ${this.connect.host} to get ${resourceName} datasource`);
81
107
  this.reportStatus();
82
108
  return false;
83
109
  }
84
110
  const isValidResource = yield this.resources.isValidResource(resourceName);
111
+ if (superseded())
112
+ return this.interruptedInit(resourceName);
85
113
  if (!isValidResource) {
86
114
  logger.error(`${resourceName} datasource does not exist on ${this.connect.host}`);
87
115
  this.reportStatus();
88
116
  return false;
89
117
  }
90
- this.resourceType = yield this.resources.getResourceTypeFor(resourceName);
118
+ const resourceType = yield this.resources.getResourceTypeFor(resourceName);
119
+ if (superseded())
120
+ return this.interruptedInit(resourceName);
121
+ this.resourceType = resourceType;
91
122
  if (!this.resourceType) {
92
123
  logger.error(`Unable to get the resource type for ${resourceName} datasource from ${this.connect.host}`);
93
124
  this.reportStatus();
94
125
  return false;
95
126
  }
96
127
  if (this.fetchMetadataRequired) {
97
- yield this.fetchAndApplyMetadata(this.options.resourceName);
128
+ yield this.fetchAndApplyMetadata(resourceName);
129
+ if (superseded())
130
+ return this.interruptedInit(resourceName);
98
131
  // Invalidate cache again after metadata fetch as availableIndexes may have changed
99
132
  this._allParams = null;
100
133
  }
@@ -103,7 +136,9 @@ let DefaultDatasource = class DefaultDatasource {
103
136
  // Recreate pollTrigger$ so pollTriggerEvents work after destroy/reinit.
104
137
  // A completed Subject ignores next(), so we need a fresh one each init.
105
138
  this.pollTrigger$ = new Subject();
106
- this.stream = yield this.createStream();
139
+ // Synchronously: opening the stream queues its DATA_LOGON, and nothing may come between that
140
+ // and this datasource holding the stream.
141
+ this.stream = this.createStream();
107
142
  }
108
143
  logger.debug(`${resourceName} datasource initialization ${this.initialized ? `was successful.` : 'has failed.'}`);
109
144
  this.reportStatus();
@@ -113,7 +148,7 @@ let DefaultDatasource = class DefaultDatasource {
113
148
  startStream() {
114
149
  return __awaiter(this, void 0, void 0, function* () {
115
150
  if (!this.options.isSnapshot && this.stream === undefined) {
116
- this.stream = yield this.createStream();
151
+ this.stream = this.createStream();
117
152
  }
118
153
  });
119
154
  }
@@ -121,6 +156,7 @@ let DefaultDatasource = class DefaultDatasource {
121
156
  destroy() {
122
157
  var _a, _b;
123
158
  logger.debug('Datasource.destroy', (_a = this.options) === null || _a === void 0 ? void 0 : _a.resourceName);
159
+ this.generation += 1;
124
160
  if (this.commitResponseUnsubscribe) {
125
161
  this.commitResponseUnsubscribe();
126
162
  this.commitResponseUnsubscribe = undefined;
@@ -266,23 +302,21 @@ let DefaultDatasource = class DefaultDatasource {
266
302
  });
267
303
  }
268
304
  createStream() {
269
- return __awaiter(this, void 0, void 0, function* () {
270
- if (![ResourceType.DATASERVER, ResourceType.REQUEST_SERVER].includes(this.resourceType)) {
271
- throw new Error(`Streaming not supported for selected resource type: ${this.resourceType}`);
272
- }
273
- if (this.resourceType === ResourceType.DATASERVER) {
274
- return this.createDataserverStream();
275
- }
276
- logger.debug(`Creating fake stream by polling ${this.options.resourceName} REQUEST_SERVER`);
277
- return this.createReqRepStream();
278
- });
305
+ if (![ResourceType.DATASERVER, ResourceType.REQUEST_SERVER].includes(this.resourceType)) {
306
+ throw new Error(`Streaming not supported for selected resource type: ${this.resourceType}`);
307
+ }
308
+ if (this.resourceType === ResourceType.DATASERVER) {
309
+ return this.createDataserverStream();
310
+ }
311
+ logger.debug(`Creating fake stream by polling ${this.options.resourceName} REQUEST_SERVER`);
312
+ return this.createReqRepStream();
279
313
  }
280
314
  createDataserverStream() {
281
- return __awaiter(this, void 0, void 0, function* () {
282
- const onMessage = (message) => { };
283
- const onError = (error) => logger.error(withErrorCode(`${this.options.resourceName} stream failed`, error), error);
284
- return this.connect.stream(this.options.resourceName, onMessage, onError, this.dataserverOnlyParams);
285
- });
315
+ // Named now: the stream can outlive the options, which destroy() clears.
316
+ const { resourceName } = this.options;
317
+ const onMessage = (message) => { };
318
+ const onError = (error) => logger.error(withErrorCode(`${resourceName} stream failed`, error), error);
319
+ return this.connect.stream(resourceName, onMessage, onError, this.dataserverOnlyParams);
286
320
  }
287
321
  createReqRepStream() {
288
322
  this.commitResponseUnsubscribe = this.connectEvents.addCommitResponseListener((event) => {
@@ -319,9 +353,13 @@ let DefaultDatasource = class DefaultDatasource {
319
353
  fetchAndApplyMetadata(resourceName) {
320
354
  return __awaiter(this, void 0, void 0, function* () {
321
355
  var _a, _b, _c, _d;
356
+ const generation = this.generation;
322
357
  try {
323
- logger.debug(`Requesting metadata for ${this.options.resourceName} Datasource`);
324
- const meta = yield this.connect.getMetadata(this.options.resourceName);
358
+ logger.debug(`Requesting metadata for ${resourceName} Datasource`);
359
+ const meta = yield this.connect.getMetadata(resourceName);
360
+ // Superseded while the request was out: the metadata is no longer this datasource's.
361
+ if (generation !== this.generation)
362
+ return;
325
363
  if (meta) {
326
364
  this.availableIndexes = (_a = meta.INDEXES) !== null && _a !== void 0 ? _a : [];
327
365
  this.availableSortableFields = (_b = meta.SORTABLE_FIELDS) !== null && _b !== void 0 ? _b : [];
@@ -340,6 +378,12 @@ let DefaultDatasource = class DefaultDatasource {
340
378
  });
341
379
  }
342
380
  catch (e) {
381
+ // Nor is a failure: the request may have failed only because of the teardown (its socket
382
+ // closing on a reconnect, say).
383
+ if (generation !== this.generation) {
384
+ logger.debug(`Metadata Fetch for ${resourceName} failed after it was superseded:`, e);
385
+ return;
386
+ }
343
387
  logger.error(withErrorCode(`Metadata Fetch failed for ${resourceName}:`, e), e);
344
388
  this.status = this.normaliseStatus({
345
389
  isInitialized: false,
@@ -382,6 +426,15 @@ let DefaultDatasource = class DefaultDatasource {
382
426
  invalidateCache() {
383
427
  this._allParams = null;
384
428
  }
429
+ // What an init() that a later init() or destroy() interrupted resolves with: the result of the
430
+ // init() that has the datasource now, or false when destroy() came last, even after a later
431
+ // init() finished. A grid restarting destroys and initialises again straight away, and its
432
+ // first init() still waits on the server.
433
+ interruptedInit(resourceName) {
434
+ logger.debug(`${resourceName} datasource initialisation was superseded`);
435
+ const latest = this.latestInit;
436
+ return latest && latest.generation === this.generation ? latest.result : false;
437
+ }
385
438
  };
386
439
  __decorate([
387
440
  observable
@@ -1,5 +1,8 @@
1
1
  const errorCodeOf = (source) => {
2
- const errors = source === null || source === void 0 ? void 0 : source.ERROR;
2
+ var _a, _b;
3
+ const carrier = source;
4
+ const nack = (_b = (_a = carrier === null || carrier === void 0 ? void 0 : carrier.receivedMessage) !== null && _a !== void 0 ? _a : carrier === null || carrier === void 0 ? void 0 : carrier.body) !== null && _b !== void 0 ? _b : source;
5
+ const errors = nack === null || nack === void 0 ? void 0 : nack.ERROR;
3
6
  const entry = Array.isArray(errors) ? errors[0] : source;
4
7
  const code = entry === null || entry === void 0 ? void 0 : entry.CODE;
5
8
  return typeof code === 'string' || typeof code === 'number' ? String(code) : undefined;
@@ -10,7 +13,8 @@ const errorCodeOf = (source) => {
10
13
  * different failures apart without sending the NACK.
11
14
  *
12
15
  * @param message - The log message.
13
- * @param source - A NACK message, or one of its `ERROR` entries.
16
+ * @param source - A NACK message, one of its `ERROR` entries, or an error carrying the NACK as
17
+ * `receivedMessage` or `body`.
14
18
  * @internal
15
19
  */
16
20
  export const withErrorCode = (message, source) => {