@aws-amplify/api-graphql 3.4.12-api-v6-models.b3abc9b.0 → 4.0.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 (118) hide show
  1. package/README.md +3 -0
  2. package/lib/GraphQLAPI.d.ts +17 -4
  3. package/lib/GraphQLAPI.js +33 -27
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  5. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +690 -0
  6. package/lib/Providers/constants.d.ts +95 -0
  7. package/lib/Providers/constants.js +103 -0
  8. package/lib/index.d.ts +1 -3
  9. package/lib/index.js +6 -10
  10. package/lib/internals/InternalGraphQLAPI.d.ts +11 -34
  11. package/lib/internals/InternalGraphQLAPI.js +219 -345
  12. package/lib/internals/index.d.ts +1 -1
  13. package/lib/internals/index.js +2 -1
  14. package/lib/internals/v6.d.ts +14 -2
  15. package/lib/internals/v6.js +21 -3
  16. package/lib/tsconfig.tsbuildinfo +6813 -0
  17. package/lib/types/PubSub.d.ts +27 -0
  18. package/lib/types/PubSub.js +46 -0
  19. package/lib/types/index.d.ts +119 -12
  20. package/lib/types/index.js +4 -3
  21. package/lib/utils/ConnectionStateMonitor.d.ts +41 -0
  22. package/lib/utils/ConnectionStateMonitor.js +131 -0
  23. package/lib/utils/ReachabilityMonitor/index.d.ts +1 -0
  24. package/lib/utils/ReachabilityMonitor/index.js +6 -0
  25. package/lib/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  26. package/lib/utils/ReachabilityMonitor/index.native.js +8 -0
  27. package/lib/utils/ReconnectionMonitor.d.ts +29 -0
  28. package/lib/utils/ReconnectionMonitor.js +68 -0
  29. package/lib/utils/errors/APIError.d.ts +7 -0
  30. package/lib/utils/errors/APIError.js +18 -0
  31. package/lib/utils/errors/assertValidationError.d.ts +5 -0
  32. package/lib/utils/errors/assertValidationError.js +16 -0
  33. package/lib/utils/errors/index.d.ts +3 -0
  34. package/lib/utils/errors/index.js +11 -0
  35. package/lib/utils/errors/validation.d.ts +7 -0
  36. package/lib/utils/errors/validation.js +25 -0
  37. package/lib/utils/index.d.ts +2 -0
  38. package/lib/utils/index.js +8 -0
  39. package/lib/utils/resolveConfig.d.ts +12 -0
  40. package/lib/utils/resolveConfig.js +22 -0
  41. package/lib/utils/resolveLibraryOptions.d.ts +11 -0
  42. package/lib/utils/resolveLibraryOptions.js +12 -0
  43. package/lib-esm/GraphQLAPI.d.ts +17 -4
  44. package/lib-esm/GraphQLAPI.js +33 -28
  45. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  46. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +687 -0
  47. package/lib-esm/Providers/constants.d.ts +95 -0
  48. package/lib-esm/Providers/constants.js +100 -0
  49. package/lib-esm/index.d.ts +1 -3
  50. package/lib-esm/index.js +1 -4
  51. package/lib-esm/internals/InternalGraphQLAPI.d.ts +11 -34
  52. package/lib-esm/internals/InternalGraphQLAPI.js +218 -345
  53. package/lib-esm/internals/index.d.ts +1 -1
  54. package/lib-esm/internals/index.js +1 -2
  55. package/lib-esm/internals/v6.d.ts +14 -2
  56. package/lib-esm/internals/v6.js +18 -2
  57. package/lib-esm/tsconfig.tsbuildinfo +6813 -0
  58. package/lib-esm/types/PubSub.d.ts +27 -0
  59. package/lib-esm/types/PubSub.js +44 -0
  60. package/lib-esm/types/index.d.ts +119 -12
  61. package/lib-esm/types/index.js +2 -3
  62. package/lib-esm/utils/ConnectionStateMonitor.d.ts +41 -0
  63. package/lib-esm/utils/ConnectionStateMonitor.js +128 -0
  64. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +1 -0
  65. package/lib-esm/utils/ReachabilityMonitor/index.js +4 -0
  66. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  67. package/lib-esm/utils/ReachabilityMonitor/index.native.js +5 -0
  68. package/lib-esm/utils/ReconnectionMonitor.d.ts +29 -0
  69. package/lib-esm/utils/ReconnectionMonitor.js +65 -0
  70. package/lib-esm/utils/errors/APIError.d.ts +7 -0
  71. package/lib-esm/utils/errors/APIError.js +15 -0
  72. package/lib-esm/utils/errors/assertValidationError.d.ts +5 -0
  73. package/lib-esm/utils/errors/assertValidationError.js +13 -0
  74. package/lib-esm/utils/errors/index.d.ts +3 -0
  75. package/lib-esm/utils/errors/index.js +5 -0
  76. package/lib-esm/utils/errors/validation.d.ts +7 -0
  77. package/lib-esm/utils/errors/validation.js +23 -0
  78. package/lib-esm/utils/index.d.ts +2 -0
  79. package/lib-esm/utils/index.js +4 -0
  80. package/lib-esm/utils/resolveConfig.d.ts +12 -0
  81. package/lib-esm/utils/resolveConfig.js +20 -0
  82. package/lib-esm/utils/resolveLibraryOptions.d.ts +11 -0
  83. package/lib-esm/utils/resolveLibraryOptions.js +10 -0
  84. package/package.json +122 -118
  85. package/src/GraphQLAPI.ts +26 -4
  86. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +998 -0
  87. package/src/Providers/constants.ts +110 -0
  88. package/src/index.ts +2 -3
  89. package/src/internals/InternalGraphQLAPI.ts +181 -218
  90. package/src/internals/index.ts +1 -1
  91. package/src/internals/v6.ts +34 -2
  92. package/src/types/PubSub.ts +56 -0
  93. package/src/types/index.ts +175 -15
  94. package/src/utils/ConnectionStateMonitor.ts +199 -0
  95. package/src/utils/ReachabilityMonitor/index.native.ts +7 -0
  96. package/src/utils/ReachabilityMonitor/index.ts +4 -0
  97. package/src/utils/ReconnectionMonitor.ts +76 -0
  98. package/src/utils/errors/APIError.ts +21 -0
  99. package/src/utils/errors/assertValidationError.ts +19 -0
  100. package/src/utils/errors/index.ts +6 -0
  101. package/src/utils/errors/validation.ts +26 -0
  102. package/src/utils/index.ts +5 -0
  103. package/src/utils/resolveConfig.ts +35 -0
  104. package/src/utils/resolveLibraryOptions.ts +13 -0
  105. package/lib/.tsbuildinfo +0 -3
  106. package/lib/GraphQLAPI.js.map +0 -1
  107. package/lib/index.js.map +0 -1
  108. package/lib/internals/InternalGraphQLAPI.js.map +0 -1
  109. package/lib/internals/index.js.map +0 -1
  110. package/lib/internals/v6.js.map +0 -1
  111. package/lib/types/index.js.map +0 -1
  112. package/lib-esm/.tsbuildinfo +0 -3
  113. package/lib-esm/GraphQLAPI.js.map +0 -1
  114. package/lib-esm/index.js.map +0 -1
  115. package/lib-esm/internals/InternalGraphQLAPI.js.map +0 -1
  116. package/lib-esm/internals/index.js.map +0 -1
  117. package/lib-esm/internals/v6.js.map +0 -1
  118. package/lib-esm/types/index.js.map +0 -1
@@ -0,0 +1,687 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { Observable } from 'rxjs';
4
+ import { GraphQLError } from 'graphql';
5
+ import { Hub, fetchAuthSession, ConsoleLogger } from '@aws-amplify/core';
6
+ import { signRequest } from '@aws-amplify/core/internals/aws-client-utils';
7
+ import { base64Encoder, NonRetryableError, USER_AGENT_HEADER, getAmplifyUserAgent, isNonRetryableError, jitteredExponentialRetry, amplifyUuid, AmplifyUrl, } from '@aws-amplify/core/internals/utils';
8
+ import { CONTROL_MSG, ConnectionState, } from '../../types/PubSub';
9
+ import { AMPLIFY_SYMBOL, AWS_APPSYNC_REALTIME_HEADERS, CONNECTION_INIT_TIMEOUT, DEFAULT_KEEP_ALIVE_TIMEOUT, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT, MAX_DELAY_MS, MESSAGE_TYPES, NON_RETRYABLE_CODES, SOCKET_STATUS, START_ACK_TIMEOUT, SUBSCRIPTION_STATUS, CONNECTION_STATE_CHANGE, } from '../constants';
10
+ import { ConnectionStateMonitor, CONNECTION_CHANGE, } from '../../utils/ConnectionStateMonitor';
11
+ import { ReconnectEvent, ReconnectionMonitor, } from '../../utils/ReconnectionMonitor';
12
+ const logger = new ConsoleLogger('AWSAppSyncRealTimeProvider');
13
+ const dispatchApiEvent = payload => {
14
+ Hub.dispatch('api', payload, 'PubSub', AMPLIFY_SYMBOL);
15
+ };
16
+ const standardDomainPattern = /^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com(?:\.cn)?\/graphql$/i;
17
+ const customDomainPath = '/realtime';
18
+ export class AWSAppSyncRealTimeProvider {
19
+ constructor(options = {}) {
20
+ this.socketStatus = SOCKET_STATUS.CLOSED;
21
+ this.keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
22
+ this.subscriptionObserverMap = new Map();
23
+ this.promiseArray = [];
24
+ this.connectionStateMonitor = new ConnectionStateMonitor();
25
+ this.reconnectionMonitor = new ReconnectionMonitor();
26
+ // Monitor the connection state and pass changes along to Hub
27
+ this.connectionStateMonitorSubscription =
28
+ this.connectionStateMonitor.connectionStateObservable.subscribe(connectionState => {
29
+ dispatchApiEvent({
30
+ event: CONNECTION_STATE_CHANGE,
31
+ data: {
32
+ provider: this,
33
+ connectionState,
34
+ },
35
+ message: `Connection state is ${connectionState}`,
36
+ });
37
+ this.connectionState = connectionState;
38
+ // Trigger START_RECONNECT when the connection is disrupted
39
+ if (connectionState === ConnectionState.ConnectionDisrupted) {
40
+ this.reconnectionMonitor.record(ReconnectEvent.START_RECONNECT);
41
+ }
42
+ // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
43
+ // ConnectionDisrupted or Connecting
44
+ if ([
45
+ ConnectionState.Connected,
46
+ ConnectionState.ConnectedPendingDisconnect,
47
+ ConnectionState.ConnectedPendingKeepAlive,
48
+ ConnectionState.ConnectedPendingNetwork,
49
+ ConnectionState.ConnectionDisruptedPendingNetwork,
50
+ ConnectionState.Disconnected,
51
+ ].includes(connectionState)) {
52
+ this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT);
53
+ }
54
+ });
55
+ }
56
+ /**
57
+ * Mark the socket closed and release all active listeners
58
+ */
59
+ close() {
60
+ // Mark the socket closed both in status and the connection monitor
61
+ this.socketStatus = SOCKET_STATUS.CLOSED;
62
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
63
+ // Turn off the subscription monitor Hub publishing
64
+ this.connectionStateMonitorSubscription.unsubscribe();
65
+ // Complete all reconnect observers
66
+ this.reconnectionMonitor.close();
67
+ }
68
+ getNewWebSocket(url, protocol) {
69
+ return new WebSocket(url, protocol);
70
+ }
71
+ getProviderName() {
72
+ return 'AWSAppSyncRealTimeProvider';
73
+ }
74
+ // Check if url matches standard domain pattern
75
+ isCustomDomain(url) {
76
+ return url.match(standardDomainPattern) === null;
77
+ }
78
+ subscribe(options, customUserAgentDetails) {
79
+ const { appSyncGraphqlEndpoint, region, query, variables, authenticationType, additionalHeaders, apiKey, } = options || {};
80
+ return new Observable(observer => {
81
+ if (!options || !appSyncGraphqlEndpoint) {
82
+ observer.error({
83
+ errors: [
84
+ {
85
+ ...new GraphQLError(`Subscribe only available for AWS AppSync endpoint`),
86
+ },
87
+ ],
88
+ });
89
+ observer.complete();
90
+ }
91
+ else {
92
+ let subscriptionStartActive = false;
93
+ const subscriptionId = amplifyUuid();
94
+ const startSubscription = () => {
95
+ if (!subscriptionStartActive) {
96
+ subscriptionStartActive = true;
97
+ const startSubscriptionPromise = this._startSubscriptionWithAWSAppSyncRealTime({
98
+ options: {
99
+ query,
100
+ variables,
101
+ region,
102
+ authenticationType,
103
+ appSyncGraphqlEndpoint,
104
+ additionalHeaders,
105
+ apiKey,
106
+ },
107
+ observer,
108
+ subscriptionId,
109
+ customUserAgentDetails,
110
+ }).catch(err => {
111
+ logger.debug(`${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`);
112
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
113
+ });
114
+ startSubscriptionPromise.finally(() => {
115
+ subscriptionStartActive = false;
116
+ });
117
+ }
118
+ };
119
+ let reconnectSubscription;
120
+ // Add an observable to the reconnection list to manage reconnection for this subscription
121
+ reconnectSubscription = new Observable(observer => {
122
+ this.reconnectionMonitor.addObserver(observer);
123
+ }).subscribe(() => {
124
+ startSubscription();
125
+ });
126
+ startSubscription();
127
+ return async () => {
128
+ // Cleanup reconnection subscription
129
+ reconnectSubscription?.unsubscribe();
130
+ // Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
131
+ try {
132
+ // Waiting that subscription has been connected before trying to unsubscribe
133
+ await this._waitForSubscriptionToBeConnected(subscriptionId);
134
+ const { subscriptionState } = this.subscriptionObserverMap.get(subscriptionId) || {};
135
+ if (!subscriptionState) {
136
+ // subscription already unsubscribed
137
+ return;
138
+ }
139
+ if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {
140
+ this._sendUnsubscriptionMessage(subscriptionId);
141
+ }
142
+ else {
143
+ throw new Error('Subscription never connected');
144
+ }
145
+ }
146
+ catch (err) {
147
+ logger.debug(`Error while unsubscribing ${err}`);
148
+ }
149
+ finally {
150
+ this._removeSubscriptionObserver(subscriptionId);
151
+ }
152
+ };
153
+ }
154
+ });
155
+ }
156
+ async _startSubscriptionWithAWSAppSyncRealTime({ options, observer, subscriptionId, customUserAgentDetails, }) {
157
+ const { appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, graphql_headers = () => ({}), additionalHeaders = {}, } = options;
158
+ const subscriptionState = SUBSCRIPTION_STATUS.PENDING;
159
+ const data = {
160
+ query,
161
+ variables,
162
+ };
163
+ // Having a subscription id map will make it simple to forward messages received
164
+ this.subscriptionObserverMap.set(subscriptionId, {
165
+ observer,
166
+ query: query ?? '',
167
+ variables: variables ?? {},
168
+ subscriptionState,
169
+ startAckTimeoutId: undefined,
170
+ });
171
+ // Preparing payload for subscription message
172
+ const dataString = JSON.stringify(data);
173
+ const headerObj = {
174
+ ...(await this._awsRealTimeHeaderBasedAuth({
175
+ apiKey,
176
+ appSyncGraphqlEndpoint,
177
+ authenticationType,
178
+ payload: dataString,
179
+ canonicalUri: '',
180
+ region,
181
+ additionalHeaders,
182
+ })),
183
+ ...(await graphql_headers()),
184
+ ...additionalHeaders,
185
+ [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
186
+ };
187
+ const subscriptionMessage = {
188
+ id: subscriptionId,
189
+ payload: {
190
+ data: dataString,
191
+ extensions: {
192
+ authorization: {
193
+ ...headerObj,
194
+ },
195
+ },
196
+ },
197
+ type: MESSAGE_TYPES.GQL_START,
198
+ };
199
+ const stringToAWSRealTime = JSON.stringify(subscriptionMessage);
200
+ try {
201
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
202
+ await this._initializeWebSocketConnection({
203
+ apiKey,
204
+ appSyncGraphqlEndpoint,
205
+ authenticationType,
206
+ region,
207
+ additionalHeaders,
208
+ });
209
+ }
210
+ catch (err) {
211
+ this._logStartSubscriptionError(subscriptionId, observer, err);
212
+ return;
213
+ }
214
+ // Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
215
+ // E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
216
+ // Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
217
+ const { subscriptionFailedCallback, subscriptionReadyCallback } = this.subscriptionObserverMap.get(subscriptionId) ?? {};
218
+ // This must be done before sending the message in order to be listening immediately
219
+ this.subscriptionObserverMap.set(subscriptionId, {
220
+ observer,
221
+ subscriptionState,
222
+ query: query ?? '',
223
+ variables: variables ?? {},
224
+ subscriptionReadyCallback,
225
+ subscriptionFailedCallback,
226
+ startAckTimeoutId: setTimeout(() => {
227
+ this._timeoutStartSubscriptionAck.call(this, subscriptionId);
228
+ }, START_ACK_TIMEOUT),
229
+ });
230
+ if (this.awsRealTimeSocket) {
231
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
232
+ }
233
+ }
234
+ // Log logic for start subscription failures
235
+ _logStartSubscriptionError(subscriptionId, observer, err) {
236
+ logger.debug({ err });
237
+ const message = String(err.message ?? '');
238
+ // Resolving to give the state observer time to propogate the update
239
+ Promise.resolve(this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED));
240
+ // Capture the error only when the network didn't cause disruption
241
+ if (this.connectionState !== ConnectionState.ConnectionDisruptedPendingNetwork) {
242
+ // When the error is non-retriable, error out the observable
243
+ if (isNonRetryableError(err)) {
244
+ observer.error({
245
+ errors: [
246
+ {
247
+ ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`),
248
+ },
249
+ ],
250
+ });
251
+ }
252
+ else {
253
+ logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
254
+ }
255
+ const { subscriptionFailedCallback } = this.subscriptionObserverMap.get(subscriptionId) || {};
256
+ // Notify concurrent unsubscription
257
+ if (typeof subscriptionFailedCallback === 'function') {
258
+ subscriptionFailedCallback();
259
+ }
260
+ }
261
+ }
262
+ // Waiting that subscription has been connected before trying to unsubscribe
263
+ async _waitForSubscriptionToBeConnected(subscriptionId) {
264
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
265
+ if (subscriptionObserver) {
266
+ const { subscriptionState } = subscriptionObserver;
267
+ // This in case unsubscribe is invoked before sending start subscription message
268
+ if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
269
+ return new Promise((res, rej) => {
270
+ const { observer, subscriptionState, variables, query } = subscriptionObserver;
271
+ this.subscriptionObserverMap.set(subscriptionId, {
272
+ observer,
273
+ subscriptionState,
274
+ variables,
275
+ query,
276
+ subscriptionReadyCallback: res,
277
+ subscriptionFailedCallback: rej,
278
+ });
279
+ });
280
+ }
281
+ }
282
+ }
283
+ _sendUnsubscriptionMessage(subscriptionId) {
284
+ try {
285
+ if (this.awsRealTimeSocket &&
286
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
287
+ this.socketStatus === SOCKET_STATUS.READY) {
288
+ // Preparing unsubscribe message to stop receiving messages for that subscription
289
+ const unsubscribeMessage = {
290
+ id: subscriptionId,
291
+ type: MESSAGE_TYPES.GQL_STOP,
292
+ };
293
+ const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
294
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
295
+ }
296
+ }
297
+ catch (err) {
298
+ // If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
299
+ logger.debug({ err });
300
+ }
301
+ }
302
+ _removeSubscriptionObserver(subscriptionId) {
303
+ this.subscriptionObserverMap.delete(subscriptionId);
304
+ // Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
305
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
306
+ }
307
+ _closeSocketIfRequired() {
308
+ if (this.subscriptionObserverMap.size > 0) {
309
+ // Active subscriptions on the WebSocket
310
+ return;
311
+ }
312
+ if (!this.awsRealTimeSocket) {
313
+ this.socketStatus = SOCKET_STATUS.CLOSED;
314
+ return;
315
+ }
316
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
317
+ if (this.awsRealTimeSocket.bufferedAmount > 0) {
318
+ // Still data on the WebSocket
319
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
320
+ }
321
+ else {
322
+ logger.debug('closing WebSocket...');
323
+ if (this.keepAliveTimeoutId) {
324
+ clearTimeout(this.keepAliveTimeoutId);
325
+ }
326
+ if (this.keepAliveAlertTimeoutId) {
327
+ clearTimeout(this.keepAliveAlertTimeoutId);
328
+ }
329
+ const tempSocket = this.awsRealTimeSocket;
330
+ // Cleaning callbacks to avoid race condition, socket still exists
331
+ tempSocket.onclose = null;
332
+ tempSocket.onerror = null;
333
+ tempSocket.close(1000);
334
+ this.awsRealTimeSocket = undefined;
335
+ this.socketStatus = SOCKET_STATUS.CLOSED;
336
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
337
+ }
338
+ }
339
+ _handleIncomingSubscriptionMessage(message) {
340
+ if (typeof message.data !== 'string') {
341
+ return;
342
+ }
343
+ logger.debug(`subscription message from AWS AppSync RealTime: ${message.data}`);
344
+ const { id = '', payload, type, } = JSON.parse(String(message.data));
345
+ const { observer = null, query = '', variables = {}, startAckTimeoutId, subscriptionReadyCallback, subscriptionFailedCallback, } = this.subscriptionObserverMap.get(id) || {};
346
+ logger.debug({ id, observer, query, variables });
347
+ if (type === MESSAGE_TYPES.GQL_DATA && payload && payload.data) {
348
+ if (observer) {
349
+ observer.next(payload);
350
+ }
351
+ else {
352
+ logger.debug(`observer not found for id: ${id}`);
353
+ }
354
+ return;
355
+ }
356
+ if (type === MESSAGE_TYPES.GQL_START_ACK) {
357
+ logger.debug(`subscription ready for ${JSON.stringify({ query, variables })}`);
358
+ if (typeof subscriptionReadyCallback === 'function') {
359
+ subscriptionReadyCallback();
360
+ }
361
+ if (startAckTimeoutId)
362
+ clearTimeout(startAckTimeoutId);
363
+ dispatchApiEvent({
364
+ event: CONTROL_MSG.SUBSCRIPTION_ACK,
365
+ data: { query, variables },
366
+ message: 'Connection established for subscription',
367
+ });
368
+ const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
369
+ if (observer) {
370
+ this.subscriptionObserverMap.set(id, {
371
+ observer,
372
+ query,
373
+ variables,
374
+ startAckTimeoutId: undefined,
375
+ subscriptionState,
376
+ subscriptionReadyCallback,
377
+ subscriptionFailedCallback,
378
+ });
379
+ }
380
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
381
+ return;
382
+ }
383
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
384
+ if (this.keepAliveTimeoutId)
385
+ clearTimeout(this.keepAliveTimeoutId);
386
+ if (this.keepAliveAlertTimeoutId)
387
+ clearTimeout(this.keepAliveAlertTimeoutId);
388
+ this.keepAliveTimeoutId = setTimeout(() => this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT), this.keepAliveTimeout);
389
+ this.keepAliveAlertTimeoutId = setTimeout(() => {
390
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
391
+ }, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
392
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);
393
+ return;
394
+ }
395
+ if (type === MESSAGE_TYPES.GQL_ERROR) {
396
+ const subscriptionState = SUBSCRIPTION_STATUS.FAILED;
397
+ if (observer) {
398
+ this.subscriptionObserverMap.set(id, {
399
+ observer,
400
+ query,
401
+ variables,
402
+ startAckTimeoutId,
403
+ subscriptionReadyCallback,
404
+ subscriptionFailedCallback,
405
+ subscriptionState,
406
+ });
407
+ logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`);
408
+ observer.error({
409
+ errors: [
410
+ {
411
+ ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`),
412
+ },
413
+ ],
414
+ });
415
+ if (startAckTimeoutId)
416
+ clearTimeout(startAckTimeoutId);
417
+ if (typeof subscriptionFailedCallback === 'function') {
418
+ subscriptionFailedCallback();
419
+ }
420
+ }
421
+ }
422
+ }
423
+ _errorDisconnect(msg) {
424
+ logger.debug(`Disconnect error: ${msg}`);
425
+ if (this.awsRealTimeSocket) {
426
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
427
+ this.awsRealTimeSocket.close();
428
+ }
429
+ this.socketStatus = SOCKET_STATUS.CLOSED;
430
+ }
431
+ _timeoutStartSubscriptionAck(subscriptionId) {
432
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
433
+ if (subscriptionObserver) {
434
+ const { observer, query, variables } = subscriptionObserver;
435
+ if (!observer) {
436
+ return;
437
+ }
438
+ this.subscriptionObserverMap.set(subscriptionId, {
439
+ observer,
440
+ query,
441
+ variables,
442
+ subscriptionState: SUBSCRIPTION_STATUS.FAILED,
443
+ });
444
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
445
+ logger.debug('timeoutStartSubscription', JSON.stringify({ query, variables }));
446
+ }
447
+ }
448
+ _initializeWebSocketConnection({ appSyncGraphqlEndpoint, authenticationType, apiKey, region, additionalHeaders, }) {
449
+ if (this.socketStatus === SOCKET_STATUS.READY) {
450
+ return;
451
+ }
452
+ return new Promise(async (res, rej) => {
453
+ this.promiseArray.push({ res, rej });
454
+ if (this.socketStatus === SOCKET_STATUS.CLOSED) {
455
+ try {
456
+ this.socketStatus = SOCKET_STATUS.CONNECTING;
457
+ const payloadString = '{}';
458
+ const authHeader = await this._awsRealTimeHeaderBasedAuth({
459
+ authenticationType,
460
+ payload: payloadString,
461
+ canonicalUri: '/connect',
462
+ apiKey,
463
+ appSyncGraphqlEndpoint,
464
+ region,
465
+ additionalHeaders,
466
+ });
467
+ const headerString = authHeader ? JSON.stringify(authHeader) : '';
468
+ const headerQs = base64Encoder.convert(headerString);
469
+ const payloadQs = base64Encoder.convert(payloadString);
470
+ let discoverableEndpoint = appSyncGraphqlEndpoint ?? '';
471
+ if (this.isCustomDomain(discoverableEndpoint)) {
472
+ discoverableEndpoint =
473
+ discoverableEndpoint.concat(customDomainPath);
474
+ }
475
+ else {
476
+ discoverableEndpoint = discoverableEndpoint
477
+ .replace('appsync-api', 'appsync-realtime-api')
478
+ .replace('gogi-beta', 'grt-beta');
479
+ }
480
+ // Creating websocket url with required query strings
481
+ const protocol = 'wss://';
482
+ discoverableEndpoint = discoverableEndpoint
483
+ .replace('https://', protocol)
484
+ .replace('http://', protocol);
485
+ const awsRealTimeUrl = `${discoverableEndpoint}?header=${headerQs}&payload=${payloadQs}`;
486
+ await this._initializeRetryableHandshake(awsRealTimeUrl);
487
+ this.promiseArray.forEach(({ res }) => {
488
+ logger.debug('Notifying connection successful');
489
+ res();
490
+ });
491
+ this.socketStatus = SOCKET_STATUS.READY;
492
+ this.promiseArray = [];
493
+ }
494
+ catch (err) {
495
+ logger.debug('Connection exited with', err);
496
+ this.promiseArray.forEach(({ rej }) => rej(err));
497
+ this.promiseArray = [];
498
+ if (this.awsRealTimeSocket &&
499
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
500
+ this.awsRealTimeSocket.close(3001);
501
+ }
502
+ this.awsRealTimeSocket = undefined;
503
+ this.socketStatus = SOCKET_STATUS.CLOSED;
504
+ }
505
+ }
506
+ });
507
+ }
508
+ async _initializeRetryableHandshake(awsRealTimeUrl) {
509
+ logger.debug(`Initializaling retryable Handshake`);
510
+ await jitteredExponentialRetry(this._initializeHandshake.bind(this), [awsRealTimeUrl], MAX_DELAY_MS);
511
+ }
512
+ async _initializeHandshake(awsRealTimeUrl) {
513
+ logger.debug(`Initializing handshake ${awsRealTimeUrl}`);
514
+ // Because connecting the socket is async, is waiting until connection is open
515
+ // Step 1: connect websocket
516
+ try {
517
+ await (() => {
518
+ return new Promise((res, rej) => {
519
+ const newSocket = this.getNewWebSocket(awsRealTimeUrl, 'graphql-ws');
520
+ newSocket.onerror = () => {
521
+ logger.debug(`WebSocket connection error`);
522
+ };
523
+ newSocket.onclose = () => {
524
+ rej(new Error('Connection handshake error'));
525
+ };
526
+ newSocket.onopen = () => {
527
+ this.awsRealTimeSocket = newSocket;
528
+ return res();
529
+ };
530
+ });
531
+ })();
532
+ // Step 2: wait for ack from AWS AppSyncReaTime after sending init
533
+ await (() => {
534
+ return new Promise((res, rej) => {
535
+ if (this.awsRealTimeSocket) {
536
+ let ackOk = false;
537
+ this.awsRealTimeSocket.onerror = error => {
538
+ logger.debug(`WebSocket error ${JSON.stringify(error)}`);
539
+ };
540
+ this.awsRealTimeSocket.onclose = event => {
541
+ logger.debug(`WebSocket closed ${event.reason}`);
542
+ rej(new Error(JSON.stringify(event)));
543
+ };
544
+ this.awsRealTimeSocket.onmessage = (message) => {
545
+ if (typeof message.data !== 'string') {
546
+ return;
547
+ }
548
+ logger.debug(`subscription message from AWS AppSyncRealTime: ${message.data} `);
549
+ const data = JSON.parse(message.data);
550
+ const { type, payload: { connectionTimeoutMs = DEFAULT_KEEP_ALIVE_TIMEOUT, } = {}, } = data;
551
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
552
+ ackOk = true;
553
+ if (this.awsRealTimeSocket) {
554
+ this.keepAliveTimeout = connectionTimeoutMs;
555
+ this.awsRealTimeSocket.onmessage =
556
+ this._handleIncomingSubscriptionMessage.bind(this);
557
+ this.awsRealTimeSocket.onerror = err => {
558
+ logger.debug(err);
559
+ this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
560
+ };
561
+ this.awsRealTimeSocket.onclose = event => {
562
+ logger.debug(`WebSocket closed ${event.reason}`);
563
+ this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
564
+ };
565
+ }
566
+ res('Cool, connected to AWS AppSyncRealTime');
567
+ return;
568
+ }
569
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
570
+ const { payload: { errors: [{ errorType = '', errorCode = 0 } = {}] = [], } = {}, } = data;
571
+ rej({ errorType, errorCode });
572
+ }
573
+ };
574
+ const gqlInit = {
575
+ type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
576
+ };
577
+ this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
578
+ const checkAckOk = (ackOk) => {
579
+ if (!ackOk) {
580
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
581
+ rej(new Error(`Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`));
582
+ }
583
+ };
584
+ setTimeout(() => checkAckOk(ackOk), CONNECTION_INIT_TIMEOUT);
585
+ }
586
+ });
587
+ })();
588
+ }
589
+ catch (err) {
590
+ const { errorType, errorCode } = err;
591
+ if (NON_RETRYABLE_CODES.includes(errorCode)) {
592
+ throw new NonRetryableError(errorType);
593
+ }
594
+ else if (errorType) {
595
+ throw new Error(errorType);
596
+ }
597
+ else {
598
+ throw err;
599
+ }
600
+ }
601
+ }
602
+ async _awsRealTimeHeaderBasedAuth({ apiKey, authenticationType, payload, canonicalUri, appSyncGraphqlEndpoint, region, additionalHeaders, }) {
603
+ const headerHandler = {
604
+ apiKey: this._awsRealTimeApiKeyHeader.bind(this),
605
+ iam: this._awsRealTimeIAMHeader.bind(this),
606
+ oidc: this._awsAuthTokenHeader.bind(this),
607
+ userPool: this._awsAuthTokenHeader.bind(this),
608
+ lambda: this._customAuthHeader,
609
+ none: this._customAuthHeader,
610
+ };
611
+ if (!authenticationType || !headerHandler[authenticationType]) {
612
+ logger.debug(`Authentication type ${authenticationType} not supported`);
613
+ return undefined;
614
+ }
615
+ else {
616
+ const handler = headerHandler[authenticationType];
617
+ const host = appSyncGraphqlEndpoint
618
+ ? new AmplifyUrl(appSyncGraphqlEndpoint).host
619
+ : undefined;
620
+ logger.debug(`Authenticating with ${JSON.stringify(authenticationType)}`);
621
+ let resolvedApiKey;
622
+ if (authenticationType === 'apiKey') {
623
+ resolvedApiKey = apiKey;
624
+ }
625
+ const result = await handler({
626
+ payload,
627
+ canonicalUri,
628
+ appSyncGraphqlEndpoint,
629
+ apiKey: resolvedApiKey,
630
+ region,
631
+ host,
632
+ additionalHeaders,
633
+ });
634
+ return result;
635
+ }
636
+ }
637
+ async _awsAuthTokenHeader({ host }) {
638
+ const session = await fetchAuthSession();
639
+ return {
640
+ Authorization: session?.tokens?.accessToken?.toString(),
641
+ host,
642
+ };
643
+ }
644
+ async _awsRealTimeApiKeyHeader({ apiKey, host, }) {
645
+ const dt = new Date();
646
+ const dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, '');
647
+ return {
648
+ host,
649
+ 'x-amz-date': dtStr,
650
+ 'x-api-key': apiKey,
651
+ };
652
+ }
653
+ async _awsRealTimeIAMHeader({ payload, canonicalUri, appSyncGraphqlEndpoint, region, }) {
654
+ const endpointInfo = {
655
+ region,
656
+ service: 'appsync',
657
+ };
658
+ const creds = (await fetchAuthSession()).credentials;
659
+ const request = {
660
+ url: `${appSyncGraphqlEndpoint}${canonicalUri}`,
661
+ data: payload,
662
+ method: 'POST',
663
+ headers: { ...AWS_APPSYNC_REALTIME_HEADERS },
664
+ };
665
+ const signed_params = signRequest({
666
+ headers: request.headers,
667
+ method: request.method,
668
+ url: new AmplifyUrl(request.url),
669
+ body: request.data,
670
+ }, {
671
+ // TODO: What do we need to do to remove these !'s?
672
+ credentials: creds,
673
+ signingRegion: endpointInfo.region,
674
+ signingService: endpointInfo.service,
675
+ });
676
+ return signed_params.headers;
677
+ }
678
+ _customAuthHeader({ host, additionalHeaders, }) {
679
+ if (!additionalHeaders?.['Authorization']) {
680
+ throw new Error('No auth token specified');
681
+ }
682
+ return {
683
+ Authorization: additionalHeaders.Authorization,
684
+ host,
685
+ };
686
+ }
687
+ }