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