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