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