@aws-amplify/api-graphql 4.4.3-local-stack.0aa9031.0 → 4.4.3-unstable.847fb51.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 +73 -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 +17 -0
  59. package/dist/esm/internals/events/index.mjs +69 -0
  60. package/dist/esm/internals/events/index.mjs.map +1 -0
  61. package/dist/esm/internals/events/types.d.ts +23 -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 +138 -0
  88. package/src/internals/events/types.ts +35 -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
@@ -1,775 +1,78 @@
1
- import { Observable } from 'rxjs';
2
- import { GraphQLError } from 'graphql';
3
- import { ConsoleLogger, fetchAuthSession, Hub } from '@aws-amplify/core';
4
- import { signRequest } from '@aws-amplify/core/internals/aws-client-utils';
5
- import { amplifyUuid, USER_AGENT_HEADER, getAmplifyUserAgent, isNonRetryableError, AmplifyUrlSearchParams, AmplifyUrl, base64Encoder, jitteredExponentialRetry, NonRetryableError, AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';
6
- import { ConnectionState, CONTROL_MSG } from '../../types/PubSub.mjs';
7
- import { SOCKET_STATUS, DEFAULT_KEEP_ALIVE_TIMEOUT, SUBSCRIPTION_STATUS, MESSAGE_TYPES, START_ACK_TIMEOUT, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT, MAX_DELAY_MS, CONNECTION_INIT_TIMEOUT, NON_RETRYABLE_CODES, AWS_APPSYNC_REALTIME_HEADERS, CONNECTION_STATE_CHANGE } from '../constants.mjs';
8
- import { ConnectionStateMonitor, CONNECTION_CHANGE } from '../../utils/ConnectionStateMonitor.mjs';
9
- import { ReconnectionMonitor, ReconnectEvent } from '../../utils/ReconnectionMonitor.mjs';
1
+ import { USER_AGENT_HEADER, getAmplifyUserAgent } from '@aws-amplify/core/internals/utils';
2
+ import { MESSAGE_TYPES } from '../constants.mjs';
3
+ import { AWSWebSocketProvider } from '../AWSWebSocketProvider/index.mjs';
4
+ import { awsRealTimeHeaderBasedAuth } from '../AWSWebSocketProvider/authHeaders.mjs';
10
5
 
11
6
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
12
7
  // SPDX-License-Identifier: Apache-2.0
13
- const logger = new ConsoleLogger('AWSAppSyncRealTimeProvider');
14
- const dispatchApiEvent = (payload) => {
15
- Hub.dispatch('api', payload, 'PubSub', AMPLIFY_SYMBOL);
16
- };
17
- const standardDomainPattern = /^https:\/\/\w{26}\.appsync-api\.\w{2}(?:(?:-\w{2,})+)-\d\.amazonaws.com(?:\.cn)?\/graphql$/i;
18
- const customDomainPath = '/realtime';
19
- class AWSAppSyncRealTimeProvider {
8
+ const PROVIDER_NAME = 'AWSAppSyncRealTimeProvider';
9
+ const WS_PROTOCOL_NAME = 'graphql-ws';
10
+ class AWSAppSyncRealTimeProvider extends AWSWebSocketProvider {
20
11
  constructor() {
21
- this.socketStatus = SOCKET_STATUS.CLOSED;
22
- this.keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
23
- this.subscriptionObserverMap = new Map();
24
- this.promiseArray = [];
25
- this.connectionStateMonitor = new ConnectionStateMonitor();
26
- this.reconnectionMonitor = new ReconnectionMonitor();
27
- // Monitor the connection state and pass changes along to Hub
28
- this.connectionStateMonitorSubscription =
29
- this.connectionStateMonitor.connectionStateObservable.subscribe(connectionState => {
30
- dispatchApiEvent({
31
- event: CONNECTION_STATE_CHANGE,
32
- data: {
33
- provider: this,
34
- connectionState,
35
- },
36
- message: `Connection state is ${connectionState}`,
37
- });
38
- this.connectionState = connectionState;
39
- // Trigger START_RECONNECT when the connection is disrupted
40
- if (connectionState === ConnectionState.ConnectionDisrupted) {
41
- this.reconnectionMonitor.record(ReconnectEvent.START_RECONNECT);
42
- }
43
- // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
44
- // ConnectionDisrupted or Connecting
45
- if ([
46
- ConnectionState.Connected,
47
- ConnectionState.ConnectedPendingDisconnect,
48
- ConnectionState.ConnectedPendingKeepAlive,
49
- ConnectionState.ConnectedPendingNetwork,
50
- ConnectionState.ConnectionDisruptedPendingNetwork,
51
- ConnectionState.Disconnected,
52
- ].includes(connectionState)) {
53
- this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT);
54
- }
55
- });
56
- }
57
- /**
58
- * Mark the socket closed and release all active listeners
59
- */
60
- close() {
61
- // Mark the socket closed both in status and the connection monitor
62
- this.socketStatus = SOCKET_STATUS.CLOSED;
63
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
64
- // Turn off the subscription monitor Hub publishing
65
- this.connectionStateMonitorSubscription.unsubscribe();
66
- // Complete all reconnect observers
67
- this.reconnectionMonitor.close();
68
- }
69
- getNewWebSocket(url, protocol) {
70
- return new WebSocket(url, protocol);
12
+ super({ providerName: PROVIDER_NAME, wsProtocolName: WS_PROTOCOL_NAME });
71
13
  }
72
14
  getProviderName() {
73
- return 'AWSAppSyncRealTimeProvider';
74
- }
75
- // Check if url matches standard domain pattern
76
- isCustomDomain(url) {
77
- return url.match(standardDomainPattern) === null;
15
+ return PROVIDER_NAME;
78
16
  }
79
17
  subscribe(options, customUserAgentDetails) {
80
- const { appSyncGraphqlEndpoint, region, query, variables, authenticationType, additionalHeaders, apiKey, authToken, libraryConfigHeaders, } = options || {};
81
- return new Observable(observer => {
82
- if (!options || !appSyncGraphqlEndpoint) {
83
- observer.error({
84
- errors: [
85
- {
86
- ...new GraphQLError(`Subscribe only available for AWS AppSync endpoint`),
87
- },
88
- ],
89
- });
90
- observer.complete();
91
- }
92
- else {
93
- let subscriptionStartActive = false;
94
- const subscriptionId = amplifyUuid();
95
- const startSubscription = () => {
96
- if (!subscriptionStartActive) {
97
- subscriptionStartActive = true;
98
- const startSubscriptionPromise = this._startSubscriptionWithAWSAppSyncRealTime({
99
- options: {
100
- query,
101
- variables,
102
- region,
103
- authenticationType,
104
- appSyncGraphqlEndpoint,
105
- additionalHeaders,
106
- apiKey,
107
- authToken,
108
- libraryConfigHeaders,
109
- },
110
- observer,
111
- subscriptionId,
112
- customUserAgentDetails,
113
- }).catch(err => {
114
- logger.debug(`${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`);
115
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
116
- });
117
- startSubscriptionPromise.finally(() => {
118
- subscriptionStartActive = false;
119
- });
120
- }
121
- };
122
- // Add an observable to the reconnection list to manage reconnection for this subscription
123
- const reconnectSubscription = new Observable(reconnectSubscriptionObserver => {
124
- this.reconnectionMonitor.addObserver(reconnectSubscriptionObserver);
125
- }).subscribe(() => {
126
- startSubscription();
127
- });
128
- startSubscription();
129
- return async () => {
130
- // Cleanup reconnection subscription
131
- reconnectSubscription?.unsubscribe();
132
- // Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
133
- try {
134
- // Waiting that subscription has been connected before trying to unsubscribe
135
- await this._waitForSubscriptionToBeConnected(subscriptionId);
136
- const { subscriptionState } = this.subscriptionObserverMap.get(subscriptionId) || {};
137
- if (!subscriptionState) {
138
- // subscription already unsubscribed
139
- return;
140
- }
141
- if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {
142
- this._sendUnsubscriptionMessage(subscriptionId);
143
- }
144
- else {
145
- throw new Error('Subscription never connected');
146
- }
147
- }
148
- catch (err) {
149
- logger.debug(`Error while unsubscribing ${err}`);
150
- }
151
- finally {
152
- this._removeSubscriptionObserver(subscriptionId);
153
- }
154
- };
155
- }
156
- });
18
+ return super.subscribe(options, customUserAgentDetails);
157
19
  }
158
- async _startSubscriptionWithAWSAppSyncRealTime({ options, observer, subscriptionId, customUserAgentDetails, }) {
159
- const { appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, libraryConfigHeaders = () => ({}), additionalHeaders = {}, authToken, } = options;
160
- let additionalCustomHeaders = {};
161
- if (typeof additionalHeaders === 'function') {
162
- const requestOptions = {
163
- url: appSyncGraphqlEndpoint || '',
164
- queryString: query || '',
165
- };
166
- additionalCustomHeaders = await additionalHeaders(requestOptions);
167
- }
168
- else {
169
- additionalCustomHeaders = additionalHeaders;
170
- }
171
- // if an authorization header is set, have the explicit authToken take precedence
172
- if (authToken) {
173
- additionalCustomHeaders = {
174
- ...additionalCustomHeaders,
175
- Authorization: authToken,
176
- };
177
- }
178
- const subscriptionState = SUBSCRIPTION_STATUS.PENDING;
20
+ async _prepareSubscriptionPayload({ options, subscriptionId, customUserAgentDetails, additionalCustomHeaders, libraryConfigHeaders, }) {
21
+ const { appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, } = options;
179
22
  const data = {
180
23
  query,
181
24
  variables,
182
25
  };
183
- // Having a subscription id map will make it simple to forward messages received
184
- this.subscriptionObserverMap.set(subscriptionId, {
185
- observer,
186
- query: query ?? '',
187
- variables: variables ?? {},
188
- subscriptionState,
189
- startAckTimeoutId: undefined,
190
- });
191
- // Preparing payload for subscription message
192
- const dataString = JSON.stringify(data);
193
- const headerObj = {
194
- ...(await this._awsRealTimeHeaderBasedAuth({
26
+ const serializedData = JSON.stringify(data);
27
+ const headers = {
28
+ ...(await awsRealTimeHeaderBasedAuth({
195
29
  apiKey,
196
30
  appSyncGraphqlEndpoint,
197
31
  authenticationType,
198
- payload: dataString,
32
+ payload: serializedData,
199
33
  canonicalUri: '',
200
34
  region,
201
35
  additionalCustomHeaders,
202
36
  })),
203
- ...(await libraryConfigHeaders()),
37
+ ...libraryConfigHeaders,
204
38
  ...additionalCustomHeaders,
205
39
  [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
206
40
  };
207
41
  const subscriptionMessage = {
208
42
  id: subscriptionId,
209
43
  payload: {
210
- data: dataString,
44
+ data: serializedData,
211
45
  extensions: {
212
46
  authorization: {
213
- ...headerObj,
47
+ ...headers,
214
48
  },
215
49
  },
216
50
  },
217
51
  type: MESSAGE_TYPES.GQL_START,
218
52
  };
219
- const stringToAWSRealTime = JSON.stringify(subscriptionMessage);
220
- try {
221
- this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
222
- await this._initializeWebSocketConnection({
223
- apiKey,
224
- appSyncGraphqlEndpoint,
225
- authenticationType,
226
- region,
227
- additionalCustomHeaders,
228
- });
229
- }
230
- catch (err) {
231
- this._logStartSubscriptionError(subscriptionId, observer, err);
232
- return;
233
- }
234
- // Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
235
- // E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
236
- // Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
237
- const { subscriptionFailedCallback, subscriptionReadyCallback } = this.subscriptionObserverMap.get(subscriptionId) ?? {};
238
- // This must be done before sending the message in order to be listening immediately
239
- this.subscriptionObserverMap.set(subscriptionId, {
240
- observer,
241
- subscriptionState,
242
- query: query ?? '',
243
- variables: variables ?? {},
244
- subscriptionReadyCallback,
245
- subscriptionFailedCallback,
246
- startAckTimeoutId: setTimeout(() => {
247
- this._timeoutStartSubscriptionAck(subscriptionId);
248
- }, START_ACK_TIMEOUT),
249
- });
250
- if (this.awsRealTimeSocket) {
251
- this.awsRealTimeSocket.send(stringToAWSRealTime);
252
- }
253
- }
254
- // Log logic for start subscription failures
255
- _logStartSubscriptionError(subscriptionId, observer, err) {
256
- logger.debug({ err });
257
- const message = String(err.message ?? '');
258
- // Resolving to give the state observer time to propogate the update
259
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
260
- // Capture the error only when the network didn't cause disruption
261
- if (this.connectionState !== ConnectionState.ConnectionDisruptedPendingNetwork) {
262
- // When the error is non-retriable, error out the observable
263
- if (isNonRetryableError(err)) {
264
- observer.error({
265
- errors: [
266
- {
267
- ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`),
268
- },
269
- ],
270
- });
271
- }
272
- else {
273
- logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
274
- }
275
- const { subscriptionFailedCallback } = this.subscriptionObserverMap.get(subscriptionId) || {};
276
- // Notify concurrent unsubscription
277
- if (typeof subscriptionFailedCallback === 'function') {
278
- subscriptionFailedCallback();
279
- }
280
- }
281
- }
282
- // Waiting that subscription has been connected before trying to unsubscribe
283
- async _waitForSubscriptionToBeConnected(subscriptionId) {
284
- const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
285
- if (subscriptionObserver) {
286
- const { subscriptionState } = subscriptionObserver;
287
- // This in case unsubscribe is invoked before sending start subscription message
288
- if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
289
- return new Promise((resolve, reject) => {
290
- const { observer, subscriptionState: observedSubscriptionState, variables, query, } = subscriptionObserver;
291
- this.subscriptionObserverMap.set(subscriptionId, {
292
- observer,
293
- subscriptionState: observedSubscriptionState,
294
- variables,
295
- query,
296
- subscriptionReadyCallback: resolve,
297
- subscriptionFailedCallback: reject,
298
- });
299
- });
300
- }
301
- }
302
- }
303
- _sendUnsubscriptionMessage(subscriptionId) {
304
- try {
305
- if (this.awsRealTimeSocket &&
306
- this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
307
- this.socketStatus === SOCKET_STATUS.READY) {
308
- // Preparing unsubscribe message to stop receiving messages for that subscription
309
- const unsubscribeMessage = {
310
- id: subscriptionId,
311
- type: MESSAGE_TYPES.GQL_STOP,
312
- };
313
- const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
314
- this.awsRealTimeSocket.send(stringToAWSRealTime);
315
- }
316
- }
317
- catch (err) {
318
- // If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
319
- logger.debug({ err });
320
- }
321
- }
322
- _removeSubscriptionObserver(subscriptionId) {
323
- this.subscriptionObserverMap.delete(subscriptionId);
324
- // Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
325
- setTimeout(this._closeSocketIfRequired.bind(this), 1000);
326
- }
327
- _closeSocketIfRequired() {
328
- if (this.subscriptionObserverMap.size > 0) {
329
- // Active subscriptions on the WebSocket
330
- return;
331
- }
332
- if (!this.awsRealTimeSocket) {
333
- this.socketStatus = SOCKET_STATUS.CLOSED;
334
- return;
335
- }
336
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
337
- if (this.awsRealTimeSocket.bufferedAmount > 0) {
338
- // Still data on the WebSocket
339
- setTimeout(this._closeSocketIfRequired.bind(this), 1000);
340
- }
341
- else {
342
- logger.debug('closing WebSocket...');
343
- if (this.keepAliveTimeoutId) {
344
- clearTimeout(this.keepAliveTimeoutId);
345
- }
346
- if (this.keepAliveAlertTimeoutId) {
347
- clearTimeout(this.keepAliveAlertTimeoutId);
348
- }
349
- const tempSocket = this.awsRealTimeSocket;
350
- // Cleaning callbacks to avoid race condition, socket still exists
351
- tempSocket.onclose = null;
352
- tempSocket.onerror = null;
353
- tempSocket.close(1000);
354
- this.awsRealTimeSocket = undefined;
355
- this.socketStatus = SOCKET_STATUS.CLOSED;
356
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
357
- }
358
- }
359
- _handleIncomingSubscriptionMessage(message) {
360
- if (typeof message.data !== 'string') {
361
- return;
362
- }
363
- logger.debug(`subscription message from AWS AppSync RealTime: ${message.data}`);
364
- const { id = '', payload, type, } = JSON.parse(String(message.data));
365
- const { observer = null, query = '', variables = {}, startAckTimeoutId, subscriptionReadyCallback, subscriptionFailedCallback, } = this.subscriptionObserverMap.get(id) || {};
366
- logger.debug({ id, observer, query, variables });
367
- if (type === MESSAGE_TYPES.GQL_DATA && payload && payload.data) {
53
+ const serializedSubscriptionMessage = JSON.stringify(subscriptionMessage);
54
+ return serializedSubscriptionMessage;
55
+ }
56
+ _handleSubscriptionData(message) {
57
+ this.logger.debug(`subscription message from AWS AppSync RealTime: ${message.data}`);
58
+ const { id = '', payload, type } = JSON.parse(String(message.data));
59
+ const { observer = null, query = '', variables = {}, } = this.subscriptionObserverMap.get(id) || {};
60
+ this.logger.debug({ id, observer, query, variables });
61
+ if (type === MESSAGE_TYPES.DATA && payload && payload.data) {
368
62
  if (observer) {
369
63
  observer.next(payload);
370
64
  }
371
65
  else {
372
- logger.debug(`observer not found for id: ${id}`);
373
- }
374
- return;
375
- }
376
- if (type === MESSAGE_TYPES.GQL_START_ACK) {
377
- logger.debug(`subscription ready for ${JSON.stringify({ query, variables })}`);
378
- if (typeof subscriptionReadyCallback === 'function') {
379
- subscriptionReadyCallback();
380
- }
381
- if (startAckTimeoutId)
382
- clearTimeout(startAckTimeoutId);
383
- dispatchApiEvent({
384
- event: CONTROL_MSG.SUBSCRIPTION_ACK,
385
- data: { query, variables },
386
- message: 'Connection established for subscription',
387
- });
388
- const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
389
- if (observer) {
390
- this.subscriptionObserverMap.set(id, {
391
- observer,
392
- query,
393
- variables,
394
- startAckTimeoutId: undefined,
395
- subscriptionState,
396
- subscriptionReadyCallback,
397
- subscriptionFailedCallback,
398
- });
399
- }
400
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
401
- return;
402
- }
403
- if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
404
- if (this.keepAliveTimeoutId)
405
- clearTimeout(this.keepAliveTimeoutId);
406
- if (this.keepAliveAlertTimeoutId)
407
- clearTimeout(this.keepAliveAlertTimeoutId);
408
- this.keepAliveTimeoutId = setTimeout(() => {
409
- this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT);
410
- }, this.keepAliveTimeout);
411
- this.keepAliveAlertTimeoutId = setTimeout(() => {
412
- this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
413
- }, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
414
- this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);
415
- return;
416
- }
417
- if (type === MESSAGE_TYPES.GQL_ERROR) {
418
- const subscriptionState = SUBSCRIPTION_STATUS.FAILED;
419
- if (observer) {
420
- this.subscriptionObserverMap.set(id, {
421
- observer,
422
- query,
423
- variables,
424
- startAckTimeoutId,
425
- subscriptionReadyCallback,
426
- subscriptionFailedCallback,
427
- subscriptionState,
428
- });
429
- logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`);
430
- observer.error({
431
- errors: [
432
- {
433
- ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`),
434
- },
435
- ],
436
- });
437
- if (startAckTimeoutId)
438
- clearTimeout(startAckTimeoutId);
439
- if (typeof subscriptionFailedCallback === 'function') {
440
- subscriptionFailedCallback();
441
- }
442
- }
443
- }
444
- }
445
- _errorDisconnect(msg) {
446
- logger.debug(`Disconnect error: ${msg}`);
447
- if (this.awsRealTimeSocket) {
448
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
449
- this.awsRealTimeSocket.close();
450
- }
451
- this.socketStatus = SOCKET_STATUS.CLOSED;
452
- }
453
- _timeoutStartSubscriptionAck(subscriptionId) {
454
- const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
455
- if (subscriptionObserver) {
456
- const { observer, query, variables } = subscriptionObserver;
457
- if (!observer) {
458
- return;
459
- }
460
- this.subscriptionObserverMap.set(subscriptionId, {
461
- observer,
462
- query,
463
- variables,
464
- subscriptionState: SUBSCRIPTION_STATUS.FAILED,
465
- });
466
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
467
- logger.debug('timeoutStartSubscription', JSON.stringify({ query, variables }));
468
- }
469
- }
470
- /**
471
- * Strips out `Authorization` header if present
472
- */
473
- _extractNonAuthHeaders(headers) {
474
- if (!headers) {
475
- return {};
476
- }
477
- if ('Authorization' in headers) {
478
- const { Authorization: _, ...nonAuthHeaders } = headers;
479
- return nonAuthHeaders;
480
- }
481
- return headers;
482
- }
483
- /**
484
- *
485
- * @param headers - http headers
486
- * @returns uri-encoded query parameters derived from custom headers
487
- */
488
- _queryParamsFromCustomHeaders(headers) {
489
- const nonAuthHeaders = this._extractNonAuthHeaders(headers);
490
- const params = new AmplifyUrlSearchParams();
491
- Object.entries(nonAuthHeaders).forEach(([k, v]) => {
492
- params.append(k, v);
493
- });
494
- return params;
495
- }
496
- /**
497
- * Normalizes AppSync realtime endpoint URL
498
- *
499
- * @param appSyncGraphqlEndpoint - AppSync endpointUri from config
500
- * @param urlParams - URLSearchParams
501
- * @returns fully resolved string realtime endpoint URL
502
- */
503
- _realtimeUrlWithQueryString(appSyncGraphqlEndpoint, urlParams) {
504
- const protocol = 'wss://';
505
- let realtimeEndpoint = appSyncGraphqlEndpoint ?? '';
506
- if (this.isCustomDomain(realtimeEndpoint)) {
507
- realtimeEndpoint = realtimeEndpoint.concat(customDomainPath);
508
- }
509
- else {
510
- realtimeEndpoint = realtimeEndpoint
511
- .replace('appsync-api', 'appsync-realtime-api')
512
- .replace('gogi-beta', 'grt-beta');
513
- }
514
- realtimeEndpoint = realtimeEndpoint
515
- .replace('https://', protocol)
516
- .replace('http://', protocol);
517
- const realtimeEndpointUrl = new AmplifyUrl(realtimeEndpoint);
518
- // preserves any query params a customer might manually set in the configuration
519
- const existingParams = new AmplifyUrlSearchParams(realtimeEndpointUrl.search);
520
- for (const [k, v] of urlParams.entries()) {
521
- existingParams.append(k, v);
522
- }
523
- realtimeEndpointUrl.search = existingParams.toString();
524
- return realtimeEndpointUrl.toString();
525
- }
526
- _initializeWebSocketConnection({ appSyncGraphqlEndpoint, authenticationType, apiKey, region, additionalCustomHeaders, }) {
527
- if (this.socketStatus === SOCKET_STATUS.READY) {
528
- return;
529
- }
530
- // TODO(Eslint): refactor to now use async function as the promise executor
531
- // eslint-disable-next-line no-async-promise-executor
532
- return new Promise(async (resolve, reject) => {
533
- this.promiseArray.push({ res: resolve, rej: reject });
534
- if (this.socketStatus === SOCKET_STATUS.CLOSED) {
535
- try {
536
- this.socketStatus = SOCKET_STATUS.CONNECTING;
537
- const payloadString = '{}';
538
- const authHeader = await this._awsRealTimeHeaderBasedAuth({
539
- authenticationType,
540
- payload: payloadString,
541
- canonicalUri: '/connect',
542
- apiKey,
543
- appSyncGraphqlEndpoint,
544
- region,
545
- additionalCustomHeaders,
546
- });
547
- const headerString = authHeader ? JSON.stringify(authHeader) : '';
548
- // base64url-encoded string
549
- const encodedHeader = base64Encoder.convert(headerString, {
550
- urlSafe: true,
551
- skipPadding: true,
552
- });
553
- const authTokenSubprotocol = `header-${encodedHeader}`;
554
- const queryParams = this._queryParamsFromCustomHeaders(additionalCustomHeaders);
555
- const awsRealTimeUrl = this._realtimeUrlWithQueryString(appSyncGraphqlEndpoint, queryParams);
556
- await this._initializeRetryableHandshake(awsRealTimeUrl, authTokenSubprotocol);
557
- this.promiseArray.forEach(({ res }) => {
558
- logger.debug('Notifying connection successful');
559
- res();
560
- });
561
- this.socketStatus = SOCKET_STATUS.READY;
562
- this.promiseArray = [];
563
- }
564
- catch (err) {
565
- logger.debug('Connection exited with', err);
566
- this.promiseArray.forEach(({ rej }) => {
567
- rej(err);
568
- });
569
- this.promiseArray = [];
570
- if (this.awsRealTimeSocket &&
571
- this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
572
- this.awsRealTimeSocket.close(3001);
573
- }
574
- this.awsRealTimeSocket = undefined;
575
- this.socketStatus = SOCKET_STATUS.CLOSED;
576
- }
577
- }
578
- });
579
- }
580
- async _initializeRetryableHandshake(awsRealTimeUrl, subprotocol) {
581
- logger.debug(`Initializaling retryable Handshake`);
582
- await jitteredExponentialRetry(this._initializeHandshake.bind(this), [awsRealTimeUrl, subprotocol], MAX_DELAY_MS);
583
- }
584
- /**
585
- *
586
- * @param subprotocol -
587
- */
588
- async _initializeHandshake(awsRealTimeUrl, subprotocol) {
589
- logger.debug(`Initializing handshake ${awsRealTimeUrl}`);
590
- // Because connecting the socket is async, is waiting until connection is open
591
- // Step 1: connect websocket
592
- try {
593
- await (() => {
594
- return new Promise((resolve, reject) => {
595
- const newSocket = this.getNewWebSocket(awsRealTimeUrl, [
596
- 'graphql-ws',
597
- subprotocol,
598
- ]);
599
- newSocket.onerror = () => {
600
- logger.debug(`WebSocket connection error`);
601
- };
602
- newSocket.onclose = () => {
603
- reject(new Error('Connection handshake error'));
604
- };
605
- newSocket.onopen = () => {
606
- this.awsRealTimeSocket = newSocket;
607
- resolve();
608
- };
609
- });
610
- })();
611
- // Step 2: wait for ack from AWS AppSyncReaTime after sending init
612
- await (() => {
613
- return new Promise((resolve, reject) => {
614
- if (this.awsRealTimeSocket) {
615
- let ackOk = false;
616
- this.awsRealTimeSocket.onerror = error => {
617
- logger.debug(`WebSocket error ${JSON.stringify(error)}`);
618
- };
619
- this.awsRealTimeSocket.onclose = event => {
620
- logger.debug(`WebSocket closed ${event.reason}`);
621
- reject(new Error(JSON.stringify(event)));
622
- };
623
- this.awsRealTimeSocket.onmessage = (message) => {
624
- if (typeof message.data !== 'string') {
625
- return;
626
- }
627
- logger.debug(`subscription message from AWS AppSyncRealTime: ${message.data} `);
628
- const data = JSON.parse(message.data);
629
- const { type, payload: { connectionTimeoutMs = DEFAULT_KEEP_ALIVE_TIMEOUT, } = {}, } = data;
630
- if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
631
- ackOk = true;
632
- if (this.awsRealTimeSocket) {
633
- this.keepAliveTimeout = connectionTimeoutMs;
634
- this.awsRealTimeSocket.onmessage =
635
- this._handleIncomingSubscriptionMessage.bind(this);
636
- this.awsRealTimeSocket.onerror = err => {
637
- logger.debug(err);
638
- this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
639
- };
640
- this.awsRealTimeSocket.onclose = event => {
641
- logger.debug(`WebSocket closed ${event.reason}`);
642
- this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
643
- };
644
- }
645
- resolve('Cool, connected to AWS AppSyncRealTime');
646
- return;
647
- }
648
- if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
649
- const { payload: { errors: [{ errorType = '', errorCode = 0 } = {}] = [], } = {}, } = data;
650
- // TODO(Eslint): refactor to reject an Error object instead of a plain object
651
- // eslint-disable-next-line prefer-promise-reject-errors
652
- reject({ errorType, errorCode });
653
- }
654
- };
655
- const gqlInit = {
656
- type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
657
- };
658
- this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
659
- const checkAckOk = (targetAckOk) => {
660
- if (!targetAckOk) {
661
- this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
662
- reject(new Error(`Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`));
663
- }
664
- };
665
- setTimeout(() => {
666
- checkAckOk(ackOk);
667
- }, CONNECTION_INIT_TIMEOUT);
668
- }
669
- });
670
- })();
671
- }
672
- catch (err) {
673
- const { errorType, errorCode } = err;
674
- if (NON_RETRYABLE_CODES.includes(errorCode)) {
675
- throw new NonRetryableError(errorType);
676
- }
677
- else if (errorType) {
678
- throw new Error(errorType);
679
- }
680
- else {
681
- throw err;
682
- }
683
- }
684
- }
685
- async _awsRealTimeHeaderBasedAuth({ apiKey, authenticationType, payload, canonicalUri, appSyncGraphqlEndpoint, region, additionalCustomHeaders, }) {
686
- const headerHandler = {
687
- apiKey: this._awsRealTimeApiKeyHeader.bind(this),
688
- iam: this._awsRealTimeIAMHeader.bind(this),
689
- oidc: this._awsAuthTokenHeader.bind(this),
690
- userPool: this._awsAuthTokenHeader.bind(this),
691
- lambda: this._customAuthHeader,
692
- none: this._customAuthHeader,
693
- };
694
- if (!authenticationType || !headerHandler[authenticationType]) {
695
- logger.debug(`Authentication type ${authenticationType} not supported`);
696
- return undefined;
697
- }
698
- else {
699
- const handler = headerHandler[authenticationType];
700
- const host = appSyncGraphqlEndpoint
701
- ? new AmplifyUrl(appSyncGraphqlEndpoint).host
702
- : undefined;
703
- logger.debug(`Authenticating with ${JSON.stringify(authenticationType)}`);
704
- let resolvedApiKey;
705
- if (authenticationType === 'apiKey') {
706
- resolvedApiKey = apiKey;
66
+ this.logger.debug(`observer not found for id: ${id}`);
707
67
  }
708
- const result = await handler({
709
- payload,
710
- canonicalUri,
711
- appSyncGraphqlEndpoint,
712
- apiKey: resolvedApiKey,
713
- region,
714
- host,
715
- additionalCustomHeaders,
716
- });
717
- return result;
68
+ return [true, { id, type, payload }];
718
69
  }
70
+ return [false, { id, type, payload }];
719
71
  }
720
- async _awsAuthTokenHeader({ host }) {
721
- const session = await fetchAuthSession();
72
+ _unsubscribeMessage(subscriptionId) {
722
73
  return {
723
- Authorization: session?.tokens?.accessToken?.toString(),
724
- host,
725
- };
726
- }
727
- async _awsRealTimeApiKeyHeader({ apiKey, host, }) {
728
- const dt = new Date();
729
- const dtStr = dt.toISOString().replace(/[:-]|\.\d{3}/g, '');
730
- return {
731
- host,
732
- 'x-amz-date': dtStr,
733
- 'x-api-key': apiKey,
734
- };
735
- }
736
- async _awsRealTimeIAMHeader({ payload, canonicalUri, appSyncGraphqlEndpoint, region, }) {
737
- const endpointInfo = {
738
- region,
739
- service: 'appsync',
740
- };
741
- const creds = (await fetchAuthSession()).credentials;
742
- const request = {
743
- url: `${appSyncGraphqlEndpoint}${canonicalUri}`,
744
- data: payload,
745
- method: 'POST',
746
- headers: { ...AWS_APPSYNC_REALTIME_HEADERS },
747
- };
748
- const signedParams = signRequest({
749
- headers: request.headers,
750
- method: request.method,
751
- url: new AmplifyUrl(request.url),
752
- body: request.data,
753
- }, {
754
- // TODO: What do we need to do to remove these !'s?
755
- credentials: creds,
756
- signingRegion: endpointInfo.region,
757
- signingService: endpointInfo.service,
758
- });
759
- return signedParams.headers;
760
- }
761
- _customAuthHeader({ host, additionalCustomHeaders, }) {
762
- /**
763
- * If `additionalHeaders` was provided to the subscription as a function,
764
- * the headers that are returned by that function will already have been
765
- * provided before this function is called.
766
- */
767
- if (!additionalCustomHeaders?.Authorization) {
768
- throw new Error('No auth token specified');
769
- }
770
- return {
771
- Authorization: additionalCustomHeaders.Authorization,
772
- host,
74
+ id: subscriptionId,
75
+ type: MESSAGE_TYPES.GQL_STOP,
773
76
  };
774
77
  }
775
78
  }