@aws-amplify/api-graphql 4.4.3-unstable.847fb51.0 → 4.4.3

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