Switch to using messaging and startable stoppable from NPM package (#7368)

* Add custom jest resolver to fix requiring "uuid" module

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Update dependencies

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Introduce test utils for rendering and running with thrown mobx reactions

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Extract startable-stoppable to NPM package

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Extract messaging to NPM package

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Switch to using startable-stoppable from NPM package

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Switch to using messaging from the Feature

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Remove old implementation of messaging

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Make setupping app paths happen earlier in renderer

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Fix typo

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Add kludge to make testing-library work properly from test-utils package

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Fix code style

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Add lint:fix -root script

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Fix unrelated failing unit tests

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Turn of no-floating-promises from typescript linting for being broken

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Make linting not happen for dist -directories

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Make linting failures appear as failure

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Stop running prettier twice

It already gets ran as eslint-plugin.

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Make CI run unit tests for all packages by consolidating name of NPM script

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Add missing unit tests for coverage

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Skip coverage for test utils

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Remove check for coverage in packages which are not ready for it

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Stop collecting coverage from index.ts files them being indirections to the implementation

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Implement sending message to channel in main

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Add missing feature dependencies

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Add dummy implementations for requesting in main from renderer

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Re-enable communicating from main to cluster frames

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Ignore trivial files from coverage

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Update package-lock

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Extract message-bridge to separate NPM package to prevent dev dependencies being in the production bundle

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Extract computed channel to own NPM package for clear dependencies

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Consolidate electron related stuff to a directory

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Add missing publish configurations

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

* Ignore test implementation from coverage being not interesting

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

---------

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne SavolainenandMikko Aspiala authored and GitHub committed 2023-03-21 11:38:43 +02:00
1 parent df49ff9b96
commit 0f1f030a06
261 files changed
+4447 -1795

No files matched your search

@@ -3,11 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { AppPaths } from "./app-path-injection-token";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
import { getRequestChannel } from "@k8slens/messaging";
export type AppPathsChannel = RequestChannel<void, AppPaths>;
export const appPathsChannel: AppPathsChannel = {
id: "app-paths",
};
export const appPathsChannel = getRequestChannel<void, AppPaths>("app-paths");
@@ -15,7 +15,7 @@ import type { GetConfigurationFileModel } from "../get-configuration-file-model/
import type { Logger } from "../logger";
import type { PersistStateToConfig } from "./save-to-file";
import type { GetBasenameOfPath } from "../path/get-basename.injectable";
import type { EnlistMessageChannelListener } from "../utils/channel/enlist-message-channel-listener-injection-token";
import type { EnlistMessageChannelListener } from "@k8slens/messaging";
import { toJS } from "../utils";
export interface BaseStoreParams<T> extends Omit<ConfOptions<T>, "migrations"> {
@@ -108,6 +108,7 @@ export abstract class BaseStore<T extends object> {
this.params.syncOptions,
),
this.dependencies.enlistMessageChannelListener({
id: this.displayName,
channel: {
id: `${this.dependencies.ipcChannelPrefixes.local}:${config.path}`,
},
@@ -4,6 +4,6 @@
*/
import type { SelfSignedCert } from "selfsigned";
import { getRequestChannel } from "../utils/channel/get-request-channel";
import { getRequestChannel } from "@k8slens/messaging";
export const lensProxyCertificateChannel = getRequestChannel<void, SelfSignedCert>("request-lens-proxy-certificate");
@@ -16,7 +16,7 @@ import { baseStoreIpcChannelPrefixesInjectionToken } from "../base-store/channel
import { shouldBaseStoreDisableSyncInIpcListenerInjectionToken } from "../base-store/disable-sync";
import { persistStateToConfigInjectionToken } from "../base-store/save-to-file";
import getBasenameOfPathInjectable from "../path/get-basename.injectable";
import { enlistMessageChannelListenerInjectionToken } from "../utils/channel/enlist-message-channel-listener-injection-token";
import { enlistMessageChannelListenerInjectionToken } from "@k8slens/messaging";
const clusterStoreInjectable = getInjectable({
id: "cluster-store",
@@ -4,7 +4,7 @@
*/
import type { ClusterId } from "../cluster-types";
import type { MessageChannel } from "../utils/channel/message-channel-listener-injection-token";
import type { MessageChannel } from "@k8slens/messaging";
export const currentClusterMessageChannel: MessageChannel<ClusterId> = {
id: "current-visible-cluster",
@@ -4,7 +4,7 @@
*/
import type { ClusterId } from "../cluster-types";
import type { MessageChannel } from "../utils/channel/message-channel-listener-injection-token";
import type { MessageChannel } from "@k8slens/messaging";
export const clusterVisibilityChannel: MessageChannel<ClusterId | null> = {
id: "cluster-visibility",
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { IpcRendererNavigationEvents } from "../ipc/navigation-events";
import type { MessageChannel } from "../utils/channel/message-channel-listener-injection-token";
import type { MessageChannel } from "@k8slens/messaging";
export type AppNavigationChannel = MessageChannel<string>;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { IpcRendererNavigationEvents } from "../ipc/navigation-events";
import type { MessageChannel } from "../utils/channel/message-channel-listener-injection-token";
import type { MessageChannel } from "@k8slens/messaging";
export type ClusterFrameNavigationChannel = MessageChannel<string>;
@@ -3,11 +3,10 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { HelmRepo } from "./helm-repo";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
import type { Result } from "@k8slens/utilities";
import { getRequestChannel } from "@k8slens/messaging";
export type AddHelmRepositoryChannel = RequestChannel<HelmRepo, AsyncResult<void, string>>;
export const addHelmRepositoryChannel: AddHelmRepositoryChannel = {
id: "add-helm-repository-channel",
};
export const addHelmRepositoryChannel = getRequestChannel<
HelmRepo,
Result<void, string>
>("add-helm-repository-channel");
@@ -4,10 +4,9 @@
*/
import type { HelmRepo } from "./helm-repo";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
import { getRequestChannel } from "@k8slens/messaging";
export type GetActiveHelmRepositoriesChannel = RequestChannel<void, AsyncResult<HelmRepo[]>>;
export const getActiveHelmRepositoriesChannel: GetActiveHelmRepositoriesChannel = {
id: "get-helm-active-list-repositories",
};
export const getActiveHelmRepositoriesChannel = getRequestChannel<
void,
AsyncResult<HelmRepo[]>
>("get-helm-active-list-repositories");
@@ -3,11 +3,10 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
import { getRequestChannel } from "@k8slens/messaging";
import type { HelmRepo } from "./helm-repo";
export type RemoveHelmRepositoryChannel = RequestChannel<HelmRepo, AsyncResult<void, string>>;
export const removeHelmRepositoryChannel: RemoveHelmRepositoryChannel = {
id: "remove-helm-repository-channel",
};
export const removeHelmRepositoryChannel = getRequestChannel<
HelmRepo,
AsyncResult<void, string>
>("remove-helm-repository-channel");
@@ -14,7 +14,7 @@ import { hotbarStoreMigrationInjectionToken } from "./migrations-token";
import getBasenameOfPathInjectable from "../path/get-basename.injectable";
import { baseStoreIpcChannelPrefixesInjectionToken } from "../base-store/channel-prefix";
import { persistStateToConfigInjectionToken } from "../base-store/save-to-file";
import { enlistMessageChannelListenerInjectionToken } from "../utils/channel/enlist-message-channel-listener-injection-token";
import { enlistMessageChannelListenerInjectionToken } from "@k8slens/messaging";
import { shouldBaseStoreDisableSyncInIpcListenerInjectionToken } from "../base-store/disable-sync";
const hotbarStoreInjectable = getInjectable({
@@ -4,11 +4,9 @@
*/
import { getInjectionToken } from "@ogre-tools/injectable";
import type { Asyncify } from "type-fest";
import type { RequestChannelHandler } from "../../main/utils/channel/channel-listeners/listener-tokens";
import type { ClusterId } from "../cluster-types";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
import type { AsyncResult, Result } from "@k8slens/utilities";
import { getRequestChannel } from "@k8slens/messaging";
export interface KubectlApplyAllArgs {
clusterId: ClusterId;
@@ -16,11 +14,12 @@ export interface KubectlApplyAllArgs {
extraArgs: string[];
}
export const kubectlApplyAllChannel: RequestChannel<KubectlApplyAllArgs, AsyncResult<string, string>> = {
id: "kubectl-apply-all",
};
export const kubectlApplyAllChannel = getRequestChannel<
KubectlApplyAllArgs,
Result<string, string>
>("kubectl-apply-all");
export type KubectlApplyAll = Asyncify<RequestChannelHandler<typeof kubectlApplyAllChannel>>;
export type KubectlApplyAll = (req: KubectlApplyAllArgs) => AsyncResult<string, string>;
export const kubectlApplyAllInjectionToken = getInjectionToken<KubectlApplyAll>({
id: "kubectl-apply-all",
@@ -32,11 +31,12 @@ export interface KubectlDeleteAllArgs {
extraArgs: string[];
}
export const kubectlDeleteAllChannel: RequestChannel<KubectlDeleteAllArgs, AsyncResult<string, string>> = {
id: "kubectl-delete-all",
};
export const kubectlDeleteAllChannel = getRequestChannel<
KubectlDeleteAllArgs,
Result<string, string>
>("kubectl-delete-all");
export type KubectlDeleteAll = Asyncify<RequestChannelHandler<typeof kubectlDeleteAllChannel>>;
export type KubectlDeleteAll = (req: KubectlDeleteAllArgs) => AsyncResult<string, string>;
export const kubectlDeleteAllInjectionToken = getInjectionToken<KubectlDeleteAll>({
id: "kubectl-delete-all",
@@ -2,7 +2,7 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { MessageChannel } from "../utils/channel/message-channel-listener-injection-token";
import type { MessageChannel } from "@k8slens/messaging";
export type RootFrameHasRenderedChannel = MessageChannel<void>;
@@ -16,7 +16,7 @@ import { baseStoreIpcChannelPrefixesInjectionToken } from "../base-store/channel
import { shouldBaseStoreDisableSyncInIpcListenerInjectionToken } from "../base-store/disable-sync";
import { persistStateToConfigInjectionToken } from "../base-store/save-to-file";
import getBasenameOfPathInjectable from "../path/get-basename.injectable";
import { enlistMessageChannelListenerInjectionToken } from "../utils/channel/enlist-message-channel-listener-injection-token";
import { enlistMessageChannelListenerInjectionToken } from "@k8slens/messaging";
import userStorePreferenceDescriptorsInjectable from "./preference-descriptors.injectable";
const userStoreInjectable = getInjectable({
@@ -1,12 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
export interface Channel<MessageTemplate = void, ReturnTemplate = void> {
id: string;
_messageTemplate?: MessageTemplate;
_returnTemplate?: ReturnTemplate;
}
@@ -1,245 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { DiContainer } from "@ogre-tools/injectable";
import { getInjectable } from "@ogre-tools/injectable";
import type { SendMessageToChannel } from "./message-to-channel-injection-token";
import { sendMessageToChannelInjectionToken } from "./message-to-channel-injection-token";
import type { ApplicationBuilder } from "../../../renderer/components/test-utils/get-application-builder";
import { getApplicationBuilder } from "../../../renderer/components/test-utils/get-application-builder";
import type { LensWindow } from "../../../main/start-main-application/lens-window/application-window/create-lens-window.injectable";
import type { MessageChannel } from "./message-channel-listener-injection-token";
import { messageChannelListenerInjectionToken } from "./message-channel-listener-injection-token";
import type { RequestFromChannel } from "./request-from-channel-injection-token";
import { requestFromChannelInjectionToken } from "./request-from-channel-injection-token";
import type { RequestChannel } from "./request-channel-listener-injection-token";
import type { AsyncFnMock } from "@async-fn/jest";
import asyncFn from "@async-fn/jest";
import { getPromiseStatus } from "@k8slens/test-utils";
import { runInAction } from "mobx";
import type { RequestChannelHandler } from "../../../main/utils/channel/channel-listeners/listener-tokens";
import {
getRequestChannelListenerInjectable,
requestChannelListenerInjectionToken,
} from "../../../main/utils/channel/channel-listeners/listener-tokens";
type TestMessageChannel = MessageChannel<string>;
type TestRequestChannel = RequestChannel<string, string>;
describe("channel", () => {
describe("messaging from main to renderer, given listener for channel in a window and application has started", () => {
let messageListenerInWindowMock: jest.Mock;
let mainDi: DiContainer;
let messageToChannel: SendMessageToChannel;
let builder: ApplicationBuilder;
beforeEach(async () => {
builder = getApplicationBuilder();
messageListenerInWindowMock = jest.fn();
const testChannelListenerInTestWindowInjectable = getInjectable({
id: "test-channel-listener-in-test-window",
instantiate: () => ({
channel: testMessageChannel,
handler: messageListenerInWindowMock,
}),
injectionToken: messageChannelListenerInjectionToken,
});
builder.beforeWindowStart(({ windowDi }) => {
runInAction(() => {
windowDi.register(testChannelListenerInTestWindowInjectable);
});
});
mainDi = builder.mainDi;
await builder.startHidden();
messageToChannel = mainDi.inject(sendMessageToChannelInjectionToken);
});
describe("given window is started", () => {
let someWindowFake: LensWindow;
beforeEach(async () => {
someWindowFake = builder.applicationWindow.create("some-window");
await someWindowFake.start();
});
it("when sending message, triggers listener in window", () => {
messageToChannel(testMessageChannel, "some-message");
expect(messageListenerInWindowMock).toHaveBeenCalledWith("some-message");
});
it("given window is hidden, when sending message, does not trigger listener in window", () => {
someWindowFake.close();
messageToChannel(testMessageChannel, "some-message");
expect(messageListenerInWindowMock).not.toHaveBeenCalled();
});
});
it("given multiple started windows, when sending message, triggers listeners in all windows", async () => {
const someWindowFake = builder.applicationWindow.create("some-window");
const someOtherWindowFake = builder.applicationWindow.create("some-other-window");
await someWindowFake.start();
await someOtherWindowFake.start();
messageToChannel(testMessageChannel, "some-message");
expect(messageListenerInWindowMock.mock.calls).toEqual([
["some-message"],
["some-message"],
]);
});
});
describe("messaging from renderer to main, given listener for channel in a main and application has started", () => {
let messageListenerInMainMock: jest.Mock;
let messageToChannel: SendMessageToChannel;
beforeEach(async () => {
const applicationBuilder = getApplicationBuilder();
messageListenerInMainMock = jest.fn();
const testChannelListenerInMainInjectable = getInjectable({
id: "test-channel-listener-in-main",
instantiate: () => ({
channel: testMessageChannel,
handler: messageListenerInMainMock,
}),
injectionToken: messageChannelListenerInjectionToken,
});
applicationBuilder.beforeApplicationStart(({ mainDi }) => {
runInAction(() => {
mainDi.register(testChannelListenerInMainInjectable);
});
});
await applicationBuilder.render();
const windowDi = applicationBuilder.applicationWindow.only.di;
messageToChannel = windowDi.inject(sendMessageToChannelInjectionToken);
});
it("when sending message, triggers listener in main", () => {
messageToChannel(testMessageChannel, "some-message");
expect(messageListenerInMainMock).toHaveBeenCalledWith("some-message");
});
});
describe("requesting from main in renderer, given listener for channel in a main and application has started", () => {
let requestListenerInMainMock: AsyncFnMock<RequestChannelHandler<TestRequestChannel>>;
let requestFromChannel: RequestFromChannel;
beforeEach(async () => {
const applicationBuilder = getApplicationBuilder();
requestListenerInMainMock = asyncFn();
const testChannelListenerInMainInjectable = getRequestChannelListenerInjectable({
channel: testRequestChannel,
handler: () => requestListenerInMainMock,
});
applicationBuilder.beforeApplicationStart(({ mainDi }) => {
runInAction(() => {
mainDi.register(testChannelListenerInMainInjectable);
});
});
await applicationBuilder.render();
const windowDi = applicationBuilder.applicationWindow.only.di;
requestFromChannel = windowDi.inject(
requestFromChannelInjectionToken,
);
});
describe("when requesting from channel", () => {
let actualPromise: Promise<string>;
beforeEach(() => {
actualPromise = requestFromChannel(testRequestChannel, "some-request");
});
it("triggers listener in main", () => {
expect(requestListenerInMainMock).toHaveBeenCalledWith("some-request");
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
it("when main resolves with response, resolves with response", async () => {
await requestListenerInMainMock.resolve("some-response");
const actual = await actualPromise;
expect(actual).toBe("some-response");
});
});
});
it("when registering multiple handlers for the same channel, throws", async () => {
const applicationBuilder = getApplicationBuilder();
const someChannelListenerInjectable = getInjectable({
id: "some-channel-listener",
instantiate: () => ({
channel: testRequestChannel,
handler: () => () => "irrelevant",
}),
injectionToken: requestChannelListenerInjectionToken,
});
const someOtherChannelListenerInjectable = getInjectable({
id: "some-other-channel-listener",
instantiate: () => ({
channel: testRequestChannel,
handler: () => () => "irrelevant",
}),
injectionToken: requestChannelListenerInjectionToken,
});
applicationBuilder.beforeApplicationStart(({ mainDi }) => {
runInAction(() => {
mainDi.register(someChannelListenerInjectable);
mainDi.register(someOtherChannelListenerInjectable);
});
});
await expect(applicationBuilder.render()).rejects.toThrow('Tried to register a multiple channel handlers for "some-request-channel-id", only one handler is supported for a request channel.');
});
});
const testMessageChannel: TestMessageChannel = {
id: "some-message-channel-id",
};
const testRequestChannel: TestRequestChannel = {
id: "some-request-channel-id",
};
@@ -1,13 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectionToken } from "@ogre-tools/injectable";
import type { Disposer } from "@k8slens/utilities";
import type { MessageChannel, MessageChannelListener } from "./message-channel-listener-injection-token";
export type EnlistMessageChannelListener = (listener: MessageChannelListener<MessageChannel<unknown>>) => Disposer;
export const enlistMessageChannelListenerInjectionToken = getInjectionToken<EnlistMessageChannelListener>({
id: "enlist-message-channel-listener",
});
@@ -1,9 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { RequestChannel } from "./request-channel-listener-injection-token";
export const getRequestChannel = <Request, Response>(id: string): RequestChannel<Request, Response> => ({
id,
});
@@ -1,25 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { getStartableStoppable } from "../get-startable-stoppable";
import { messageChannelListenerInjectionToken } from "./message-channel-listener-injection-token";
import { enlistMessageChannelListenerInjectionToken } from "./enlist-message-channel-listener-injection-token";
import { disposer } from "@k8slens/utilities";
const listeningOnMessageChannelsInjectable = getInjectable({
id: "listening-on-message-channels",
instantiate: (di) => {
const enlistMessageChannelListener = di.inject(enlistMessageChannelListenerInjectionToken);
const messageChannelListeners = di.injectMany(messageChannelListenerInjectionToken);
return getStartableStoppable("listening-on-channels", () => (
disposer(messageChannelListeners.map(enlistMessageChannelListener))
));
},
});
export default listeningOnMessageChannelsInjectable;
@@ -1,51 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { DiContainerForInjection } from "@ogre-tools/injectable";
import { getInjectable, getInjectionToken } from "@ogre-tools/injectable";
export interface MessageChannel<Message> {
id: string;
_messageSignature?: Message; // only used to mark `Message` as used
}
export type MessageChannelHandler<Channel> = Channel extends MessageChannel<infer Message>
? (message: Message) => void
: never;
export interface MessageChannelListener<Channel> {
channel: Channel;
handler: MessageChannelHandler<Channel>;
}
export const messageChannelListenerInjectionToken = getInjectionToken<MessageChannelListener<MessageChannel<unknown>>>(
{
id: "message-channel-listener",
},
);
export interface GetMessageChannelListenerInfo<
Channel extends MessageChannel<Message>,
Message,
> {
id: string;
channel: Channel;
handler: (di: DiContainerForInjection) => MessageChannelHandler<Channel>;
causesSideEffects?: boolean;
}
export function getMessageChannelListenerInjectable<
Channel extends MessageChannel<Message>,
Message,
>(info: GetMessageChannelListenerInfo<Channel, Message>) {
return getInjectable({
id: `${info.channel.id}-listener-${info.id}`,
instantiate: (di) => ({
channel: info.channel,
handler: info.handler(di),
}),
injectionToken: messageChannelListenerInjectionToken,
causesSideEffects: info.causesSideEffects,
});
}
@@ -1,21 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectionToken } from "@ogre-tools/injectable";
import type { MessageChannel } from "./message-channel-listener-injection-token";
export interface SendMessageToChannel {
(channel: MessageChannel<void>): void;
<Message>(channel: MessageChannel<Message>, message: Message): void;
}
export type MessageChannelSender<Channel> = Channel extends MessageChannel<void | undefined>
? () => void
: Channel extends MessageChannel<infer Message>
? (message: Message) => void
: never;
export const sendMessageToChannelInjectionToken = getInjectionToken<SendMessageToChannel>({
id: "send-message-to-message-channel",
});
@@ -1,10 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
export interface RequestChannel<Request, Response> {
id: string;
_requestSignature?: Request; // used only to mark `Request` as "used"
_responseSignature?: Response; // used only to mark `Response` as "used"
}
@@ -1,19 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectionToken } from "@ogre-tools/injectable";
import type { RequestChannel } from "./request-channel-listener-injection-token";
export interface RequestFromChannel {
<Request, Response>(channel: RequestChannel<Request, Response>, request: Request): Promise<Awaited<Response>>;
<Response>(channel: RequestChannel<void, Response>): Promise<Awaited<Response>>;
}
export type ChannelRequester<Channel> = Channel extends RequestChannel<infer Request, infer Response>
? (req: Request) => Promise<Awaited<Response>>
: never;
export const requestFromChannelInjectionToken = getInjectionToken<RequestFromChannel>({
id: "request-from-request-channel",
});
@@ -1,62 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { StartableStoppable } from "./get-startable-stoppable";
import { getStartableStoppable } from "./get-startable-stoppable";
describe("getStartableStoppable", () => {
let stopMock: jest.MockedFunction<() => void>;
let startMock: jest.MockedFunction<() => () => void>;
let actual: StartableStoppable;
beforeEach(() => {
stopMock = jest.fn();
startMock = jest.fn().mockImplementation(() => stopMock);
actual = getStartableStoppable("some-id", startMock);
});
it("does not start yet", () => {
expect(startMock).not.toHaveBeenCalled();
});
it("does not stop yet", () => {
expect(stopMock).not.toHaveBeenCalled();
});
it("when stopping before ever starting, throws", () => {
expect(() => actual.stop()).toThrow("Tried to stop \"some-id\", but it is already stopped.");
});
it("is not started", () => {
expect(actual.started).toBe(false);
});
describe("when started", () => {
beforeEach(() => {
actual.start();
});
it("calls start function", () => {
expect(startMock).toHaveBeenCalled();
});
it("is started", () => {
expect(actual.started).toBe(true);
});
describe("when stopped", () => {
beforeEach(() => {
actual.stop();
});
it("calls stop function", () => {
expect(stopMock).toBeCalled();
});
it("is stopped", () => {
expect(actual.started).toBe(false);
});
});
});
});
@@ -1,45 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
export type Stopper = () => void;
export type Starter = () => Stopper;
export interface StartableStoppable {
readonly started: boolean;
start: () => void;
stop: () => void;
}
type StartableStoppableState = "stopped" | "started" | "starting";
export function getStartableStoppable(id: string, startAndGetStopper: Starter): StartableStoppable {
let stop: Stopper;
let state: StartableStoppableState = "stopped";
return {
get started() {
return state === "started";
},
start: () => {
if (state !== "stopped") {
throw new Error(`Tried to start "${id}", but it is already ${state}.`);
}
state = "starting";
stop = startAndGetStopper();
state = "started";
},
stop: () => {
if (state !== "started") {
throw new Error(`Tried to stop "${id}", but it is already ${state}.`);
}
stop();
state = "stopped";
},
};
}
@@ -2,10 +2,8 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { RequestChannel } from "../channel/request-channel-listener-injection-token";
import { getRequestChannel } from "@k8slens/messaging";
export type ResolveSystemProxyChannel = RequestChannel<string, string>;
export const resolveSystemProxyChannel: ResolveSystemProxyChannel = {
id: "resolve-system-proxy-channel",
};
export const resolveSystemProxyChannel = getRequestChannel<string, string>(
"resolve-system-proxy-channel",
);
@@ -3,13 +3,13 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { syncBoxChannel } from "./channels";
import { getMessageChannelListenerInjectable } from "../channel/message-channel-listener-injection-token";
import { getMessageChannelListenerInjectable } from "@k8slens/messaging";
import syncBoxStateInjectable from "./sync-box-state.injectable";
const syncBoxChannelListenerInjectable = getMessageChannelListenerInjectable({
id: "init",
channel: syncBoxChannel,
handler: (di) => ({ id, value }) => di.inject(syncBoxStateInjectable, id).set(value),
getHandler: (di) => ({ id, value }) => di.inject(syncBoxStateInjectable, id).set(value),
});
export default syncBoxChannelListenerInjectable;
@@ -2,20 +2,12 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { MessageChannel } from "../channel/message-channel-listener-injection-token";
import type { RequestChannel } from "../channel/request-channel-listener-injection-token";
import { getMessageChannel, getRequestChannel } from "@k8slens/messaging";
export type SyncBoxChannel = MessageChannel<{ id: string; value: any }>;
export const syncBoxChannel =
getMessageChannel<{ id: string; value: any }>("sync-box-channel");
export const syncBoxChannel: SyncBoxChannel = {
id: "sync-box-channel",
};
export type SyncBoxInitialValueChannel = RequestChannel<
export const syncBoxInitialValueChannel = getRequestChannel<
void,
{ id: string; value: any }[]
>;
export const syncBoxInitialValueChannel: SyncBoxInitialValueChannel = {
id: "sync-box-initial-value-channel",
};
>("sync-box-initial-value-channel");
@@ -6,7 +6,7 @@ import { getInjectable } from "@ogre-tools/injectable";
import type { IObservableValue } from "mobx";
import { computed } from "mobx";
import { syncBoxChannel } from "./channels";
import { sendMessageToChannelInjectionToken } from "../channel/message-to-channel-injection-token";
import { sendMessageToChannelInjectionToken } from "@k8slens/messaging";
import syncBoxStateInjectable from "./sync-box-state.injectable";
import type { SyncBox } from "./sync-box-injection-token";
import { toJS } from "../toJS";
@@ -1,19 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { MessageChannelHandler } from "../channel/message-channel-listener-injection-token";
import type { SyncBoxChannel } from "./channels";
import syncBoxStateInjectable from "./sync-box-state.injectable";
const syncBoxChannelHandlerInjectable = getInjectable({
id: "sync-box-channel-handler",
instantiate: (di): MessageChannelHandler<SyncBoxChannel> => {
const getSyncBoxState = (id: string) => di.inject(syncBoxStateInjectable, id);
return ({ id, value }) => getSyncBoxState(id)?.set(value);
},
});
export default syncBoxChannelHandlerInjectable;
@@ -7,7 +7,7 @@ import { getInjectionToken } from "@ogre-tools/injectable";
import { SemVer } from "semver";
import type { InitializableState } from "../initializable-state/create";
import { createInitializableState } from "../initializable-state/create";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
import type { RequestChannel } from "@k8slens/messaging";
export const buildVersionInjectionToken = getInjectionToken<InitializableState<string>>({
id: "build-version-token",
@@ -11,7 +11,7 @@ import { persistStateToConfigInjectionToken } from "../base-store/save-to-file";
import getConfigurationFileModelInjectable from "../get-configuration-file-model/get-configuration-file-model.injectable";
import loggerInjectable from "../logger.injectable";
import getBasenameOfPathInjectable from "../path/get-basename.injectable";
import { enlistMessageChannelListenerInjectionToken } from "../utils/channel/enlist-message-channel-listener-injection-token";
import { enlistMessageChannelListenerInjectionToken } from "@k8slens/messaging";
import storeMigrationVersionInjectable from "../vars/store-migration-version.injectable";
import { weblinkStoreMigrationInjectionToken } from "./migration-token";
import { WeblinkStore } from "./weblink-store";