@aws-amplify/pubsub 4.4.7 → 4.4.8-next.2

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 (41) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/aws-amplify-pubsub.js +318 -8
  3. package/dist/aws-amplify-pubsub.js.map +1 -1
  4. package/dist/aws-amplify-pubsub.min.js +2 -2
  5. package/dist/aws-amplify-pubsub.min.js.map +1 -1
  6. package/lib/Providers/AWSAppSyncRealTimeProvider/constants.d.ts +4 -0
  7. package/lib/Providers/AWSAppSyncRealTimeProvider/constants.js +4 -0
  8. package/lib/Providers/AWSAppSyncRealTimeProvider/constants.js.map +1 -1
  9. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +3 -0
  10. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +34 -5
  11. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -1
  12. package/lib/index.d.ts +2 -0
  13. package/lib/index.js +3 -0
  14. package/lib/index.js.map +1 -1
  15. package/lib/types/index.d.ts +11 -0
  16. package/lib/types/index.js +36 -0
  17. package/lib/types/index.js.map +1 -1
  18. package/lib/utils/ConnectionStateMonitor.d.ts +40 -0
  19. package/lib/utils/ConnectionStateMonitor.js +159 -0
  20. package/lib/utils/ConnectionStateMonitor.js.map +1 -0
  21. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/constants.d.ts +4 -0
  22. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/constants.js +4 -0
  23. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/constants.js.map +1 -1
  24. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +3 -0
  25. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +36 -7
  26. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -1
  27. package/lib-esm/index.d.ts +2 -0
  28. package/lib-esm/index.js +2 -0
  29. package/lib-esm/index.js.map +1 -1
  30. package/lib-esm/types/index.d.ts +11 -0
  31. package/lib-esm/types/index.js +36 -0
  32. package/lib-esm/types/index.js.map +1 -1
  33. package/lib-esm/utils/ConnectionStateMonitor.d.ts +40 -0
  34. package/lib-esm/utils/ConnectionStateMonitor.js +154 -0
  35. package/lib-esm/utils/ConnectionStateMonitor.js.map +1 -0
  36. package/package.json +5 -5
  37. package/src/Providers/AWSAppSyncRealTimeProvider/constants.ts +5 -0
  38. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +56 -4
  39. package/src/index.ts +3 -0
  40. package/src/types/index.ts +36 -0
  41. package/src/utils/ConnectionStateMonitor.ts +191 -0
@@ -30,12 +30,14 @@ import {
30
30
  import Cache from '@aws-amplify/cache';
31
31
  import Auth, { GRAPHQL_AUTH_MODE } from '@aws-amplify/auth';
32
32
  import { AbstractPubSubProvider } from '../PubSubProvider';
33
- import { CONTROL_MSG } from '../../index';
33
+ import { CONNECTION_STATE_CHANGE, CONTROL_MSG } from '../../index';
34
+
34
35
  import {
35
36
  AMPLIFY_SYMBOL,
36
37
  AWS_APPSYNC_REALTIME_HEADERS,
37
38
  CONNECTION_INIT_TIMEOUT,
38
39
  DEFAULT_KEEP_ALIVE_TIMEOUT,
40
+ DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT,
39
41
  MAX_DELAY_MS,
40
42
  MESSAGE_TYPES,
41
43
  NON_RETRYABLE_CODES,
@@ -43,6 +45,10 @@ import {
43
45
  START_ACK_TIMEOUT,
44
46
  SUBSCRIPTION_STATUS,
45
47
  } from './constants';
48
+ import {
49
+ ConnectionStateMonitor,
50
+ CONNECTION_CHANGE,
51
+ } from '../../utils/ConnectionStateMonitor';
46
52
 
47
53
  const logger = new Logger('AWSAppSyncRealTimeProvider');
48
54
 
@@ -89,8 +95,27 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
89
95
  private socketStatus: SOCKET_STATUS = SOCKET_STATUS.CLOSED;
90
96
  private keepAliveTimeoutId?: ReturnType<typeof setTimeout>;
91
97
  private keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
98
+ private keepAliveAlertTimeoutId?: ReturnType<typeof setTimeout>;
92
99
  private subscriptionObserverMap: Map<string, ObserverQuery> = new Map();
93
100
  private promiseArray: Array<{ res: Function; rej: Function }> = [];
101
+ private readonly connectionStateMonitor = new ConnectionStateMonitor();
102
+
103
+ constructor(options: ProviderOptions = {}) {
104
+ super(options);
105
+ // Monitor the connection state and pass changes along to Hub
106
+ this.connectionStateMonitor.connectionStateObservable.subscribe(
107
+ ConnectionState => {
108
+ dispatchApiEvent(
109
+ CONNECTION_STATE_CHANGE,
110
+ {
111
+ provider: this,
112
+ connectionState: ConnectionState,
113
+ },
114
+ `Connection state is ${ConnectionState}`
115
+ );
116
+ }
117
+ );
118
+ }
94
119
 
95
120
  getNewWebSocket(url, protocol) {
96
121
  return new WebSocket(url, protocol);
@@ -147,6 +172,7 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
147
172
  },
148
173
  ],
149
174
  });
175
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
150
176
  observer.complete();
151
177
  });
152
178
 
@@ -252,6 +278,7 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
252
278
  const stringToAWSRealTime = JSON.stringify(subscriptionMessage);
253
279
 
254
280
  try {
281
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
255
282
  await this._initializeWebSocketConnection({
256
283
  apiKey,
257
284
  appSyncGraphqlEndpoint,
@@ -262,6 +289,7 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
262
289
  } catch (err) {
263
290
  logger.debug({ err });
264
291
  const message = err['message'] ?? '';
292
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
265
293
  observer.error({
266
294
  errors: [
267
295
  {
@@ -366,12 +394,20 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
366
394
  this.socketStatus = SOCKET_STATUS.CLOSED;
367
395
  return;
368
396
  }
397
+
398
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
399
+
369
400
  if (this.awsRealTimeSocket.bufferedAmount > 0) {
370
401
  // Still data on the WebSocket
371
402
  setTimeout(this._closeSocketIfRequired.bind(this), 1000);
372
403
  } else {
373
404
  logger.debug('closing WebSocket...');
374
- if (this.keepAliveTimeoutId) clearTimeout(this.keepAliveTimeoutId);
405
+ if (this.keepAliveTimeoutId) {
406
+ clearTimeout(this.keepAliveTimeoutId);
407
+ }
408
+ if (this.keepAliveAlertTimeoutId) {
409
+ clearTimeout(this.keepAliveAlertTimeoutId);
410
+ }
375
411
  const tempSocket = this.awsRealTimeSocket;
376
412
  // Cleaning callbacks to avoid race condition, socket still exists
377
413
  tempSocket.onclose = null;
@@ -379,6 +415,7 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
379
415
  tempSocket.close(1000);
380
416
  this.awsRealTimeSocket = undefined;
381
417
  this.socketStatus = SOCKET_STATUS.CLOSED;
418
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
382
419
  }
383
420
  }
384
421
 
@@ -432,17 +469,25 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
432
469
  subscriptionFailedCallback,
433
470
  });
434
471
  }
472
+ this.connectionStateMonitor.record(
473
+ CONNECTION_CHANGE.CONNECTION_ESTABLISHED
474
+ );
435
475
 
436
- // TODO: emit event on hub but it requires to store the id first
437
476
  return;
438
477
  }
439
478
 
440
479
  if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
441
480
  if (this.keepAliveTimeoutId) clearTimeout(this.keepAliveTimeoutId);
481
+ if (this.keepAliveAlertTimeoutId)
482
+ clearTimeout(this.keepAliveAlertTimeoutId);
442
483
  this.keepAliveTimeoutId = setTimeout(
443
- this._errorDisconnect.bind(this, CONTROL_MSG.TIMEOUT_DISCONNECT),
484
+ () => this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT),
444
485
  this.keepAliveTimeout
445
486
  );
487
+ this.keepAliveAlertTimeoutId = setTimeout(() => {
488
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
489
+ }, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
490
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);
446
491
  return;
447
492
  }
448
493
 
@@ -489,6 +534,7 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
489
534
  });
490
535
  this.subscriptionObserverMap.clear();
491
536
  if (this.awsRealTimeSocket) {
537
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
492
538
  this.awsRealTimeSocket.close();
493
539
  }
494
540
 
@@ -630,6 +676,9 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
630
676
  logger.debug(`WebSocket connection error`);
631
677
  };
632
678
  newSocket.onclose = () => {
679
+ this.connectionStateMonitor.record(
680
+ CONNECTION_CHANGE.CONNECTION_FAILED
681
+ );
633
682
  rej(new Error('Connection handshake error'));
634
683
  };
635
684
  newSocket.onopen = () => {
@@ -703,6 +752,9 @@ export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
703
752
 
704
753
  function checkAckOk(ackOk: boolean) {
705
754
  if (!ackOk) {
755
+ this.connectionStateMonitor.record(
756
+ CONNECTION_CHANGE.CONNECTION_FAILED
757
+ );
706
758
  rej(
707
759
  new Error(
708
760
  `Connection timeout: ack from AWSRealTime was not received on ${CONNECTION_INIT_TIMEOUT} ms`
package/src/index.ts CHANGED
@@ -22,6 +22,9 @@ enum CONTROL_MSG {
22
22
  TIMEOUT_DISCONNECT = 'Timeout disconnect',
23
23
  }
24
24
 
25
+ export const CONNECTION_STATE_CHANGE = 'ConnectionStateChange';
26
+ export { ConnectionState } from './types';
27
+
25
28
  export { PubSub, CONTROL_MSG };
26
29
 
27
30
  /**
@@ -19,3 +19,39 @@ export interface SubscriptionObserver<T> {
19
19
  error(errorValue: any): void;
20
20
  complete(): void;
21
21
  }
22
+
23
+ /** @enum {string} */
24
+ export enum ConnectionState {
25
+ /*
26
+ * The connection is alive and healthy
27
+ */
28
+ Connected = 'Connected',
29
+ /*
30
+ * The connection is alive, but the connection is offline
31
+ */
32
+ ConnectedPendingNetwork = 'ConnectedPendingNetwork',
33
+ /*
34
+ * The connection has been disconnected while in use
35
+ */
36
+ ConnectionDisrupted = 'ConnectionDisrupted',
37
+ /*
38
+ * The connection has been disconnected and the network is offline
39
+ */
40
+ ConnectionDisruptedPendingNetwork = 'ConnectionDisruptedPendingNetwork',
41
+ /*
42
+ * The connection is in the process of connecting
43
+ */
44
+ Connecting = 'Connecting',
45
+ /*
46
+ * The connection is not in use and is being disconnected
47
+ */
48
+ ConnectedPendingDisconnect = 'ConnectedPendingDisconnect',
49
+ /*
50
+ * The connection is not in use and has been disconnected
51
+ */
52
+ Disconnected = 'Disconnected',
53
+ /*
54
+ * The connection is alive, but a keep alive message has been missed
55
+ */
56
+ ConnectedPendingKeepAlive = 'ConnectedPendingKeepAlive',
57
+ }
@@ -0,0 +1,191 @@
1
+ /*
2
+ * Copyright 2017-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
5
+ * the License. A copy of the License is located at
6
+ *
7
+ * http://aws.amazon.com/apache2.0/
8
+ *
9
+ * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
10
+ * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
11
+ * and limitations under the License.
12
+ */
13
+
14
+ import { Reachability } from '@aws-amplify/core';
15
+ import Observable, { ZenObservable } from 'zen-observable-ts';
16
+ import { ConnectionState } from '../index';
17
+
18
+ // Internal types for tracking different connection states
19
+ type LinkedConnectionState = 'connected' | 'disconnected';
20
+ type LinkedHealthState = 'healthy' | 'unhealthy';
21
+ type LinkedConnectionStates = {
22
+ networkState: LinkedConnectionState;
23
+ connectionState: LinkedConnectionState | 'connecting';
24
+ intendedConnectionState: LinkedConnectionState;
25
+ keepAliveState: LinkedHealthState;
26
+ };
27
+
28
+ export const CONNECTION_CHANGE: {
29
+ [key in
30
+ | 'KEEP_ALIVE_MISSED'
31
+ | 'KEEP_ALIVE'
32
+ | 'CONNECTION_ESTABLISHED'
33
+ | 'CONNECTION_FAILED'
34
+ | 'CLOSING_CONNECTION'
35
+ | 'OPENING_CONNECTION'
36
+ | 'CLOSED'
37
+ | 'ONLINE'
38
+ | 'OFFLINE']: Partial<LinkedConnectionStates>;
39
+ } = {
40
+ KEEP_ALIVE_MISSED: { keepAliveState: 'unhealthy' },
41
+ KEEP_ALIVE: { keepAliveState: 'healthy' },
42
+ CONNECTION_ESTABLISHED: { connectionState: 'connected' },
43
+ CONNECTION_FAILED: {
44
+ intendedConnectionState: 'disconnected',
45
+ connectionState: 'disconnected',
46
+ },
47
+ CLOSING_CONNECTION: { intendedConnectionState: 'disconnected' },
48
+ OPENING_CONNECTION: {
49
+ intendedConnectionState: 'connected',
50
+ connectionState: 'connecting',
51
+ },
52
+ CLOSED: { connectionState: 'disconnected' },
53
+ ONLINE: { networkState: 'connected' },
54
+ OFFLINE: { networkState: 'disconnected' },
55
+ };
56
+
57
+ export class ConnectionStateMonitor {
58
+ /**
59
+ * @private
60
+ */
61
+ private _linkedConnectionState: LinkedConnectionStates;
62
+ private _linkedConnectionStateObservable: Observable<LinkedConnectionStates>;
63
+ private _linkedConnectionStateObserver: ZenObservable.SubscriptionObserver<LinkedConnectionStates>;
64
+ private _networkMonitoringSubscription?: ZenObservable.Subscription;
65
+
66
+ constructor() {
67
+ this._networkMonitoringSubscription = undefined;
68
+ this._linkedConnectionState = {
69
+ networkState: 'connected',
70
+ connectionState: 'disconnected',
71
+ intendedConnectionState: 'disconnected',
72
+ keepAliveState: 'healthy',
73
+ };
74
+
75
+ this._linkedConnectionStateObservable =
76
+ new Observable<LinkedConnectionStates>(connectionStateObserver => {
77
+ connectionStateObserver.next(this._linkedConnectionState);
78
+ this._linkedConnectionStateObserver = connectionStateObserver;
79
+ });
80
+ }
81
+
82
+ /**
83
+ * Turn network state monitoring on if it isn't on already
84
+ */
85
+ private enableNetworkMonitoring() {
86
+ // Maintain the network state based on the reachability monitor
87
+ if (this._networkMonitoringSubscription === undefined) {
88
+ this._networkMonitoringSubscription = new Reachability()
89
+ .networkMonitor()
90
+ .subscribe(({ online }) => {
91
+ this.record(
92
+ online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE
93
+ );
94
+ });
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Turn network state monitoring off if it isn't off already
100
+ */
101
+ private disableNetworkMonitoring() {
102
+ this._networkMonitoringSubscription?.unsubscribe();
103
+ this._networkMonitoringSubscription = undefined;
104
+ }
105
+
106
+ /**
107
+ * Get the observable that allows us to monitor the connection state
108
+ *
109
+ * @returns {Observable<ConnectionState>} - The observable that emits ConnectionState updates
110
+ */
111
+ public get connectionStateObservable(): Observable<ConnectionState> {
112
+ let previous: ConnectionState;
113
+
114
+ // The linked state aggregates state changes to any of the network, connection,
115
+ // intendedConnection and keepAliveHealth. Some states will change these independent
116
+ // states without changing the overall connection state.
117
+
118
+ // After translating from linked states to ConnectionState, then remove any duplicates
119
+ return this._linkedConnectionStateObservable
120
+ .map(value => {
121
+ return this.connectionStatesTranslator(value);
122
+ })
123
+ .filter(current => {
124
+ const toInclude = current !== previous;
125
+ previous = current;
126
+ return toInclude;
127
+ });
128
+ }
129
+
130
+ /*
131
+ * Updates local connection state and emits the full state to the observer.
132
+ */
133
+ record(statusUpdates: Partial<LinkedConnectionStates>) {
134
+ // Maintain the network monitor
135
+ if (statusUpdates.intendedConnectionState === 'connected') {
136
+ this.enableNetworkMonitoring();
137
+ } else if (statusUpdates.intendedConnectionState === 'disconnected') {
138
+ this.disableNetworkMonitoring();
139
+ }
140
+
141
+ // Maintain the socket state
142
+ const newSocketStatus = {
143
+ ...this._linkedConnectionState,
144
+ ...statusUpdates,
145
+ };
146
+
147
+ this._linkedConnectionState = { ...newSocketStatus };
148
+
149
+ this._linkedConnectionStateObserver.next(this._linkedConnectionState);
150
+ }
151
+
152
+ /*
153
+ * Translate the ConnectionState structure into a specific ConnectionState string literal union
154
+ */
155
+ private connectionStatesTranslator({
156
+ connectionState,
157
+ networkState,
158
+ intendedConnectionState,
159
+ keepAliveState,
160
+ }: LinkedConnectionStates): ConnectionState {
161
+ if (connectionState === 'connected' && networkState === 'disconnected')
162
+ return ConnectionState.ConnectedPendingNetwork;
163
+
164
+ if (
165
+ connectionState === 'connected' &&
166
+ intendedConnectionState === 'disconnected'
167
+ )
168
+ return ConnectionState.ConnectedPendingDisconnect;
169
+
170
+ if (
171
+ connectionState === 'disconnected' &&
172
+ intendedConnectionState === 'connected' &&
173
+ networkState === 'disconnected'
174
+ )
175
+ return ConnectionState.ConnectionDisruptedPendingNetwork;
176
+
177
+ if (
178
+ connectionState === 'disconnected' &&
179
+ intendedConnectionState === 'connected'
180
+ )
181
+ return ConnectionState.ConnectionDisrupted;
182
+
183
+ if (connectionState === 'connected' && keepAliveState === 'unhealthy')
184
+ return ConnectionState.ConnectedPendingKeepAlive;
185
+
186
+ // All remaining states directly correspond to the connection state
187
+ if (connectionState === 'connecting') return ConnectionState.Connecting;
188
+ if (connectionState === 'disconnected') return ConnectionState.Disconnected;
189
+ return ConnectionState.Connected;
190
+ }
191
+ }