@interopio/browser-platform 3.0.1
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/browser.platform.d.ts +455 -0
- package/changelog.md +69 -0
- package/dist/browser.platform.es.js +46074 -0
- package/dist/browser.platform.es.js.map +1 -0
- package/dist/browser.platform.umd.js +46082 -0
- package/dist/browser.platform.umd.js.map +1 -0
- package/license.md +21 -0
- package/package.json +78 -0
- package/readme.md +9 -0
- package/rollup.config.js +45 -0
- package/src/common/constants.ts +46 -0
- package/src/common/defaultConfig.ts +56 -0
- package/src/common/gateway.d.ts +32 -0
- package/src/common/types.ts +222 -0
- package/src/connection/gateway.ts +132 -0
- package/src/connection/no-gateway.ts +1 -0
- package/src/connection/portsBridge.ts +441 -0
- package/src/connection/preferred.ts +247 -0
- package/src/controllers/domains.ts +156 -0
- package/src/controllers/glue.ts +604 -0
- package/src/controllers/interception.ts +53 -0
- package/src/controllers/license.ts +50 -0
- package/src/controllers/main.ts +256 -0
- package/src/controllers/plugins.ts +121 -0
- package/src/controllers/serviceWorker.ts +193 -0
- package/src/controllers/state.ts +84 -0
- package/src/controllers/system.ts +99 -0
- package/src/controllers/transactions.ts +80 -0
- package/src/factory.ts +40 -0
- package/src/fallbacks/browser.ts +47 -0
- package/src/fallbacks/dekstop.ts +21 -0
- package/src/index.ts +18 -0
- package/src/libs/applications/appStore/directory.ts +235 -0
- package/src/libs/applications/appStore/remoteWatcher.ts +112 -0
- package/src/libs/applications/controller.ts +469 -0
- package/src/libs/applications/decoders.ts +98 -0
- package/src/libs/applications/defaults.ts +6 -0
- package/src/libs/applications/types.ts +98 -0
- package/src/libs/channels/controller.ts +109 -0
- package/src/libs/channels/decoders.ts +19 -0
- package/src/libs/extension/controller.ts +120 -0
- package/src/libs/extension/decoders.ts +18 -0
- package/src/libs/extension/types.ts +11 -0
- package/src/libs/intents/constants.ts +9 -0
- package/src/libs/intents/controller.ts +500 -0
- package/src/libs/intents/decoders.ts +96 -0
- package/src/libs/intents/resolverHelper.ts +264 -0
- package/src/libs/intents/types.ts +119 -0
- package/src/libs/layouts/constants.ts +3 -0
- package/src/libs/layouts/controller.ts +476 -0
- package/src/libs/layouts/decoders.ts +132 -0
- package/src/libs/layouts/global/builder.ts +400 -0
- package/src/libs/layouts/global/resetter.ts +116 -0
- package/src/libs/layouts/global/restorer.ts +217 -0
- package/src/libs/layouts/global/validator.ts +169 -0
- package/src/libs/layouts/idbStore.ts +63 -0
- package/src/libs/layouts/types.ts +133 -0
- package/src/libs/manager/controller.ts +175 -0
- package/src/libs/manager/decoders.ts +6 -0
- package/src/libs/manager/defaults.ts +5 -0
- package/src/libs/manager/identity.ts +92 -0
- package/src/libs/manager/session.ts +195 -0
- package/src/libs/manager/types.ts +51 -0
- package/src/libs/notifications/controller.ts +447 -0
- package/src/libs/notifications/decoders.ts +166 -0
- package/src/libs/notifications/types.ts +49 -0
- package/src/libs/notifications/utils.ts +7 -0
- package/src/libs/search/controller.ts +232 -0
- package/src/libs/search/decoders.ts +6 -0
- package/src/libs/search/repositories/applications.ts +62 -0
- package/src/libs/search/repositories/layouts.ts +48 -0
- package/src/libs/search/repositories/workspaces.ts +47 -0
- package/src/libs/search/types.ts +9 -0
- package/src/libs/themes/constants.ts +9 -0
- package/src/libs/themes/controller.ts +153 -0
- package/src/libs/themes/decoders.ts +28 -0
- package/src/libs/themes/types.ts +28 -0
- package/src/libs/windows/controller.ts +498 -0
- package/src/libs/windows/decoders.ts +64 -0
- package/src/libs/windows/types.ts +59 -0
- package/src/libs/workspaces/controller.ts +922 -0
- package/src/libs/workspaces/decoders.ts +868 -0
- package/src/libs/workspaces/defaultConfig.ts +11 -0
- package/src/libs/workspaces/frames.ts +239 -0
- package/src/libs/workspaces/hibernationWatcher.ts +231 -0
- package/src/libs/workspaces/types.ts +506 -0
- package/src/platform.ts +156 -0
- package/src/shared/decoders.ts +479 -0
- package/src/shared/fetchTimeout.ts +25 -0
- package/src/shared/ioc.ts +580 -0
- package/src/shared/logger.ts +19 -0
- package/src/shared/promisePlus.ts +62 -0
- package/src/shared/sequelizer.ts +48 -0
- package/src/shared/utils.ts +86 -0
- package/src/storage/local.ts +111 -0
- package/src/storage/session.ts +436 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
/* tslint:disable:no-console no-empty */
|
|
3
|
+
import { Gateway } from "./gateway";
|
|
4
|
+
import { IoC } from "../shared/ioc";
|
|
5
|
+
import { Glue42CoreMessageTypes, webPlatformTransportName } from "../common/constants";
|
|
6
|
+
import {
|
|
7
|
+
default as CallbackRegistryFactory,
|
|
8
|
+
CallbackRegistry,
|
|
9
|
+
UnsubscribeFunction,
|
|
10
|
+
} from "callback-registry";
|
|
11
|
+
import { ClientPortRequest, CoreClientData, InternalPlatformConfig, SessionWindowData, TransportState } from "../common/types";
|
|
12
|
+
import { SessionStorageController } from "../storage/session";
|
|
13
|
+
import { IOConnectCore } from "@interopio/core";
|
|
14
|
+
import { GwClient } from "@glue42/gateway-web/web/gateway-web.js";
|
|
15
|
+
import { TransactionsController } from "../controllers/transactions";
|
|
16
|
+
import { defaultClientPortRequestTimeoutMS, defaultClientPreferredLogicTestTimeoutMS } from "../common/defaultConfig";
|
|
17
|
+
import logger from "../shared/logger";
|
|
18
|
+
|
|
19
|
+
export class PortsBridge {
|
|
20
|
+
|
|
21
|
+
private readonly registry: CallbackRegistry = CallbackRegistryFactory();
|
|
22
|
+
private readonly transactionsController: TransactionsController;
|
|
23
|
+
private allPorts: { [key: string]: MessagePort | chrome.runtime.Port } = {};
|
|
24
|
+
private allClients: Array<{ bridgeInstanceId: string, clientId: string, client: GwClient }> = [];
|
|
25
|
+
private unLoadStarted = false;
|
|
26
|
+
private isPreferredActivated = false;
|
|
27
|
+
private activePreferredTransportConfig: IOConnectCore.Connection.TransportSwitchSettings | undefined;
|
|
28
|
+
private _communicationId!: string;
|
|
29
|
+
private startUpPromise!: Promise<void>;
|
|
30
|
+
private startupResolve!: (value: void | PromiseLike<void>) => void;
|
|
31
|
+
private _genericMessageHandler!: (event: MessageEvent<any>) => Promise<void> | undefined;
|
|
32
|
+
private _unloaderHandler!: () => void;
|
|
33
|
+
|
|
34
|
+
constructor(
|
|
35
|
+
private readonly gateway: Gateway,
|
|
36
|
+
private readonly sessionStorage: SessionStorageController,
|
|
37
|
+
private readonly ioc: IoC
|
|
38
|
+
) {
|
|
39
|
+
this.transactionsController = this.ioc.transactionsController;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private get logger(): IOConnectCore.Logger.API | undefined {
|
|
43
|
+
return logger.get("ports.bridge.controller");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
public shutdown(): void {
|
|
47
|
+
window.removeEventListener("message", this._genericMessageHandler);
|
|
48
|
+
|
|
49
|
+
window.removeEventListener("unload", this._unloaderHandler);
|
|
50
|
+
|
|
51
|
+
this.registry.clear();
|
|
52
|
+
|
|
53
|
+
this.allPorts = {};
|
|
54
|
+
this.allClients = [];
|
|
55
|
+
this.isPreferredActivated = false;
|
|
56
|
+
this.unLoadStarted = false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
public async configure(config: InternalPlatformConfig): Promise<void> {
|
|
60
|
+
this.startUpPromise = new Promise<void>((resolve) => {
|
|
61
|
+
this.startupResolve = resolve;
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const systemSettings = this.sessionStorage.getSystemSettings();
|
|
65
|
+
|
|
66
|
+
if (!systemSettings) {
|
|
67
|
+
throw new Error("Cannot initiate the platform port bridge, because the system settings are not defined");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
this._communicationId = systemSettings.systemInstanceId;
|
|
71
|
+
|
|
72
|
+
await this.gateway.start(config?.gateway);
|
|
73
|
+
|
|
74
|
+
this.setupListeners();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
public start(): void {
|
|
78
|
+
this.startupResolve();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
public async createInternalClient(): Promise<MessagePort> {
|
|
82
|
+
|
|
83
|
+
const channel = this.ioc.createMessageChannel();
|
|
84
|
+
|
|
85
|
+
await this.gateway.setupInternalClient(channel.port1);
|
|
86
|
+
|
|
87
|
+
return channel.port2;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
public onClientUnloaded(callback: (client: CoreClientData) => void): UnsubscribeFunction {
|
|
91
|
+
return this.registry.add("client-unloaded", callback);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
95
|
+
public async handleExtConnectionRequest(clientData: any, port: chrome.runtime.Port): Promise<void> {
|
|
96
|
+
|
|
97
|
+
const client = clientData.glue42core;
|
|
98
|
+
|
|
99
|
+
const hasImpersonatedWindowId = !!client.parentWindowId;
|
|
100
|
+
|
|
101
|
+
if (!hasImpersonatedWindowId) {
|
|
102
|
+
// I am a real window
|
|
103
|
+
const id = client.clientId;
|
|
104
|
+
|
|
105
|
+
const windowData: SessionWindowData = {
|
|
106
|
+
windowId: id,
|
|
107
|
+
name: id
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
await this.ioc.windowsController.processNewWindow(windowData);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
await this.gateway.connectExtClient(port, this.removeClient.bind(this));
|
|
114
|
+
|
|
115
|
+
const myWindowId = this.sessionStorage.getWindowDataByName("Platform")?.windowId;
|
|
116
|
+
|
|
117
|
+
const message = {
|
|
118
|
+
glue42core: {
|
|
119
|
+
type: Glue42CoreMessageTypes.connectionAccepted.name,
|
|
120
|
+
parentWindowId: myWindowId,
|
|
121
|
+
appName: "ext-no-app",
|
|
122
|
+
clientId: client.clientId,
|
|
123
|
+
clientType: "child"
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
this.allPorts[client.clientId] = port;
|
|
128
|
+
|
|
129
|
+
port.postMessage(message);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
public setActivePreferredTransportConfig(transportConfig: IOConnectCore.Connection.TransportSwitchSettings): void {
|
|
133
|
+
if (transportConfig.type === "secondary") {
|
|
134
|
+
this.activePreferredTransportConfig = transportConfig;
|
|
135
|
+
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
delete this.activePreferredTransportConfig;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
public setPreferredActivated(): void {
|
|
143
|
+
this.isPreferredActivated = true;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
public async switchAllClientsTransport(transportConfig: IOConnectCore.Connection.TransportSwitchSettings): Promise<void> {
|
|
147
|
+
|
|
148
|
+
const transactions: Array<Promise<void>> = Object.keys(this.allPorts)
|
|
149
|
+
.map((id) => this.sendClientPortRequest<void>({
|
|
150
|
+
type: Glue42CoreMessageTypes.transportSwitchRequest.name,
|
|
151
|
+
timeout: defaultClientPortRequestTimeoutMS,
|
|
152
|
+
clientId: id,
|
|
153
|
+
args: { switchSettings: transportConfig }
|
|
154
|
+
}));
|
|
155
|
+
|
|
156
|
+
await Promise.all(transactions);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
public async checkClientsPreferredLogic(): Promise<{ success: boolean }> {
|
|
160
|
+
const transactions: Array<Promise<void>> = Object.keys(this.allPorts)
|
|
161
|
+
.map((id) => this.sendClientPortRequest<void>({
|
|
162
|
+
type: Glue42CoreMessageTypes.checkPreferredLogic.name,
|
|
163
|
+
timeout: defaultClientPreferredLogicTestTimeoutMS,
|
|
164
|
+
clientId: id
|
|
165
|
+
}));
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
await Promise.all(transactions);
|
|
169
|
+
return { success: true };
|
|
170
|
+
} catch (error) {
|
|
171
|
+
return { success: false };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
public async checkClientsPreferredConnection(url: string): Promise<{ success: boolean }> {
|
|
176
|
+
const transactions: Array<Promise<void>> = Object.keys(this.allPorts)
|
|
177
|
+
.map((id) => this.sendClientPortRequest<void>({
|
|
178
|
+
type: Glue42CoreMessageTypes.checkPreferredConnection.name,
|
|
179
|
+
args: { url },
|
|
180
|
+
timeout: defaultClientPortRequestTimeoutMS,
|
|
181
|
+
clientId: id
|
|
182
|
+
}));
|
|
183
|
+
|
|
184
|
+
try {
|
|
185
|
+
await Promise.all(transactions);
|
|
186
|
+
return { success: true };
|
|
187
|
+
} catch (error) {
|
|
188
|
+
return { success: false };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
public removeGwClient(windowId: string): void {
|
|
193
|
+
const foundClient = this.allClients.find((client) => client.bridgeInstanceId === windowId);
|
|
194
|
+
|
|
195
|
+
if (!foundClient) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
this.allClients = this.allClients.filter((client) => client.bridgeInstanceId !== windowId);
|
|
200
|
+
foundClient.client.disconnect();
|
|
201
|
+
|
|
202
|
+
if (this.allPorts[foundClient.clientId]) {
|
|
203
|
+
delete this.allPorts[foundClient.clientId];
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private unloader(): void {
|
|
208
|
+
this.unLoadStarted = true;
|
|
209
|
+
|
|
210
|
+
for (const id in this.allPorts) {
|
|
211
|
+
this.allPorts[id].postMessage({ type: "platformUnload" });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private genericMessageHandler(event: MessageEvent<any>): Promise<void> | undefined {
|
|
216
|
+
const data = event.data?.glue42core;
|
|
217
|
+
|
|
218
|
+
if (!data || this.unLoadStarted) {
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// todo: domain whitelisting
|
|
223
|
+
|
|
224
|
+
if (data.type === Glue42CoreMessageTypes.clientUnload.name) {
|
|
225
|
+
|
|
226
|
+
const client = {
|
|
227
|
+
windowId: data.data.ownWindowId,
|
|
228
|
+
win: event.source
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
this.registry.execute("client-unloaded", client);
|
|
232
|
+
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (data.type === Glue42CoreMessageTypes.connectionRequest.name) {
|
|
237
|
+
return this.startUpPromise.then(() => this.handleRemoteConnectionRequest(event.source as Window, event.origin, data.clientId, data.clientType, data.bridgeInstanceId, data.selfAssignedWindowId));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (data.type === Glue42CoreMessageTypes.platformPing.name) {
|
|
241
|
+
return this.startUpPromise.then(() => this.handlePlatformPing(event.source as Window, event.origin));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (data.type === Glue42CoreMessageTypes.parentPing.name) {
|
|
245
|
+
return this.startUpPromise.then(() => this.handleParentPing(event.source as Window, event.origin));
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private async handleRemoteConnectionRequest(source: Window, origin: string, clientId: string, clientType: "child" | "grandChild", bridgeInstanceId: string, selfAssignedWindowId: string): Promise<void> {
|
|
250
|
+
const channel = this.ioc.createMessageChannel();
|
|
251
|
+
|
|
252
|
+
const client = await this.gateway.connectClient(channel.port1);
|
|
253
|
+
|
|
254
|
+
this.setupGwClientPort({ client, clientId, clientPort: channel.port1 });
|
|
255
|
+
|
|
256
|
+
this.allClients.push({ client, bridgeInstanceId, clientId });
|
|
257
|
+
|
|
258
|
+
const foundData = this.sessionStorage.getBridgeInstanceData(bridgeInstanceId);
|
|
259
|
+
const appName = foundData?.appName;
|
|
260
|
+
|
|
261
|
+
const myWindowId = this.sessionStorage.getWindowDataByName("Platform")?.windowId;
|
|
262
|
+
|
|
263
|
+
const message = {
|
|
264
|
+
glue42core: {
|
|
265
|
+
type: Glue42CoreMessageTypes.connectionAccepted.name,
|
|
266
|
+
port: channel.port2,
|
|
267
|
+
communicationId: this._communicationId,
|
|
268
|
+
isPreferredActivated: this.isPreferredActivated,
|
|
269
|
+
parentWindowId: myWindowId,
|
|
270
|
+
appName, clientId, clientType
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
if (selfAssignedWindowId) {
|
|
275
|
+
await this.ioc.windowsController.registerSelfAssignedWindow({windowId: selfAssignedWindowId, name: selfAssignedWindowId}, selfAssignedWindowId);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
source.postMessage(message, origin, [channel.port2]);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private handleParentPing(source: Window, origin: string): void {
|
|
282
|
+
const message = {
|
|
283
|
+
glue42core: {
|
|
284
|
+
type: Glue42CoreMessageTypes.parentReady.name
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
source.postMessage(message, origin);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
private handlePlatformPing(source: Window, origin: string): void {
|
|
292
|
+
const message = {
|
|
293
|
+
glue42core: {
|
|
294
|
+
type: Glue42CoreMessageTypes.platformReady.name
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
source.postMessage(message, origin);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private removeClient(clientId: string, announce?: boolean, preservePort?: boolean): void {
|
|
302
|
+
if (!clientId) {
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (this.allPorts[clientId] && !preservePort) {
|
|
307
|
+
delete this.allPorts[clientId];
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (!announce) {
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const client = { windowId: clientId };
|
|
315
|
+
|
|
316
|
+
this.registry.execute("client-unloaded", client);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private setupGwClientPort(config: { client: GwClient; clientPort: MessagePort; clientId: string }): void {
|
|
320
|
+
|
|
321
|
+
if (this.allPorts[config.clientId] && (this.allPorts[config.clientId] as MessagePort).onmessage) {
|
|
322
|
+
(this.allPorts[config.clientId] as MessagePort).onmessage = null;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
this.allPorts[config.clientId] = config.clientPort;
|
|
326
|
+
|
|
327
|
+
config.clientPort.onmessage = (event): void => {
|
|
328
|
+
|
|
329
|
+
const data = event.data?.glue42core;
|
|
330
|
+
|
|
331
|
+
if (data && (data.type === Glue42CoreMessageTypes.clientUnload.name || data.type === Glue42CoreMessageTypes.gatewayDisconnect.name)) {
|
|
332
|
+
|
|
333
|
+
this.removeClient(data.data.clientId, false, data.type === Glue42CoreMessageTypes.gatewayDisconnect.name);
|
|
334
|
+
|
|
335
|
+
if (this.allClients.some((client) => client.clientId === data.data.clientId)) {
|
|
336
|
+
this.allClients = this.allClients.filter((client) => client.clientId !== data.data.clientId);
|
|
337
|
+
config.client.disconnect();
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
if (data && data.type === Glue42CoreMessageTypes.transportSwitchResponse.name) {
|
|
344
|
+
|
|
345
|
+
const args = data.args;
|
|
346
|
+
|
|
347
|
+
if (args.success) {
|
|
348
|
+
this.transactionsController.completeTransaction(data.transactionId);
|
|
349
|
+
} else {
|
|
350
|
+
this.transactionsController.failTransaction(data.transactionId, `The client: ${config.clientId} could not connect using the provided transport config.`);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
if (data && data.type === Glue42CoreMessageTypes.getCurrentTransport.name) {
|
|
357
|
+
|
|
358
|
+
const transactionId = data.transactionId;
|
|
359
|
+
|
|
360
|
+
config.clientPort.postMessage({
|
|
361
|
+
type: Glue42CoreMessageTypes.getCurrentTransportResponse.name,
|
|
362
|
+
args: {
|
|
363
|
+
transportState: this.getCurrentTransportState(),
|
|
364
|
+
},
|
|
365
|
+
transactionId
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (data && data.type === Glue42CoreMessageTypes.checkPreferredLogicResponse.name) {
|
|
372
|
+
return this.transactionsController.completeTransaction(data.transactionId);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (data && data.type === Glue42CoreMessageTypes.checkPreferredConnectionResponse.name) {
|
|
376
|
+
|
|
377
|
+
const args = data.args;
|
|
378
|
+
|
|
379
|
+
if (args.error) {
|
|
380
|
+
return this.transactionsController.failTransaction(data.transactionId, args.error);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (!args.live) {
|
|
384
|
+
return this.transactionsController.failTransaction(data.transactionId, `Client ${config.clientId} could not connect to the preferred WS.`);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
return this.transactionsController.completeTransaction(data.transactionId);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
if (this.allClients.every((client) => client.client !== config.client)) {
|
|
391
|
+
// this was put in place in particular because of focus lost not being prevented when the client is closing
|
|
392
|
+
// this made triggering focus lost on already disappeared window impractical
|
|
393
|
+
this.logger?.trace(`Ignoring a protocol message, because the destination client has been disconnected: ${JSON.stringify(event.data)}`);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
config.client.send(event.data);
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
private getCurrentTransportState(): TransportState {
|
|
402
|
+
// my transport state === the system glue transport state
|
|
403
|
+
|
|
404
|
+
const transportName = this.ioc.glueController.getSystemGlueTransportName();
|
|
405
|
+
|
|
406
|
+
const transportState: TransportState = {
|
|
407
|
+
transportName,
|
|
408
|
+
type: transportName === webPlatformTransportName ? "default" : "secondary",
|
|
409
|
+
transportConfig: transportName === webPlatformTransportName ? undefined : this.activePreferredTransportConfig?.transportConfig
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
return transportState;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private sendClientPortRequest<T>(request: ClientPortRequest): Promise<T> {
|
|
416
|
+
const client = this.allPorts[request.clientId];
|
|
417
|
+
|
|
418
|
+
if (!client) {
|
|
419
|
+
throw new Error(`Cannot sent port request: ${request.type} to ${request.clientId}, because there is no such client`);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const transaction = this.transactionsController.createTransaction<T>(request.type, request.timeout || defaultClientPortRequestTimeoutMS);
|
|
423
|
+
|
|
424
|
+
const type = request.type;
|
|
425
|
+
const args = request.args;
|
|
426
|
+
|
|
427
|
+
client.postMessage({ type, args, transactionId: transaction.id });
|
|
428
|
+
|
|
429
|
+
return transaction.lock;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
private setupListeners(): void {
|
|
433
|
+
this._genericMessageHandler = this.genericMessageHandler.bind(this);
|
|
434
|
+
|
|
435
|
+
window.addEventListener("message", this._genericMessageHandler);
|
|
436
|
+
|
|
437
|
+
this._unloaderHandler = this.unloader.bind(this);
|
|
438
|
+
|
|
439
|
+
window.addEventListener("unload", this._unloaderHandler);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import { IOConnectCore } from "@interopio/core";
|
|
3
|
+
import {
|
|
4
|
+
default as CallbackRegistryFactory,
|
|
5
|
+
CallbackRegistry,
|
|
6
|
+
UnsubscribeFunction,
|
|
7
|
+
} from "callback-registry";
|
|
8
|
+
import { IOConnectBrowserPlatform } from "../../browser.platform";
|
|
9
|
+
import { GlueController } from "../controllers/glue";
|
|
10
|
+
import { wait } from "../shared/utils";
|
|
11
|
+
import { PortsBridge } from "./portsBridge";
|
|
12
|
+
import logger from "../shared/logger";
|
|
13
|
+
import { AsyncSequelizer } from "../shared/sequelizer";
|
|
14
|
+
import { defaultPreferredDiscoveryIntervalMS } from "../common/defaultConfig";
|
|
15
|
+
|
|
16
|
+
export class PreferredConnectionController {
|
|
17
|
+
private readonly registry: CallbackRegistry = CallbackRegistryFactory();
|
|
18
|
+
private unsub: UnsubscribeFunction | undefined;
|
|
19
|
+
private discoveryInterval!: number;
|
|
20
|
+
private shouldForceTransfer!: boolean;
|
|
21
|
+
private preferredUrl!: string;
|
|
22
|
+
private preferredAuth!: IOConnectCore.Auth;
|
|
23
|
+
private stopped = false;
|
|
24
|
+
|
|
25
|
+
constructor(
|
|
26
|
+
private readonly glueController: GlueController,
|
|
27
|
+
private readonly portsBridge: PortsBridge,
|
|
28
|
+
private readonly sequelizer: AsyncSequelizer
|
|
29
|
+
) {}
|
|
30
|
+
|
|
31
|
+
private get logger(): IOConnectCore.Logger.API | undefined {
|
|
32
|
+
return logger.get("preferred.connection.controller");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
public shutdown(): void {
|
|
36
|
+
this.stopped = true;
|
|
37
|
+
|
|
38
|
+
this.registry.clear();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
public async start(config: IOConnectBrowserPlatform.Connection.Config): Promise<void> {
|
|
42
|
+
|
|
43
|
+
this.logger?.trace(`Starting the preferred connection with config: ${JSON.stringify(config)}`);
|
|
44
|
+
|
|
45
|
+
this.stopped = false;
|
|
46
|
+
|
|
47
|
+
this.portsBridge.setPreferredActivated();
|
|
48
|
+
|
|
49
|
+
if (!config.preferred) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
this.preferredUrl = config.preferred.url;
|
|
54
|
+
|
|
55
|
+
this.preferredAuth = Object.assign({}, { provider: "core" }, config.preferred.auth);
|
|
56
|
+
|
|
57
|
+
this.shouldForceTransfer = typeof config.preferred.forceIncompleteSwitch === "boolean" ? config.preferred.forceIncompleteSwitch : false;
|
|
58
|
+
|
|
59
|
+
this.discoveryInterval = typeof config.preferred.discoveryIntervalMS === "number" ? config.preferred.discoveryIntervalMS : defaultPreferredDiscoveryIntervalMS;
|
|
60
|
+
|
|
61
|
+
this.logger?.trace("Starting the initial preferred connection check");
|
|
62
|
+
|
|
63
|
+
await this.connectPreferred();
|
|
64
|
+
|
|
65
|
+
this.logger?.trace("The preferred connection controller initiated.");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
public onReconnect(callback: () => void): UnsubscribeFunction {
|
|
69
|
+
return this.registry.add("system-reconnect", callback);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
public async connectPreferred(manual?: boolean, url?: string, auth?: IOConnectCore.Auth): Promise<void> {
|
|
73
|
+
if (this.stopped && !manual) {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const check = await this.checkPreFlight(url);
|
|
78
|
+
|
|
79
|
+
if (!check.ready && manual) {
|
|
80
|
+
throw new Error("The provided preferred connection is not ready.");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (!check.ready) {
|
|
84
|
+
this.logger?.trace("The preflight is not ready, restarting the preferred tracking.");
|
|
85
|
+
wait(this.discoveryInterval).then(() => this.connectPreferred(manual, url, auth));
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const transportSwitchConfig: IOConnectCore.Connection.TransportSwitchSettings = {
|
|
90
|
+
type: "secondary",
|
|
91
|
+
transportConfig: Object.assign({ url: url || this.preferredUrl }, { auth: auth || this.preferredAuth })
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
this.logger?.trace("Switching the system glue.");
|
|
95
|
+
|
|
96
|
+
if (this.stopped) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const switched = (await this.glueController.switchTransport(transportSwitchConfig, "system")).success;
|
|
101
|
+
|
|
102
|
+
if (!switched) {
|
|
103
|
+
this.logger?.trace("The switch attempt was not successful, revered to default.");
|
|
104
|
+
wait(this.discoveryInterval).then(() => this.connectPreferred(manual, url, auth));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
this.portsBridge.setActivePreferredTransportConfig(transportSwitchConfig);
|
|
109
|
+
|
|
110
|
+
this.logger?.trace("The switch to the preferred connection was successful, transferring all children.");
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
await this.changeClientsConnection(transportSwitchConfig);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
|
|
116
|
+
this.logger?.warn(`Some platform clients could not connect to the preferred connection, reverting all to the default connection. Reason: ${JSON.stringify(error)}`);
|
|
117
|
+
|
|
118
|
+
this.fullDefaultRevert()
|
|
119
|
+
.then(() => wait(this.discoveryInterval).then(() => this.connectPreferred(manual, url, auth)))
|
|
120
|
+
.catch(() => wait(this.discoveryInterval).then(() => this.connectPreferred(manual, url, auth)));
|
|
121
|
+
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
this.logger?.trace("The platform is now fully connected to the preferred connection, hooking up disconnection logic.");
|
|
126
|
+
|
|
127
|
+
this.registry.execute("system-reconnect");
|
|
128
|
+
|
|
129
|
+
const unsub = this.glueController.onDisconnected(() => this.handleDisconnected(unsub, manual));
|
|
130
|
+
this.unsub = unsub;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
public async revertToDefault(): Promise<void> {
|
|
134
|
+
if (this.unsub) {
|
|
135
|
+
this.unsub();
|
|
136
|
+
delete this.unsub;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
await this.fullDefaultRevert();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
private async fullDefaultRevert(): Promise<void> {
|
|
143
|
+
await this.glueController.switchTransport({ type: "default" }, "system");
|
|
144
|
+
|
|
145
|
+
this.portsBridge.setActivePreferredTransportConfig({ type: "default" });
|
|
146
|
+
|
|
147
|
+
await this.changeClientsConnection({ type: "default" });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private handleDisconnected(unsub: UnsubscribeFunction, manual?: boolean): void {
|
|
151
|
+
this.logger?.trace("The platform has been disconnected from the preferred transport, reverting all to the default one.");
|
|
152
|
+
|
|
153
|
+
unsub();
|
|
154
|
+
|
|
155
|
+
this.fullDefaultRevert()
|
|
156
|
+
.then(() => {
|
|
157
|
+
this.registry.execute("system-reconnect");
|
|
158
|
+
this.logger?.trace("The platform reversion to default completed, restarting the preferred tracking.");
|
|
159
|
+
if (manual) {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
wait(this.discoveryInterval).then(() => this.connectPreferred());
|
|
163
|
+
})
|
|
164
|
+
.catch(() => wait(this.discoveryInterval).then(() => this.connectPreferred()));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private changeClientsConnection(config: IOConnectCore.Connection.TransportSwitchSettings): Promise<void> {
|
|
168
|
+
return this.sequelizer.enqueue<void>(async () => {
|
|
169
|
+
|
|
170
|
+
try {
|
|
171
|
+
|
|
172
|
+
await Promise.all([
|
|
173
|
+
this.glueController.switchTransport(config, "client"),
|
|
174
|
+
this.portsBridge.switchAllClientsTransport(config)
|
|
175
|
+
]);
|
|
176
|
+
|
|
177
|
+
} catch (error: any) {
|
|
178
|
+
this.logger?.trace(`Some clients could not connect to the preferred transport with error: ${JSON.stringify(error)}`);
|
|
179
|
+
|
|
180
|
+
if (!this.shouldForceTransfer) {
|
|
181
|
+
|
|
182
|
+
this.logger?.trace("The platform is not forcing a transfer in cases of errors, re-throwing.");
|
|
183
|
+
|
|
184
|
+
throw new Error(error);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
this.logger?.trace("The platform is forcing a transfer regardless of the errors.");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
await this.glueController.switchTransport(config, "contextsTrack");
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private checkPreferredConnection(url: string): Promise<{ live: boolean }> {
|
|
195
|
+
|
|
196
|
+
return new Promise<{ live: boolean }>((resolve) => {
|
|
197
|
+
const ws = new WebSocket(url);
|
|
198
|
+
|
|
199
|
+
ws.onerror = (): void => resolve({ live: false });
|
|
200
|
+
|
|
201
|
+
ws.onopen = (): void => {
|
|
202
|
+
ws.close();
|
|
203
|
+
resolve({ live: true });
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private async checkPreFlight(url?: string): Promise<{ ready: boolean }> {
|
|
211
|
+
|
|
212
|
+
this.logger?.trace("Starting the preflight check");
|
|
213
|
+
|
|
214
|
+
const isPreferredLive = (await this.checkPreferredConnection(url || this.preferredUrl)).live;
|
|
215
|
+
|
|
216
|
+
if (!isPreferredLive) {
|
|
217
|
+
this.logger?.trace("The preferred connection is not live.");
|
|
218
|
+
return { ready: false };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
this.logger?.trace(`Found a live preferred connection at: ${url || this.preferredUrl}, testing the availability of transport switching logic in all current clients`);
|
|
222
|
+
|
|
223
|
+
const logicTestResult = await this.portsBridge.checkClientsPreferredLogic();
|
|
224
|
+
|
|
225
|
+
this.logger?.trace(`The logic check returned: ${JSON.stringify(logicTestResult)}`);
|
|
226
|
+
|
|
227
|
+
if (!logicTestResult.success && !this.shouldForceTransfer) {
|
|
228
|
+
this.logger?.trace("The preflight check is marked as not ready");
|
|
229
|
+
return { ready: false };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
this.logger?.trace("Checking the possibility of all clients to connect to the preferred connection");
|
|
233
|
+
|
|
234
|
+
const connectionTest = await this.portsBridge.checkClientsPreferredConnection(url || this.preferredUrl);
|
|
235
|
+
|
|
236
|
+
this.logger?.trace(`The connection check returned: ${JSON.stringify(connectionTest)}`);
|
|
237
|
+
|
|
238
|
+
if (!connectionTest.success && !this.shouldForceTransfer) {
|
|
239
|
+
this.logger?.trace("The preflight check is marked as not ready");
|
|
240
|
+
return { ready: false };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
this.logger?.trace("The preflight check is marked as ready");
|
|
244
|
+
|
|
245
|
+
return { ready: true };
|
|
246
|
+
}
|
|
247
|
+
}
|