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