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