@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,998 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { Observable, SubscriptionLike } 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 {
8
+ base64Encoder,
9
+ GraphQLAuthMode,
10
+ CustomUserAgentDetails,
11
+ NonRetryableError,
12
+ USER_AGENT_HEADER,
13
+ getAmplifyUserAgent,
14
+ isNonRetryableError,
15
+ jitteredExponentialRetry,
16
+ DocumentType,
17
+ amplifyUuid,
18
+ AmplifyUrl,
19
+ } from '@aws-amplify/core/internals/utils';
20
+
21
+ import {
22
+ CONTROL_MSG,
23
+ ConnectionState,
24
+ PubSubContentObserver,
25
+ } from '../../types/PubSub';
26
+ import {
27
+ AMPLIFY_SYMBOL,
28
+ AWS_APPSYNC_REALTIME_HEADERS,
29
+ CONNECTION_INIT_TIMEOUT,
30
+ DEFAULT_KEEP_ALIVE_TIMEOUT,
31
+ DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT,
32
+ MAX_DELAY_MS,
33
+ MESSAGE_TYPES,
34
+ NON_RETRYABLE_CODES,
35
+ SOCKET_STATUS,
36
+ START_ACK_TIMEOUT,
37
+ SUBSCRIPTION_STATUS,
38
+ CONNECTION_STATE_CHANGE,
39
+ } from '../constants';
40
+ import {
41
+ ConnectionStateMonitor,
42
+ CONNECTION_CHANGE,
43
+ } from '../../utils/ConnectionStateMonitor';
44
+ import {
45
+ ReconnectEvent,
46
+ ReconnectionMonitor,
47
+ } from '../../utils/ReconnectionMonitor';
48
+
49
+ const logger = new ConsoleLogger('AWSAppSyncRealTimeProvider');
50
+
51
+ const dispatchApiEvent = payload => {
52
+ Hub.dispatch('api', payload, 'PubSub', AMPLIFY_SYMBOL);
53
+ };
54
+
55
+ export type ObserverQuery = {
56
+ observer: PubSubContentObserver;
57
+ query: string;
58
+ variables: Record<string, DocumentType>;
59
+ subscriptionState: SUBSCRIPTION_STATUS;
60
+ subscriptionReadyCallback?: Function;
61
+ subscriptionFailedCallback?: Function;
62
+ startAckTimeoutId?: ReturnType<typeof setTimeout>;
63
+ };
64
+
65
+ const standardDomainPattern =
66
+ /^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com(?:\.cn)?\/graphql$/i;
67
+
68
+ const customDomainPath = '/realtime';
69
+
70
+ type DataObject = {
71
+ data: Record<string, unknown>;
72
+ };
73
+
74
+ type DataPayload = {
75
+ id: string;
76
+ payload: DataObject;
77
+ type: string;
78
+ };
79
+
80
+ type ParsedMessagePayload = {
81
+ type: string;
82
+ payload: {
83
+ connectionTimeoutMs: number;
84
+ errors?: [{ errorType: string; errorCode: number }];
85
+ };
86
+ };
87
+
88
+ export interface AWSAppSyncRealTimeProviderOptions {
89
+ appSyncGraphqlEndpoint?: string;
90
+ authenticationType?: GraphQLAuthMode;
91
+ query?: string;
92
+ variables?: Record<string, DocumentType>;
93
+ apiKey?: string;
94
+ region?: string;
95
+ graphql_headers?: () => {} | (() => Promise<{}>);
96
+ additionalHeaders?: { [key: string]: string };
97
+ }
98
+
99
+ type AWSAppSyncRealTimeAuthInput =
100
+ Partial<AWSAppSyncRealTimeProviderOptions> & {
101
+ canonicalUri: string;
102
+ payload: string;
103
+ host?: string | undefined;
104
+ };
105
+
106
+ export class AWSAppSyncRealTimeProvider {
107
+ private awsRealTimeSocket?: WebSocket;
108
+ private socketStatus: SOCKET_STATUS = SOCKET_STATUS.CLOSED;
109
+ private keepAliveTimeoutId?: ReturnType<typeof setTimeout>;
110
+ private keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
111
+ private keepAliveAlertTimeoutId?: ReturnType<typeof setTimeout>;
112
+ private subscriptionObserverMap: Map<string, ObserverQuery> = new Map();
113
+ private promiseArray: Array<{ res: Function; rej: Function }> = [];
114
+ private connectionState: ConnectionState;
115
+ private readonly connectionStateMonitor = new ConnectionStateMonitor();
116
+ private readonly reconnectionMonitor = new ReconnectionMonitor();
117
+ private connectionStateMonitorSubscription: SubscriptionLike;
118
+
119
+ constructor(options: AWSAppSyncRealTimeProviderOptions = {}) {
120
+ // Monitor the connection state and pass changes along to Hub
121
+ this.connectionStateMonitorSubscription =
122
+ this.connectionStateMonitor.connectionStateObservable.subscribe(
123
+ connectionState => {
124
+ dispatchApiEvent({
125
+ event: CONNECTION_STATE_CHANGE,
126
+ data: {
127
+ provider: this,
128
+ connectionState,
129
+ },
130
+ message: `Connection state is ${connectionState}`,
131
+ });
132
+ this.connectionState = connectionState;
133
+
134
+ // Trigger START_RECONNECT when the connection is disrupted
135
+ if (connectionState === ConnectionState.ConnectionDisrupted) {
136
+ this.reconnectionMonitor.record(ReconnectEvent.START_RECONNECT);
137
+ }
138
+
139
+ // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
140
+ // ConnectionDisrupted or Connecting
141
+ if (
142
+ [
143
+ ConnectionState.Connected,
144
+ ConnectionState.ConnectedPendingDisconnect,
145
+ ConnectionState.ConnectedPendingKeepAlive,
146
+ ConnectionState.ConnectedPendingNetwork,
147
+ ConnectionState.ConnectionDisruptedPendingNetwork,
148
+ ConnectionState.Disconnected,
149
+ ].includes(connectionState)
150
+ ) {
151
+ this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT);
152
+ }
153
+ }
154
+ );
155
+ }
156
+
157
+ /**
158
+ * Mark the socket closed and release all active listeners
159
+ */
160
+ close() {
161
+ // Mark the socket closed both in status and the connection monitor
162
+ this.socketStatus = SOCKET_STATUS.CLOSED;
163
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
164
+
165
+ // Turn off the subscription monitor Hub publishing
166
+ this.connectionStateMonitorSubscription.unsubscribe();
167
+ // Complete all reconnect observers
168
+ this.reconnectionMonitor.close();
169
+ }
170
+
171
+ getNewWebSocket(url: string, protocol: string) {
172
+ return new WebSocket(url, protocol);
173
+ }
174
+
175
+ getProviderName() {
176
+ return 'AWSAppSyncRealTimeProvider';
177
+ }
178
+
179
+ // Check if url matches standard domain pattern
180
+ private isCustomDomain(url: string): boolean {
181
+ return url.match(standardDomainPattern) === null;
182
+ }
183
+
184
+ subscribe(
185
+ options?: AWSAppSyncRealTimeProviderOptions,
186
+ customUserAgentDetails?: CustomUserAgentDetails
187
+ ): Observable<Record<string, unknown>> {
188
+ const {
189
+ appSyncGraphqlEndpoint,
190
+ region,
191
+ query,
192
+ variables,
193
+ authenticationType,
194
+ additionalHeaders,
195
+ apiKey,
196
+ } = options || {};
197
+
198
+ return new Observable(observer => {
199
+ if (!options || !appSyncGraphqlEndpoint) {
200
+ observer.error({
201
+ errors: [
202
+ {
203
+ ...new GraphQLError(
204
+ `Subscribe only available for AWS AppSync endpoint`
205
+ ),
206
+ },
207
+ ],
208
+ });
209
+ observer.complete();
210
+ } else {
211
+ let subscriptionStartActive = false;
212
+ const subscriptionId = amplifyUuid();
213
+ const startSubscription = () => {
214
+ if (!subscriptionStartActive) {
215
+ subscriptionStartActive = true;
216
+
217
+ const startSubscriptionPromise =
218
+ this._startSubscriptionWithAWSAppSyncRealTime({
219
+ options: {
220
+ query,
221
+ variables,
222
+ region,
223
+ authenticationType,
224
+ appSyncGraphqlEndpoint,
225
+ additionalHeaders,
226
+ apiKey,
227
+ },
228
+ observer,
229
+ subscriptionId,
230
+ customUserAgentDetails,
231
+ }).catch<any>(err => {
232
+ logger.debug(
233
+ `${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`
234
+ );
235
+
236
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
237
+ });
238
+ startSubscriptionPromise.finally(() => {
239
+ subscriptionStartActive = false;
240
+ });
241
+ }
242
+ };
243
+
244
+ let reconnectSubscription: SubscriptionLike;
245
+
246
+ // Add an observable to the reconnection list to manage reconnection for this subscription
247
+ reconnectSubscription = new Observable(observer => {
248
+ this.reconnectionMonitor.addObserver(observer);
249
+ }).subscribe(() => {
250
+ startSubscription();
251
+ });
252
+
253
+ startSubscription();
254
+
255
+ return async () => {
256
+ // Cleanup reconnection subscription
257
+ reconnectSubscription?.unsubscribe();
258
+
259
+ // Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
260
+ try {
261
+ // Waiting that subscription has been connected before trying to unsubscribe
262
+ await this._waitForSubscriptionToBeConnected(subscriptionId);
263
+
264
+ const { subscriptionState } =
265
+ this.subscriptionObserverMap.get(subscriptionId) || {};
266
+
267
+ if (!subscriptionState) {
268
+ // subscription already unsubscribed
269
+ return;
270
+ }
271
+
272
+ if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {
273
+ this._sendUnsubscriptionMessage(subscriptionId);
274
+ } else {
275
+ throw new Error('Subscription never connected');
276
+ }
277
+ } catch (err) {
278
+ logger.debug(`Error while unsubscribing ${err}`);
279
+ } finally {
280
+ this._removeSubscriptionObserver(subscriptionId);
281
+ }
282
+ };
283
+ }
284
+ });
285
+ }
286
+
287
+ private async _startSubscriptionWithAWSAppSyncRealTime({
288
+ options,
289
+ observer,
290
+ subscriptionId,
291
+ customUserAgentDetails,
292
+ }: {
293
+ options: AWSAppSyncRealTimeProviderOptions;
294
+ observer: PubSubContentObserver;
295
+ subscriptionId: string;
296
+ customUserAgentDetails: CustomUserAgentDetails | undefined;
297
+ }) {
298
+ const {
299
+ appSyncGraphqlEndpoint,
300
+ authenticationType,
301
+ query,
302
+ variables,
303
+ apiKey,
304
+ region,
305
+ graphql_headers = () => ({}),
306
+ additionalHeaders = {},
307
+ } = options;
308
+
309
+ const subscriptionState: SUBSCRIPTION_STATUS = SUBSCRIPTION_STATUS.PENDING;
310
+ const data = {
311
+ query,
312
+ variables,
313
+ };
314
+ // Having a subscription id map will make it simple to forward messages received
315
+ this.subscriptionObserverMap.set(subscriptionId, {
316
+ observer,
317
+ query: query ?? '',
318
+ variables: variables ?? {},
319
+ subscriptionState,
320
+ startAckTimeoutId: undefined,
321
+ });
322
+
323
+ // Preparing payload for subscription message
324
+
325
+ const dataString = JSON.stringify(data);
326
+ const headerObj = {
327
+ ...(await this._awsRealTimeHeaderBasedAuth({
328
+ apiKey,
329
+ appSyncGraphqlEndpoint,
330
+ authenticationType,
331
+ payload: dataString,
332
+ canonicalUri: '',
333
+ region,
334
+ additionalHeaders,
335
+ })),
336
+ ...(await graphql_headers()),
337
+ ...additionalHeaders,
338
+ [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
339
+ };
340
+
341
+ const subscriptionMessage = {
342
+ id: subscriptionId,
343
+ payload: {
344
+ data: dataString,
345
+ extensions: {
346
+ authorization: {
347
+ ...headerObj,
348
+ },
349
+ },
350
+ },
351
+ type: MESSAGE_TYPES.GQL_START,
352
+ };
353
+
354
+ const stringToAWSRealTime = JSON.stringify(subscriptionMessage);
355
+
356
+ try {
357
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
358
+ await this._initializeWebSocketConnection({
359
+ apiKey,
360
+ appSyncGraphqlEndpoint,
361
+ authenticationType,
362
+ region,
363
+ additionalHeaders,
364
+ });
365
+ } catch (err) {
366
+ this._logStartSubscriptionError(subscriptionId, observer, err);
367
+ return;
368
+ }
369
+
370
+ // Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
371
+ // E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
372
+ // Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
373
+
374
+ const { subscriptionFailedCallback, subscriptionReadyCallback } =
375
+ this.subscriptionObserverMap.get(subscriptionId) ?? {};
376
+
377
+ // This must be done before sending the message in order to be listening immediately
378
+ this.subscriptionObserverMap.set(subscriptionId, {
379
+ observer,
380
+ subscriptionState,
381
+ query: query ?? '',
382
+ variables: variables ?? {},
383
+ subscriptionReadyCallback,
384
+ subscriptionFailedCallback,
385
+ startAckTimeoutId: setTimeout(() => {
386
+ this._timeoutStartSubscriptionAck.call(this, subscriptionId);
387
+ }, START_ACK_TIMEOUT),
388
+ });
389
+ if (this.awsRealTimeSocket) {
390
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
391
+ }
392
+ }
393
+
394
+ // Log logic for start subscription failures
395
+ private _logStartSubscriptionError(
396
+ subscriptionId: string,
397
+ observer: PubSubContentObserver,
398
+ err: { message?: string }
399
+ ) {
400
+ logger.debug({ err });
401
+ const message = String(err.message ?? '');
402
+ // Resolving to give the state observer time to propogate the update
403
+ Promise.resolve(
404
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED)
405
+ );
406
+
407
+ // Capture the error only when the network didn't cause disruption
408
+ if (
409
+ this.connectionState !== ConnectionState.ConnectionDisruptedPendingNetwork
410
+ ) {
411
+ // When the error is non-retriable, error out the observable
412
+ if (isNonRetryableError(err)) {
413
+ observer.error({
414
+ errors: [
415
+ {
416
+ ...new GraphQLError(
417
+ `${CONTROL_MSG.CONNECTION_FAILED}: ${message}`
418
+ ),
419
+ },
420
+ ],
421
+ });
422
+ } else {
423
+ logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
424
+ }
425
+
426
+ const { subscriptionFailedCallback } =
427
+ this.subscriptionObserverMap.get(subscriptionId) || {};
428
+
429
+ // Notify concurrent unsubscription
430
+ if (typeof subscriptionFailedCallback === 'function') {
431
+ subscriptionFailedCallback();
432
+ }
433
+ }
434
+ }
435
+
436
+ // Waiting that subscription has been connected before trying to unsubscribe
437
+ private async _waitForSubscriptionToBeConnected(subscriptionId: string) {
438
+ const subscriptionObserver =
439
+ this.subscriptionObserverMap.get(subscriptionId);
440
+ if (subscriptionObserver) {
441
+ const { subscriptionState } = subscriptionObserver;
442
+ // This in case unsubscribe is invoked before sending start subscription message
443
+ if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
444
+ return new Promise((res, rej) => {
445
+ const { observer, subscriptionState, variables, query } =
446
+ subscriptionObserver;
447
+ this.subscriptionObserverMap.set(subscriptionId, {
448
+ observer,
449
+ subscriptionState,
450
+ variables,
451
+ query,
452
+ subscriptionReadyCallback: res,
453
+ subscriptionFailedCallback: rej,
454
+ });
455
+ });
456
+ }
457
+ }
458
+ }
459
+
460
+ private _sendUnsubscriptionMessage(subscriptionId: string) {
461
+ try {
462
+ if (
463
+ this.awsRealTimeSocket &&
464
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
465
+ this.socketStatus === SOCKET_STATUS.READY
466
+ ) {
467
+ // Preparing unsubscribe message to stop receiving messages for that subscription
468
+ const unsubscribeMessage = {
469
+ id: subscriptionId,
470
+ type: MESSAGE_TYPES.GQL_STOP,
471
+ };
472
+ const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
473
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
474
+ }
475
+ } catch (err) {
476
+ // If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
477
+ logger.debug({ err });
478
+ }
479
+ }
480
+
481
+ private _removeSubscriptionObserver(subscriptionId: string) {
482
+ this.subscriptionObserverMap.delete(subscriptionId);
483
+
484
+ // Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
485
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
486
+ }
487
+
488
+ private _closeSocketIfRequired() {
489
+ if (this.subscriptionObserverMap.size > 0) {
490
+ // Active subscriptions on the WebSocket
491
+ return;
492
+ }
493
+
494
+ if (!this.awsRealTimeSocket) {
495
+ this.socketStatus = SOCKET_STATUS.CLOSED;
496
+ return;
497
+ }
498
+
499
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
500
+
501
+ if (this.awsRealTimeSocket.bufferedAmount > 0) {
502
+ // Still data on the WebSocket
503
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
504
+ } else {
505
+ logger.debug('closing WebSocket...');
506
+ if (this.keepAliveTimeoutId) {
507
+ clearTimeout(this.keepAliveTimeoutId);
508
+ }
509
+ if (this.keepAliveAlertTimeoutId) {
510
+ clearTimeout(this.keepAliveAlertTimeoutId);
511
+ }
512
+ const tempSocket = this.awsRealTimeSocket;
513
+ // Cleaning callbacks to avoid race condition, socket still exists
514
+ tempSocket.onclose = null;
515
+ tempSocket.onerror = null;
516
+ tempSocket.close(1000);
517
+ this.awsRealTimeSocket = undefined;
518
+ this.socketStatus = SOCKET_STATUS.CLOSED;
519
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
520
+ }
521
+ }
522
+
523
+ private _handleIncomingSubscriptionMessage(message: MessageEvent) {
524
+ if (typeof message.data !== 'string') {
525
+ return;
526
+ }
527
+ logger.debug(
528
+ `subscription message from AWS AppSync RealTime: ${message.data}`
529
+ );
530
+ const {
531
+ id = '',
532
+ payload,
533
+ type,
534
+ }: DataPayload = JSON.parse(String(message.data));
535
+ const {
536
+ observer = null,
537
+ query = '',
538
+ variables = {},
539
+ startAckTimeoutId,
540
+ subscriptionReadyCallback,
541
+ subscriptionFailedCallback,
542
+ } = this.subscriptionObserverMap.get(id) || {};
543
+
544
+ logger.debug({ id, observer, query, variables });
545
+
546
+ if (type === MESSAGE_TYPES.GQL_DATA && payload && payload.data) {
547
+ if (observer) {
548
+ observer.next(payload);
549
+ } else {
550
+ logger.debug(`observer not found for id: ${id}`);
551
+ }
552
+ return;
553
+ }
554
+
555
+ if (type === MESSAGE_TYPES.GQL_START_ACK) {
556
+ logger.debug(
557
+ `subscription ready for ${JSON.stringify({ query, variables })}`
558
+ );
559
+ if (typeof subscriptionReadyCallback === 'function') {
560
+ subscriptionReadyCallback();
561
+ }
562
+ if (startAckTimeoutId) clearTimeout(startAckTimeoutId);
563
+ dispatchApiEvent({
564
+ event: CONTROL_MSG.SUBSCRIPTION_ACK,
565
+ data: { query, variables },
566
+ message: 'Connection established for subscription',
567
+ });
568
+ const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
569
+ if (observer) {
570
+ this.subscriptionObserverMap.set(id, {
571
+ observer,
572
+ query,
573
+ variables,
574
+ startAckTimeoutId: undefined,
575
+ subscriptionState,
576
+ subscriptionReadyCallback,
577
+ subscriptionFailedCallback,
578
+ });
579
+ }
580
+ this.connectionStateMonitor.record(
581
+ CONNECTION_CHANGE.CONNECTION_ESTABLISHED
582
+ );
583
+
584
+ return;
585
+ }
586
+
587
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
588
+ if (this.keepAliveTimeoutId) clearTimeout(this.keepAliveTimeoutId);
589
+ if (this.keepAliveAlertTimeoutId)
590
+ clearTimeout(this.keepAliveAlertTimeoutId);
591
+ this.keepAliveTimeoutId = setTimeout(
592
+ () => this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT),
593
+ this.keepAliveTimeout
594
+ );
595
+ this.keepAliveAlertTimeoutId = setTimeout(() => {
596
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
597
+ }, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
598
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);
599
+ return;
600
+ }
601
+
602
+ if (type === MESSAGE_TYPES.GQL_ERROR) {
603
+ const subscriptionState = SUBSCRIPTION_STATUS.FAILED;
604
+ if (observer) {
605
+ this.subscriptionObserverMap.set(id, {
606
+ observer,
607
+ query,
608
+ variables,
609
+ startAckTimeoutId,
610
+ subscriptionReadyCallback,
611
+ subscriptionFailedCallback,
612
+ subscriptionState,
613
+ });
614
+
615
+ logger.debug(
616
+ `${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`
617
+ );
618
+
619
+ observer.error({
620
+ errors: [
621
+ {
622
+ ...new GraphQLError(
623
+ `${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`
624
+ ),
625
+ },
626
+ ],
627
+ });
628
+
629
+ if (startAckTimeoutId) clearTimeout(startAckTimeoutId);
630
+
631
+ if (typeof subscriptionFailedCallback === 'function') {
632
+ subscriptionFailedCallback();
633
+ }
634
+ }
635
+ }
636
+ }
637
+
638
+ private _errorDisconnect(msg: string) {
639
+ logger.debug(`Disconnect error: ${msg}`);
640
+
641
+ if (this.awsRealTimeSocket) {
642
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
643
+ this.awsRealTimeSocket.close();
644
+ }
645
+
646
+ this.socketStatus = SOCKET_STATUS.CLOSED;
647
+ }
648
+
649
+ private _timeoutStartSubscriptionAck(subscriptionId: string) {
650
+ const subscriptionObserver =
651
+ this.subscriptionObserverMap.get(subscriptionId);
652
+ if (subscriptionObserver) {
653
+ const { observer, query, variables } = subscriptionObserver;
654
+ if (!observer) {
655
+ return;
656
+ }
657
+ this.subscriptionObserverMap.set(subscriptionId, {
658
+ observer,
659
+ query,
660
+ variables,
661
+ subscriptionState: SUBSCRIPTION_STATUS.FAILED,
662
+ });
663
+
664
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
665
+ logger.debug(
666
+ 'timeoutStartSubscription',
667
+ JSON.stringify({ query, variables })
668
+ );
669
+ }
670
+ }
671
+
672
+ private _initializeWebSocketConnection({
673
+ appSyncGraphqlEndpoint,
674
+ authenticationType,
675
+ apiKey,
676
+ region,
677
+ additionalHeaders,
678
+ }: AWSAppSyncRealTimeProviderOptions) {
679
+ if (this.socketStatus === SOCKET_STATUS.READY) {
680
+ return;
681
+ }
682
+ return new Promise(async (res, rej) => {
683
+ this.promiseArray.push({ res, rej });
684
+
685
+ if (this.socketStatus === SOCKET_STATUS.CLOSED) {
686
+ try {
687
+ this.socketStatus = SOCKET_STATUS.CONNECTING;
688
+
689
+ const payloadString = '{}';
690
+
691
+ const authHeader = await this._awsRealTimeHeaderBasedAuth({
692
+ authenticationType,
693
+ payload: payloadString,
694
+ canonicalUri: '/connect',
695
+ apiKey,
696
+ appSyncGraphqlEndpoint,
697
+ region,
698
+ additionalHeaders,
699
+ });
700
+
701
+ const headerString = authHeader ? JSON.stringify(authHeader) : '';
702
+ const headerQs = base64Encoder.convert(headerString);
703
+
704
+ const payloadQs = base64Encoder.convert(payloadString);
705
+
706
+ let discoverableEndpoint = appSyncGraphqlEndpoint ?? '';
707
+
708
+ if (this.isCustomDomain(discoverableEndpoint)) {
709
+ discoverableEndpoint =
710
+ discoverableEndpoint.concat(customDomainPath);
711
+ } else {
712
+ discoverableEndpoint = discoverableEndpoint
713
+ .replace('appsync-api', 'appsync-realtime-api')
714
+ .replace('gogi-beta', 'grt-beta');
715
+ }
716
+
717
+ // Creating websocket url with required query strings
718
+ const protocol = 'wss://';
719
+ discoverableEndpoint = discoverableEndpoint
720
+ .replace('https://', protocol)
721
+ .replace('http://', protocol);
722
+
723
+ const awsRealTimeUrl = `${discoverableEndpoint}?header=${headerQs}&payload=${payloadQs}`;
724
+
725
+ await this._initializeRetryableHandshake(awsRealTimeUrl);
726
+
727
+ this.promiseArray.forEach(({ res }) => {
728
+ logger.debug('Notifying connection successful');
729
+ res();
730
+ });
731
+ this.socketStatus = SOCKET_STATUS.READY;
732
+ this.promiseArray = [];
733
+ } catch (err) {
734
+ logger.debug('Connection exited with', err);
735
+ this.promiseArray.forEach(({ rej }) => rej(err));
736
+ this.promiseArray = [];
737
+ if (
738
+ this.awsRealTimeSocket &&
739
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN
740
+ ) {
741
+ this.awsRealTimeSocket.close(3001);
742
+ }
743
+ this.awsRealTimeSocket = undefined;
744
+ this.socketStatus = SOCKET_STATUS.CLOSED;
745
+ }
746
+ }
747
+ });
748
+ }
749
+
750
+ private async _initializeRetryableHandshake(awsRealTimeUrl: string) {
751
+ logger.debug(`Initializaling retryable Handshake`);
752
+ await jitteredExponentialRetry(
753
+ this._initializeHandshake.bind(this),
754
+ [awsRealTimeUrl],
755
+ MAX_DELAY_MS
756
+ );
757
+ }
758
+
759
+ private async _initializeHandshake(awsRealTimeUrl: string) {
760
+ logger.debug(`Initializing handshake ${awsRealTimeUrl}`);
761
+ // Because connecting the socket is async, is waiting until connection is open
762
+ // Step 1: connect websocket
763
+ try {
764
+ await (() => {
765
+ return new Promise<void>((res, rej) => {
766
+ const newSocket = this.getNewWebSocket(awsRealTimeUrl, 'graphql-ws');
767
+ newSocket.onerror = () => {
768
+ logger.debug(`WebSocket connection error`);
769
+ };
770
+ newSocket.onclose = () => {
771
+ rej(new Error('Connection handshake error'));
772
+ };
773
+ newSocket.onopen = () => {
774
+ this.awsRealTimeSocket = newSocket;
775
+ return res();
776
+ };
777
+ });
778
+ })();
779
+ // Step 2: wait for ack from AWS AppSyncReaTime after sending init
780
+ await (() => {
781
+ return new Promise((res, rej) => {
782
+ if (this.awsRealTimeSocket) {
783
+ let ackOk = false;
784
+ this.awsRealTimeSocket.onerror = error => {
785
+ logger.debug(`WebSocket error ${JSON.stringify(error)}`);
786
+ };
787
+ this.awsRealTimeSocket.onclose = event => {
788
+ logger.debug(`WebSocket closed ${event.reason}`);
789
+ rej(new Error(JSON.stringify(event)));
790
+ };
791
+
792
+ this.awsRealTimeSocket.onmessage = (message: MessageEvent) => {
793
+ if (typeof message.data !== 'string') {
794
+ return;
795
+ }
796
+ logger.debug(
797
+ `subscription message from AWS AppSyncRealTime: ${message.data} `
798
+ );
799
+ const data = JSON.parse(message.data) as ParsedMessagePayload;
800
+ const {
801
+ type,
802
+ payload: {
803
+ connectionTimeoutMs = DEFAULT_KEEP_ALIVE_TIMEOUT,
804
+ } = {},
805
+ } = data;
806
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
807
+ ackOk = true;
808
+ if (this.awsRealTimeSocket) {
809
+ this.keepAliveTimeout = connectionTimeoutMs;
810
+ this.awsRealTimeSocket.onmessage =
811
+ this._handleIncomingSubscriptionMessage.bind(this);
812
+ this.awsRealTimeSocket.onerror = err => {
813
+ logger.debug(err);
814
+ this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
815
+ };
816
+ this.awsRealTimeSocket.onclose = event => {
817
+ logger.debug(`WebSocket closed ${event.reason}`);
818
+ this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
819
+ };
820
+ }
821
+ res('Cool, connected to AWS AppSyncRealTime');
822
+ return;
823
+ }
824
+
825
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
826
+ const {
827
+ payload: {
828
+ errors: [{ errorType = '', errorCode = 0 } = {}] = [],
829
+ } = {},
830
+ } = data;
831
+
832
+ rej({ errorType, errorCode });
833
+ }
834
+ };
835
+
836
+ const gqlInit = {
837
+ type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
838
+ };
839
+ this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
840
+
841
+ const checkAckOk = (ackOk: boolean) => {
842
+ if (!ackOk) {
843
+ this.connectionStateMonitor.record(
844
+ CONNECTION_CHANGE.CONNECTION_FAILED
845
+ );
846
+ rej(
847
+ new Error(
848
+ `Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`
849
+ )
850
+ );
851
+ }
852
+ };
853
+
854
+ setTimeout(() => checkAckOk(ackOk), CONNECTION_INIT_TIMEOUT);
855
+ }
856
+ });
857
+ })();
858
+ } catch (err) {
859
+ const { errorType, errorCode } = err as {
860
+ errorType: string;
861
+ errorCode: number;
862
+ };
863
+
864
+ if (NON_RETRYABLE_CODES.includes(errorCode)) {
865
+ throw new NonRetryableError(errorType);
866
+ } else if (errorType) {
867
+ throw new Error(errorType);
868
+ } else {
869
+ throw err;
870
+ }
871
+ }
872
+ }
873
+
874
+ private async _awsRealTimeHeaderBasedAuth({
875
+ apiKey,
876
+ authenticationType,
877
+ payload,
878
+ canonicalUri,
879
+ appSyncGraphqlEndpoint,
880
+ region,
881
+ additionalHeaders,
882
+ }: AWSAppSyncRealTimeAuthInput): Promise<
883
+ Record<string, unknown> | undefined
884
+ > {
885
+ const headerHandler: {
886
+ [key in GraphQLAuthMode]: (arg0: AWSAppSyncRealTimeAuthInput) => {};
887
+ } = {
888
+ apiKey: this._awsRealTimeApiKeyHeader.bind(this),
889
+ iam: this._awsRealTimeIAMHeader.bind(this),
890
+ oidc: this._awsAuthTokenHeader.bind(this),
891
+ userPool: this._awsAuthTokenHeader.bind(this),
892
+ lambda: this._customAuthHeader,
893
+ none: this._customAuthHeader,
894
+ };
895
+
896
+ if (!authenticationType || !headerHandler[authenticationType]) {
897
+ logger.debug(`Authentication type ${authenticationType} not supported`);
898
+ return undefined;
899
+ } else {
900
+ const handler = headerHandler[authenticationType];
901
+
902
+ const host = appSyncGraphqlEndpoint
903
+ ? new AmplifyUrl(appSyncGraphqlEndpoint).host
904
+ : undefined;
905
+
906
+ logger.debug(`Authenticating with ${JSON.stringify(authenticationType)}`);
907
+ let resolvedApiKey;
908
+ if (authenticationType === 'apiKey') {
909
+ resolvedApiKey = apiKey;
910
+ }
911
+ const result = await handler({
912
+ payload,
913
+ canonicalUri,
914
+ appSyncGraphqlEndpoint,
915
+ apiKey: resolvedApiKey,
916
+ region,
917
+ host,
918
+ additionalHeaders,
919
+ });
920
+
921
+ return result;
922
+ }
923
+ }
924
+
925
+ private async _awsAuthTokenHeader({ host }: AWSAppSyncRealTimeAuthInput) {
926
+ const session = await fetchAuthSession();
927
+
928
+ return {
929
+ Authorization: session?.tokens?.accessToken?.toString(),
930
+ host,
931
+ };
932
+ }
933
+
934
+ private async _awsRealTimeApiKeyHeader({
935
+ apiKey,
936
+ host,
937
+ }: AWSAppSyncRealTimeAuthInput) {
938
+ const dt = new Date();
939
+ const dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, '');
940
+
941
+ return {
942
+ host,
943
+ 'x-amz-date': dtStr,
944
+ 'x-api-key': apiKey,
945
+ };
946
+ }
947
+
948
+ private async _awsRealTimeIAMHeader({
949
+ payload,
950
+ canonicalUri,
951
+ appSyncGraphqlEndpoint,
952
+ region,
953
+ }: AWSAppSyncRealTimeAuthInput) {
954
+ const endpointInfo = {
955
+ region,
956
+ service: 'appsync',
957
+ };
958
+
959
+ const creds = (await fetchAuthSession()).credentials;
960
+
961
+ const request = {
962
+ url: `${appSyncGraphqlEndpoint}${canonicalUri}`,
963
+ data: payload,
964
+ method: 'POST',
965
+ headers: { ...AWS_APPSYNC_REALTIME_HEADERS },
966
+ };
967
+
968
+ const signed_params = signRequest(
969
+ {
970
+ headers: request.headers,
971
+ method: request.method,
972
+ url: new AmplifyUrl(request.url),
973
+ body: request.data,
974
+ },
975
+ {
976
+ // TODO: What do we need to do to remove these !'s?
977
+ credentials: creds!,
978
+ signingRegion: endpointInfo.region!,
979
+ signingService: endpointInfo.service,
980
+ }
981
+ );
982
+ return signed_params.headers;
983
+ }
984
+
985
+ private _customAuthHeader({
986
+ host,
987
+ additionalHeaders,
988
+ }: AWSAppSyncRealTimeAuthInput) {
989
+ if (!additionalHeaders?.['Authorization']) {
990
+ throw new Error('No auth token specified');
991
+ }
992
+
993
+ return {
994
+ Authorization: additionalHeaders.Authorization,
995
+ host,
996
+ };
997
+ }
998
+ }