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