Switch to more specific IPC helpers (#2821)

This commit is contained in:
Sebastian Malton authored and GitHub committed 2021-06-10 10:34:22 -04:00
1 parent a12cb0a16e
commit 280af6391e
18 files changed
+191 -178

No files matched your search

+6 -12
View File
@@ -22,11 +22,11 @@
import path from "path";
import Config from "conf";
import type { Options as ConfOptions } from "conf/dist/source/types";
import { app, ipcMain, IpcMainEvent, ipcRenderer, IpcRendererEvent, remote } from "electron";
import { app, ipcMain, ipcRenderer, remote } from "electron";
import { IReactionOptions, makeObservable, observable, reaction, runInAction, when } from "mobx";
import { getAppVersion, Singleton, toJS, Disposer } from "./utils";
import logger from "../main/logger";
import { broadcastMessage, subscribeToBroadcast, unsubscribeFromBroadcast } from "./ipc";
import { broadcastMessage, ipcMainOn, ipcRendererOn } from "./ipc";
import isEqual from "lodash/isEqual";
export interface BaseStoreParams<T = any> extends ConfOptions<T> {
@@ -126,23 +126,17 @@ export abstract class BaseStore<T = any> extends Singleton {
);
if (ipcMain) {
const callback = (event: IpcMainEvent, model: T) => {
this.syncDisposers.push(ipcMainOn(this.syncMainChannel, (event, model: T) => {
logger.silly(`[STORE]: SYNC ${this.name} from renderer`, { model });
this.onSync(model);
};
subscribeToBroadcast(this.syncMainChannel, callback);
this.syncDisposers.push(() => unsubscribeFromBroadcast(this.syncMainChannel, callback));
}));
}
if (ipcRenderer) {
const callback = (event: IpcRendererEvent, model: T) => {
this.syncDisposers.push(ipcRendererOn(this.syncRendererChannel, (event, model: T) => {
logger.silly(`[STORE]: SYNC ${this.name} from main`, { model });
this.onSyncFromMain(model);
};
subscribeToBroadcast(this.syncRendererChannel, callback);
this.syncDisposers.push(() => unsubscribeFromBroadcast(this.syncRendererChannel, callback));
}));
}
}
-92
View File
@@ -19,15 +19,6 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { handleRequest } from "./ipc";
import { ClusterId, ClusterStore } from "./cluster-store";
import { appEventBus } from "./event-bus";
import { ResourceApplier } from "../main/resource-applier";
import { ipcMain, IpcMainInvokeEvent } from "electron";
import { clusterFrameMap } from "./cluster-frames";
import { catalogEntityRegistry } from "../main/catalog";
import type { KubernetesCluster } from "./catalog-entities";
export const clusterActivateHandler = "cluster:activate";
export const clusterSetFrameIdHandler = "cluster:set-frame-id";
export const clusterVisibilityHandler = "cluster:visibility";
@@ -35,86 +26,3 @@ export const clusterRefreshHandler = "cluster:refresh";
export const clusterDisconnectHandler = "cluster:disconnect";
export const clusterKubectlApplyAllHandler = "cluster:kubectl-apply-all";
export const clusterKubectlDeleteAllHandler = "cluster:kubectl-delete-all";
if (ipcMain) {
handleRequest(clusterActivateHandler, (event, clusterId: ClusterId, force = false) => {
return ClusterStore.getInstance()
.getById(clusterId)
?.activate(force);
});
handleRequest(clusterSetFrameIdHandler, (event: IpcMainInvokeEvent, clusterId: ClusterId) => {
const cluster = ClusterStore.getInstance().getById(clusterId);
if (cluster) {
clusterFrameMap.set(cluster.id, { frameId: event.frameId, processId: event.processId });
cluster.pushState();
}
});
handleRequest(clusterVisibilityHandler, (event: IpcMainInvokeEvent, clusterId: ClusterId, visible: boolean) => {
const entity = catalogEntityRegistry.getById<KubernetesCluster>(clusterId);
for (const kubeEntity of catalogEntityRegistry.getItemsForApiKind(entity.apiVersion, entity.kind)) {
kubeEntity.status.active = false;
}
if (entity) {
entity.status.active = visible;
}
});
handleRequest(clusterRefreshHandler, (event, clusterId: ClusterId) => {
return ClusterStore.getInstance()
.getById(clusterId)
?.refresh({ refreshMetadata: true });
});
handleRequest(clusterDisconnectHandler, (event, clusterId: ClusterId) => {
appEventBus.emit({name: "cluster", action: "stop"});
const cluster = ClusterStore.getInstance().getById(clusterId);
if (cluster) {
cluster.disconnect();
clusterFrameMap.delete(cluster.id);
}
});
handleRequest(clusterKubectlApplyAllHandler, async (event, clusterId: ClusterId, resources: string[], extraArgs: string[]) => {
appEventBus.emit({name: "cluster", action: "kubectl-apply-all"});
const cluster = ClusterStore.getInstance().getById(clusterId);
if (cluster) {
const applier = new ResourceApplier(cluster);
try {
const stdout = await applier.kubectlApplyAll(resources, extraArgs);
return { stdout };
} catch (error: any) {
return { stderr: error };
}
} else {
throw `${clusterId} is not a valid cluster id`;
}
});
handleRequest(clusterKubectlDeleteAllHandler, async (event, clusterId: ClusterId, resources: string[], extraArgs: string[]) => {
appEventBus.emit({name: "cluster", action: "kubectl-delete-all"});
const cluster = ClusterStore.getInstance().getById(clusterId);
if (cluster) {
const applier = new ResourceApplier(cluster);
try {
const stdout = await applier.kubectlDeleteAll(resources, extraArgs);
return { stdout };
} catch (error: any) {
return { stderr: error };
}
} else {
throw `${clusterId} is not a valid cluster id`;
}
});
}
+17 -7
View File
@@ -29,7 +29,7 @@ import migrations from "../migrations/cluster-store";
import * as uuid from "uuid";
import logger from "../main/logger";
import { appEventBus } from "./event-bus";
import { handleRequest, requestMain, subscribeToBroadcast, unsubscribeAllFromBroadcast } from "./ipc";
import { ipcMainHandle, ipcMainOn, ipcRendererOn, requestMain } from "./ipc";
import { disposer, noop, toJS } from "./utils";
export interface ClusterIconUpload {
@@ -110,6 +110,8 @@ export interface ClusterPrometheusPreferences {
}
export class ClusterStore extends BaseStore<ClusterStoreModel> {
private static StateChannel = "cluster:state";
static get storedKubeConfigFolder(): string {
return path.resolve((app || remote.app).getPath("userData"), "kubeconfigs");
}
@@ -158,7 +160,7 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
}
});
} else if (ipcMain) {
handleRequest(ClusterStore.stateRequestChannel, (): clusterStateSync[] => {
ipcMainHandle(ClusterStore.stateRequestChannel, (): clusterStateSync[] => {
const clusterStates: clusterStateSync[] = [];
this.clustersList.forEach((cluster) => {
@@ -179,17 +181,25 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
reaction(() => this.connectedClustersList, () => {
this.pushState();
}),
() => unsubscribeAllFromBroadcast("cluster:state"),
);
}
}
handleStateChange = (event: any, clusterId: string, state: ClusterState) => {
logger.silly(`[CLUSTER-STORE]: received push-state at ${location.host} (${webFrame.routingId})`, clusterId, state);
this.getById(clusterId)?.setState(state);
};
registerIpcListener() {
logger.info(`[CLUSTER-STORE] start to listen (${webFrame.routingId})`);
subscribeToBroadcast("cluster:state", (event, clusterId: string, state: ClusterState) => {
logger.silly(`[CLUSTER-STORE]: received push-state at ${location.host} (${webFrame.routingId})`, clusterId, state);
this.getById(clusterId)?.setState(state);
});
if (ipcMain) {
this.disposer.push(ipcMainOn(ClusterStore.StateChannel, this.handleStateChange));
}
if (ipcRenderer) {
this.disposer.push(ipcRendererOn(ClusterStore.StateChannel, this.handleStateChange));
}
}
unregisterIpcListener() {
+15 -30
View File
@@ -26,22 +26,21 @@
import { ipcMain, ipcRenderer, remote, webContents } from "electron";
import { toJS } from "../utils/toJS";
import logger from "../../main/logger";
import { ClusterFrameInfo, clusterFrameMap } from "../cluster-frames";
import { ClusterFrameInfo, clusterFrameMap } from "../cluster-frames";
import type { Disposer } from "../utils";
const subFramesChannel = "ipc:get-sub-frames";
export function handleRequest(channel: string, listener: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any) {
ipcMain.handle(channel, async (event, ...args) => {
const payload = await listener(event, ...args);
return sanitizePayload(payload);
});
}
export async function requestMain(channel: string, ...args: any[]) {
return ipcRenderer.invoke(channel, ...args.map(sanitizePayload));
}
export function ipcMainHandle(channel: string, listener: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any) {
ipcMain.handle(channel, async (event, ...args) => {
return sanitizePayload(await listener(event, ...args));
});
}
function getSubFrames(): ClusterFrameInfo[] {
return Array.from(clusterFrameMap.values());
}
@@ -76,34 +75,20 @@ export function broadcastMessage(channel: string, ...args: any[]) {
});
}
export function subscribeToBroadcast(channel: string, listener: (...args: any[]) => any) {
if (ipcRenderer) {
ipcRenderer.on(channel, listener);
} else if (ipcMain) {
ipcMain.on(channel, listener);
}
export function ipcMainOn(channel: string, listener: (event: Electron.IpcMainEvent, ...args: any[]) => any): Disposer {
ipcMain.on(channel, listener);
return listener;
return () => ipcMain.off(channel, listener);
}
export function unsubscribeFromBroadcast(channel: string, listener: (...args: any[]) => any) {
if (ipcRenderer) {
ipcRenderer.off(channel, listener);
} else if (ipcMain) {
ipcMain.off(channel, listener);
}
}
export function ipcRendererOn(channel: string, listener: (event: Electron.IpcRendererEvent, ...args: any[]) => any): Disposer {
ipcRenderer.on(channel, listener);
export function unsubscribeAllFromBroadcast(channel: string) {
if (ipcRenderer) {
ipcRenderer.removeAllListeners(channel);
} else if (ipcMain) {
ipcMain.removeAllListeners(channel);
}
return () => ipcRenderer.off(channel, listener);
}
export function bindBroadcastHandlers() {
handleRequest(subFramesChannel, () => getSubFrames());
ipcMainHandle(subFramesChannel, () => getSubFrames());
}
/**
+2 -1
View File
@@ -23,6 +23,7 @@ import type { EventEmitter } from "events";
import { ipcMain } from "electron";
import logger from "../../main/logger";
import type { Disposer } from "../utils";
import { ipcMainHandle } from "./ipc";
export type ListenerEvent<EM extends EventEmitter> = Parameters<Parameters<EM["on"]>[1]>[0];
export type ListVerifier<T extends any[]> = (args: unknown[]) => args is T;
@@ -116,7 +117,7 @@ export function handleCorrect<
throw new TypeError(`Invalid args for invoke on channel: ${channel}`);
}
ipcMain.handle(channel, wrappedHandler);
ipcMainHandle(channel, wrappedHandler);
return () => ipcMain.removeHandler(channel);
}