@aws-amplify/pubsub 5.5.6-api-v6-models.b3abc9b.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/iot/packages.json +7 -0
- package/lib/Providers/AWSIot.d.ts +10 -0
- package/lib/Providers/AWSIot.js +34 -0
- package/lib/Providers/{MqttOverWSProvider.d.ts → MqttOverWS.d.ts} +16 -16
- package/lib/Providers/MqttOverWS.js +274 -0
- package/lib/Providers/PubSub.d.ts +11 -0
- package/lib/Providers/PubSub.js +19 -0
- package/lib/Providers/constants.d.ts +1 -1
- package/lib/Providers/constants.js +3 -4
- package/lib/Providers/index.d.ts +3 -4
- package/lib/Providers/index.js +8 -10
- package/lib/clients/iot.d.ts +1 -0
- package/lib/clients/iot.js +7 -0
- package/lib/clients/mqtt.d.ts +1 -0
- package/lib/clients/mqtt.js +7 -0
- package/lib/index.d.ts +2 -2
- package/lib/index.js +7 -11
- package/lib/tsconfig.tsbuildinfo +1 -0
- package/lib/types/PubSub.d.ts +21 -3
- package/lib/types/PubSub.js +1 -1
- package/lib/types/index.d.ts +0 -1
- package/lib/types/index.js +5 -3
- package/lib/utils/ConnectionStateMonitor.d.ts +5 -5
- package/lib/utils/ConnectionStateMonitor.js +52 -64
- package/lib/utils/ReachabilityMonitor/index.d.ts +1 -3
- package/lib/utils/ReachabilityMonitor/index.js +4 -3
- package/lib/utils/ReachabilityMonitor/index.native.d.ts +1 -3
- package/lib/utils/ReachabilityMonitor/index.native.js +7 -8
- package/lib/utils/ReconnectionMonitor.d.ts +1 -1
- package/lib/utils/ReconnectionMonitor.js +21 -25
- package/lib-esm/Providers/AWSIot.d.ts +10 -0
- package/lib-esm/Providers/AWSIot.js +30 -0
- package/lib-esm/Providers/{MqttOverWSProvider.d.ts → MqttOverWS.d.ts} +16 -16
- package/lib-esm/Providers/MqttOverWS.js +268 -0
- package/lib-esm/Providers/PubSub.d.ts +11 -0
- package/lib-esm/Providers/PubSub.js +15 -0
- package/lib-esm/Providers/constants.d.ts +1 -1
- package/lib-esm/Providers/constants.js +11 -14
- package/lib-esm/Providers/index.d.ts +3 -4
- package/lib-esm/Providers/index.js +3 -5
- package/lib-esm/clients/iot.d.ts +1 -0
- package/{src/internals/index.ts → lib-esm/clients/iot.js} +1 -1
- package/lib-esm/clients/mqtt.d.ts +1 -0
- package/lib-esm/{internals/index.js → clients/mqtt.js} +1 -2
- package/lib-esm/index.d.ts +2 -2
- package/lib-esm/index.js +2 -3
- package/lib-esm/tsconfig.tsbuildinfo +1 -0
- package/lib-esm/types/PubSub.d.ts +21 -3
- package/lib-esm/types/PubSub.js +0 -1
- package/lib-esm/types/index.d.ts +0 -1
- package/lib-esm/types/index.js +2 -1
- package/lib-esm/utils/ConnectionStateMonitor.d.ts +5 -5
- package/lib-esm/utils/ConnectionStateMonitor.js +50 -64
- package/lib-esm/utils/ReachabilityMonitor/index.d.ts +1 -3
- package/lib-esm/utils/ReachabilityMonitor/index.js +2 -3
- package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +1 -3
- package/lib-esm/utils/ReachabilityMonitor/index.native.js +2 -5
- package/lib-esm/utils/ReconnectionMonitor.d.ts +1 -1
- package/lib-esm/utils/ReconnectionMonitor.js +19 -25
- package/mqtt/packages.json +7 -0
- package/package.json +146 -126
- package/src/Providers/{AWSIotProvider.ts → AWSIot.ts} +17 -15
- package/src/Providers/{MqttOverWSProvider.ts → MqttOverWS.ts} +38 -50
- package/src/Providers/PubSub.ts +40 -0
- package/src/Providers/constants.ts +2 -6
- package/src/Providers/index.ts +3 -12
- package/src/clients/iot.ts +4 -0
- package/src/clients/mqtt.ts +7 -0
- package/src/index.ts +3 -12
- package/src/types/PubSub.ts +28 -5
- package/src/types/index.ts +0 -1
- package/src/utils/ConnectionStateMonitor.ts +17 -13
- package/src/utils/ReachabilityMonitor/index.native.ts +2 -1
- package/src/utils/ReachabilityMonitor/index.ts +1 -1
- package/src/utils/ReconnectionMonitor.ts +1 -1
- package/internals/package.json +0 -8
- package/lib/.tsbuildinfo +0 -3
- package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +0 -77
- package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +0 -856
- package/lib/Providers/AWSAppSyncRealTimeProvider/index.js.map +0 -1
- package/lib/Providers/AWSIotProvider.d.ts +0 -11
- package/lib/Providers/AWSIotProvider.js +0 -53
- package/lib/Providers/AWSIotProvider.js.map +0 -1
- package/lib/Providers/MqttOverWSProvider.js +0 -396
- package/lib/Providers/MqttOverWSProvider.js.map +0 -1
- package/lib/Providers/PubSubProvider.d.ts +0 -15
- package/lib/Providers/PubSubProvider.js +0 -28
- package/lib/Providers/PubSubProvider.js.map +0 -1
- package/lib/Providers/constants.js.map +0 -1
- package/lib/Providers/index.js.map +0 -1
- package/lib/PubSub.d.ts +0 -13
- package/lib/PubSub.js +0 -22
- package/lib/PubSub.js.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/internals/InternalPubSub.d.ts +0 -50
- package/lib/internals/InternalPubSub.js +0 -136
- package/lib/internals/InternalPubSub.js.map +0 -1
- package/lib/internals/index.d.ts +0 -1
- package/lib/internals/index.js +0 -8
- package/lib/internals/index.js.map +0 -1
- package/lib/types/Provider.d.ts +0 -18
- package/lib/types/Provider.js +0 -3
- package/lib/types/Provider.js.map +0 -1
- package/lib/types/PubSub.js.map +0 -1
- package/lib/types/index.js.map +0 -1
- package/lib/utils/ConnectionStateMonitor.js.map +0 -1
- package/lib/utils/ReachabilityMonitor/index.js.map +0 -1
- package/lib/utils/ReachabilityMonitor/index.native.js.map +0 -1
- package/lib/utils/ReconnectionMonitor.js.map +0 -1
- package/lib/vendor/paho-mqtt.d.ts +0 -2
- package/lib/vendor/paho-mqtt.js.map +0 -1
- package/lib-esm/.tsbuildinfo +0 -3
- package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +0 -77
- package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +0 -854
- package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js.map +0 -1
- package/lib-esm/Providers/AWSIotProvider.d.ts +0 -11
- package/lib-esm/Providers/AWSIotProvider.js +0 -51
- package/lib-esm/Providers/AWSIotProvider.js.map +0 -1
- package/lib-esm/Providers/MqttOverWSProvider.js +0 -393
- package/lib-esm/Providers/MqttOverWSProvider.js.map +0 -1
- package/lib-esm/Providers/PubSubProvider.d.ts +0 -15
- package/lib-esm/Providers/PubSubProvider.js +0 -26
- package/lib-esm/Providers/PubSubProvider.js.map +0 -1
- package/lib-esm/Providers/constants.js.map +0 -1
- package/lib-esm/Providers/index.js.map +0 -1
- package/lib-esm/PubSub.d.ts +0 -13
- package/lib-esm/PubSub.js +0 -20
- package/lib-esm/PubSub.js.map +0 -1
- package/lib-esm/index.js.map +0 -1
- package/lib-esm/internals/InternalPubSub.d.ts +0 -50
- package/lib-esm/internals/InternalPubSub.js +0 -134
- package/lib-esm/internals/InternalPubSub.js.map +0 -1
- package/lib-esm/internals/index.d.ts +0 -1
- package/lib-esm/internals/index.js.map +0 -1
- package/lib-esm/types/Provider.d.ts +0 -18
- package/lib-esm/types/Provider.js +0 -1
- package/lib-esm/types/Provider.js.map +0 -1
- package/lib-esm/types/PubSub.js.map +0 -1
- package/lib-esm/types/index.js.map +0 -1
- package/lib-esm/utils/ConnectionStateMonitor.js.map +0 -1
- package/lib-esm/utils/ReachabilityMonitor/index.js.map +0 -1
- package/lib-esm/utils/ReachabilityMonitor/index.native.js.map +0 -1
- package/lib-esm/utils/ReconnectionMonitor.js.map +0 -1
- package/lib-esm/vendor/paho-mqtt.d.ts +0 -2
- package/lib-esm/vendor/paho-mqtt.js.map +0 -1
- package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +0 -1049
- package/src/Providers/PubSubProvider.ts +0 -53
- package/src/PubSub.ts +0 -33
- package/src/internals/InternalPubSub.ts +0 -185
- package/src/types/Provider.ts +0 -37
|
@@ -1,1049 +0,0 @@
|
|
|
1
|
-
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
-
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
-
import Observable, { ZenObservable } from 'zen-observable-ts';
|
|
4
|
-
import { GraphQLError } from 'graphql';
|
|
5
|
-
import * as url from 'url';
|
|
6
|
-
import { v4 as uuid } from 'uuid';
|
|
7
|
-
import { Buffer } from 'buffer';
|
|
8
|
-
import { ProviderOptions } from '../../types/Provider';
|
|
9
|
-
import {
|
|
10
|
-
Logger,
|
|
11
|
-
Credentials,
|
|
12
|
-
Signer,
|
|
13
|
-
Hub,
|
|
14
|
-
Constants,
|
|
15
|
-
USER_AGENT_HEADER,
|
|
16
|
-
jitteredExponentialRetry,
|
|
17
|
-
NonRetryableError,
|
|
18
|
-
ICredentials,
|
|
19
|
-
isNonRetryableError,
|
|
20
|
-
CustomUserAgentDetails,
|
|
21
|
-
getAmplifyUserAgent,
|
|
22
|
-
} from '@aws-amplify/core';
|
|
23
|
-
import { Cache } from '@aws-amplify/cache';
|
|
24
|
-
import { Auth, GRAPHQL_AUTH_MODE } from '@aws-amplify/auth';
|
|
25
|
-
import { AbstractPubSubProvider } from '../PubSubProvider';
|
|
26
|
-
import {
|
|
27
|
-
CONTROL_MSG,
|
|
28
|
-
ConnectionState,
|
|
29
|
-
PubSubContent,
|
|
30
|
-
PubSubContentObserver,
|
|
31
|
-
} from '../../types/PubSub';
|
|
32
|
-
|
|
33
|
-
import {
|
|
34
|
-
AMPLIFY_SYMBOL,
|
|
35
|
-
AWS_APPSYNC_REALTIME_HEADERS,
|
|
36
|
-
CONNECTION_INIT_TIMEOUT,
|
|
37
|
-
DEFAULT_KEEP_ALIVE_TIMEOUT,
|
|
38
|
-
DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT,
|
|
39
|
-
MAX_DELAY_MS,
|
|
40
|
-
MESSAGE_TYPES,
|
|
41
|
-
NON_RETRYABLE_CODES,
|
|
42
|
-
SOCKET_STATUS,
|
|
43
|
-
START_ACK_TIMEOUT,
|
|
44
|
-
SUBSCRIPTION_STATUS,
|
|
45
|
-
CONNECTION_STATE_CHANGE,
|
|
46
|
-
} from '../constants';
|
|
47
|
-
import {
|
|
48
|
-
ConnectionStateMonitor,
|
|
49
|
-
CONNECTION_CHANGE,
|
|
50
|
-
} from '../../utils/ConnectionStateMonitor';
|
|
51
|
-
import {
|
|
52
|
-
ReconnectEvent,
|
|
53
|
-
ReconnectionMonitor,
|
|
54
|
-
} from '../../utils/ReconnectionMonitor';
|
|
55
|
-
|
|
56
|
-
const logger = new Logger('AWSAppSyncRealTimeProvider');
|
|
57
|
-
|
|
58
|
-
const dispatchApiEvent = (
|
|
59
|
-
event: string,
|
|
60
|
-
data: Record<string, unknown>,
|
|
61
|
-
message: string
|
|
62
|
-
) => {
|
|
63
|
-
Hub.dispatch('api', { event, data, message }, 'PubSub', AMPLIFY_SYMBOL);
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
export type ObserverQuery = {
|
|
67
|
-
observer: PubSubContentObserver;
|
|
68
|
-
query: string;
|
|
69
|
-
variables: Record<string, unknown>;
|
|
70
|
-
subscriptionState: SUBSCRIPTION_STATUS;
|
|
71
|
-
subscriptionReadyCallback?: Function;
|
|
72
|
-
subscriptionFailedCallback?: Function;
|
|
73
|
-
startAckTimeoutId?: ReturnType<typeof setTimeout>;
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
const standardDomainPattern =
|
|
77
|
-
/^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com(?:\.cn)?\/graphql$/i;
|
|
78
|
-
|
|
79
|
-
const customDomainPath = '/realtime';
|
|
80
|
-
|
|
81
|
-
type GraphqlAuthModes = keyof typeof GRAPHQL_AUTH_MODE;
|
|
82
|
-
|
|
83
|
-
type DataObject = {
|
|
84
|
-
data: Record<string, unknown>;
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
type DataPayload = {
|
|
88
|
-
id: string;
|
|
89
|
-
payload: DataObject;
|
|
90
|
-
type: string;
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
type ParsedMessagePayload = {
|
|
94
|
-
type: string;
|
|
95
|
-
payload: {
|
|
96
|
-
connectionTimeoutMs: number;
|
|
97
|
-
errors?: [{ errorType: string; errorCode: number }];
|
|
98
|
-
};
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
export interface AWSAppSyncRealTimeProviderOptions extends ProviderOptions {
|
|
102
|
-
appSyncGraphqlEndpoint?: string;
|
|
103
|
-
authenticationType?: GraphqlAuthModes;
|
|
104
|
-
query?: string;
|
|
105
|
-
variables?: Record<string, unknown>;
|
|
106
|
-
apiKey?: string;
|
|
107
|
-
region?: string;
|
|
108
|
-
graphql_headers?: () => {} | (() => Promise<{}>);
|
|
109
|
-
additionalHeaders?: { [key: string]: string };
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
type AWSAppSyncRealTimeAuthInput =
|
|
113
|
-
Partial<AWSAppSyncRealTimeProviderOptions> & {
|
|
114
|
-
canonicalUri: string;
|
|
115
|
-
payload: string;
|
|
116
|
-
host?: string | undefined;
|
|
117
|
-
};
|
|
118
|
-
|
|
119
|
-
export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider<AWSAppSyncRealTimeProviderOptions> {
|
|
120
|
-
private awsRealTimeSocket?: WebSocket;
|
|
121
|
-
private socketStatus: SOCKET_STATUS = SOCKET_STATUS.CLOSED;
|
|
122
|
-
private keepAliveTimeoutId?: ReturnType<typeof setTimeout>;
|
|
123
|
-
private keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
|
|
124
|
-
private keepAliveAlertTimeoutId?: ReturnType<typeof setTimeout>;
|
|
125
|
-
private subscriptionObserverMap: Map<string, ObserverQuery> = new Map();
|
|
126
|
-
private promiseArray: Array<{ res: Function; rej: Function }> = [];
|
|
127
|
-
private connectionState: ConnectionState;
|
|
128
|
-
private readonly connectionStateMonitor = new ConnectionStateMonitor();
|
|
129
|
-
private readonly reconnectionMonitor = new ReconnectionMonitor();
|
|
130
|
-
private connectionStateMonitorSubscription: ZenObservable.Subscription;
|
|
131
|
-
|
|
132
|
-
constructor(options: ProviderOptions = {}) {
|
|
133
|
-
super(options);
|
|
134
|
-
// Monitor the connection state and pass changes along to Hub
|
|
135
|
-
this.connectionStateMonitorSubscription =
|
|
136
|
-
this.connectionStateMonitor.connectionStateObservable.subscribe(
|
|
137
|
-
connectionState => {
|
|
138
|
-
dispatchApiEvent(
|
|
139
|
-
CONNECTION_STATE_CHANGE,
|
|
140
|
-
{
|
|
141
|
-
provider: this,
|
|
142
|
-
connectionState,
|
|
143
|
-
},
|
|
144
|
-
`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
|
-
}
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* Mark the socket closed and release all active listeners
|
|
173
|
-
*/
|
|
174
|
-
close() {
|
|
175
|
-
// Mark the socket closed both in status and the connection monitor
|
|
176
|
-
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
177
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
|
|
178
|
-
|
|
179
|
-
// Turn off the subscription monitor Hub publishing
|
|
180
|
-
this.connectionStateMonitorSubscription.unsubscribe();
|
|
181
|
-
// Complete all reconnect observers
|
|
182
|
-
this.reconnectionMonitor.close();
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
getNewWebSocket(url: string, protocol: string) {
|
|
186
|
-
return new WebSocket(url, protocol);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
getProviderName() {
|
|
190
|
-
return 'AWSAppSyncRealTimeProvider';
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
newClient(): Promise<any> {
|
|
194
|
-
throw new Error('Not used here');
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
public async publish(
|
|
198
|
-
_topics: string[] | string,
|
|
199
|
-
_msg: PubSubContent,
|
|
200
|
-
_options?: AWSAppSyncRealTimeProviderOptions
|
|
201
|
-
) {
|
|
202
|
-
throw new Error('Operation not supported');
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
// Check if url matches standard domain pattern
|
|
206
|
-
private isCustomDomain(url: string): boolean {
|
|
207
|
-
return url.match(standardDomainPattern) === null;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
subscribe(
|
|
211
|
-
_topics: string[] | string,
|
|
212
|
-
options?: AWSAppSyncRealTimeProviderOptions,
|
|
213
|
-
customUserAgentDetails?: CustomUserAgentDetails
|
|
214
|
-
): Observable<Record<string, unknown>> {
|
|
215
|
-
const appSyncGraphqlEndpoint = options?.appSyncGraphqlEndpoint;
|
|
216
|
-
|
|
217
|
-
return new Observable(observer => {
|
|
218
|
-
if (!options || !appSyncGraphqlEndpoint) {
|
|
219
|
-
observer.error({
|
|
220
|
-
errors: [
|
|
221
|
-
{
|
|
222
|
-
...new GraphQLError(
|
|
223
|
-
`Subscribe only available for AWS AppSync endpoint`
|
|
224
|
-
),
|
|
225
|
-
},
|
|
226
|
-
],
|
|
227
|
-
});
|
|
228
|
-
observer.complete();
|
|
229
|
-
} else {
|
|
230
|
-
let subscriptionStartActive = false;
|
|
231
|
-
const subscriptionId = uuid();
|
|
232
|
-
const startSubscription = () => {
|
|
233
|
-
if (!subscriptionStartActive) {
|
|
234
|
-
subscriptionStartActive = true;
|
|
235
|
-
|
|
236
|
-
const startSubscriptionPromise =
|
|
237
|
-
this._startSubscriptionWithAWSAppSyncRealTime({
|
|
238
|
-
options,
|
|
239
|
-
observer,
|
|
240
|
-
subscriptionId,
|
|
241
|
-
customUserAgentDetails,
|
|
242
|
-
}).catch<any>(err => {
|
|
243
|
-
logger.debug(
|
|
244
|
-
`${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`
|
|
245
|
-
);
|
|
246
|
-
|
|
247
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
248
|
-
});
|
|
249
|
-
startSubscriptionPromise.finally(() => {
|
|
250
|
-
subscriptionStartActive = false;
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
};
|
|
254
|
-
|
|
255
|
-
let reconnectSubscription: ZenObservable.Subscription;
|
|
256
|
-
|
|
257
|
-
// Add an observable to the reconnection list to manage reconnection for this subscription
|
|
258
|
-
reconnectSubscription = new Observable(observer => {
|
|
259
|
-
this.reconnectionMonitor.addObserver(observer);
|
|
260
|
-
}).subscribe(() => {
|
|
261
|
-
startSubscription();
|
|
262
|
-
});
|
|
263
|
-
|
|
264
|
-
startSubscription();
|
|
265
|
-
|
|
266
|
-
return async () => {
|
|
267
|
-
// Cleanup reconnection subscription
|
|
268
|
-
reconnectSubscription?.unsubscribe();
|
|
269
|
-
|
|
270
|
-
// Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
|
|
271
|
-
try {
|
|
272
|
-
// Waiting that subscription has been connected before trying to unsubscribe
|
|
273
|
-
await this._waitForSubscriptionToBeConnected(subscriptionId);
|
|
274
|
-
|
|
275
|
-
const { subscriptionState } =
|
|
276
|
-
this.subscriptionObserverMap.get(subscriptionId) || {};
|
|
277
|
-
|
|
278
|
-
if (!subscriptionState) {
|
|
279
|
-
// subscription already unsubscribed
|
|
280
|
-
return;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {
|
|
284
|
-
this._sendUnsubscriptionMessage(subscriptionId);
|
|
285
|
-
} else {
|
|
286
|
-
throw new Error('Subscription never connected');
|
|
287
|
-
}
|
|
288
|
-
} catch (err) {
|
|
289
|
-
logger.debug(`Error while unsubscribing ${err}`);
|
|
290
|
-
} finally {
|
|
291
|
-
this._removeSubscriptionObserver(subscriptionId);
|
|
292
|
-
}
|
|
293
|
-
};
|
|
294
|
-
}
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
protected get isSSLEnabled() {
|
|
299
|
-
return !this.options[
|
|
300
|
-
'aws_appsync_dangerously_connect_to_http_endpoint_for_testing'
|
|
301
|
-
];
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
private async _startSubscriptionWithAWSAppSyncRealTime({
|
|
305
|
-
options,
|
|
306
|
-
observer,
|
|
307
|
-
subscriptionId,
|
|
308
|
-
customUserAgentDetails,
|
|
309
|
-
}: {
|
|
310
|
-
options: AWSAppSyncRealTimeProviderOptions;
|
|
311
|
-
observer: PubSubContentObserver;
|
|
312
|
-
subscriptionId: string;
|
|
313
|
-
customUserAgentDetails: CustomUserAgentDetails;
|
|
314
|
-
}) {
|
|
315
|
-
const {
|
|
316
|
-
appSyncGraphqlEndpoint,
|
|
317
|
-
authenticationType,
|
|
318
|
-
query,
|
|
319
|
-
variables,
|
|
320
|
-
apiKey,
|
|
321
|
-
region,
|
|
322
|
-
graphql_headers = () => ({}),
|
|
323
|
-
additionalHeaders = {},
|
|
324
|
-
} = options;
|
|
325
|
-
|
|
326
|
-
const subscriptionState: SUBSCRIPTION_STATUS = SUBSCRIPTION_STATUS.PENDING;
|
|
327
|
-
const data = {
|
|
328
|
-
query,
|
|
329
|
-
variables,
|
|
330
|
-
};
|
|
331
|
-
// Having a subscription id map will make it simple to forward messages received
|
|
332
|
-
this.subscriptionObserverMap.set(subscriptionId, {
|
|
333
|
-
observer,
|
|
334
|
-
query: query ?? '',
|
|
335
|
-
variables: variables ?? {},
|
|
336
|
-
subscriptionState,
|
|
337
|
-
startAckTimeoutId: undefined,
|
|
338
|
-
});
|
|
339
|
-
|
|
340
|
-
// Preparing payload for subscription message
|
|
341
|
-
|
|
342
|
-
const dataString = JSON.stringify(data);
|
|
343
|
-
const headerObj = {
|
|
344
|
-
...(await this._awsRealTimeHeaderBasedAuth({
|
|
345
|
-
apiKey,
|
|
346
|
-
appSyncGraphqlEndpoint,
|
|
347
|
-
authenticationType,
|
|
348
|
-
payload: dataString,
|
|
349
|
-
canonicalUri: '',
|
|
350
|
-
region,
|
|
351
|
-
additionalHeaders,
|
|
352
|
-
})),
|
|
353
|
-
...(await graphql_headers()),
|
|
354
|
-
...additionalHeaders,
|
|
355
|
-
[USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
|
|
356
|
-
};
|
|
357
|
-
|
|
358
|
-
const subscriptionMessage = {
|
|
359
|
-
id: subscriptionId,
|
|
360
|
-
payload: {
|
|
361
|
-
data: dataString,
|
|
362
|
-
extensions: {
|
|
363
|
-
authorization: {
|
|
364
|
-
...headerObj,
|
|
365
|
-
},
|
|
366
|
-
},
|
|
367
|
-
},
|
|
368
|
-
type: MESSAGE_TYPES.GQL_START,
|
|
369
|
-
};
|
|
370
|
-
|
|
371
|
-
const stringToAWSRealTime = JSON.stringify(subscriptionMessage);
|
|
372
|
-
|
|
373
|
-
try {
|
|
374
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
|
|
375
|
-
await this._initializeWebSocketConnection({
|
|
376
|
-
apiKey,
|
|
377
|
-
appSyncGraphqlEndpoint,
|
|
378
|
-
authenticationType,
|
|
379
|
-
region,
|
|
380
|
-
additionalHeaders,
|
|
381
|
-
});
|
|
382
|
-
} catch (err) {
|
|
383
|
-
this._logStartSubscriptionError(subscriptionId, observer, err);
|
|
384
|
-
return;
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
// Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
|
|
388
|
-
// E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
|
|
389
|
-
// Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
|
|
390
|
-
|
|
391
|
-
const { subscriptionFailedCallback, subscriptionReadyCallback } =
|
|
392
|
-
this.subscriptionObserverMap.get(subscriptionId) ?? {};
|
|
393
|
-
|
|
394
|
-
// This must be done before sending the message in order to be listening immediately
|
|
395
|
-
this.subscriptionObserverMap.set(subscriptionId, {
|
|
396
|
-
observer,
|
|
397
|
-
subscriptionState,
|
|
398
|
-
query: query ?? '',
|
|
399
|
-
variables: variables ?? {},
|
|
400
|
-
subscriptionReadyCallback,
|
|
401
|
-
subscriptionFailedCallback,
|
|
402
|
-
startAckTimeoutId: setTimeout(() => {
|
|
403
|
-
this._timeoutStartSubscriptionAck.call(this, subscriptionId);
|
|
404
|
-
}, START_ACK_TIMEOUT),
|
|
405
|
-
});
|
|
406
|
-
if (this.awsRealTimeSocket) {
|
|
407
|
-
this.awsRealTimeSocket.send(stringToAWSRealTime);
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
// Log logic for start subscription failures
|
|
412
|
-
private _logStartSubscriptionError(
|
|
413
|
-
subscriptionId: string,
|
|
414
|
-
observer: PubSubContentObserver,
|
|
415
|
-
err: { message?: string }
|
|
416
|
-
) {
|
|
417
|
-
logger.debug({ err });
|
|
418
|
-
const message = String(err.message ?? '');
|
|
419
|
-
// Resolving to give the state observer time to propogate the update
|
|
420
|
-
Promise.resolve(
|
|
421
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED)
|
|
422
|
-
);
|
|
423
|
-
|
|
424
|
-
// Capture the error only when the network didn't cause disruption
|
|
425
|
-
if (
|
|
426
|
-
this.connectionState !== ConnectionState.ConnectionDisruptedPendingNetwork
|
|
427
|
-
) {
|
|
428
|
-
// When the error is non-retriable, error out the observable
|
|
429
|
-
if (isNonRetryableError(err)) {
|
|
430
|
-
observer.error({
|
|
431
|
-
errors: [
|
|
432
|
-
{
|
|
433
|
-
...new GraphQLError(
|
|
434
|
-
`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`
|
|
435
|
-
),
|
|
436
|
-
},
|
|
437
|
-
],
|
|
438
|
-
});
|
|
439
|
-
} else {
|
|
440
|
-
logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
const { subscriptionFailedCallback } =
|
|
444
|
-
this.subscriptionObserverMap.get(subscriptionId) || {};
|
|
445
|
-
|
|
446
|
-
// Notify concurrent unsubscription
|
|
447
|
-
if (typeof subscriptionFailedCallback === 'function') {
|
|
448
|
-
subscriptionFailedCallback();
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
// Waiting that subscription has been connected before trying to unsubscribe
|
|
454
|
-
private async _waitForSubscriptionToBeConnected(subscriptionId: string) {
|
|
455
|
-
const subscriptionObserver =
|
|
456
|
-
this.subscriptionObserverMap.get(subscriptionId);
|
|
457
|
-
if (subscriptionObserver) {
|
|
458
|
-
const { subscriptionState } = subscriptionObserver;
|
|
459
|
-
// This in case unsubscribe is invoked before sending start subscription message
|
|
460
|
-
if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
|
|
461
|
-
return new Promise((res, rej) => {
|
|
462
|
-
const { observer, subscriptionState, variables, query } =
|
|
463
|
-
subscriptionObserver;
|
|
464
|
-
this.subscriptionObserverMap.set(subscriptionId, {
|
|
465
|
-
observer,
|
|
466
|
-
subscriptionState,
|
|
467
|
-
variables,
|
|
468
|
-
query,
|
|
469
|
-
subscriptionReadyCallback: res,
|
|
470
|
-
subscriptionFailedCallback: rej,
|
|
471
|
-
});
|
|
472
|
-
});
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
private _sendUnsubscriptionMessage(subscriptionId: string) {
|
|
478
|
-
try {
|
|
479
|
-
if (
|
|
480
|
-
this.awsRealTimeSocket &&
|
|
481
|
-
this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
|
|
482
|
-
this.socketStatus === SOCKET_STATUS.READY
|
|
483
|
-
) {
|
|
484
|
-
// Preparing unsubscribe message to stop receiving messages for that subscription
|
|
485
|
-
const unsubscribeMessage = {
|
|
486
|
-
id: subscriptionId,
|
|
487
|
-
type: MESSAGE_TYPES.GQL_STOP,
|
|
488
|
-
};
|
|
489
|
-
const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
|
|
490
|
-
this.awsRealTimeSocket.send(stringToAWSRealTime);
|
|
491
|
-
}
|
|
492
|
-
} catch (err) {
|
|
493
|
-
// If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
|
|
494
|
-
logger.debug({ err });
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
private _removeSubscriptionObserver(subscriptionId: string) {
|
|
499
|
-
this.subscriptionObserverMap.delete(subscriptionId);
|
|
500
|
-
|
|
501
|
-
// Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
|
|
502
|
-
setTimeout(this._closeSocketIfRequired.bind(this), 1000);
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
private _closeSocketIfRequired() {
|
|
506
|
-
if (this.subscriptionObserverMap.size > 0) {
|
|
507
|
-
// Active subscriptions on the WebSocket
|
|
508
|
-
return;
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
if (!this.awsRealTimeSocket) {
|
|
512
|
-
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
513
|
-
return;
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
|
|
517
|
-
|
|
518
|
-
if (this.awsRealTimeSocket.bufferedAmount > 0) {
|
|
519
|
-
// Still data on the WebSocket
|
|
520
|
-
setTimeout(this._closeSocketIfRequired.bind(this), 1000);
|
|
521
|
-
} else {
|
|
522
|
-
logger.debug('closing WebSocket...');
|
|
523
|
-
if (this.keepAliveTimeoutId) {
|
|
524
|
-
clearTimeout(this.keepAliveTimeoutId);
|
|
525
|
-
}
|
|
526
|
-
if (this.keepAliveAlertTimeoutId) {
|
|
527
|
-
clearTimeout(this.keepAliveAlertTimeoutId);
|
|
528
|
-
}
|
|
529
|
-
const tempSocket = this.awsRealTimeSocket;
|
|
530
|
-
// Cleaning callbacks to avoid race condition, socket still exists
|
|
531
|
-
tempSocket.onclose = null;
|
|
532
|
-
tempSocket.onerror = null;
|
|
533
|
-
tempSocket.close(1000);
|
|
534
|
-
this.awsRealTimeSocket = undefined;
|
|
535
|
-
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
536
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
private _handleIncomingSubscriptionMessage(message: MessageEvent) {
|
|
541
|
-
if (typeof message.data !== 'string') {
|
|
542
|
-
return;
|
|
543
|
-
}
|
|
544
|
-
logger.debug(
|
|
545
|
-
`subscription message from AWS AppSync RealTime: ${message.data}`
|
|
546
|
-
);
|
|
547
|
-
const {
|
|
548
|
-
id = '',
|
|
549
|
-
payload,
|
|
550
|
-
type,
|
|
551
|
-
}: DataPayload = JSON.parse(String(message.data));
|
|
552
|
-
const {
|
|
553
|
-
observer = null,
|
|
554
|
-
query = '',
|
|
555
|
-
variables = {},
|
|
556
|
-
startAckTimeoutId,
|
|
557
|
-
subscriptionReadyCallback,
|
|
558
|
-
subscriptionFailedCallback,
|
|
559
|
-
} = this.subscriptionObserverMap.get(id) || {};
|
|
560
|
-
|
|
561
|
-
logger.debug({ id, observer, query, variables });
|
|
562
|
-
|
|
563
|
-
if (type === MESSAGE_TYPES.GQL_DATA && payload && payload.data) {
|
|
564
|
-
if (observer) {
|
|
565
|
-
observer.next(payload);
|
|
566
|
-
} else {
|
|
567
|
-
logger.debug(`observer not found for id: ${id}`);
|
|
568
|
-
}
|
|
569
|
-
return;
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
if (type === MESSAGE_TYPES.GQL_START_ACK) {
|
|
573
|
-
logger.debug(
|
|
574
|
-
`subscription ready for ${JSON.stringify({ query, variables })}`
|
|
575
|
-
);
|
|
576
|
-
if (typeof subscriptionReadyCallback === 'function') {
|
|
577
|
-
subscriptionReadyCallback();
|
|
578
|
-
}
|
|
579
|
-
if (startAckTimeoutId) clearTimeout(startAckTimeoutId);
|
|
580
|
-
dispatchApiEvent(
|
|
581
|
-
CONTROL_MSG.SUBSCRIPTION_ACK,
|
|
582
|
-
{ query, variables },
|
|
583
|
-
'Connection established for subscription'
|
|
584
|
-
);
|
|
585
|
-
const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
|
|
586
|
-
if (observer) {
|
|
587
|
-
this.subscriptionObserverMap.set(id, {
|
|
588
|
-
observer,
|
|
589
|
-
query,
|
|
590
|
-
variables,
|
|
591
|
-
startAckTimeoutId: undefined,
|
|
592
|
-
subscriptionState,
|
|
593
|
-
subscriptionReadyCallback,
|
|
594
|
-
subscriptionFailedCallback,
|
|
595
|
-
});
|
|
596
|
-
}
|
|
597
|
-
this.connectionStateMonitor.record(
|
|
598
|
-
CONNECTION_CHANGE.CONNECTION_ESTABLISHED
|
|
599
|
-
);
|
|
600
|
-
|
|
601
|
-
return;
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
|
|
605
|
-
if (this.keepAliveTimeoutId) clearTimeout(this.keepAliveTimeoutId);
|
|
606
|
-
if (this.keepAliveAlertTimeoutId)
|
|
607
|
-
clearTimeout(this.keepAliveAlertTimeoutId);
|
|
608
|
-
this.keepAliveTimeoutId = setTimeout(
|
|
609
|
-
() => this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT),
|
|
610
|
-
this.keepAliveTimeout
|
|
611
|
-
);
|
|
612
|
-
this.keepAliveAlertTimeoutId = setTimeout(() => {
|
|
613
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
|
|
614
|
-
}, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
|
|
615
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);
|
|
616
|
-
return;
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
if (type === MESSAGE_TYPES.GQL_ERROR) {
|
|
620
|
-
const subscriptionState = SUBSCRIPTION_STATUS.FAILED;
|
|
621
|
-
if (observer) {
|
|
622
|
-
this.subscriptionObserverMap.set(id, {
|
|
623
|
-
observer,
|
|
624
|
-
query,
|
|
625
|
-
variables,
|
|
626
|
-
startAckTimeoutId,
|
|
627
|
-
subscriptionReadyCallback,
|
|
628
|
-
subscriptionFailedCallback,
|
|
629
|
-
subscriptionState,
|
|
630
|
-
});
|
|
631
|
-
|
|
632
|
-
logger.debug(
|
|
633
|
-
`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`
|
|
634
|
-
);
|
|
635
|
-
|
|
636
|
-
observer.error({
|
|
637
|
-
errors: [
|
|
638
|
-
{
|
|
639
|
-
...new GraphQLError(
|
|
640
|
-
`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`
|
|
641
|
-
),
|
|
642
|
-
},
|
|
643
|
-
],
|
|
644
|
-
});
|
|
645
|
-
|
|
646
|
-
if (startAckTimeoutId) clearTimeout(startAckTimeoutId);
|
|
647
|
-
|
|
648
|
-
if (typeof subscriptionFailedCallback === 'function') {
|
|
649
|
-
subscriptionFailedCallback();
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
private _errorDisconnect(msg: string) {
|
|
656
|
-
logger.debug(`Disconnect error: ${msg}`);
|
|
657
|
-
|
|
658
|
-
if (this.awsRealTimeSocket) {
|
|
659
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
660
|
-
this.awsRealTimeSocket.close();
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
private _timeoutStartSubscriptionAck(subscriptionId: string) {
|
|
667
|
-
const subscriptionObserver =
|
|
668
|
-
this.subscriptionObserverMap.get(subscriptionId);
|
|
669
|
-
if (subscriptionObserver) {
|
|
670
|
-
const { observer, query, variables } = subscriptionObserver;
|
|
671
|
-
if (!observer) {
|
|
672
|
-
return;
|
|
673
|
-
}
|
|
674
|
-
this.subscriptionObserverMap.set(subscriptionId, {
|
|
675
|
-
observer,
|
|
676
|
-
query,
|
|
677
|
-
variables,
|
|
678
|
-
subscriptionState: SUBSCRIPTION_STATUS.FAILED,
|
|
679
|
-
});
|
|
680
|
-
|
|
681
|
-
this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
|
|
682
|
-
logger.debug(
|
|
683
|
-
'timeoutStartSubscription',
|
|
684
|
-
JSON.stringify({ query, variables })
|
|
685
|
-
);
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
private _initializeWebSocketConnection({
|
|
690
|
-
appSyncGraphqlEndpoint,
|
|
691
|
-
authenticationType,
|
|
692
|
-
apiKey,
|
|
693
|
-
region,
|
|
694
|
-
additionalHeaders,
|
|
695
|
-
}: AWSAppSyncRealTimeProviderOptions) {
|
|
696
|
-
if (this.socketStatus === SOCKET_STATUS.READY) {
|
|
697
|
-
return;
|
|
698
|
-
}
|
|
699
|
-
return new Promise(async (res, rej) => {
|
|
700
|
-
this.promiseArray.push({ res, rej });
|
|
701
|
-
|
|
702
|
-
if (this.socketStatus === SOCKET_STATUS.CLOSED) {
|
|
703
|
-
try {
|
|
704
|
-
this.socketStatus = SOCKET_STATUS.CONNECTING;
|
|
705
|
-
|
|
706
|
-
const payloadString = '{}';
|
|
707
|
-
|
|
708
|
-
const authHeader = await this._awsRealTimeHeaderBasedAuth({
|
|
709
|
-
authenticationType,
|
|
710
|
-
payload: payloadString,
|
|
711
|
-
canonicalUri: '/connect',
|
|
712
|
-
apiKey,
|
|
713
|
-
appSyncGraphqlEndpoint,
|
|
714
|
-
region,
|
|
715
|
-
additionalHeaders,
|
|
716
|
-
});
|
|
717
|
-
|
|
718
|
-
const headerString = authHeader ? JSON.stringify(authHeader) : '';
|
|
719
|
-
const headerQs = Buffer.from(headerString).toString('base64');
|
|
720
|
-
|
|
721
|
-
const payloadQs = Buffer.from(payloadString).toString('base64');
|
|
722
|
-
|
|
723
|
-
let discoverableEndpoint = appSyncGraphqlEndpoint ?? '';
|
|
724
|
-
|
|
725
|
-
if (this.isCustomDomain(discoverableEndpoint)) {
|
|
726
|
-
discoverableEndpoint =
|
|
727
|
-
discoverableEndpoint.concat(customDomainPath);
|
|
728
|
-
} else {
|
|
729
|
-
discoverableEndpoint = discoverableEndpoint
|
|
730
|
-
.replace('appsync-api', 'appsync-realtime-api')
|
|
731
|
-
.replace('gogi-beta', 'grt-beta');
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
// Creating websocket url with required query strings
|
|
735
|
-
const protocol = this.isSSLEnabled ? 'wss://' : 'ws://';
|
|
736
|
-
discoverableEndpoint = discoverableEndpoint
|
|
737
|
-
.replace('https://', protocol)
|
|
738
|
-
.replace('http://', protocol);
|
|
739
|
-
|
|
740
|
-
const awsRealTimeUrl = `${discoverableEndpoint}?header=${headerQs}&payload=${payloadQs}`;
|
|
741
|
-
|
|
742
|
-
await this._initializeRetryableHandshake(awsRealTimeUrl);
|
|
743
|
-
|
|
744
|
-
this.promiseArray.forEach(({ res }) => {
|
|
745
|
-
logger.debug('Notifying connection successful');
|
|
746
|
-
res();
|
|
747
|
-
});
|
|
748
|
-
this.socketStatus = SOCKET_STATUS.READY;
|
|
749
|
-
this.promiseArray = [];
|
|
750
|
-
} catch (err) {
|
|
751
|
-
logger.debug('Connection exited with', err);
|
|
752
|
-
this.promiseArray.forEach(({ rej }) => rej(err));
|
|
753
|
-
this.promiseArray = [];
|
|
754
|
-
if (
|
|
755
|
-
this.awsRealTimeSocket &&
|
|
756
|
-
this.awsRealTimeSocket.readyState === WebSocket.OPEN
|
|
757
|
-
) {
|
|
758
|
-
this.awsRealTimeSocket.close(3001);
|
|
759
|
-
}
|
|
760
|
-
this.awsRealTimeSocket = undefined;
|
|
761
|
-
this.socketStatus = SOCKET_STATUS.CLOSED;
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
private async _initializeRetryableHandshake(awsRealTimeUrl: string) {
|
|
768
|
-
logger.debug(`Initializaling retryable Handshake`);
|
|
769
|
-
await jitteredExponentialRetry(
|
|
770
|
-
this._initializeHandshake.bind(this),
|
|
771
|
-
[awsRealTimeUrl],
|
|
772
|
-
MAX_DELAY_MS
|
|
773
|
-
);
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
private async _initializeHandshake(awsRealTimeUrl: string) {
|
|
777
|
-
logger.debug(`Initializing handshake ${awsRealTimeUrl}`);
|
|
778
|
-
// Because connecting the socket is async, is waiting until connection is open
|
|
779
|
-
// Step 1: connect websocket
|
|
780
|
-
try {
|
|
781
|
-
await (() => {
|
|
782
|
-
return new Promise<void>((res, rej) => {
|
|
783
|
-
const newSocket = this.getNewWebSocket(awsRealTimeUrl, 'graphql-ws');
|
|
784
|
-
newSocket.onerror = () => {
|
|
785
|
-
logger.debug(`WebSocket connection error`);
|
|
786
|
-
};
|
|
787
|
-
newSocket.onclose = () => {
|
|
788
|
-
rej(new Error('Connection handshake error'));
|
|
789
|
-
};
|
|
790
|
-
newSocket.onopen = () => {
|
|
791
|
-
this.awsRealTimeSocket = newSocket;
|
|
792
|
-
return res();
|
|
793
|
-
};
|
|
794
|
-
});
|
|
795
|
-
})();
|
|
796
|
-
// Step 2: wait for ack from AWS AppSyncReaTime after sending init
|
|
797
|
-
await (() => {
|
|
798
|
-
return new Promise((res, rej) => {
|
|
799
|
-
if (this.awsRealTimeSocket) {
|
|
800
|
-
let ackOk = false;
|
|
801
|
-
this.awsRealTimeSocket.onerror = error => {
|
|
802
|
-
logger.debug(`WebSocket error ${JSON.stringify(error)}`);
|
|
803
|
-
};
|
|
804
|
-
this.awsRealTimeSocket.onclose = event => {
|
|
805
|
-
logger.debug(`WebSocket closed ${event.reason}`);
|
|
806
|
-
rej(new Error(JSON.stringify(event)));
|
|
807
|
-
};
|
|
808
|
-
|
|
809
|
-
this.awsRealTimeSocket.onmessage = (message: MessageEvent) => {
|
|
810
|
-
if (typeof message.data !== 'string') {
|
|
811
|
-
return;
|
|
812
|
-
}
|
|
813
|
-
logger.debug(
|
|
814
|
-
`subscription message from AWS AppSyncRealTime: ${message.data} `
|
|
815
|
-
);
|
|
816
|
-
const data = JSON.parse(message.data) as ParsedMessagePayload;
|
|
817
|
-
const {
|
|
818
|
-
type,
|
|
819
|
-
payload: {
|
|
820
|
-
connectionTimeoutMs = DEFAULT_KEEP_ALIVE_TIMEOUT,
|
|
821
|
-
} = {},
|
|
822
|
-
} = data;
|
|
823
|
-
if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
|
|
824
|
-
ackOk = true;
|
|
825
|
-
if (this.awsRealTimeSocket) {
|
|
826
|
-
this.keepAliveTimeout = connectionTimeoutMs;
|
|
827
|
-
this.awsRealTimeSocket.onmessage =
|
|
828
|
-
this._handleIncomingSubscriptionMessage.bind(this);
|
|
829
|
-
this.awsRealTimeSocket.onerror = err => {
|
|
830
|
-
logger.debug(err);
|
|
831
|
-
this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
|
|
832
|
-
};
|
|
833
|
-
this.awsRealTimeSocket.onclose = event => {
|
|
834
|
-
logger.debug(`WebSocket closed ${event.reason}`);
|
|
835
|
-
this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
|
|
836
|
-
};
|
|
837
|
-
}
|
|
838
|
-
res('Cool, connected to AWS AppSyncRealTime');
|
|
839
|
-
return;
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
|
|
843
|
-
const {
|
|
844
|
-
payload: {
|
|
845
|
-
errors: [{ errorType = '', errorCode = 0 } = {}] = [],
|
|
846
|
-
} = {},
|
|
847
|
-
} = data;
|
|
848
|
-
|
|
849
|
-
rej({ errorType, errorCode });
|
|
850
|
-
}
|
|
851
|
-
};
|
|
852
|
-
|
|
853
|
-
const gqlInit = {
|
|
854
|
-
type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
|
|
855
|
-
};
|
|
856
|
-
this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
|
|
857
|
-
|
|
858
|
-
const checkAckOk = (ackOk: boolean) => {
|
|
859
|
-
if (!ackOk) {
|
|
860
|
-
this.connectionStateMonitor.record(
|
|
861
|
-
CONNECTION_CHANGE.CONNECTION_FAILED
|
|
862
|
-
);
|
|
863
|
-
rej(
|
|
864
|
-
new Error(
|
|
865
|
-
`Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`
|
|
866
|
-
)
|
|
867
|
-
);
|
|
868
|
-
}
|
|
869
|
-
};
|
|
870
|
-
|
|
871
|
-
setTimeout(() => checkAckOk(ackOk), CONNECTION_INIT_TIMEOUT);
|
|
872
|
-
}
|
|
873
|
-
});
|
|
874
|
-
})();
|
|
875
|
-
} catch (err) {
|
|
876
|
-
const { errorType, errorCode } = err as {
|
|
877
|
-
errorType: string;
|
|
878
|
-
errorCode: number;
|
|
879
|
-
};
|
|
880
|
-
|
|
881
|
-
if (NON_RETRYABLE_CODES.includes(errorCode)) {
|
|
882
|
-
throw new NonRetryableError(errorType);
|
|
883
|
-
} else if (errorType) {
|
|
884
|
-
throw new Error(errorType);
|
|
885
|
-
} else {
|
|
886
|
-
throw err;
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
private async _awsRealTimeHeaderBasedAuth({
|
|
892
|
-
authenticationType,
|
|
893
|
-
payload,
|
|
894
|
-
canonicalUri,
|
|
895
|
-
appSyncGraphqlEndpoint,
|
|
896
|
-
apiKey,
|
|
897
|
-
region,
|
|
898
|
-
additionalHeaders,
|
|
899
|
-
}: AWSAppSyncRealTimeAuthInput): Promise<
|
|
900
|
-
Record<string, unknown> | undefined
|
|
901
|
-
> {
|
|
902
|
-
const headerHandler: {
|
|
903
|
-
[key in GraphqlAuthModes]: (AWSAppSyncRealTimeAuthInput) => {};
|
|
904
|
-
} = {
|
|
905
|
-
API_KEY: this._awsRealTimeApiKeyHeader.bind(this),
|
|
906
|
-
AWS_IAM: this._awsRealTimeIAMHeader.bind(this),
|
|
907
|
-
OPENID_CONNECT: this._awsRealTimeOPENIDHeader.bind(this),
|
|
908
|
-
AMAZON_COGNITO_USER_POOLS: this._awsRealTimeCUPHeader.bind(this),
|
|
909
|
-
AWS_LAMBDA: this._customAuthHeader,
|
|
910
|
-
};
|
|
911
|
-
|
|
912
|
-
if (!authenticationType || !headerHandler[authenticationType]) {
|
|
913
|
-
logger.debug(`Authentication type ${authenticationType} not supported`);
|
|
914
|
-
return undefined;
|
|
915
|
-
} else {
|
|
916
|
-
const handler = headerHandler[authenticationType];
|
|
917
|
-
|
|
918
|
-
const { host } = url.parse(appSyncGraphqlEndpoint ?? '');
|
|
919
|
-
|
|
920
|
-
logger.debug(`Authenticating with ${authenticationType}`);
|
|
921
|
-
|
|
922
|
-
const result = await handler({
|
|
923
|
-
payload,
|
|
924
|
-
canonicalUri,
|
|
925
|
-
appSyncGraphqlEndpoint,
|
|
926
|
-
apiKey,
|
|
927
|
-
region,
|
|
928
|
-
host,
|
|
929
|
-
additionalHeaders,
|
|
930
|
-
});
|
|
931
|
-
|
|
932
|
-
return result;
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
private async _awsRealTimeCUPHeader({ host }: AWSAppSyncRealTimeAuthInput) {
|
|
937
|
-
const session = await Auth.currentSession();
|
|
938
|
-
return {
|
|
939
|
-
Authorization: session.getAccessToken().getJwtToken(),
|
|
940
|
-
host,
|
|
941
|
-
};
|
|
942
|
-
}
|
|
943
|
-
|
|
944
|
-
private async _awsRealTimeOPENIDHeader({
|
|
945
|
-
host,
|
|
946
|
-
}: AWSAppSyncRealTimeAuthInput) {
|
|
947
|
-
let token;
|
|
948
|
-
// backwards compatibility
|
|
949
|
-
const federatedInfo = await Cache.getItem('federatedInfo');
|
|
950
|
-
if (federatedInfo) {
|
|
951
|
-
token = federatedInfo.token;
|
|
952
|
-
} else {
|
|
953
|
-
const currentUser = await Auth.currentAuthenticatedUser();
|
|
954
|
-
if (currentUser) {
|
|
955
|
-
token = currentUser.token;
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
if (!token) {
|
|
959
|
-
throw new Error('No federated jwt');
|
|
960
|
-
}
|
|
961
|
-
return {
|
|
962
|
-
Authorization: token,
|
|
963
|
-
host,
|
|
964
|
-
};
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
private async _awsRealTimeApiKeyHeader({
|
|
968
|
-
apiKey,
|
|
969
|
-
host,
|
|
970
|
-
}: AWSAppSyncRealTimeAuthInput) {
|
|
971
|
-
const dt = new Date();
|
|
972
|
-
const dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, '');
|
|
973
|
-
|
|
974
|
-
return {
|
|
975
|
-
host,
|
|
976
|
-
'x-amz-date': dtStr,
|
|
977
|
-
'x-api-key': apiKey,
|
|
978
|
-
};
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
private async _awsRealTimeIAMHeader({
|
|
982
|
-
payload,
|
|
983
|
-
canonicalUri,
|
|
984
|
-
appSyncGraphqlEndpoint,
|
|
985
|
-
region,
|
|
986
|
-
}: AWSAppSyncRealTimeAuthInput) {
|
|
987
|
-
const endpointInfo = {
|
|
988
|
-
region,
|
|
989
|
-
service: 'appsync',
|
|
990
|
-
};
|
|
991
|
-
|
|
992
|
-
const credentialsOK = await this._ensureCredentials();
|
|
993
|
-
if (!credentialsOK) {
|
|
994
|
-
throw new Error('No credentials');
|
|
995
|
-
}
|
|
996
|
-
const creds = await Credentials.get().then((credentials: any) => {
|
|
997
|
-
const { secretAccessKey, accessKeyId, sessionToken } =
|
|
998
|
-
credentials as ICredentials;
|
|
999
|
-
|
|
1000
|
-
return {
|
|
1001
|
-
secret_key: secretAccessKey,
|
|
1002
|
-
access_key: accessKeyId,
|
|
1003
|
-
session_token: sessionToken,
|
|
1004
|
-
};
|
|
1005
|
-
});
|
|
1006
|
-
|
|
1007
|
-
const request = {
|
|
1008
|
-
url: `${appSyncGraphqlEndpoint}${canonicalUri}`,
|
|
1009
|
-
data: payload,
|
|
1010
|
-
method: 'POST',
|
|
1011
|
-
headers: { ...AWS_APPSYNC_REALTIME_HEADERS },
|
|
1012
|
-
};
|
|
1013
|
-
|
|
1014
|
-
const signed_params = Signer.sign(request, creds, endpointInfo);
|
|
1015
|
-
return signed_params.headers;
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
private _customAuthHeader({
|
|
1019
|
-
host,
|
|
1020
|
-
additionalHeaders,
|
|
1021
|
-
}: AWSAppSyncRealTimeAuthInput) {
|
|
1022
|
-
if (!additionalHeaders || !additionalHeaders['Authorization']) {
|
|
1023
|
-
throw new Error('No auth token specified');
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
return {
|
|
1027
|
-
Authorization: additionalHeaders.Authorization,
|
|
1028
|
-
host,
|
|
1029
|
-
};
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
/**
|
|
1033
|
-
* @private
|
|
1034
|
-
*/
|
|
1035
|
-
_ensureCredentials() {
|
|
1036
|
-
return Credentials.get()
|
|
1037
|
-
.then((credentials: any) => {
|
|
1038
|
-
if (!credentials) return false;
|
|
1039
|
-
const cred = Credentials.shear(credentials);
|
|
1040
|
-
logger.debug('set credentials for AWSAppSyncRealTimeProvider', cred);
|
|
1041
|
-
|
|
1042
|
-
return true;
|
|
1043
|
-
})
|
|
1044
|
-
.catch((err: any) => {
|
|
1045
|
-
logger.warn('ensure credentials error', err);
|
|
1046
|
-
return false;
|
|
1047
|
-
});
|
|
1048
|
-
}
|
|
1049
|
-
}
|