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