@aws-amplify/api-graphql 4.4.3-unstable.cc0910b.0 → 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
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
import { Observable } from 'rxjs';
|
|
2
|
+
import { GraphQLError } from 'graphql';
|
|
3
|
+
import { ConsoleLogger, Hub } from '@aws-amplify/core';
|
|
4
|
+
import { NonRetryableError, amplifyUuid, isNonRetryableError, base64Encoder, jitteredExponentialRetry, AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';
|
|
5
|
+
import { ConnectionState, CONTROL_MSG } from '../../types/PubSub.mjs';
|
|
6
|
+
import { SOCKET_STATUS, DEFAULT_KEEP_ALIVE_TIMEOUT, NON_RETRYABLE_CODES, SUBSCRIPTION_STATUS, START_ACK_TIMEOUT, MESSAGE_TYPES, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT, MAX_DELAY_MS, CONNECTION_INIT_TIMEOUT, CONNECTION_STATE_CHANGE } from '../constants.mjs';
|
|
7
|
+
import { ConnectionStateMonitor, CONNECTION_CHANGE } from '../../utils/ConnectionStateMonitor.mjs';
|
|
8
|
+
import { ReconnectionMonitor, ReconnectEvent } from '../../utils/ReconnectionMonitor.mjs';
|
|
9
|
+
import { additionalHeadersFromOptions, queryParamsFromCustomHeaders, realtimeUrlWithQueryString } from './appsyncUrl.mjs';
|
|
10
|
+
import { awsRealTimeHeaderBasedAuth } from './authHeaders.mjs';
|
|
11
|
+
|
|
12
|
+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
13
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
14
|
+
const dispatchApiEvent = (payload) => {
|
|
15
|
+
Hub.dispatch('api', payload, 'PubSub', AMPLIFY_SYMBOL);
|
|
16
|
+
};
|
|
17
|
+
class AWSWebSocketProvider {
|
|
18
|
+
constructor(args) {
|
|
19
|
+
this.subscriptionObserverMap = new Map();
|
|
20
|
+
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
21
|
+
this.keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
|
|
22
|
+
this.promiseArray = [];
|
|
23
|
+
this.connectionStateMonitor = new ConnectionStateMonitor();
|
|
24
|
+
this.reconnectionMonitor = new ReconnectionMonitor();
|
|
25
|
+
/**
|
|
26
|
+
* Open WebSocket connection & perform handshake
|
|
27
|
+
* Ref: https://docs.aws.amazon.com/appsync/latest/devguide/real-time-websocket-client.html#appsynclong-real-time-websocket-client-implementation-guide-for-graphql-subscriptions
|
|
28
|
+
*
|
|
29
|
+
* @param subprotocol -
|
|
30
|
+
*/
|
|
31
|
+
this._establishConnection = async (awsRealTimeUrl, subprotocol) => {
|
|
32
|
+
this.logger.debug(`Establishing WebSocket connection to ${awsRealTimeUrl}`);
|
|
33
|
+
try {
|
|
34
|
+
await this._openConnection(awsRealTimeUrl, subprotocol);
|
|
35
|
+
await this._initiateHandshake();
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
const { errorType, errorCode } = err;
|
|
39
|
+
if (NON_RETRYABLE_CODES.includes(errorCode)) {
|
|
40
|
+
throw new NonRetryableError(errorType);
|
|
41
|
+
}
|
|
42
|
+
else if (errorType) {
|
|
43
|
+
throw new Error(errorType);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
this.logger = new ConsoleLogger(args.providerName);
|
|
51
|
+
this.wsProtocolName = args.wsProtocolName;
|
|
52
|
+
this.connectionStateMonitorSubscription =
|
|
53
|
+
this._startConnectionStateMonitoring();
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Mark the socket closed and release all active listeners
|
|
57
|
+
*/
|
|
58
|
+
close() {
|
|
59
|
+
// Mark the socket closed both in status and the connection monitor
|
|
60
|
+
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
61
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
|
|
62
|
+
// Turn off the subscription monitor Hub publishing
|
|
63
|
+
this.connectionStateMonitorSubscription.unsubscribe();
|
|
64
|
+
// Complete all reconnect observers
|
|
65
|
+
this.reconnectionMonitor.close();
|
|
66
|
+
}
|
|
67
|
+
subscribe(options, customUserAgentDetails) {
|
|
68
|
+
return new Observable(observer => {
|
|
69
|
+
if (!options?.appSyncGraphqlEndpoint) {
|
|
70
|
+
observer.error({
|
|
71
|
+
errors: [
|
|
72
|
+
{
|
|
73
|
+
...new GraphQLError(`Subscribe only available for AWS AppSync endpoint`),
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
});
|
|
77
|
+
observer.complete();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
let subscriptionStartInProgress = false;
|
|
81
|
+
const subscriptionId = amplifyUuid();
|
|
82
|
+
const startSubscription = () => {
|
|
83
|
+
if (!subscriptionStartInProgress) {
|
|
84
|
+
subscriptionStartInProgress = true;
|
|
85
|
+
this._startSubscriptionWithAWSAppSyncRealTime({
|
|
86
|
+
options,
|
|
87
|
+
observer,
|
|
88
|
+
subscriptionId,
|
|
89
|
+
customUserAgentDetails,
|
|
90
|
+
})
|
|
91
|
+
.catch(err => {
|
|
92
|
+
this.logger.debug(`${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`);
|
|
93
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
94
|
+
})
|
|
95
|
+
.finally(() => {
|
|
96
|
+
subscriptionStartInProgress = false;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
// Add an observable to the reconnection list to manage reconnection for this subscription
|
|
101
|
+
const reconnectSubscription = new Observable(reconnectSubscriptionObserver => {
|
|
102
|
+
this.reconnectionMonitor.addObserver(reconnectSubscriptionObserver);
|
|
103
|
+
}).subscribe(() => {
|
|
104
|
+
startSubscription();
|
|
105
|
+
});
|
|
106
|
+
startSubscription();
|
|
107
|
+
return async () => {
|
|
108
|
+
await this._cleanupSubscription(subscriptionId, reconnectSubscription);
|
|
109
|
+
};
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async connect(options) {
|
|
113
|
+
if (this.socketStatus === SOCKET_STATUS.READY) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
await this._connectWebSocket(options);
|
|
117
|
+
}
|
|
118
|
+
async publish(options, customUserAgentDetails) {
|
|
119
|
+
if (this.socketStatus !== SOCKET_STATUS.READY) {
|
|
120
|
+
throw new Error('Subscription has not been initialized');
|
|
121
|
+
}
|
|
122
|
+
return this._publishMessage(options, customUserAgentDetails);
|
|
123
|
+
}
|
|
124
|
+
async _connectWebSocket(options) {
|
|
125
|
+
const { apiKey, appSyncGraphqlEndpoint, authenticationType, region } = options;
|
|
126
|
+
const { additionalCustomHeaders } = await additionalHeadersFromOptions(options);
|
|
127
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
|
|
128
|
+
await this._initializeWebSocketConnection({
|
|
129
|
+
apiKey,
|
|
130
|
+
appSyncGraphqlEndpoint,
|
|
131
|
+
authenticationType,
|
|
132
|
+
region,
|
|
133
|
+
additionalCustomHeaders,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
async _publishMessage(options, customUserAgentDetails) {
|
|
137
|
+
const subscriptionId = amplifyUuid();
|
|
138
|
+
const { additionalCustomHeaders, libraryConfigHeaders } = await additionalHeadersFromOptions(options);
|
|
139
|
+
const serializedSubscriptionMessage = await this._prepareSubscriptionPayload({
|
|
140
|
+
options,
|
|
141
|
+
subscriptionId,
|
|
142
|
+
customUserAgentDetails,
|
|
143
|
+
additionalCustomHeaders,
|
|
144
|
+
libraryConfigHeaders,
|
|
145
|
+
publish: true,
|
|
146
|
+
});
|
|
147
|
+
return new Promise((resolve, reject) => {
|
|
148
|
+
if (this.awsRealTimeSocket) {
|
|
149
|
+
const publishListener = (event) => {
|
|
150
|
+
const data = JSON.parse(event.data);
|
|
151
|
+
if (data.id === subscriptionId && data.type === 'publish_success') {
|
|
152
|
+
this.awsRealTimeSocket &&
|
|
153
|
+
this.awsRealTimeSocket.removeEventListener('message', publishListener);
|
|
154
|
+
resolve();
|
|
155
|
+
}
|
|
156
|
+
if (data.erroredEvents && data.erroredEvents.length > 0) ;
|
|
157
|
+
};
|
|
158
|
+
this.awsRealTimeSocket.addEventListener('message', publishListener);
|
|
159
|
+
this.awsRealTimeSocket.addEventListener('close', () => {
|
|
160
|
+
reject(new Error('WebSocket is closed'));
|
|
161
|
+
});
|
|
162
|
+
//
|
|
163
|
+
// this.awsRealTimeSocket.addEventListener('error', publishListener);
|
|
164
|
+
this.awsRealTimeSocket.send(serializedSubscriptionMessage);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
async _cleanupSubscription(subscriptionId, reconnectSubscription) {
|
|
169
|
+
// Cleanup reconnection subscription
|
|
170
|
+
reconnectSubscription?.unsubscribe();
|
|
171
|
+
// Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
|
|
172
|
+
try {
|
|
173
|
+
// Waiting that subscription has been connected before trying to unsubscribe
|
|
174
|
+
await this._waitForSubscriptionToBeConnected(subscriptionId);
|
|
175
|
+
const { subscriptionState } = this.subscriptionObserverMap.get(subscriptionId) || {};
|
|
176
|
+
if (!subscriptionState) {
|
|
177
|
+
// subscription already unsubscribed
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {
|
|
181
|
+
this._sendUnsubscriptionMessage(subscriptionId);
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
throw new Error('Subscription never connected');
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
this.logger.debug(`Error while unsubscribing ${err}`);
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
this._removeSubscriptionObserver(subscriptionId);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// Monitor the connection state and pass changes along to Hub
|
|
195
|
+
_startConnectionStateMonitoring() {
|
|
196
|
+
return this.connectionStateMonitor.connectionStateObservable.subscribe(connectionState => {
|
|
197
|
+
dispatchApiEvent({
|
|
198
|
+
event: CONNECTION_STATE_CHANGE,
|
|
199
|
+
data: {
|
|
200
|
+
provider: this,
|
|
201
|
+
connectionState,
|
|
202
|
+
},
|
|
203
|
+
message: `Connection state is ${connectionState}`,
|
|
204
|
+
});
|
|
205
|
+
this.connectionState = connectionState;
|
|
206
|
+
// Trigger START_RECONNECT when the connection is disrupted
|
|
207
|
+
if (connectionState === ConnectionState.ConnectionDisrupted) {
|
|
208
|
+
this.reconnectionMonitor.record(ReconnectEvent.START_RECONNECT);
|
|
209
|
+
}
|
|
210
|
+
// Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
|
|
211
|
+
// ConnectionDisrupted or Connecting
|
|
212
|
+
if ([
|
|
213
|
+
ConnectionState.Connected,
|
|
214
|
+
ConnectionState.ConnectedPendingDisconnect,
|
|
215
|
+
ConnectionState.ConnectedPendingKeepAlive,
|
|
216
|
+
ConnectionState.ConnectedPendingNetwork,
|
|
217
|
+
ConnectionState.ConnectionDisruptedPendingNetwork,
|
|
218
|
+
ConnectionState.Disconnected,
|
|
219
|
+
].includes(connectionState)) {
|
|
220
|
+
this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT);
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
async _startSubscriptionWithAWSAppSyncRealTime({ options, observer, subscriptionId, customUserAgentDetails, }) {
|
|
225
|
+
const { query, variables } = options;
|
|
226
|
+
const { additionalCustomHeaders, libraryConfigHeaders } = await additionalHeadersFromOptions(options);
|
|
227
|
+
this.subscriptionObserverMap.set(subscriptionId, {
|
|
228
|
+
observer,
|
|
229
|
+
query: query ?? '',
|
|
230
|
+
variables: variables ?? {},
|
|
231
|
+
subscriptionState: SUBSCRIPTION_STATUS.PENDING,
|
|
232
|
+
startAckTimeoutId: undefined,
|
|
233
|
+
});
|
|
234
|
+
const serializedSubscriptionMessage = await this._prepareSubscriptionPayload({
|
|
235
|
+
options,
|
|
236
|
+
subscriptionId,
|
|
237
|
+
customUserAgentDetails,
|
|
238
|
+
additionalCustomHeaders,
|
|
239
|
+
libraryConfigHeaders,
|
|
240
|
+
});
|
|
241
|
+
try {
|
|
242
|
+
await this._connectWebSocket(options);
|
|
243
|
+
}
|
|
244
|
+
catch (err) {
|
|
245
|
+
this._logStartSubscriptionError(subscriptionId, observer, err);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
// Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
|
|
249
|
+
// E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
|
|
250
|
+
// Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
|
|
251
|
+
const { subscriptionFailedCallback, subscriptionReadyCallback } = this.subscriptionObserverMap.get(subscriptionId) ?? {};
|
|
252
|
+
// This must be done before sending the message in order to be listening immediately
|
|
253
|
+
this.subscriptionObserverMap.set(subscriptionId, {
|
|
254
|
+
observer,
|
|
255
|
+
subscriptionState: SUBSCRIPTION_STATUS.PENDING,
|
|
256
|
+
query: query ?? '',
|
|
257
|
+
variables: variables ?? {},
|
|
258
|
+
subscriptionReadyCallback,
|
|
259
|
+
subscriptionFailedCallback,
|
|
260
|
+
startAckTimeoutId: setTimeout(() => {
|
|
261
|
+
this._timeoutStartSubscriptionAck(subscriptionId);
|
|
262
|
+
}, START_ACK_TIMEOUT),
|
|
263
|
+
});
|
|
264
|
+
if (this.awsRealTimeSocket) {
|
|
265
|
+
this.awsRealTimeSocket.send(serializedSubscriptionMessage);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
// Log logic for start subscription failures
|
|
269
|
+
_logStartSubscriptionError(subscriptionId, observer, err) {
|
|
270
|
+
this.logger.debug({ err });
|
|
271
|
+
const message = String(err.message ?? '');
|
|
272
|
+
// Resolving to give the state observer time to propogate the update
|
|
273
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
274
|
+
// Capture the error only when the network didn't cause disruption
|
|
275
|
+
if (this.connectionState !== ConnectionState.ConnectionDisruptedPendingNetwork) {
|
|
276
|
+
// When the error is non-retriable, error out the observable
|
|
277
|
+
if (isNonRetryableError(err)) {
|
|
278
|
+
observer.error({
|
|
279
|
+
errors: [
|
|
280
|
+
{
|
|
281
|
+
...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`),
|
|
282
|
+
},
|
|
283
|
+
],
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
this.logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
|
|
288
|
+
}
|
|
289
|
+
const { subscriptionFailedCallback } = this.subscriptionObserverMap.get(subscriptionId) || {};
|
|
290
|
+
// Notify concurrent unsubscription
|
|
291
|
+
if (typeof subscriptionFailedCallback === 'function') {
|
|
292
|
+
subscriptionFailedCallback();
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
// Waiting that subscription has been connected before trying to unsubscribe
|
|
297
|
+
async _waitForSubscriptionToBeConnected(subscriptionId) {
|
|
298
|
+
const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
|
|
299
|
+
if (subscriptionObserver) {
|
|
300
|
+
const { subscriptionState } = subscriptionObserver;
|
|
301
|
+
// This in case unsubscribe is invoked before sending start subscription message
|
|
302
|
+
if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
|
|
303
|
+
return new Promise((resolve, reject) => {
|
|
304
|
+
const { observer, subscriptionState: observedSubscriptionState, variables, query, } = subscriptionObserver;
|
|
305
|
+
this.subscriptionObserverMap.set(subscriptionId, {
|
|
306
|
+
observer,
|
|
307
|
+
subscriptionState: observedSubscriptionState,
|
|
308
|
+
variables,
|
|
309
|
+
query,
|
|
310
|
+
subscriptionReadyCallback: resolve,
|
|
311
|
+
subscriptionFailedCallback: reject,
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
_sendUnsubscriptionMessage(subscriptionId) {
|
|
318
|
+
try {
|
|
319
|
+
if (this.awsRealTimeSocket &&
|
|
320
|
+
this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
|
|
321
|
+
this.socketStatus === SOCKET_STATUS.READY) {
|
|
322
|
+
// Preparing unsubscribe message to stop receiving messages for that subscription
|
|
323
|
+
const unsubscribeMessage = this._unsubscribeMessage(subscriptionId);
|
|
324
|
+
const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
|
|
325
|
+
this.awsRealTimeSocket.send(stringToAWSRealTime);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
// If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
|
|
330
|
+
this.logger.debug({ err });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
_removeSubscriptionObserver(subscriptionId) {
|
|
334
|
+
this.subscriptionObserverMap.delete(subscriptionId);
|
|
335
|
+
// Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
|
|
336
|
+
setTimeout(this._closeSocketIfRequired.bind(this), 1000);
|
|
337
|
+
}
|
|
338
|
+
_closeSocketIfRequired() {
|
|
339
|
+
if (this.subscriptionObserverMap.size > 0) {
|
|
340
|
+
// Active subscriptions on the WebSocket
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (!this.awsRealTimeSocket) {
|
|
344
|
+
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
|
|
348
|
+
if (this.awsRealTimeSocket.bufferedAmount > 0) {
|
|
349
|
+
// Still data on the WebSocket
|
|
350
|
+
setTimeout(this._closeSocketIfRequired.bind(this), 1000);
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
this.logger.debug('closing WebSocket...');
|
|
354
|
+
if (this.keepAliveTimeoutId) {
|
|
355
|
+
clearTimeout(this.keepAliveTimeoutId);
|
|
356
|
+
}
|
|
357
|
+
if (this.keepAliveAlertTimeoutId) {
|
|
358
|
+
clearTimeout(this.keepAliveAlertTimeoutId);
|
|
359
|
+
}
|
|
360
|
+
const tempSocket = this.awsRealTimeSocket;
|
|
361
|
+
// Cleaning callbacks to avoid race condition, socket still exists
|
|
362
|
+
tempSocket.onclose = null;
|
|
363
|
+
tempSocket.onerror = null;
|
|
364
|
+
tempSocket.close(1000);
|
|
365
|
+
this.awsRealTimeSocket = undefined;
|
|
366
|
+
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
367
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
_handleIncomingSubscriptionMessage(message) {
|
|
371
|
+
if (typeof message.data !== 'string') {
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const [isData, data] = this._handleSubscriptionData(message);
|
|
375
|
+
if (isData)
|
|
376
|
+
return;
|
|
377
|
+
const { type, id, payload } = data;
|
|
378
|
+
const { observer = null, query = '', variables = {}, startAckTimeoutId, subscriptionReadyCallback, subscriptionFailedCallback, } = this.subscriptionObserverMap.get(id) || {};
|
|
379
|
+
if (type === MESSAGE_TYPES.GQL_START_ACK ||
|
|
380
|
+
type === MESSAGE_TYPES.EVENT_SUBSCRIBE_ACK) {
|
|
381
|
+
this.logger.debug(`subscription ready for ${JSON.stringify({ query, variables })}`);
|
|
382
|
+
if (typeof subscriptionReadyCallback === 'function') {
|
|
383
|
+
subscriptionReadyCallback();
|
|
384
|
+
}
|
|
385
|
+
if (startAckTimeoutId)
|
|
386
|
+
clearTimeout(startAckTimeoutId);
|
|
387
|
+
dispatchApiEvent({
|
|
388
|
+
event: CONTROL_MSG.SUBSCRIPTION_ACK,
|
|
389
|
+
data: { query, variables },
|
|
390
|
+
message: 'Connection established for subscription',
|
|
391
|
+
});
|
|
392
|
+
const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
|
|
393
|
+
if (observer) {
|
|
394
|
+
this.subscriptionObserverMap.set(id, {
|
|
395
|
+
observer,
|
|
396
|
+
query,
|
|
397
|
+
variables,
|
|
398
|
+
startAckTimeoutId: undefined,
|
|
399
|
+
subscriptionState,
|
|
400
|
+
subscriptionReadyCallback,
|
|
401
|
+
subscriptionFailedCallback,
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
|
|
408
|
+
if (this.keepAliveTimeoutId)
|
|
409
|
+
clearTimeout(this.keepAliveTimeoutId);
|
|
410
|
+
if (this.keepAliveAlertTimeoutId)
|
|
411
|
+
clearTimeout(this.keepAliveAlertTimeoutId);
|
|
412
|
+
this.keepAliveTimeoutId = setTimeout(() => {
|
|
413
|
+
this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT);
|
|
414
|
+
}, this.keepAliveTimeout);
|
|
415
|
+
this.keepAliveAlertTimeoutId = setTimeout(() => {
|
|
416
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
|
|
417
|
+
}, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
|
|
418
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
if (type === MESSAGE_TYPES.GQL_ERROR) {
|
|
422
|
+
const subscriptionState = SUBSCRIPTION_STATUS.FAILED;
|
|
423
|
+
if (observer) {
|
|
424
|
+
this.subscriptionObserverMap.set(id, {
|
|
425
|
+
observer,
|
|
426
|
+
query,
|
|
427
|
+
variables,
|
|
428
|
+
startAckTimeoutId,
|
|
429
|
+
subscriptionReadyCallback,
|
|
430
|
+
subscriptionFailedCallback,
|
|
431
|
+
subscriptionState,
|
|
432
|
+
});
|
|
433
|
+
this.logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`);
|
|
434
|
+
observer.error({
|
|
435
|
+
errors: [
|
|
436
|
+
{
|
|
437
|
+
...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`),
|
|
438
|
+
},
|
|
439
|
+
],
|
|
440
|
+
});
|
|
441
|
+
if (startAckTimeoutId)
|
|
442
|
+
clearTimeout(startAckTimeoutId);
|
|
443
|
+
if (typeof subscriptionFailedCallback === 'function') {
|
|
444
|
+
subscriptionFailedCallback();
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
_errorDisconnect(msg) {
|
|
450
|
+
this.logger.debug(`Disconnect error: ${msg}`);
|
|
451
|
+
if (this.awsRealTimeSocket) {
|
|
452
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
453
|
+
this.awsRealTimeSocket.close();
|
|
454
|
+
}
|
|
455
|
+
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
456
|
+
}
|
|
457
|
+
_timeoutStartSubscriptionAck(subscriptionId) {
|
|
458
|
+
const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
|
|
459
|
+
if (subscriptionObserver) {
|
|
460
|
+
const { observer, query, variables } = subscriptionObserver;
|
|
461
|
+
if (!observer) {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
this.subscriptionObserverMap.set(subscriptionId, {
|
|
465
|
+
observer,
|
|
466
|
+
query,
|
|
467
|
+
variables,
|
|
468
|
+
subscriptionState: SUBSCRIPTION_STATUS.FAILED,
|
|
469
|
+
});
|
|
470
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
471
|
+
this.logger.debug('timeoutStartSubscription', JSON.stringify({ query, variables }));
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
_initializeWebSocketConnection({ appSyncGraphqlEndpoint, authenticationType, apiKey, region, additionalCustomHeaders, }) {
|
|
475
|
+
if (this.socketStatus === SOCKET_STATUS.READY) {
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
// TODO(Eslint): refactor to now use async function as the promise executor
|
|
479
|
+
// eslint-disable-next-line no-async-promise-executor
|
|
480
|
+
return new Promise(async (resolve, reject) => {
|
|
481
|
+
this.promiseArray.push({ res: resolve, rej: reject });
|
|
482
|
+
if (this.socketStatus === SOCKET_STATUS.CLOSED) {
|
|
483
|
+
try {
|
|
484
|
+
this.socketStatus = SOCKET_STATUS.CONNECTING;
|
|
485
|
+
// Empty payload on connect
|
|
486
|
+
const payloadString = '{}';
|
|
487
|
+
const authHeader = await awsRealTimeHeaderBasedAuth({
|
|
488
|
+
authenticationType,
|
|
489
|
+
payload: payloadString,
|
|
490
|
+
canonicalUri: '/connect',
|
|
491
|
+
apiKey,
|
|
492
|
+
appSyncGraphqlEndpoint,
|
|
493
|
+
region,
|
|
494
|
+
additionalCustomHeaders,
|
|
495
|
+
});
|
|
496
|
+
const headerString = authHeader ? JSON.stringify(authHeader) : '';
|
|
497
|
+
// base64url-encoded string
|
|
498
|
+
const encodedHeader = base64Encoder.convert(headerString, {
|
|
499
|
+
urlSafe: true,
|
|
500
|
+
skipPadding: true,
|
|
501
|
+
});
|
|
502
|
+
const authTokenSubprotocol = `header-${encodedHeader}`;
|
|
503
|
+
const queryParams = queryParamsFromCustomHeaders(additionalCustomHeaders);
|
|
504
|
+
const awsRealTimeUrl = realtimeUrlWithQueryString(appSyncGraphqlEndpoint, queryParams);
|
|
505
|
+
await this._establishRetryableConnection(awsRealTimeUrl, authTokenSubprotocol);
|
|
506
|
+
this.promiseArray.forEach(({ res }) => {
|
|
507
|
+
this.logger.debug('Notifying connection successful');
|
|
508
|
+
res();
|
|
509
|
+
});
|
|
510
|
+
this.socketStatus = SOCKET_STATUS.READY;
|
|
511
|
+
this.promiseArray = [];
|
|
512
|
+
}
|
|
513
|
+
catch (err) {
|
|
514
|
+
this.logger.debug('Connection exited with', err);
|
|
515
|
+
this.promiseArray.forEach(({ rej }) => {
|
|
516
|
+
rej(err);
|
|
517
|
+
});
|
|
518
|
+
this.promiseArray = [];
|
|
519
|
+
if (this.awsRealTimeSocket &&
|
|
520
|
+
this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
|
|
521
|
+
this.awsRealTimeSocket.close(3001);
|
|
522
|
+
}
|
|
523
|
+
this.awsRealTimeSocket = undefined;
|
|
524
|
+
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
async _establishRetryableConnection(awsRealTimeUrl, subprotocol) {
|
|
530
|
+
this.logger.debug(`Establishing retryable connection`);
|
|
531
|
+
await jitteredExponentialRetry(this._establishConnection.bind(this), [awsRealTimeUrl, subprotocol], MAX_DELAY_MS);
|
|
532
|
+
}
|
|
533
|
+
async _openConnection(awsRealTimeUrl, subprotocol) {
|
|
534
|
+
return new Promise((resolve, reject) => {
|
|
535
|
+
const newSocket = this._getNewWebSocket(awsRealTimeUrl, [
|
|
536
|
+
this.wsProtocolName,
|
|
537
|
+
subprotocol,
|
|
538
|
+
]);
|
|
539
|
+
newSocket.onerror = () => {
|
|
540
|
+
this.logger.debug(`WebSocket connection error`);
|
|
541
|
+
};
|
|
542
|
+
newSocket.onclose = () => {
|
|
543
|
+
reject(new Error('Connection handshake error'));
|
|
544
|
+
};
|
|
545
|
+
newSocket.onopen = () => {
|
|
546
|
+
this.awsRealTimeSocket = newSocket;
|
|
547
|
+
resolve();
|
|
548
|
+
};
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
_getNewWebSocket(url, protocol) {
|
|
552
|
+
return new WebSocket(url, protocol);
|
|
553
|
+
}
|
|
554
|
+
async _initiateHandshake() {
|
|
555
|
+
return new Promise((resolve, reject) => {
|
|
556
|
+
if (!this.awsRealTimeSocket) {
|
|
557
|
+
reject(new Error('awsRealTimeSocket undefined'));
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
let ackOk = false;
|
|
561
|
+
this.awsRealTimeSocket.onerror = error => {
|
|
562
|
+
this.logger.debug(`WebSocket error ${JSON.stringify(error)}`);
|
|
563
|
+
};
|
|
564
|
+
this.awsRealTimeSocket.onclose = event => {
|
|
565
|
+
this.logger.debug(`WebSocket closed ${event.reason}`);
|
|
566
|
+
reject(new Error(JSON.stringify(event)));
|
|
567
|
+
};
|
|
568
|
+
this.awsRealTimeSocket.onmessage = (message) => {
|
|
569
|
+
if (typeof message.data !== 'string') {
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
this.logger.debug(`subscription message from AWS AppSyncRealTime: ${message.data} `);
|
|
573
|
+
const data = JSON.parse(message.data);
|
|
574
|
+
const { type, payload: { connectionTimeoutMs = DEFAULT_KEEP_ALIVE_TIMEOUT } = {}, } = data;
|
|
575
|
+
if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
|
|
576
|
+
ackOk = true;
|
|
577
|
+
this._registerWebsocketHandlers(connectionTimeoutMs);
|
|
578
|
+
resolve('Connected to AWS AppSyncRealTime');
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
|
|
582
|
+
const { payload: { errors: [{ errorType = '', errorCode = 0 } = {}] = [], } = {}, } = data;
|
|
583
|
+
// TODO(Eslint): refactor to reject an Error object instead of a plain object
|
|
584
|
+
// eslint-disable-next-line prefer-promise-reject-errors
|
|
585
|
+
reject({ errorType, errorCode });
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
const gqlInit = {
|
|
589
|
+
type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
|
|
590
|
+
};
|
|
591
|
+
this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
|
|
592
|
+
const checkAckOk = (targetAckOk) => {
|
|
593
|
+
if (!targetAckOk) {
|
|
594
|
+
this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
|
|
595
|
+
reject(new Error(`Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`));
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
setTimeout(() => {
|
|
599
|
+
checkAckOk(ackOk);
|
|
600
|
+
}, CONNECTION_INIT_TIMEOUT);
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
_registerWebsocketHandlers(connectionTimeoutMs) {
|
|
604
|
+
if (!this.awsRealTimeSocket) {
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
this.keepAliveTimeout = connectionTimeoutMs;
|
|
608
|
+
this.awsRealTimeSocket.onmessage =
|
|
609
|
+
this._handleIncomingSubscriptionMessage.bind(this);
|
|
610
|
+
this.awsRealTimeSocket.onerror = err => {
|
|
611
|
+
this.logger.debug(err);
|
|
612
|
+
this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
|
|
613
|
+
};
|
|
614
|
+
this.awsRealTimeSocket.onclose = event => {
|
|
615
|
+
this.logger.debug(`WebSocket closed ${event.reason}`);
|
|
616
|
+
this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
export { AWSWebSocketProvider };
|
|
622
|
+
//# sourceMappingURL=index.mjs.map
|