@openfin/cloud-interop-core-api 0.0.1-alpha.fba3468 → 0.0.1-alpha.fe79c9b
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/bundle.d.ts +882 -0
- package/index.cjs +665 -0
- package/index.mjs +661 -0
- package/package.json +16 -229
- package/dist/api.d.ts +0 -63
- package/dist/errors/api.error.d.ts +0 -7
- package/dist/index.cjs +0 -296
- package/dist/index.d.ts +0 -3
- package/dist/index.mjs +0 -4058
- package/dist/interfaces.d.ts +0 -147
package/index.cjs
ADDED
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var buffer = require('buffer');
|
|
4
|
+
var mqtt = require('mqtt');
|
|
5
|
+
|
|
6
|
+
class CloudInteropAPIError extends Error {
|
|
7
|
+
code;
|
|
8
|
+
constructor(message = 'An unexpected error has occurred', code = 'UNEXPECTED_ERROR', cause) {
|
|
9
|
+
super(message, { cause: cause });
|
|
10
|
+
this.name = this.constructor.name;
|
|
11
|
+
this.code = code;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
class AuthorizationError extends CloudInteropAPIError {
|
|
15
|
+
constructor(message = 'Not authorized', code = 'ERR_UNAUTHORIZED') {
|
|
16
|
+
super(message, code, undefined);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
class EventController {
|
|
21
|
+
#eventListeners = new Map();
|
|
22
|
+
addEventListener(type, callback) {
|
|
23
|
+
const listeners = this.#eventListeners.get(type) || [];
|
|
24
|
+
listeners.push(callback);
|
|
25
|
+
this.#eventListeners.set(type, listeners);
|
|
26
|
+
}
|
|
27
|
+
removeEventListener(type, callback) {
|
|
28
|
+
const listeners = this.#eventListeners.get(type) || [];
|
|
29
|
+
const index = listeners.indexOf(callback);
|
|
30
|
+
if (index !== -1) {
|
|
31
|
+
listeners.splice(index, 1);
|
|
32
|
+
}
|
|
33
|
+
this.#eventListeners.set(type, listeners);
|
|
34
|
+
}
|
|
35
|
+
once(type, callback) {
|
|
36
|
+
const listener = (...args) => {
|
|
37
|
+
this.removeEventListener(type, listener);
|
|
38
|
+
// @ts-expect-error - TS doesn't like the spread operator here
|
|
39
|
+
callback(...args);
|
|
40
|
+
};
|
|
41
|
+
this.addEventListener(type, listener);
|
|
42
|
+
}
|
|
43
|
+
emitEvent(type, ...args) {
|
|
44
|
+
const listeners = this.#eventListeners.get(type) || [];
|
|
45
|
+
listeners.forEach((listener) => listener(...args));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const isErrorIntentResult = (result) => 'error' in result;
|
|
50
|
+
|
|
51
|
+
const APP_ID_DELIM = '::';
|
|
52
|
+
const getRequestHeaders = (connectionParameters) => {
|
|
53
|
+
const headers = {};
|
|
54
|
+
headers['Content-Type'] = 'application/json';
|
|
55
|
+
if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
|
|
56
|
+
const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
57
|
+
if (!tokenResult) {
|
|
58
|
+
throw new Error('jwtRequestCallback must return a token');
|
|
59
|
+
}
|
|
60
|
+
headers['x-of-auth-id'] = connectionParameters.jwtAuthenticationParameters.authenticationId;
|
|
61
|
+
headers['Authorization'] =
|
|
62
|
+
typeof tokenResult === 'string' ? `Bearer ${tokenResult}` : `Bearer ${buffer.Buffer.from(JSON.stringify(tokenResult)).toString('base64')}`;
|
|
63
|
+
}
|
|
64
|
+
if (connectionParameters.authenticationType === 'basic' && connectionParameters.basicAuthenticationParameters) {
|
|
65
|
+
const { username, password } = connectionParameters.basicAuthenticationParameters;
|
|
66
|
+
headers['Authorization'] = `Basic ${buffer.Buffer.from(`${username}:${password}`).toString('base64')}`;
|
|
67
|
+
}
|
|
68
|
+
return headers;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Encodes all app intents in the format: `appId::sourceId::sessionId`,
|
|
72
|
+
* where sourceId and sessionId are URI encoded
|
|
73
|
+
* @param appIntents
|
|
74
|
+
* @param source
|
|
75
|
+
* @returns
|
|
76
|
+
*/
|
|
77
|
+
const encodeAppIntents = (appIntents, source) => appIntents.map((intent) => ({
|
|
78
|
+
...intent,
|
|
79
|
+
apps: intent.apps.map((app) => ({ ...app, appId: encodeAppId(app.appId, source) })),
|
|
80
|
+
}));
|
|
81
|
+
/**
|
|
82
|
+
* Decodes all app intents by URI decoding the parts previously encoded by `encodeAppIntents`
|
|
83
|
+
* @param appIntents
|
|
84
|
+
* @returns
|
|
85
|
+
*/
|
|
86
|
+
const decodeAppIntents = (appIntents) => appIntents.map((intent) => ({
|
|
87
|
+
...intent,
|
|
88
|
+
apps: intent.apps.map((app) => ({ ...app, appId: decodeAppId(app.appId) })),
|
|
89
|
+
}));
|
|
90
|
+
const encodeAppId = (appIdString, { sessionId, sourceId }) => {
|
|
91
|
+
const id = encodeURIComponent(appIdString);
|
|
92
|
+
const sId = encodeURIComponent(sourceId);
|
|
93
|
+
return `${id}${APP_ID_DELIM}${sId}${APP_ID_DELIM}${sessionId}`;
|
|
94
|
+
};
|
|
95
|
+
const decodeAppId = (appId) => {
|
|
96
|
+
const [encodedAppId, encodedSourceId, sessionId] = appId.split(APP_ID_DELIM);
|
|
97
|
+
const id = decodeURIComponent(encodedAppId);
|
|
98
|
+
const sourceId = decodeURIComponent(encodedSourceId);
|
|
99
|
+
return `${id}${APP_ID_DELIM}${sourceId}${APP_ID_DELIM}${sessionId}`;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Decodes the AppIdentifier to extract the appId, sourceId, and sessionId.
|
|
103
|
+
* @returns an object with:
|
|
104
|
+
* - appId: The appId, or the original appId if unable to parse.
|
|
105
|
+
* - sourceId: The sourceId, or an '' if unable to parse.
|
|
106
|
+
* - sessionId: The sessionId, or an '' if unable to parse.
|
|
107
|
+
*/
|
|
108
|
+
const parseCloudAppId = (appId = '') => {
|
|
109
|
+
const originalAppString = typeof appId === 'string' ? appId : (appId.appId ?? '');
|
|
110
|
+
const parts = originalAppString.split(APP_ID_DELIM);
|
|
111
|
+
return {
|
|
112
|
+
appId: parts[0]?.trim() ?? originalAppString,
|
|
113
|
+
sourceId: parts[1]?.trim() ?? '',
|
|
114
|
+
sessionId: parts[2]?.trim() ?? '',
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
const getSourceFromSession = (sessionDetails) => ({
|
|
118
|
+
sessionId: sessionDetails.sessionId,
|
|
119
|
+
sourceId: sessionDetails.sourceId,
|
|
120
|
+
userId: sessionDetails.sub,
|
|
121
|
+
orgId: sessionDetails.orgId,
|
|
122
|
+
platformId: sessionDetails.platformId,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const MIN_TIMEOUT = 500;
|
|
126
|
+
const DEFAULT_TIMEOUT = 3000;
|
|
127
|
+
const newDiscovery = () => ({
|
|
128
|
+
id: undefined,
|
|
129
|
+
pendingIntentDetailsEvents: [],
|
|
130
|
+
sessionCount: 0,
|
|
131
|
+
responseCount: 0,
|
|
132
|
+
state: 'not-started',
|
|
133
|
+
});
|
|
134
|
+
class IntentController {
|
|
135
|
+
#url;
|
|
136
|
+
#mqttClient;
|
|
137
|
+
#sessionDetails;
|
|
138
|
+
#connectionParams;
|
|
139
|
+
#events;
|
|
140
|
+
#logger;
|
|
141
|
+
#discovery = newDiscovery();
|
|
142
|
+
#discoveryTimeout;
|
|
143
|
+
constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
|
|
144
|
+
this.#url = url;
|
|
145
|
+
this.#mqttClient = mqttClient;
|
|
146
|
+
this.#sessionDetails = sessionDetails;
|
|
147
|
+
this.#connectionParams = connectionParameters;
|
|
148
|
+
this.#events = events;
|
|
149
|
+
this.#logger = logger;
|
|
150
|
+
}
|
|
151
|
+
async startIntentDiscovery(options) {
|
|
152
|
+
if (this.#discovery.state === 'in-progress') {
|
|
153
|
+
throw new Error('Intent discovery already in progress');
|
|
154
|
+
}
|
|
155
|
+
const { timeout = DEFAULT_TIMEOUT, findOptions } = options;
|
|
156
|
+
// clamp min value to 500ms
|
|
157
|
+
const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
|
|
158
|
+
try {
|
|
159
|
+
const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
|
|
160
|
+
method: 'POST',
|
|
161
|
+
headers: getRequestHeaders(this.#connectionParams),
|
|
162
|
+
body: JSON.stringify({ findOptions }),
|
|
163
|
+
});
|
|
164
|
+
if (!startResponse.ok) {
|
|
165
|
+
throw new Error(`Error creating intent discovery record: ${startResponse.statusText}`);
|
|
166
|
+
}
|
|
167
|
+
// TODO: type this response?
|
|
168
|
+
const json = await startResponse.json();
|
|
169
|
+
this.#discovery.id = json.discoveryId;
|
|
170
|
+
this.#discovery.sessionCount = json.sessionCount;
|
|
171
|
+
this.#discovery.state = 'in-progress';
|
|
172
|
+
if (this.#discovery.sessionCount === 1) {
|
|
173
|
+
// since we have no other connected sessions, we can end discovery immediately
|
|
174
|
+
await this.#endIntentDiscovery(false);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
// Listen out for discovery results directly sent to us
|
|
178
|
+
await this.#mqttClient.subscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`);
|
|
179
|
+
this.#discoveryTimeout = setTimeout(() => this.#endIntentDiscovery(), clampedTimeout);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
// Clean up any ongoing discoveries
|
|
183
|
+
this.#endIntentDiscovery();
|
|
184
|
+
throw new CloudInteropAPIError('Error starting intent discovery', 'ERR_STARTING_INTENT_DISCOVERY', error);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async #endIntentDiscovery(mqttUnsubscribe = true) {
|
|
188
|
+
if (this.#discovery.state !== 'in-progress') {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (this.#discoveryTimeout) {
|
|
192
|
+
clearTimeout(this.#discoveryTimeout);
|
|
193
|
+
this.#discoveryTimeout = undefined;
|
|
194
|
+
}
|
|
195
|
+
this.#discovery.state = 'ended';
|
|
196
|
+
// emit our aggregated events
|
|
197
|
+
this.#events.emitEvent('aggregate-intent-details', { responses: this.#discovery.pendingIntentDetailsEvents });
|
|
198
|
+
if (mqttUnsubscribe) {
|
|
199
|
+
// gracefully end discovery
|
|
200
|
+
await this.#mqttClient.unsubscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`).catch(() => {
|
|
201
|
+
this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
|
|
205
|
+
method: 'DELETE',
|
|
206
|
+
headers: getRequestHeaders(this.#connectionParams),
|
|
207
|
+
})
|
|
208
|
+
.then((deleteResponse) => {
|
|
209
|
+
if (!deleteResponse.ok) {
|
|
210
|
+
throw new Error(`Error ending intent discovery: ${deleteResponse.statusText}`);
|
|
211
|
+
}
|
|
212
|
+
})
|
|
213
|
+
.catch((error) => {
|
|
214
|
+
this.#logger('warn', `Error ending intent discovery: ${error}`);
|
|
215
|
+
});
|
|
216
|
+
// clean up
|
|
217
|
+
this.#discovery = newDiscovery();
|
|
218
|
+
}
|
|
219
|
+
async raiseIntent({ raiseOptions, appId }) {
|
|
220
|
+
const targetSessionId = parseCloudAppId(appId).sessionId;
|
|
221
|
+
if (!targetSessionId) {
|
|
222
|
+
// TODO: should we add more info here about the format?
|
|
223
|
+
throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
|
|
224
|
+
}
|
|
225
|
+
const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
|
|
226
|
+
method: 'POST',
|
|
227
|
+
headers: getRequestHeaders(this.#connectionParams),
|
|
228
|
+
body: JSON.stringify({ raiseOptions }),
|
|
229
|
+
});
|
|
230
|
+
if (!postResponse.ok) {
|
|
231
|
+
// TODO: maybe add a debug flag to print these when dev'ing?
|
|
232
|
+
// console.log(`Error raising intent: ${await postResponse.text()}`);
|
|
233
|
+
throw new CloudInteropAPIError(`Error raising intent`, 'ERR_RAISING_INTENT', new Error(postResponse.statusText));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
async reportAppIntents(discoveryId, intents) {
|
|
237
|
+
intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
|
|
238
|
+
try {
|
|
239
|
+
const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
|
|
240
|
+
method: 'POST',
|
|
241
|
+
headers: getRequestHeaders(this.#connectionParams),
|
|
242
|
+
body: JSON.stringify({ intents }),
|
|
243
|
+
});
|
|
244
|
+
if (reportResponse.ok) {
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
throw new CloudInteropAPIError('Error reporting intents', 'ERR_REPORTING_INTENTS', new Error(reportResponse.statusText));
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
this.#logger('warn', `Error reporting intents for discovery ID ${discoveryId}: ${error}`);
|
|
251
|
+
}
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
async sendIntentResult(initiatingSessionId, result) {
|
|
255
|
+
if (!isErrorIntentResult(result)) {
|
|
256
|
+
// cloud-encode the source app id to support chained intent actions over cloud
|
|
257
|
+
// https://fdc3.finos.org/docs/2.0/api/spec#resolution-object -> "Use metadata about the resolving app instance to target a further intent"
|
|
258
|
+
const source = getSourceFromSession(this.#sessionDetails);
|
|
259
|
+
const encoded = encodeAppId(typeof result.source === 'string' ? result.source : result.source.appId, source);
|
|
260
|
+
result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
|
|
261
|
+
}
|
|
262
|
+
const { sessionId } = getSourceFromSession(this.#sessionDetails);
|
|
263
|
+
const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
|
|
264
|
+
method: 'POST',
|
|
265
|
+
headers: getRequestHeaders(this.#connectionParams),
|
|
266
|
+
body: JSON.stringify({ result }),
|
|
267
|
+
});
|
|
268
|
+
if (!resultResponse.ok) {
|
|
269
|
+
throw new CloudInteropAPIError('Error sending intent result', 'ERR_SENDING_INTENT_RESULT', new Error(resultResponse.statusText));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
handleCommandMessage(message) {
|
|
273
|
+
switch (message.command) {
|
|
274
|
+
case 'report-intents': {
|
|
275
|
+
if (message.initiatingSessionId === this.#sessionDetails?.sessionId) {
|
|
276
|
+
// Ignore if this originated from us
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const { command: _, ...event } = message;
|
|
280
|
+
this.#events.emitEvent('report-intents', event);
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
case 'intent-details': {
|
|
284
|
+
/**
|
|
285
|
+
* We aggregate intent details commands from all connected sessions on the server side
|
|
286
|
+
* to ensure upstream clients don't have to do this. Also given @openfin/cloud-interop
|
|
287
|
+
* exposes FDC3 compliant APIs, there is no concept of streaming available, hence we
|
|
288
|
+
* aggregate the responses here and send them in a synchronous manner.
|
|
289
|
+
*/
|
|
290
|
+
const { command: _, ...event } = message;
|
|
291
|
+
// Decode intents before emitting to client
|
|
292
|
+
event.intents = decodeAppIntents(event.intents);
|
|
293
|
+
// always emit individual intent-details events in addition to aggregate-intent-details
|
|
294
|
+
// for flexibility after intent discovery has ended, this can be useful for late-joining
|
|
295
|
+
// clients nearing the timeout
|
|
296
|
+
this.#events.emitEvent('intent-details', event);
|
|
297
|
+
if (message.discoveryId !== this.#discovery.id || this.#discovery.state !== 'in-progress') {
|
|
298
|
+
// Ignore if its any other discovery id for some reason, or
|
|
299
|
+
// if we're not in the middle of a discovery
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
this.#discovery.responseCount += 1;
|
|
303
|
+
this.#logger('debug', `Received intent details from ${message.source.sessionId}, received: ${this.#discovery.responseCount}, out of connected sessions: ${this.#discovery.sessionCount - 1}`);
|
|
304
|
+
this.#discovery.pendingIntentDetailsEvents.push(event);
|
|
305
|
+
const allResponded = this.#discovery.responseCount === this.#discovery.sessionCount - 1;
|
|
306
|
+
if (allResponded) {
|
|
307
|
+
this.#endIntentDiscovery();
|
|
308
|
+
}
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
case 'raise-intent': {
|
|
312
|
+
if (message.targetSessionId === this.#sessionDetails?.sessionId) {
|
|
313
|
+
const { command: _, ...event } = message;
|
|
314
|
+
this.#events.emitEvent('raise-intent', event);
|
|
315
|
+
}
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
case 'intent-result': {
|
|
319
|
+
if (message.initiatingSessionId === this.#sessionDetails?.sessionId) {
|
|
320
|
+
// Return result to originator and end discovery
|
|
321
|
+
const { command: _, ...resultEvent } = message;
|
|
322
|
+
this.#events.emitEvent('intent-result', resultEvent);
|
|
323
|
+
}
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
default: {
|
|
327
|
+
this.#logger('warn', `Unknown command message received:\n${JSON.stringify(message, null, 2)}`);
|
|
328
|
+
break;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Error codes as defined in https://docs.emqx.com/en/cloud/latest/connect_to_deployments/mqtt_client_error_codes.html
|
|
335
|
+
const BadUserNamePasswordError = 134;
|
|
336
|
+
/**
|
|
337
|
+
* Represents a single connection to a Cloud Interop service
|
|
338
|
+
*
|
|
339
|
+
* @public
|
|
340
|
+
* @class
|
|
341
|
+
*/
|
|
342
|
+
class CloudInteropAPI {
|
|
343
|
+
#cloudInteropSettings;
|
|
344
|
+
#sessionDetails;
|
|
345
|
+
#mqttClient;
|
|
346
|
+
#reconnectRetryLimit = 30;
|
|
347
|
+
#keepAliveIntervalSeconds = 30;
|
|
348
|
+
#logger = (level, message) => {
|
|
349
|
+
console[level](message);
|
|
350
|
+
};
|
|
351
|
+
#reconnectRetries = 0;
|
|
352
|
+
#connectionParams;
|
|
353
|
+
#attemptingToReconnect = false;
|
|
354
|
+
#events = new EventController();
|
|
355
|
+
#intents;
|
|
356
|
+
constructor(cloudInteropSettings) {
|
|
357
|
+
this.#cloudInteropSettings = cloudInteropSettings;
|
|
358
|
+
}
|
|
359
|
+
get sessionDetails() {
|
|
360
|
+
return this.#sessionDetails;
|
|
361
|
+
}
|
|
362
|
+
get mqttClient() {
|
|
363
|
+
return this.#mqttClient;
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Connects and creates a session on the Cloud Interop service
|
|
367
|
+
*
|
|
368
|
+
* @param {ConnectParameters} parameters - The parameters to use to connect
|
|
369
|
+
* @returns {*} {Promise<void>}
|
|
370
|
+
* @memberof CloudInteropAPI
|
|
371
|
+
* @throws {CloudInteropAPIError} - If an error occurs during connection
|
|
372
|
+
* @throws {AuthorizationError} - If the connection is unauthorized
|
|
373
|
+
*/
|
|
374
|
+
async connect(parameters) {
|
|
375
|
+
this.#validateConnectParams(parameters);
|
|
376
|
+
this.#connectionParams = parameters;
|
|
377
|
+
this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
|
|
378
|
+
this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
|
|
379
|
+
this.#logger = parameters.logger || this.#logger;
|
|
380
|
+
const { sourceId, platformId } = this.#connectionParams;
|
|
381
|
+
const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
|
|
382
|
+
method: 'POST',
|
|
383
|
+
headers: getRequestHeaders(this.#connectionParams),
|
|
384
|
+
body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
|
|
385
|
+
});
|
|
386
|
+
if (!createSessionResponse.ok) {
|
|
387
|
+
if (createSessionResponse.status === 401 || createSessionResponse.status === 403) {
|
|
388
|
+
throw new AuthorizationError();
|
|
389
|
+
}
|
|
390
|
+
throw new CloudInteropAPIError();
|
|
391
|
+
}
|
|
392
|
+
if (createSessionResponse.status !== 201) {
|
|
393
|
+
throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
|
|
394
|
+
}
|
|
395
|
+
this.#sessionDetails = (await createSessionResponse.json());
|
|
396
|
+
const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
|
|
397
|
+
const clientOptions = {
|
|
398
|
+
keepalive: this.#keepAliveIntervalSeconds,
|
|
399
|
+
clientId: this.#sessionDetails.sessionId,
|
|
400
|
+
clean: true,
|
|
401
|
+
protocolVersion: 5,
|
|
402
|
+
// The "will" message will be published on an unexpected disconnection
|
|
403
|
+
// The server can then tidy up. So it needs every for this client to do that, the session details is perfect
|
|
404
|
+
will: {
|
|
405
|
+
topic: 'interop/lastwill',
|
|
406
|
+
payload: buffer.Buffer.from(JSON.stringify(this.#sessionDetails)),
|
|
407
|
+
qos: 0,
|
|
408
|
+
retain: false,
|
|
409
|
+
},
|
|
410
|
+
username: this.#sessionDetails.token,
|
|
411
|
+
};
|
|
412
|
+
this.#mqttClient = await mqtt.connectAsync(this.#sessionDetails.url, clientOptions);
|
|
413
|
+
// TODO: Dynamic intent discovery
|
|
414
|
+
// search for any ongoing discoveries in DB and fire report-intents on self
|
|
415
|
+
this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
|
|
416
|
+
this.#mqttClient.on('error', async (error) => {
|
|
417
|
+
// We will receive errors for each failed reconnection attempt
|
|
418
|
+
// We don't want to disconnect on these else we will never reconnect
|
|
419
|
+
if (!this.#attemptingToReconnect) {
|
|
420
|
+
await this.#disconnect(false);
|
|
421
|
+
}
|
|
422
|
+
if (error instanceof mqtt.ErrorWithReasonCode) {
|
|
423
|
+
switch (error.code) {
|
|
424
|
+
case BadUserNamePasswordError: {
|
|
425
|
+
await this.#disconnect(false);
|
|
426
|
+
this.#logger('warn', `Session expired`);
|
|
427
|
+
this.#events.emitEvent('session-expired');
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
default: {
|
|
431
|
+
this.#logger('error', `Unknown Infrastructure Error Code ${error.code} : ${error.message}${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}`);
|
|
432
|
+
// As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
|
|
433
|
+
if (!this.#attemptingToReconnect) {
|
|
434
|
+
this.#events.emitEvent('error', new CloudInteropAPIError(`Unknown Infrastructure Error Code ${error.code} : ${error.message}`, 'ERR_INFRASTRUCTURE', error));
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
else {
|
|
441
|
+
this.#logger('error', `Unknown Error${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}: ${error}`);
|
|
442
|
+
// As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
|
|
443
|
+
if (!this.#attemptingToReconnect) {
|
|
444
|
+
this.#events.emitEvent('error', new CloudInteropAPIError(`Unknown Error`, 'ERR_UNKNOWN', error));
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
this.#mqttClient.on('reconnect', () => {
|
|
449
|
+
this.#attemptingToReconnect = true;
|
|
450
|
+
this.#reconnectRetries += 1;
|
|
451
|
+
this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
|
|
452
|
+
if (this.#reconnectRetries === this.#reconnectRetryLimit) {
|
|
453
|
+
this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
|
|
454
|
+
this.#disconnect(true);
|
|
455
|
+
}
|
|
456
|
+
this.#events.emitEvent('reconnecting', this.#reconnectRetries);
|
|
457
|
+
});
|
|
458
|
+
// Does not fire on initial connection, only successful reconnection attempts
|
|
459
|
+
this.#mqttClient.on('connect', () => {
|
|
460
|
+
this.#logger('debug', `Cloud Interop successfully reconnected after ${this.#reconnectRetries} attempts`);
|
|
461
|
+
this.#reconnectRetries = 0;
|
|
462
|
+
this.#attemptingToReconnect = false;
|
|
463
|
+
this.#events.emitEvent('reconnected');
|
|
464
|
+
});
|
|
465
|
+
this.#mqttClient.on('message', (topic, message) => {
|
|
466
|
+
if (!this.#sessionDetails) {
|
|
467
|
+
this.#logger('warn', 'Received message when session not connected');
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
this.#handleMessage(topic, message, this.#sessionDetails);
|
|
471
|
+
});
|
|
472
|
+
// Subscribe to all context groups
|
|
473
|
+
this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
|
|
474
|
+
// Listen out for global commands
|
|
475
|
+
this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
|
|
476
|
+
this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Disconnects from the Cloud Interop service
|
|
480
|
+
*
|
|
481
|
+
* @returns {*} {Promise<void>}
|
|
482
|
+
* @memberof CloudInteropAPI
|
|
483
|
+
* @throws {CloudInteropAPIError} - If an error occurs during disconnection
|
|
484
|
+
*/
|
|
485
|
+
async disconnect() {
|
|
486
|
+
await this.#disconnect(true);
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Publishes a new context for the given context group to the other connected sessions
|
|
490
|
+
*
|
|
491
|
+
* @param {string} contextGroup - The context group to publish to
|
|
492
|
+
* @param {object} context - The context to publish
|
|
493
|
+
* @returns {*} {Promise<void>}
|
|
494
|
+
* @memberof CloudInteropAPI
|
|
495
|
+
*/
|
|
496
|
+
async setContext(contextGroup, context) {
|
|
497
|
+
// TODO: make context of type OpenFin.Context
|
|
498
|
+
if (!this.#sessionDetails || !this.#connectionParams) {
|
|
499
|
+
throw new Error('Session not connected');
|
|
500
|
+
}
|
|
501
|
+
if (!this.#mqttClient) {
|
|
502
|
+
throw new Error('MQTT client not connected');
|
|
503
|
+
}
|
|
504
|
+
const payload = {
|
|
505
|
+
context,
|
|
506
|
+
timestamp: Date.now(),
|
|
507
|
+
};
|
|
508
|
+
const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
|
|
509
|
+
method: 'POST',
|
|
510
|
+
headers: getRequestHeaders(this.#connectionParams),
|
|
511
|
+
body: JSON.stringify(payload),
|
|
512
|
+
});
|
|
513
|
+
if (!postResponse.ok) {
|
|
514
|
+
throw new CloudInteropAPIError(`Error setting context for ${contextGroup}`, 'ERR_SETTING_CONTEXT', new Error(postResponse.statusText));
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Starts an intent discovery operation
|
|
519
|
+
*
|
|
520
|
+
* @returns {*} {Promise<void>}
|
|
521
|
+
* @memberof CloudInteropAPI
|
|
522
|
+
* @throws {CloudInteropAPIError} - If an error occurs during intent discovery
|
|
523
|
+
*/
|
|
524
|
+
async startIntentDiscovery(options) {
|
|
525
|
+
this.#throwIfNotConnected();
|
|
526
|
+
return this.#intents?.startIntentDiscovery(options);
|
|
527
|
+
}
|
|
528
|
+
async raiseIntent(options) {
|
|
529
|
+
this.#throwIfNotConnected();
|
|
530
|
+
return this.#intents?.raiseIntent(options);
|
|
531
|
+
}
|
|
532
|
+
async reportAppIntents(discoveryId, intents) {
|
|
533
|
+
this.#throwIfNotConnected();
|
|
534
|
+
return this.#intents?.reportAppIntents(discoveryId, intents) ?? false;
|
|
535
|
+
}
|
|
536
|
+
async sendIntentResult(initiatingSessionId, result) {
|
|
537
|
+
this.#throwIfNotConnected();
|
|
538
|
+
return this.#intents?.sendIntentResult(initiatingSessionId, result);
|
|
539
|
+
}
|
|
540
|
+
parseSessionId(appId) {
|
|
541
|
+
return parseCloudAppId(appId).sessionId;
|
|
542
|
+
}
|
|
543
|
+
parseAppId(appId) {
|
|
544
|
+
return parseCloudAppId(appId).appId;
|
|
545
|
+
}
|
|
546
|
+
addEventListener(type, callback) {
|
|
547
|
+
this.#events.addEventListener(type, callback);
|
|
548
|
+
}
|
|
549
|
+
removeEventListener(type, callback) {
|
|
550
|
+
this.#events.removeEventListener(type, callback);
|
|
551
|
+
}
|
|
552
|
+
once(type, callback) {
|
|
553
|
+
this.#events.once(type, callback);
|
|
554
|
+
}
|
|
555
|
+
async #disconnect(fireDisconnectedEvent) {
|
|
556
|
+
if (!this.#sessionDetails) {
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
try {
|
|
560
|
+
if (!this.#connectionParams) {
|
|
561
|
+
throw new Error('Connect parameters must be provided');
|
|
562
|
+
}
|
|
563
|
+
const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
|
|
564
|
+
method: 'DELETE',
|
|
565
|
+
headers: getRequestHeaders(this.#connectionParams),
|
|
566
|
+
});
|
|
567
|
+
if (disconnectResponse.status !== 200) {
|
|
568
|
+
throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
catch (error) {
|
|
572
|
+
throw new CloudInteropAPIError('Error during disconnection', 'ERR_DISCONNECT', error);
|
|
573
|
+
}
|
|
574
|
+
finally {
|
|
575
|
+
this.#destroyControllers();
|
|
576
|
+
this.#mqttClient?.removeAllListeners();
|
|
577
|
+
await this.#mqttClient?.endAsync(true);
|
|
578
|
+
this.#sessionDetails = undefined;
|
|
579
|
+
this.#mqttClient = undefined;
|
|
580
|
+
this.#reconnectRetries = 0;
|
|
581
|
+
this.#attemptingToReconnect = false;
|
|
582
|
+
if (fireDisconnectedEvent) {
|
|
583
|
+
this.#events.emitEvent('disconnected');
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
#handleMessage(topic, message, sessionDetails) {
|
|
588
|
+
if (message.length === 0 || !sessionDetails) {
|
|
589
|
+
// Ignore clean up messages
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
const messageEnvelope = JSON.parse(message.toString());
|
|
593
|
+
if (topic.startsWith(`${sessionDetails.sessionRootTopic}/context-groups/`)) {
|
|
594
|
+
const contextEvent = messageEnvelope;
|
|
595
|
+
if (contextEvent.source.sessionId === sessionDetails.sessionId) {
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
const { context, payload, contextGroup, channelName, source, history } = contextEvent;
|
|
599
|
+
this.#events.emitEvent('context', {
|
|
600
|
+
contextGroup: channelName || contextGroup,
|
|
601
|
+
context: payload || context,
|
|
602
|
+
source,
|
|
603
|
+
history: { ...history, clientReceived: Date.now() },
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
else if (topic.startsWith(`${sessionDetails.sessionRootTopic}/commands`)) {
|
|
607
|
+
this.#handleCommandMessage(messageEnvelope);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
#handleCommandMessage(message) {
|
|
611
|
+
switch (message.command) {
|
|
612
|
+
case 'report-intents':
|
|
613
|
+
case 'intent-details':
|
|
614
|
+
case 'raise-intent':
|
|
615
|
+
case 'intent-result': {
|
|
616
|
+
this.#intents?.handleCommandMessage(message);
|
|
617
|
+
break;
|
|
618
|
+
}
|
|
619
|
+
default: {
|
|
620
|
+
this.#logger('warn', `Unknown command message received:\n${JSON.stringify(message, null, 2)}`);
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
#validateConnectParams = (parameters) => {
|
|
626
|
+
if (!parameters) {
|
|
627
|
+
throw new Error('Connect parameters must be provided');
|
|
628
|
+
}
|
|
629
|
+
if (!parameters.sourceId) {
|
|
630
|
+
throw new Error('sourceId must be provided');
|
|
631
|
+
}
|
|
632
|
+
if (parameters.sourceId.includes(APP_ID_DELIM)) {
|
|
633
|
+
throw new Error(`sourceId cannot contain "${APP_ID_DELIM}"`);
|
|
634
|
+
}
|
|
635
|
+
if (!parameters.platformId) {
|
|
636
|
+
throw new Error('platformId must be provided');
|
|
637
|
+
}
|
|
638
|
+
if (parameters.authenticationType === 'jwt' &&
|
|
639
|
+
(!parameters.jwtAuthenticationParameters?.jwtRequestCallback || !parameters.jwtAuthenticationParameters?.authenticationId)) {
|
|
640
|
+
throw new Error('jwtAuthenticationParameters must be provided when using jwt authentication');
|
|
641
|
+
}
|
|
642
|
+
if (parameters.authenticationType === 'basic' &&
|
|
643
|
+
(!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
|
|
644
|
+
throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
#initControllers(mqttClient, sessionDetails, connectionParameters) {
|
|
648
|
+
this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, connectionParameters, this.#events, this.#logger);
|
|
649
|
+
}
|
|
650
|
+
#destroyControllers() {
|
|
651
|
+
this.#intents = undefined;
|
|
652
|
+
}
|
|
653
|
+
#throwIfNotConnected() {
|
|
654
|
+
if (!this.#sessionDetails || !this.#connectionParams) {
|
|
655
|
+
throw new Error('Session not connected');
|
|
656
|
+
}
|
|
657
|
+
if (!this.#mqttClient) {
|
|
658
|
+
throw new Error('MQTT client not connected');
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
exports.AuthorizationError = AuthorizationError;
|
|
664
|
+
exports.CloudInteropAPI = CloudInteropAPI;
|
|
665
|
+
exports.CloudInteropAPIError = CloudInteropAPIError;
|