@aws-amplify/api-graphql 4.4.1-events.619318.0 → 4.4.1

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