Replace global state usages of ExtensionLoader with DI

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne Savolainen committed 2021-12-15 15:37:36 +02:00
1 parent 0b172de741
commit c92c8f8a11
56 files changed
+2110 -761

No files matched your search

+20 -23
View File
@@ -36,11 +36,9 @@ import { mangleProxyEnv } from "./proxy-env";
import { registerFileProtocol } from "../common/register-protocol";
import logger from "./logger";
import { appEventBus } from "../common/event-bus";
import { ExtensionLoader } from "../extensions/extension-loader";
import { InstalledExtension, ExtensionDiscovery } from "../extensions/extension-discovery";
import type { LensExtensionId } from "../extensions/lens-extension";
import { installDeveloperTools } from "./developer-tools";
import { LensProtocolRouterMain } from "./protocol-handler";
import { disposer, getAppVersion, getAppVersionFromProxyServer, storedKubeConfigFolder } from "../common/utils";
import { bindBroadcastHandlers, ipcMainOn } from "../common/ipc";
import { startUpdateChecking } from "./app-updater";
@@ -68,6 +66,8 @@ import { AppPaths } from "../common/app-paths";
import { ShellSession } from "./shell-session/shell-session";
import { getDi } from "./getDi";
import electronMenuItemsInjectable from "./menu/electron-menu-items.injectable";
import extensionLoaderInjectable from "../extensions/extension-loader/extension-loader.injectable";
import lensProtocolRouterMainInjectable from "./protocol-handler/lens-protocol-router-main/lens-protocol-router-main.injectable";
const di = getDi();
@@ -79,7 +79,6 @@ const onQuitCleanup = disposer();
SentryInit();
app.setName(appName);
logger.info(`📟 Setting ${productName} as protocol client for lens://`);
if (app.setAsDefaultProtocolClient("lens")) {
@@ -111,14 +110,14 @@ if (app.commandLine.getSwitchValue("proxy-server") !== "") {
logger.debug("[APP-MAIN] Lens protocol routing main");
const lensProtocolRouterMain = di.inject(lensProtocolRouterMainInjectable);
if (!app.requestSingleInstanceLock()) {
app.exit();
} else {
const lprm = LensProtocolRouterMain.createInstance();
for (const arg of process.argv) {
if (arg.toLowerCase().startsWith("lens://")) {
lprm.route(arg);
lensProtocolRouterMain.route(arg);
}
}
}
@@ -126,11 +125,9 @@ if (!app.requestSingleInstanceLock()) {
app.on("second-instance", (event, argv) => {
logger.debug("second-instance message");
const lprm = LensProtocolRouterMain.createInstance();
for (const arg of argv) {
if (arg.toLowerCase().startsWith("lens://")) {
lprm.route(arg);
lensProtocolRouterMain.route(arg);
}
}
@@ -227,9 +224,12 @@ app.on("ready", async () => {
return app.exit();
}
const extensionDiscovery = ExtensionDiscovery.createInstance();
const extensionLoader = di.inject(extensionLoaderInjectable);
extensionLoader.init();
const extensionDiscovery = ExtensionDiscovery.createInstance(extensionLoader);
ExtensionLoader.createInstance().init();
extensionDiscovery.init();
// Start the app without showing the main window when auto starting on login
@@ -258,7 +258,7 @@ app.on("ready", async () => {
await ensureDir(storedKubeConfigFolder());
KubeconfigSyncManager.getInstance().startSync();
startUpdateChecking();
LensProtocolRouterMain.getInstance().rendererLoaded = true;
lensProtocolRouterMain.rendererLoaded = true;
});
logger.info("🧩 Initializing extensions");
@@ -273,13 +273,13 @@ app.on("ready", async () => {
// Subscribe to extensions that are copied or deleted to/from the extensions folder
extensionDiscovery.events
.on("add", (extension: InstalledExtension) => {
ExtensionLoader.getInstance().addExtension(extension);
extensionLoader.addExtension(extension);
})
.on("remove", (lensExtensionId: LensExtensionId) => {
ExtensionLoader.getInstance().removeExtension(lensExtensionId);
extensionLoader.removeExtension(lensExtensionId);
});
ExtensionLoader.getInstance().initExtensions(extensions);
extensionLoader.initExtensions(extensions);
} catch (error) {
dialog.showErrorBox("Lens Error", `Could not load extensions${error?.message ? `: ${error.message}` : ""}`);
console.error(error);
@@ -314,7 +314,6 @@ app.on("will-quit", (event) => {
// This is called when the close button of the main window is clicked
const lprm = LensProtocolRouterMain.getInstance(false);
logger.info("APP:QUIT");
appEventBus.emit({ name: "app", action: "close" });
@@ -322,11 +321,9 @@ app.on("will-quit", (event) => {
KubeconfigSyncManager.getInstance(false)?.stopSync();
onCloseCleanup();
if (lprm) {
// This is set to false here so that LPRM can wait to send future lens://
// requests until after it loads again
lprm.rendererLoaded = false;
}
// This is set to false here so that LPRM can wait to send future lens://
// requests until after it loads again
lensProtocolRouterMain.rendererLoaded = false;
if (blockQuit) {
// Quit app on Cmd+Q (MacOS)
@@ -336,7 +333,7 @@ app.on("will-quit", (event) => {
return; // skip exit to make tray work, to quit go to app's global menu or tray's menu
}
lprm?.cleanup();
lensProtocolRouterMain.cleanup();
onQuitCleanup();
});
@@ -345,7 +342,7 @@ app.on("open-url", (event, rawUrl) => {
// lens:// protocol handler
event.preventDefault();
LensProtocolRouterMain.getInstance().route(rawUrl);
lensProtocolRouterMain.route(rawUrl);
});
/**
@@ -25,11 +25,15 @@ import { broadcastMessage } from "../../../common/ipc";
import { ProtocolHandlerExtension, ProtocolHandlerInternal } from "../../../common/protocol-handler";
import { delay, noop } from "../../../common/utils";
import { LensExtension } from "../../../extensions/main-api";
import { ExtensionLoader } from "../../../extensions/extension-loader";
import { ExtensionsStore } from "../../../extensions/extensions-store";
import { LensProtocolRouterMain } from "../router";
import type { LensProtocolRouterMain } from "../lens-protocol-router-main/lens-protocol-router-main";
import mockFs from "mock-fs";
import { AppPaths } from "../../../common/app-paths";
import { getDiForUnitTesting } from "../../getDiForUnitTesting";
import extensionLoaderInjectable
from "../../../extensions/extension-loader/extension-loader.injectable";
import lensProtocolRouterMainInjectable
from "../lens-protocol-router-main/lens-protocol-router-main.injectable";
jest.mock("../../../common/ipc");
@@ -58,14 +62,22 @@ function throwIfDefined(val: any): void {
}
describe("protocol router tests", () => {
// TODO: This test suite is using any to access protected property.
// Unit tests are allowed to only public interfaces.
let extensionLoader: any;
let lpr: LensProtocolRouterMain;
beforeEach(() => {
const di = getDiForUnitTesting();
extensionLoader = di.inject(extensionLoaderInjectable);
mockFs({
"tmp": {},
});
ExtensionsStore.createInstance();
ExtensionLoader.createInstance();
const lpr = LensProtocolRouterMain.createInstance();
lpr = di.inject(lensProtocolRouterMainInjectable);
lpr.rendererLoaded = true;
});
@@ -74,15 +86,11 @@ describe("protocol router tests", () => {
jest.clearAllMocks();
ExtensionsStore.resetInstance();
ExtensionLoader.resetInstance();
LensProtocolRouterMain.resetInstance();
mockFs.restore();
});
it("should throw on non-lens URLS", async () => {
try {
const lpr = LensProtocolRouterMain.getInstance();
expect(await lpr.route("https://google.ca")).toBeUndefined();
} catch (error) {
expect(error).toBeInstanceOf(Error);
@@ -91,8 +99,6 @@ describe("protocol router tests", () => {
it("should throw when host not internal or extension", async () => {
try {
const lpr = LensProtocolRouterMain.getInstance();
expect(await lpr.route("lens://foobar")).toBeUndefined();
} catch (error) {
expect(error).toBeInstanceOf(Error);
@@ -113,14 +119,13 @@ describe("protocol router tests", () => {
isCompatible: true,
absolutePath: "/foo/bar",
});
const lpr = LensProtocolRouterMain.getInstance();
ext.protocolHandlers.push({
pathSchema: "/",
handler: noop,
});
(ExtensionLoader.getInstance() as any).instances.set(extId, ext);
extensionLoader.instances.set(extId, ext);
(ExtensionsStore.getInstance() as any).state.set(extId, { enabled: true, name: "@mirantis/minikube" });
lpr.addInternalHandler("/", noop);
@@ -143,7 +148,6 @@ describe("protocol router tests", () => {
});
it("should call handler if matches", async () => {
const lpr = LensProtocolRouterMain.getInstance();
let called = false;
lpr.addInternalHandler("/page", () => { called = true; });
@@ -159,7 +163,6 @@ describe("protocol router tests", () => {
});
it("should call most exact handler", async () => {
const lpr = LensProtocolRouterMain.getInstance();
let called: any = 0;
lpr.addInternalHandler("/page", () => { called = 1; });
@@ -178,7 +181,6 @@ describe("protocol router tests", () => {
it("should call most exact handler for an extension", async () => {
let called: any = 0;
const lpr = LensProtocolRouterMain.getInstance();
const extId = uuid.v4();
const ext = new LensExtension({
id: extId,
@@ -202,7 +204,7 @@ describe("protocol router tests", () => {
handler: params => { called = params.pathname.id; },
});
(ExtensionLoader.getInstance() as any).instances.set(extId, ext);
extensionLoader.instances.set(extId, ext);
(ExtensionsStore.getInstance() as any).state.set(extId, { enabled: true, name: "@foobar/icecream" });
try {
@@ -217,7 +219,6 @@ describe("protocol router tests", () => {
});
it("should work with non-org extensions", async () => {
const lpr = LensProtocolRouterMain.getInstance();
let called: any = 0;
{
@@ -241,7 +242,7 @@ describe("protocol router tests", () => {
handler: params => { called = params.pathname.id; },
});
(ExtensionLoader.getInstance() as any).instances.set(extId, ext);
extensionLoader.instances.set(extId, ext);
(ExtensionsStore.getInstance() as any).state.set(extId, { enabled: true, name: "@foobar/icecream" });
}
@@ -266,7 +267,7 @@ describe("protocol router tests", () => {
handler: () => { called = 1; },
});
(ExtensionLoader.getInstance() as any).instances.set(extId, ext);
extensionLoader.instances.set(extId, ext);
(ExtensionsStore.getInstance() as any).state.set(extId, { enabled: true, name: "icecream" });
}
@@ -286,13 +287,10 @@ describe("protocol router tests", () => {
});
it("should throw if urlSchema is invalid", () => {
const lpr = LensProtocolRouterMain.getInstance();
expect(() => lpr.addInternalHandler("/:@", noop)).toThrowError();
});
it("should call most exact handler with 3 found handlers", async () => {
const lpr = LensProtocolRouterMain.getInstance();
let called: any = 0;
lpr.addInternalHandler("/", () => { called = 2; });
@@ -311,7 +309,6 @@ describe("protocol router tests", () => {
});
it("should call most exact handler with 2 found handlers", async () => {
const lpr = LensProtocolRouterMain.getInstance();
let called: any = 0;
lpr.addInternalHandler("/", () => { called = 2; });
+1 -1
View File
@@ -19,4 +19,4 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
export * from "./router";
export * from "./lens-protocol-router-main/lens-protocol-router-main";
@@ -0,0 +1,40 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { Injectable } from "@ogre-tools/injectable";
import { lifecycleEnum } from "@ogre-tools/injectable";
import extensionLoaderInjectable from "../../../extensions/extension-loader/extension-loader.injectable";
import type { Dependencies } from "./lens-protocol-router-main";
import { LensProtocolRouterMain } from "./lens-protocol-router-main";
const lensProtocolRouterMainInjectable: Injectable<
LensProtocolRouterMain,
Dependencies
> = {
getDependencies: di => ({
extensionLoader: di.inject(extensionLoaderInjectable),
}),
instantiate: dependencies => new LensProtocolRouterMain(dependencies),
lifecycle: lifecycleEnum.singleton,
};
export default lensProtocolRouterMainInjectable;
@@ -19,15 +19,16 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import logger from "../logger";
import * as proto from "../../common/protocol-handler";
import logger from "../../logger";
import * as proto from "../../../common/protocol-handler";
import URLParse from "url-parse";
import type { LensExtension } from "../../extensions/lens-extension";
import { broadcastMessage } from "../../common/ipc";
import type { LensExtension } from "../../../extensions/lens-extension";
import { broadcastMessage } from "../../../common/ipc";
import { observable, when, makeObservable } from "mobx";
import { ProtocolHandlerInvalid, RouteAttempt } from "../../common/protocol-handler";
import { disposer, noop } from "../../common/utils";
import { WindowManager } from "../window-manager";
import { ProtocolHandlerInvalid, RouteAttempt } from "../../../common/protocol-handler";
import { disposer, noop } from "../../../common/utils";
import { WindowManager } from "../../window-manager";
import type { ExtensionLoader } from "../../../extensions/extension-loader";
export interface FallbackHandler {
(name: string): Promise<boolean>;
@@ -50,6 +51,10 @@ function checkHost<Query>(url: URLParse<Query>): boolean {
}
}
export interface Dependencies {
extensionLoader: ExtensionLoader
}
export class LensProtocolRouterMain extends proto.LensProtocolRouter {
private missingExtensionHandlers: FallbackHandler[] = [];
@@ -57,8 +62,8 @@ export class LensProtocolRouterMain extends proto.LensProtocolRouter {
protected disposers = disposer();
constructor() {
super();
constructor(protected dependencies: Dependencies) {
super(dependencies);
makeObservable(this);
}