@aws-amplify/api-graphql 4.4.2 → 4.4.3-unstable.847fb51.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.
Files changed (93) hide show
  1. package/dist/cjs/Providers/AWSAppSyncEventsProvider/index.js +98 -0
  2. package/dist/cjs/Providers/AWSAppSyncEventsProvider/index.js.map +1 -0
  3. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js +34 -731
  4. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -1
  5. package/dist/cjs/Providers/AWSWebSocketProvider/appsyncUrl.js +112 -0
  6. package/dist/cjs/Providers/AWSWebSocketProvider/appsyncUrl.js.map +1 -0
  7. package/dist/cjs/Providers/AWSWebSocketProvider/authHeaders.js +99 -0
  8. package/dist/cjs/Providers/AWSWebSocketProvider/authHeaders.js.map +1 -0
  9. package/dist/cjs/Providers/AWSWebSocketProvider/index.js +624 -0
  10. package/dist/cjs/Providers/AWSWebSocketProvider/index.js.map +1 -0
  11. package/dist/cjs/Providers/constants.js +32 -2
  12. package/dist/cjs/Providers/constants.js.map +1 -1
  13. package/dist/cjs/index.js +4 -1
  14. package/dist/cjs/index.js.map +1 -1
  15. package/dist/cjs/internals/InternalGraphQLAPI.js +8 -67
  16. package/dist/cjs/internals/InternalGraphQLAPI.js.map +1 -1
  17. package/dist/cjs/internals/events/appsyncRequest.js +97 -0
  18. package/dist/cjs/internals/events/appsyncRequest.js.map +1 -0
  19. package/dist/cjs/internals/events/index.js +73 -0
  20. package/dist/cjs/internals/events/index.js.map +1 -0
  21. package/dist/cjs/internals/events/types.js +6 -0
  22. package/dist/cjs/internals/events/types.js.map +1 -0
  23. package/dist/cjs/internals/events/utils.js +57 -0
  24. package/dist/cjs/internals/events/utils.js.map +1 -0
  25. package/dist/cjs/internals/graphqlAuth.js +64 -0
  26. package/dist/cjs/internals/graphqlAuth.js.map +1 -0
  27. package/dist/cjs/internals/graphqlRequest.js +20 -0
  28. package/dist/cjs/internals/graphqlRequest.js.map +1 -0
  29. package/dist/cjs/utils/ReconnectionMonitor.js +1 -1
  30. package/dist/cjs/utils/ReconnectionMonitor.js.map +1 -1
  31. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.d.ts +43 -0
  32. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.mjs +97 -0
  33. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.mjs.map +1 -0
  34. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +24 -71
  35. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs +34 -731
  36. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs.map +1 -1
  37. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.d.ts +21 -0
  38. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.mjs +106 -0
  39. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.mjs.map +1 -0
  40. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.d.ts +8 -0
  41. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.mjs +97 -0
  42. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.mjs.map +1 -0
  43. package/dist/esm/Providers/AWSWebSocketProvider/index.d.ts +89 -0
  44. package/dist/esm/Providers/AWSWebSocketProvider/index.mjs +622 -0
  45. package/dist/esm/Providers/AWSWebSocketProvider/index.mjs.map +1 -0
  46. package/dist/esm/Providers/constants.d.ts +33 -3
  47. package/dist/esm/Providers/constants.mjs +32 -2
  48. package/dist/esm/Providers/constants.mjs.map +1 -1
  49. package/dist/esm/index.d.ts +3 -0
  50. package/dist/esm/index.mjs +2 -0
  51. package/dist/esm/index.mjs.map +1 -1
  52. package/dist/esm/internals/InternalGraphQLAPI.d.ts +0 -1
  53. package/dist/esm/internals/InternalGraphQLAPI.mjs +9 -68
  54. package/dist/esm/internals/InternalGraphQLAPI.mjs.map +1 -1
  55. package/dist/esm/internals/events/appsyncRequest.d.ts +14 -0
  56. package/dist/esm/internals/events/appsyncRequest.mjs +96 -0
  57. package/dist/esm/internals/events/appsyncRequest.mjs.map +1 -0
  58. package/dist/esm/internals/events/index.d.ts +17 -0
  59. package/dist/esm/internals/events/index.mjs +69 -0
  60. package/dist/esm/internals/events/index.mjs.map +1 -0
  61. package/dist/esm/internals/events/types.d.ts +23 -0
  62. package/dist/esm/internals/events/types.mjs +2 -0
  63. package/dist/esm/internals/events/types.mjs.map +1 -0
  64. package/dist/esm/internals/events/utils.d.ts +16 -0
  65. package/dist/esm/internals/events/utils.mjs +53 -0
  66. package/dist/esm/internals/events/utils.mjs.map +1 -0
  67. package/dist/esm/internals/graphqlAuth.d.ts +3 -0
  68. package/dist/esm/internals/graphqlAuth.mjs +64 -0
  69. package/dist/esm/internals/graphqlAuth.mjs.map +1 -0
  70. package/dist/esm/internals/graphqlRequest.d.ts +3 -0
  71. package/dist/esm/internals/graphqlRequest.mjs +18 -0
  72. package/dist/esm/internals/graphqlRequest.mjs.map +1 -0
  73. package/dist/esm/utils/ConnectionStateMonitor.d.ts +29 -1
  74. package/dist/esm/utils/ReconnectionMonitor.d.ts +1 -1
  75. package/dist/esm/utils/ReconnectionMonitor.mjs +1 -1
  76. package/dist/esm/utils/ReconnectionMonitor.mjs.map +1 -1
  77. package/package.json +4 -4
  78. package/src/Providers/AWSAppSyncEventsProvider/index.ts +192 -0
  79. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +56 -1049
  80. package/src/Providers/AWSWebSocketProvider/appsyncUrl.ts +151 -0
  81. package/src/Providers/AWSWebSocketProvider/authHeaders.ts +146 -0
  82. package/src/Providers/AWSWebSocketProvider/index.ts +932 -0
  83. package/src/Providers/constants.ts +32 -2
  84. package/src/index.ts +5 -0
  85. package/src/internals/InternalGraphQLAPI.ts +15 -102
  86. package/src/internals/events/appsyncRequest.ts +169 -0
  87. package/src/internals/events/index.ts +138 -0
  88. package/src/internals/events/types.ts +35 -0
  89. package/src/internals/events/utils.ts +77 -0
  90. package/src/internals/graphqlAuth.ts +87 -0
  91. package/src/internals/graphqlRequest.ts +30 -0
  92. package/src/utils/ConnectionStateMonitor.ts +2 -13
  93. package/src/utils/ReconnectionMonitor.ts +1 -1
@@ -0,0 +1,624 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.AWSWebSocketProvider = void 0;
5
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ // SPDX-License-Identifier: Apache-2.0
7
+ const rxjs_1 = require("rxjs");
8
+ const graphql_1 = require("graphql");
9
+ const core_1 = require("@aws-amplify/core");
10
+ const utils_1 = require("@aws-amplify/core/internals/utils");
11
+ const PubSub_1 = require("../../types/PubSub");
12
+ const constants_1 = require("../constants");
13
+ const ConnectionStateMonitor_1 = require("../../utils/ConnectionStateMonitor");
14
+ const ReconnectionMonitor_1 = require("../../utils/ReconnectionMonitor");
15
+ const appsyncUrl_1 = require("./appsyncUrl");
16
+ const authHeaders_1 = require("./authHeaders");
17
+ const dispatchApiEvent = (payload) => {
18
+ core_1.Hub.dispatch('api', payload, 'PubSub', constants_1.AMPLIFY_SYMBOL);
19
+ };
20
+ class AWSWebSocketProvider {
21
+ constructor(args) {
22
+ this.subscriptionObserverMap = new Map();
23
+ this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
24
+ this.keepAliveTimeout = constants_1.DEFAULT_KEEP_ALIVE_TIMEOUT;
25
+ this.promiseArray = [];
26
+ this.connectionStateMonitor = new ConnectionStateMonitor_1.ConnectionStateMonitor();
27
+ this.reconnectionMonitor = new ReconnectionMonitor_1.ReconnectionMonitor();
28
+ /**
29
+ * Open WebSocket connection & perform handshake
30
+ * Ref: https://docs.aws.amazon.com/appsync/latest/devguide/real-time-websocket-client.html#appsynclong-real-time-websocket-client-implementation-guide-for-graphql-subscriptions
31
+ *
32
+ * @param subprotocol -
33
+ */
34
+ this._establishConnection = async (awsRealTimeUrl, subprotocol) => {
35
+ this.logger.debug(`Establishing WebSocket connection to ${awsRealTimeUrl}`);
36
+ try {
37
+ await this._openConnection(awsRealTimeUrl, subprotocol);
38
+ await this._initiateHandshake();
39
+ }
40
+ catch (err) {
41
+ const { errorType, errorCode } = err;
42
+ if (constants_1.NON_RETRYABLE_CODES.includes(errorCode)) {
43
+ throw new utils_1.NonRetryableError(errorType);
44
+ }
45
+ else if (errorType) {
46
+ throw new Error(errorType);
47
+ }
48
+ else {
49
+ throw err;
50
+ }
51
+ }
52
+ };
53
+ this.logger = new core_1.ConsoleLogger(args.providerName);
54
+ this.wsProtocolName = args.wsProtocolName;
55
+ this.connectionStateMonitorSubscription =
56
+ this._startConnectionStateMonitoring();
57
+ }
58
+ /**
59
+ * Mark the socket closed and release all active listeners
60
+ */
61
+ close() {
62
+ // Mark the socket closed both in status and the connection monitor
63
+ this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
64
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_FAILED);
65
+ // Turn off the subscription monitor Hub publishing
66
+ this.connectionStateMonitorSubscription.unsubscribe();
67
+ // Complete all reconnect observers
68
+ this.reconnectionMonitor.close();
69
+ }
70
+ subscribe(options, customUserAgentDetails) {
71
+ return new rxjs_1.Observable(observer => {
72
+ if (!options?.appSyncGraphqlEndpoint) {
73
+ observer.error({
74
+ errors: [
75
+ {
76
+ ...new graphql_1.GraphQLError(`Subscribe only available for AWS AppSync endpoint`),
77
+ },
78
+ ],
79
+ });
80
+ observer.complete();
81
+ return;
82
+ }
83
+ let subscriptionStartInProgress = false;
84
+ const subscriptionId = (0, utils_1.amplifyUuid)();
85
+ const startSubscription = () => {
86
+ if (!subscriptionStartInProgress) {
87
+ subscriptionStartInProgress = true;
88
+ this._startSubscriptionWithAWSAppSyncRealTime({
89
+ options,
90
+ observer,
91
+ subscriptionId,
92
+ customUserAgentDetails,
93
+ })
94
+ .catch(err => {
95
+ this.logger.debug(`${PubSub_1.CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`);
96
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
97
+ })
98
+ .finally(() => {
99
+ subscriptionStartInProgress = false;
100
+ });
101
+ }
102
+ };
103
+ // Add an observable to the reconnection list to manage reconnection for this subscription
104
+ const reconnectSubscription = new rxjs_1.Observable(reconnectSubscriptionObserver => {
105
+ this.reconnectionMonitor.addObserver(reconnectSubscriptionObserver);
106
+ }).subscribe(() => {
107
+ startSubscription();
108
+ });
109
+ startSubscription();
110
+ return async () => {
111
+ await this._cleanupSubscription(subscriptionId, reconnectSubscription);
112
+ };
113
+ });
114
+ }
115
+ async connect(options) {
116
+ if (this.socketStatus === constants_1.SOCKET_STATUS.READY) {
117
+ return;
118
+ }
119
+ await this._connectWebSocket(options);
120
+ }
121
+ async publish(options, customUserAgentDetails) {
122
+ if (this.socketStatus !== constants_1.SOCKET_STATUS.READY) {
123
+ throw new Error('Subscription has not been initialized');
124
+ }
125
+ return this._publishMessage(options, customUserAgentDetails);
126
+ }
127
+ async _connectWebSocket(options) {
128
+ const { apiKey, appSyncGraphqlEndpoint, authenticationType, region } = options;
129
+ const { additionalCustomHeaders } = await (0, appsyncUrl_1.additionalHeadersFromOptions)(options);
130
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.OPENING_CONNECTION);
131
+ await this._initializeWebSocketConnection({
132
+ apiKey,
133
+ appSyncGraphqlEndpoint,
134
+ authenticationType,
135
+ region,
136
+ additionalCustomHeaders,
137
+ });
138
+ }
139
+ async _publishMessage(options, customUserAgentDetails) {
140
+ const subscriptionId = (0, utils_1.amplifyUuid)();
141
+ const { additionalCustomHeaders, libraryConfigHeaders } = await (0, appsyncUrl_1.additionalHeadersFromOptions)(options);
142
+ const serializedSubscriptionMessage = await this._prepareSubscriptionPayload({
143
+ options,
144
+ subscriptionId,
145
+ customUserAgentDetails,
146
+ additionalCustomHeaders,
147
+ libraryConfigHeaders,
148
+ publish: true,
149
+ });
150
+ return new Promise((resolve, reject) => {
151
+ if (this.awsRealTimeSocket) {
152
+ const publishListener = (event) => {
153
+ const data = JSON.parse(event.data);
154
+ if (data.id === subscriptionId && data.type === 'publish_success') {
155
+ this.awsRealTimeSocket &&
156
+ this.awsRealTimeSocket.removeEventListener('message', publishListener);
157
+ resolve();
158
+ }
159
+ if (data.erroredEvents && data.erroredEvents.length > 0) ;
160
+ };
161
+ this.awsRealTimeSocket.addEventListener('message', publishListener);
162
+ this.awsRealTimeSocket.addEventListener('close', () => {
163
+ reject(new Error('WebSocket is closed'));
164
+ });
165
+ //
166
+ // this.awsRealTimeSocket.addEventListener('error', publishListener);
167
+ this.awsRealTimeSocket.send(serializedSubscriptionMessage);
168
+ }
169
+ });
170
+ }
171
+ async _cleanupSubscription(subscriptionId, reconnectSubscription) {
172
+ // Cleanup reconnection subscription
173
+ reconnectSubscription?.unsubscribe();
174
+ // Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
175
+ try {
176
+ // Waiting that subscription has been connected before trying to unsubscribe
177
+ await this._waitForSubscriptionToBeConnected(subscriptionId);
178
+ const { subscriptionState } = this.subscriptionObserverMap.get(subscriptionId) || {};
179
+ if (!subscriptionState) {
180
+ // subscription already unsubscribed
181
+ return;
182
+ }
183
+ if (subscriptionState === constants_1.SUBSCRIPTION_STATUS.CONNECTED) {
184
+ this._sendUnsubscriptionMessage(subscriptionId);
185
+ }
186
+ else {
187
+ throw new Error('Subscription never connected');
188
+ }
189
+ }
190
+ catch (err) {
191
+ this.logger.debug(`Error while unsubscribing ${err}`);
192
+ }
193
+ finally {
194
+ this._removeSubscriptionObserver(subscriptionId);
195
+ }
196
+ }
197
+ // Monitor the connection state and pass changes along to Hub
198
+ _startConnectionStateMonitoring() {
199
+ return this.connectionStateMonitor.connectionStateObservable.subscribe(connectionState => {
200
+ dispatchApiEvent({
201
+ event: constants_1.CONNECTION_STATE_CHANGE,
202
+ data: {
203
+ provider: this,
204
+ connectionState,
205
+ },
206
+ message: `Connection state is ${connectionState}`,
207
+ });
208
+ this.connectionState = connectionState;
209
+ // Trigger START_RECONNECT when the connection is disrupted
210
+ if (connectionState === PubSub_1.ConnectionState.ConnectionDisrupted) {
211
+ this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.START_RECONNECT);
212
+ }
213
+ // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
214
+ // ConnectionDisrupted or Connecting
215
+ if ([
216
+ PubSub_1.ConnectionState.Connected,
217
+ PubSub_1.ConnectionState.ConnectedPendingDisconnect,
218
+ PubSub_1.ConnectionState.ConnectedPendingKeepAlive,
219
+ PubSub_1.ConnectionState.ConnectedPendingNetwork,
220
+ PubSub_1.ConnectionState.ConnectionDisruptedPendingNetwork,
221
+ PubSub_1.ConnectionState.Disconnected,
222
+ ].includes(connectionState)) {
223
+ this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.HALT_RECONNECT);
224
+ }
225
+ });
226
+ }
227
+ async _startSubscriptionWithAWSAppSyncRealTime({ options, observer, subscriptionId, customUserAgentDetails, }) {
228
+ const { query, variables } = options;
229
+ const { additionalCustomHeaders, libraryConfigHeaders } = await (0, appsyncUrl_1.additionalHeadersFromOptions)(options);
230
+ this.subscriptionObserverMap.set(subscriptionId, {
231
+ observer,
232
+ query: query ?? '',
233
+ variables: variables ?? {},
234
+ subscriptionState: constants_1.SUBSCRIPTION_STATUS.PENDING,
235
+ startAckTimeoutId: undefined,
236
+ });
237
+ const serializedSubscriptionMessage = await this._prepareSubscriptionPayload({
238
+ options,
239
+ subscriptionId,
240
+ customUserAgentDetails,
241
+ additionalCustomHeaders,
242
+ libraryConfigHeaders,
243
+ });
244
+ try {
245
+ await this._connectWebSocket(options);
246
+ }
247
+ catch (err) {
248
+ this._logStartSubscriptionError(subscriptionId, observer, err);
249
+ return;
250
+ }
251
+ // Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
252
+ // E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
253
+ // Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
254
+ const { subscriptionFailedCallback, subscriptionReadyCallback } = this.subscriptionObserverMap.get(subscriptionId) ?? {};
255
+ // This must be done before sending the message in order to be listening immediately
256
+ this.subscriptionObserverMap.set(subscriptionId, {
257
+ observer,
258
+ subscriptionState: constants_1.SUBSCRIPTION_STATUS.PENDING,
259
+ query: query ?? '',
260
+ variables: variables ?? {},
261
+ subscriptionReadyCallback,
262
+ subscriptionFailedCallback,
263
+ startAckTimeoutId: setTimeout(() => {
264
+ this._timeoutStartSubscriptionAck(subscriptionId);
265
+ }, constants_1.START_ACK_TIMEOUT),
266
+ });
267
+ if (this.awsRealTimeSocket) {
268
+ this.awsRealTimeSocket.send(serializedSubscriptionMessage);
269
+ }
270
+ }
271
+ // Log logic for start subscription failures
272
+ _logStartSubscriptionError(subscriptionId, observer, err) {
273
+ this.logger.debug({ err });
274
+ const message = String(err.message ?? '');
275
+ // Resolving to give the state observer time to propogate the update
276
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
277
+ // Capture the error only when the network didn't cause disruption
278
+ if (this.connectionState !== PubSub_1.ConnectionState.ConnectionDisruptedPendingNetwork) {
279
+ // When the error is non-retriable, error out the observable
280
+ if ((0, utils_1.isNonRetryableError)(err)) {
281
+ observer.error({
282
+ errors: [
283
+ {
284
+ ...new graphql_1.GraphQLError(`${PubSub_1.CONTROL_MSG.CONNECTION_FAILED}: ${message}`),
285
+ },
286
+ ],
287
+ });
288
+ }
289
+ else {
290
+ this.logger.debug(`${PubSub_1.CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
291
+ }
292
+ const { subscriptionFailedCallback } = this.subscriptionObserverMap.get(subscriptionId) || {};
293
+ // Notify concurrent unsubscription
294
+ if (typeof subscriptionFailedCallback === 'function') {
295
+ subscriptionFailedCallback();
296
+ }
297
+ }
298
+ }
299
+ // Waiting that subscription has been connected before trying to unsubscribe
300
+ async _waitForSubscriptionToBeConnected(subscriptionId) {
301
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
302
+ if (subscriptionObserver) {
303
+ const { subscriptionState } = subscriptionObserver;
304
+ // This in case unsubscribe is invoked before sending start subscription message
305
+ if (subscriptionState === constants_1.SUBSCRIPTION_STATUS.PENDING) {
306
+ return new Promise((resolve, reject) => {
307
+ const { observer, subscriptionState: observedSubscriptionState, variables, query, } = subscriptionObserver;
308
+ this.subscriptionObserverMap.set(subscriptionId, {
309
+ observer,
310
+ subscriptionState: observedSubscriptionState,
311
+ variables,
312
+ query,
313
+ subscriptionReadyCallback: resolve,
314
+ subscriptionFailedCallback: reject,
315
+ });
316
+ });
317
+ }
318
+ }
319
+ }
320
+ _sendUnsubscriptionMessage(subscriptionId) {
321
+ try {
322
+ if (this.awsRealTimeSocket &&
323
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
324
+ this.socketStatus === constants_1.SOCKET_STATUS.READY) {
325
+ // Preparing unsubscribe message to stop receiving messages for that subscription
326
+ const unsubscribeMessage = this._unsubscribeMessage(subscriptionId);
327
+ const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
328
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
329
+ }
330
+ }
331
+ catch (err) {
332
+ // If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
333
+ this.logger.debug({ err });
334
+ }
335
+ }
336
+ _removeSubscriptionObserver(subscriptionId) {
337
+ this.subscriptionObserverMap.delete(subscriptionId);
338
+ // Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
339
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
340
+ }
341
+ _closeSocketIfRequired() {
342
+ if (this.subscriptionObserverMap.size > 0) {
343
+ // Active subscriptions on the WebSocket
344
+ return;
345
+ }
346
+ if (!this.awsRealTimeSocket) {
347
+ this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
348
+ return;
349
+ }
350
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSING_CONNECTION);
351
+ if (this.awsRealTimeSocket.bufferedAmount > 0) {
352
+ // Still data on the WebSocket
353
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
354
+ }
355
+ else {
356
+ this.logger.debug('closing WebSocket...');
357
+ if (this.keepAliveTimeoutId) {
358
+ clearTimeout(this.keepAliveTimeoutId);
359
+ }
360
+ if (this.keepAliveAlertTimeoutId) {
361
+ clearTimeout(this.keepAliveAlertTimeoutId);
362
+ }
363
+ const tempSocket = this.awsRealTimeSocket;
364
+ // Cleaning callbacks to avoid race condition, socket still exists
365
+ tempSocket.onclose = null;
366
+ tempSocket.onerror = null;
367
+ tempSocket.close(1000);
368
+ this.awsRealTimeSocket = undefined;
369
+ this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
370
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
371
+ }
372
+ }
373
+ _handleIncomingSubscriptionMessage(message) {
374
+ if (typeof message.data !== 'string') {
375
+ return;
376
+ }
377
+ const [isData, data] = this._handleSubscriptionData(message);
378
+ if (isData)
379
+ return;
380
+ const { type, id, payload } = data;
381
+ const { observer = null, query = '', variables = {}, startAckTimeoutId, subscriptionReadyCallback, subscriptionFailedCallback, } = this.subscriptionObserverMap.get(id) || {};
382
+ if (type === constants_1.MESSAGE_TYPES.GQL_START_ACK ||
383
+ type === constants_1.MESSAGE_TYPES.EVENT_SUBSCRIBE_ACK) {
384
+ this.logger.debug(`subscription ready for ${JSON.stringify({ query, variables })}`);
385
+ if (typeof subscriptionReadyCallback === 'function') {
386
+ subscriptionReadyCallback();
387
+ }
388
+ if (startAckTimeoutId)
389
+ clearTimeout(startAckTimeoutId);
390
+ dispatchApiEvent({
391
+ event: PubSub_1.CONTROL_MSG.SUBSCRIPTION_ACK,
392
+ data: { query, variables },
393
+ message: 'Connection established for subscription',
394
+ });
395
+ const subscriptionState = constants_1.SUBSCRIPTION_STATUS.CONNECTED;
396
+ if (observer) {
397
+ this.subscriptionObserverMap.set(id, {
398
+ observer,
399
+ query,
400
+ variables,
401
+ startAckTimeoutId: undefined,
402
+ subscriptionState,
403
+ subscriptionReadyCallback,
404
+ subscriptionFailedCallback,
405
+ });
406
+ }
407
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
408
+ return;
409
+ }
410
+ if (type === constants_1.MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
411
+ if (this.keepAliveTimeoutId)
412
+ clearTimeout(this.keepAliveTimeoutId);
413
+ if (this.keepAliveAlertTimeoutId)
414
+ clearTimeout(this.keepAliveAlertTimeoutId);
415
+ this.keepAliveTimeoutId = setTimeout(() => {
416
+ this._errorDisconnect(PubSub_1.CONTROL_MSG.TIMEOUT_DISCONNECT);
417
+ }, this.keepAliveTimeout);
418
+ this.keepAliveAlertTimeoutId = setTimeout(() => {
419
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
420
+ }, constants_1.DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
421
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.KEEP_ALIVE);
422
+ return;
423
+ }
424
+ if (type === constants_1.MESSAGE_TYPES.GQL_ERROR) {
425
+ const subscriptionState = constants_1.SUBSCRIPTION_STATUS.FAILED;
426
+ if (observer) {
427
+ this.subscriptionObserverMap.set(id, {
428
+ observer,
429
+ query,
430
+ variables,
431
+ startAckTimeoutId,
432
+ subscriptionReadyCallback,
433
+ subscriptionFailedCallback,
434
+ subscriptionState,
435
+ });
436
+ this.logger.debug(`${PubSub_1.CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`);
437
+ observer.error({
438
+ errors: [
439
+ {
440
+ ...new graphql_1.GraphQLError(`${PubSub_1.CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`),
441
+ },
442
+ ],
443
+ });
444
+ if (startAckTimeoutId)
445
+ clearTimeout(startAckTimeoutId);
446
+ if (typeof subscriptionFailedCallback === 'function') {
447
+ subscriptionFailedCallback();
448
+ }
449
+ }
450
+ }
451
+ }
452
+ _errorDisconnect(msg) {
453
+ this.logger.debug(`Disconnect error: ${msg}`);
454
+ if (this.awsRealTimeSocket) {
455
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
456
+ this.awsRealTimeSocket.close();
457
+ }
458
+ this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
459
+ }
460
+ _timeoutStartSubscriptionAck(subscriptionId) {
461
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
462
+ if (subscriptionObserver) {
463
+ const { observer, query, variables } = subscriptionObserver;
464
+ if (!observer) {
465
+ return;
466
+ }
467
+ this.subscriptionObserverMap.set(subscriptionId, {
468
+ observer,
469
+ query,
470
+ variables,
471
+ subscriptionState: constants_1.SUBSCRIPTION_STATUS.FAILED,
472
+ });
473
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
474
+ this.logger.debug('timeoutStartSubscription', JSON.stringify({ query, variables }));
475
+ }
476
+ }
477
+ _initializeWebSocketConnection({ appSyncGraphqlEndpoint, authenticationType, apiKey, region, additionalCustomHeaders, }) {
478
+ if (this.socketStatus === constants_1.SOCKET_STATUS.READY) {
479
+ return;
480
+ }
481
+ // TODO(Eslint): refactor to now use async function as the promise executor
482
+ // eslint-disable-next-line no-async-promise-executor
483
+ return new Promise(async (resolve, reject) => {
484
+ this.promiseArray.push({ res: resolve, rej: reject });
485
+ if (this.socketStatus === constants_1.SOCKET_STATUS.CLOSED) {
486
+ try {
487
+ this.socketStatus = constants_1.SOCKET_STATUS.CONNECTING;
488
+ // Empty payload on connect
489
+ const payloadString = '{}';
490
+ const authHeader = await (0, authHeaders_1.awsRealTimeHeaderBasedAuth)({
491
+ authenticationType,
492
+ payload: payloadString,
493
+ canonicalUri: '/connect',
494
+ apiKey,
495
+ appSyncGraphqlEndpoint,
496
+ region,
497
+ additionalCustomHeaders,
498
+ });
499
+ const headerString = authHeader ? JSON.stringify(authHeader) : '';
500
+ // base64url-encoded string
501
+ const encodedHeader = utils_1.base64Encoder.convert(headerString, {
502
+ urlSafe: true,
503
+ skipPadding: true,
504
+ });
505
+ const authTokenSubprotocol = `header-${encodedHeader}`;
506
+ const queryParams = (0, appsyncUrl_1.queryParamsFromCustomHeaders)(additionalCustomHeaders);
507
+ const awsRealTimeUrl = (0, appsyncUrl_1.realtimeUrlWithQueryString)(appSyncGraphqlEndpoint, queryParams);
508
+ await this._establishRetryableConnection(awsRealTimeUrl, authTokenSubprotocol);
509
+ this.promiseArray.forEach(({ res }) => {
510
+ this.logger.debug('Notifying connection successful');
511
+ res();
512
+ });
513
+ this.socketStatus = constants_1.SOCKET_STATUS.READY;
514
+ this.promiseArray = [];
515
+ }
516
+ catch (err) {
517
+ this.logger.debug('Connection exited with', err);
518
+ this.promiseArray.forEach(({ rej }) => {
519
+ rej(err);
520
+ });
521
+ this.promiseArray = [];
522
+ if (this.awsRealTimeSocket &&
523
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
524
+ this.awsRealTimeSocket.close(3001);
525
+ }
526
+ this.awsRealTimeSocket = undefined;
527
+ this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
528
+ }
529
+ }
530
+ });
531
+ }
532
+ async _establishRetryableConnection(awsRealTimeUrl, subprotocol) {
533
+ this.logger.debug(`Establishing retryable connection`);
534
+ await (0, utils_1.jitteredExponentialRetry)(this._establishConnection.bind(this), [awsRealTimeUrl, subprotocol], constants_1.MAX_DELAY_MS);
535
+ }
536
+ async _openConnection(awsRealTimeUrl, subprotocol) {
537
+ return new Promise((resolve, reject) => {
538
+ const newSocket = this._getNewWebSocket(awsRealTimeUrl, [
539
+ this.wsProtocolName,
540
+ subprotocol,
541
+ ]);
542
+ newSocket.onerror = () => {
543
+ this.logger.debug(`WebSocket connection error`);
544
+ };
545
+ newSocket.onclose = () => {
546
+ reject(new Error('Connection handshake error'));
547
+ };
548
+ newSocket.onopen = () => {
549
+ this.awsRealTimeSocket = newSocket;
550
+ resolve();
551
+ };
552
+ });
553
+ }
554
+ _getNewWebSocket(url, protocol) {
555
+ return new WebSocket(url, protocol);
556
+ }
557
+ async _initiateHandshake() {
558
+ return new Promise((resolve, reject) => {
559
+ if (!this.awsRealTimeSocket) {
560
+ reject(new Error('awsRealTimeSocket undefined'));
561
+ return;
562
+ }
563
+ let ackOk = false;
564
+ this.awsRealTimeSocket.onerror = error => {
565
+ this.logger.debug(`WebSocket error ${JSON.stringify(error)}`);
566
+ };
567
+ this.awsRealTimeSocket.onclose = event => {
568
+ this.logger.debug(`WebSocket closed ${event.reason}`);
569
+ reject(new Error(JSON.stringify(event)));
570
+ };
571
+ this.awsRealTimeSocket.onmessage = (message) => {
572
+ if (typeof message.data !== 'string') {
573
+ return;
574
+ }
575
+ this.logger.debug(`subscription message from AWS AppSyncRealTime: ${message.data} `);
576
+ const data = JSON.parse(message.data);
577
+ const { type, payload: { connectionTimeoutMs = constants_1.DEFAULT_KEEP_ALIVE_TIMEOUT } = {}, } = data;
578
+ if (type === constants_1.MESSAGE_TYPES.GQL_CONNECTION_ACK) {
579
+ ackOk = true;
580
+ this._registerWebsocketHandlers(connectionTimeoutMs);
581
+ resolve('Connected to AWS AppSyncRealTime');
582
+ return;
583
+ }
584
+ if (type === constants_1.MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
585
+ const { payload: { errors: [{ errorType = '', errorCode = 0 } = {}] = [], } = {}, } = data;
586
+ // TODO(Eslint): refactor to reject an Error object instead of a plain object
587
+ // eslint-disable-next-line prefer-promise-reject-errors
588
+ reject({ errorType, errorCode });
589
+ }
590
+ };
591
+ const gqlInit = {
592
+ type: constants_1.MESSAGE_TYPES.GQL_CONNECTION_INIT,
593
+ };
594
+ this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
595
+ const checkAckOk = (targetAckOk) => {
596
+ if (!targetAckOk) {
597
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_FAILED);
598
+ reject(new Error(`Connection timeout: ack from AWSAppSyncRealTime was not received after ${constants_1.CONNECTION_INIT_TIMEOUT} ms`));
599
+ }
600
+ };
601
+ setTimeout(() => {
602
+ checkAckOk(ackOk);
603
+ }, constants_1.CONNECTION_INIT_TIMEOUT);
604
+ });
605
+ }
606
+ _registerWebsocketHandlers(connectionTimeoutMs) {
607
+ if (!this.awsRealTimeSocket) {
608
+ return;
609
+ }
610
+ this.keepAliveTimeout = connectionTimeoutMs;
611
+ this.awsRealTimeSocket.onmessage =
612
+ this._handleIncomingSubscriptionMessage.bind(this);
613
+ this.awsRealTimeSocket.onerror = err => {
614
+ this.logger.debug(err);
615
+ this._errorDisconnect(PubSub_1.CONTROL_MSG.CONNECTION_CLOSED);
616
+ };
617
+ this.awsRealTimeSocket.onclose = event => {
618
+ this.logger.debug(`WebSocket closed ${event.reason}`);
619
+ this._errorDisconnect(PubSub_1.CONTROL_MSG.CONNECTION_CLOSED);
620
+ };
621
+ }
622
+ }
623
+ exports.AWSWebSocketProvider = AWSWebSocketProvider;
624
+ //# sourceMappingURL=index.js.map