Convert runMany and runManySync to use injectManyWithMeta + move to seperate package (#7244)

* Convert runMany and runManySync to use injectManyWithMeta

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fixup type errors due to new Runnable requirements

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Add documentation for verifyRunnablesAreDAG

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Simplify convertToWithIdWith

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Move all utility functions to separate package

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Move testing utilities to separate package

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Move run-many and run-many-sync to separate package

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Replace all internal uses of utilities with new packages

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Use new @k8slens/run-many package in core

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Add dep to open-lens

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fixup type errors

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fixup uses of @k8slens/test-utils

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fixup getGlobalOverride

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Move tests to new package too

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix type errors

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fixup uses of AsyncResult and autoBind

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fixup remaining import issues

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Finial fixups to fix build

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix lint

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Revert moving "testUsingFakeTime" to separate package

- This fixes tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix integration tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix unit test failing due to spelling fix

Signed-off-by: Sebastian Malton <sebastian@malton.name>

---------

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton authored and GitHub committed 2023-03-10 10:07:28 +02:00
1 parent ad9bafe2a5
commit 2789bcebcb
754 files changed
+2715 -2752

No files matched your search

+3 -1
View File
@@ -135,7 +135,6 @@
"@ogre-tools/injectable-extension-for-auto-registration": "^15.1.2",
"@ogre-tools/injectable-extension-for-mobx": "^15.1.2",
"@ogre-tools/injectable-react": "^15.1.2",
"@ogre-tools/injectable-utils": "^15.1.2",
"@sentry/electron": "^3.0.8",
"@sentry/integrations": "^6.19.3",
"@side/jest-runtime": "^1.1.0",
@@ -332,6 +331,9 @@
"peerDependencies": {
"@k8slens/application": "^6.5.0-alpha.0",
"@k8slens/application-for-electron-main": "^6.5.0-alpha.0",
"@k8slens/run-many": "^1.0.0",
"@k8slens/test-utils": "^1.0.0",
"@k8slens/utilities": "^1.0.0",
"@types/byline": "^4.2.33",
"@types/chart.js": "^2.9.36",
"@types/color": "^3.0.3",
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import pathToNpmCliInjectable from "./path-to-npm-cli.injectable";
export default getGlobalOverride(pathToNpmCliInjectable, () => "/some/npm/cli/path");
@@ -7,7 +7,7 @@ import type Config from "conf";
import type { Migrations, Options as ConfOptions } from "conf/dist/source/types";
import type { IEqualsComparer } from "mobx";
import { makeObservable, reaction } from "mobx";
import { disposer, isPromiseLike, toJS } from "../utils";
import { disposer, isPromiseLike } from "@k8slens/utilities";
import { broadcastMessage } from "../ipc";
import isEqual from "lodash/isEqual";
import { kebabCase } from "lodash";
@@ -16,6 +16,7 @@ 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 { toJS } from "../utils";
export interface BaseStoreParams<T> extends Omit<ConfOptions<T>, "migrations"> {
syncOptions?: {
@@ -7,7 +7,7 @@ import { lifecycleEnum, getInjectable } from "@ogre-tools/injectable";
import type Conf from "conf/dist/source";
import type { Migrations } from "conf/dist/source/types";
import loggerInjectable from "../logger.injectable";
import { getOrInsert, iter } from "../utils";
import { getOrInsert, iter } from "@k8slens/utilities";
export interface MigrationDeclaration {
version: string;
@@ -5,7 +5,7 @@
import { getInjectable } from "@ogre-tools/injectable";
import { generalCatalogEntityInjectionToken } from "../general-catalog-entity-injection-token";
import { GeneralEntity } from "../../index";
import { buildURL } from "../../../utils/buildUrl";
import { buildURL } from "@k8slens/utilities";
import catalogRouteInjectable from "../../../front-end-routing/routes/catalog/catalog-route.injectable";
const catalogCatalogEntityInjectable = getInjectable({
@@ -5,7 +5,7 @@
import { getInjectable } from "@ogre-tools/injectable";
import { generalCatalogEntityInjectionToken } from "../general-catalog-entity-injection-token";
import { GeneralEntity } from "../../index";
import { buildURL } from "../../../utils/buildUrl";
import { buildURL } from "@k8slens/utilities";
import welcomeRouteInjectable from "../../../front-end-routing/routes/welcome/welcome-route.injectable";
const welcomeCatalogEntityInjectable = getInjectable({
@@ -7,8 +7,8 @@ import EventEmitter from "events";
import type TypedEmitter from "typed-emitter";
import { observable, makeObservable } from "mobx";
import { once } from "lodash";
import type { Disposer } from "../utils";
import { iter } from "../utils";
import type { Disposer } from "@k8slens/utilities";
import { iter } from "@k8slens/utilities";
import type { CategoryColumnRegistration, TitleCellProps } from "../../renderer/components/+catalog/custom-category-columns";
export type { CategoryColumnRegistration, TitleCellProps };
@@ -5,8 +5,8 @@
import { action, computed, observable, makeObservable } from "mobx";
import { once } from "lodash";
import { iter, getOrInsertMap, strictSet } from "../utils";
import type { Disposer } from "../utils";
import { iter, getOrInsertMap, strictSet } from "@k8slens/utilities";
import type { Disposer } from "@k8slens/utilities";
import type { CatalogCategory, CatalogEntityData, CatalogEntityKindData } from "./catalog-entity";
export type CategoryFilter = (category: CatalogCategory) => any;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import lensProxyCertificateInjectable from "./lens-proxy-certificate.injectable";
export default getGlobalOverride(lensProxyCertificateInjectable, () => {
@@ -5,7 +5,7 @@
import type { KubeConfig } from "@kubernetes/client-node";
import { CoreV1Api } from "@kubernetes/client-node";
import { getInjectable } from "@ogre-tools/injectable";
import { isDefined } from "../utils";
import { isDefined } from "@k8slens/utilities";
export type ListNamespaces = () => Promise<string[]>;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import initializeSentryReportingWithInjectable from "./initialize-sentry-reporting.injectable";
export default getGlobalOverride(initializeSentryReportingWithInjectable, () => () => {});
@@ -4,14 +4,14 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { RequestInit, Response } from "@k8slens/node-fetch";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import fetchInjectable from "./fetch.injectable";
export interface DownloadBinaryOptions {
signal?: AbortSignal | null | undefined;
}
export type DownloadBinary = (url: string, opts?: DownloadBinaryOptions) => Promise<AsyncResult<Buffer, string>>;
export type DownloadBinary = (url: string, opts?: DownloadBinaryOptions) => AsyncResult<Buffer, string>;
const downloadBinaryInjectable = getInjectable({
id: "download-binary",
@@ -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 { AsyncResult } from "../../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { Fetch } from "../fetch.injectable";
import type { RequestInit, Response } from "@k8slens/node-fetch";
@@ -10,7 +10,7 @@ export interface DownloadJsonOptions {
signal?: AbortSignal | null | undefined;
}
export type DownloadJson = (url: string, opts?: DownloadJsonOptions) => Promise<AsyncResult<unknown, string>>;
export type DownloadJson = (url: string, opts?: DownloadJsonOptions) => AsyncResult<unknown, string>;
export const downloadJsonWith = (fetch: Fetch): DownloadJson => async (url, opts) => {
let result: Response;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "../test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "@k8slens/test-utils";
import fetchInjectable from "./fetch.injectable";
export default getGlobalOverrideForFunction(fetchInjectable);
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "../test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "@k8slens/test-utils";
import lensFetchInjectable from "./lens-fetch.injectable";
export default getGlobalOverrideForFunction(lensFetchInjectable);
@@ -4,7 +4,7 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import { shouldShowResourceInjectionToken } from "../../../../../cluster-store/allowed-resources-injection-token";
import { computedOr } from "../../../../../utils/computed-or";
import { computedOr } from "@k8slens/utilities";
import { frontEndRouteInjectionToken } from "../../../../front-end-route-injection-token";
const ingressesRouteInjectable = getInjectable({
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import copyInjectable from "./copy.injectable";
export default getGlobalOverride(copyInjectable, () => async () => {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "../test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "@k8slens/test-utils";
import execFileInjectable from "./exec-file.injectable";
export default getGlobalOverrideForFunction(execFileInjectable);
@@ -5,14 +5,14 @@
import { getInjectable } from "@ogre-tools/injectable";
import type { ExecFileException, ExecFileOptions } from "child_process";
import { execFile } from "child_process";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
export type ExecFileError = ExecFileException & { stderr: string };
export interface ExecFile {
(filePath: string): Promise<AsyncResult<string, ExecFileError>>;
(filePath: string, argsOrOptions: string[] | ExecFileOptions): Promise<AsyncResult<string, ExecFileError>>;
(filePath: string, args: string[], options: ExecFileOptions): Promise<AsyncResult<string, ExecFileError>>;
(filePath: string): AsyncResult<string, ExecFileError>;
(filePath: string, argsOrOptions: string[] | ExecFileOptions): AsyncResult<string, ExecFileError>;
(filePath: string, args: string[], options: ExecFileOptions): AsyncResult<string, ExecFileError>;
}
const execFileInjectable = getInjectable({
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import extractTarInjectable from "./extract-tar.injectable";
export default getGlobalOverride(extractTarInjectable, () => async () => {
@@ -21,6 +21,7 @@ const fsInjectable = getInjectable({
rm,
access,
stat,
unlink,
},
ensureDir,
ensureDirSync,
@@ -56,6 +57,7 @@ const fsInjectable = getInjectable({
ensureDirSync,
createReadStream,
stat,
unlink,
};
},
causesSideEffects: true,
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import lstatInjectable from "./lstat.injectable";
export default getGlobalOverride(lstatInjectable, () => async () => {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import readDirectoryInjectable from "./read-directory.injectable";
export default getGlobalOverride(readDirectoryInjectable, () => async () => {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import removePathInjectable from "./remove.injectable";
export default getGlobalOverride(removePathInjectable, () => async () => {
@@ -0,0 +1,15 @@
/**
* 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 fsInjectable from "./fs.injectable";
export type Unlink = (path: string) => Promise<void>;
const unlinkInjectable = getInjectable({
id: "unlink",
instantiate: (di): Unlink => di.inject(fsInjectable).unlink,
});
export default unlinkInjectable;
@@ -3,13 +3,13 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { AsyncResult } from "../utils/async-result";
import { isErrnoException } from "../utils";
import type { AsyncResult } from "@k8slens/utilities";
import { isErrnoException } from "@k8slens/utilities";
import type { Stats } from "fs-extra";
import { lowerFirst } from "lodash/fp";
import statInjectable from "./stat.injectable";
export type ValidateDirectory = (path: string) => Promise<AsyncResult<undefined>>;
export type ValidateDirectory = (path: string) => AsyncResult<undefined>;
function getUserReadableFileType(stats: Stats): string {
if (stats.isFile()) {
@@ -2,7 +2,7 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import watchInjectable from "./watch.injectable";
export default getGlobalOverride(watchInjectable, () => () => {
@@ -6,7 +6,7 @@ import { getInjectable } from "@ogre-tools/injectable";
import { watch } from "chokidar";
import type { Stats } from "fs";
import type TypedEventEmitter from "typed-emitter";
import type { SingleOrMany } from "../../utils";
import type { SingleOrMany } from "@k8slens/utilities";
export interface AlwaysStatWatcherEvents {
add: (path: string, stats: Stats) => void;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import writeFileInjectable from "./write-file.injectable";
export default getGlobalOverride(writeFileInjectable, () => async () => {
@@ -5,7 +5,7 @@
import assert from "assert";
import path from "path";
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import getConfigurationFileModelInjectable from "./get-configuration-file-model.injectable";
import type Config from "conf";
import readJsonSyncInjectable from "../fs/read-json-sync.injectable";
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { HelmRepo } from "./helm-repo";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
export type AddHelmRepositoryChannel = RequestChannel<HelmRepo, AsyncResult<void, string>>;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { HelmRepo } from "./helm-repo";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
export type GetActiveHelmRepositoriesChannel = RequestChannel<void, AsyncResult<HelmRepo[]>>;
@@ -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 { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
import type { HelmRepo } from "./helm-repo";
+2 -2
View File
@@ -4,8 +4,8 @@
*/
import * as uuid from "uuid";
import type { Tuple } from "../utils";
import { tuple } from "../utils";
import type { Tuple } from "@k8slens/utilities";
import { tuple } from "@k8slens/utilities";
export interface HotbarItem {
entity: {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "../test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "@k8slens/test-utils";
import broadcastMessageInjectable from "./broadcast-message.injectable";
export default getGlobalOverrideForFunction(broadcastMessageInjectable);
+1 -1
View File
@@ -11,7 +11,7 @@ import { ipcMain, ipcRenderer, webContents } from "electron";
import { toJS } from "../utils/toJS";
import type { ClusterFrameInfo } from "../cluster-frames";
import { clusterFrameMap } from "../cluster-frames";
import type { Disposer } from "../utils";
import type { Disposer } from "@k8slens/utilities";
import { getLegacyGlobalDiForExtensionApi } from "../../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import ipcRendererInjectable from "../../renderer/utils/channel/ipc-renderer.injectable";
import loggerInjectable from "../logger.injectable";
+1 -1
View File
@@ -3,8 +3,8 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import autoBind from "auto-bind";
import orderBy from "lodash/orderBy";
import { autoBind } from "./utils";
import { action, computed, observable, when, makeObservable } from "mobx";
export interface ItemObject {
@@ -10,7 +10,7 @@ import type { Fetch } from "../../fetch/fetch.injectable";
import fetchInjectable from "../../fetch/fetch.injectable";
import type { AsyncFnMock } from "@async-fn/jest";
import asyncFn from "@async-fn/jest";
import { flushPromises } from "../../test-utils/flush-promises";
import { flushPromises } from "@k8slens/test-utils";
import setupAutoRegistrationInjectable from "../../../renderer/before-frame-starts/runnables/setup-auto-registration.injectable";
import { createMockResponseFromString } from "../../../test-utils/mock-responses";
import storesAndApisCanBeCreatedInjectable from "../../../renderer/stores-apis-can-be-created.injectable";
@@ -119,7 +119,7 @@ describe("KubeApi", () => {
]);
});
describe("when resource request fufills with a resource", () => {
describe("when resource request fulfills with a resource", () => {
beforeEach(async () => {
await fetchMock.resolveSpecific(
["https://127.0.0.1:12345/api-kube/apis/networking.k8s.io/v1"],
@@ -281,7 +281,7 @@ describe("KubeApi", () => {
});
});
describe("when resource request fufills with no resource", () => {
describe("when resource request fulfills with no resource", () => {
beforeEach(async () => {
await fetchMock.resolveSpecific(
["https://127.0.0.1:12345/api-kube/apis/networking.k8s.io/v1"],
@@ -305,7 +305,7 @@ describe("KubeApi", () => {
describe("when resource request fufills with a resource", () => {
describe("when resource request fulfills with a resource", () => {
beforeEach(async () => {
await fetchMock.resolveSpecific(
["https://127.0.0.1:12345/api-kube/apis/networking.k8s.io/v1beta1"],
@@ -507,7 +507,7 @@ describe("KubeApi", () => {
]);
});
describe("when resource request fufills with a resource", () => {
describe("when resource request fulfills with a resource", () => {
beforeEach(async () => {
await fetchMock.resolveSpecific(
["https://127.0.0.1:12345/api-kube/apis/extensions"],
@@ -15,7 +15,7 @@ import type { CreateKubeApiForRemoteCluster } from "../create-kube-api-for-remot
import createKubeApiForRemoteClusterInjectable from "../create-kube-api-for-remote-cluster.injectable";
import type { AsyncFnMock } from "@async-fn/jest";
import asyncFn from "@async-fn/jest";
import { flushPromises } from "../../test-utils/flush-promises";
import { flushPromises } from "@k8slens/test-utils";
import createKubeJsonApiInjectable from "../create-kube-json-api.injectable";
import type { IKubeWatchEvent } from "../kube-watch-event";
import type { KubeJsonApiDataFor } from "../kube-object";
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { noop } from "../../utils";
import { noop } from "@k8slens/utilities";
import type { KubeApi } from "../kube-api";
import { KubeObject } from "../kube-object";
import type { KubeObjectStoreLoadingParams } from "../kube-object.store";
@@ -10,7 +10,7 @@ import { autorun, action, observable } from "mobx";
import type { KubeApi } from "../kube-api";
import type { KubeObject, ObjectReference } from "../kube-object";
import { parseKubeApi, createKubeApiURL } from "../kube-api-parse";
import { chain, find } from "../../utils/iter";
import { iter } from "@k8slens/utilities";
export type RegisterableStore<Store> = Store extends KubeObjectStore<any, any, any>
? Store
@@ -38,7 +38,7 @@ export class ApiManager {
constructor(private readonly dependencies: Dependencies) {
// NOTE: this is done to preserve the old behaviour of an API being discoverable using all previous apiBases
autorun(() => {
const apis = chain(this.dependencies.apis.get().values())
const apis = iter.chain(this.dependencies.apis.get().values())
.concat(this.externalApis.values());
const removedApis = new Set(this.apis.values());
const newState = new Map(this.apis);
@@ -62,7 +62,7 @@ export class ApiManager {
getApi(pathOrCallback: string | FindApiCallback) {
if (typeof pathOrCallback === "function") {
return find(this.apis.values(), pathOrCallback);
return iter.find(this.apis.values(), pathOrCallback);
}
const { apiBase } = parseKubeApi(pathOrCallback);
@@ -130,7 +130,7 @@ export class ApiManager {
return undefined;
}
return chain(this.dependencies.stores.get().values())
return iter.chain(this.dependencies.stores.get().values())
.concat(this.externalStores.values())
.find(store => store.api.apiBase === api.apiBase);
}
@@ -8,7 +8,7 @@ import { KubeObject } from "../kube-object";
import type { KubeJsonApiData } from "../kube-json-api";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import { autoBind } from "../../utils";
import autoBind from "auto-bind";
export interface ConfigMapData extends KubeJsonApiData<KubeObjectMetadata<KubeObjectScope.Namespace>, void, void> {
data?: Partial<Record<string, string>>;
@@ -6,7 +6,7 @@
import moment from "moment";
import type { NamespaceScopedMetadata, ObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import { formatDuration } from "../../utils/formatDuration";
import { formatDuration } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { JobTemplateSpec } from "./types/job-template-spec";
@@ -5,7 +5,7 @@
import { getLegacyGlobalDiForExtensionApi } from "../../../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import customResourcesRouteInjectable from "../../front-end-routing/routes/cluster/custom-resources/custom-resources/custom-resources-route.injectable";
import { buildURL } from "../../utils/buildUrl";
import { buildURL } from "@k8slens/utilities";
import type { BaseKubeObjectCondition, ClusterScopedMetadata } from "../kube-object";
import { KubeObject } from "../kube-object";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
@@ -10,7 +10,7 @@ import { KubeApi } from "../kube-api";
import type { PodSpec } from "./pod.api";
import type { KubeObjectStatus, LabelSelector, NamespaceScopedMetadata } from "../kube-object";
import { KubeObject } from "../kube-object";
import { hasTypedProperty, isNumber, isObject } from "../../utils";
import { hasTypedProperty, isNumber, isObject } from "@k8slens/utilities";
export class DeploymentApi extends KubeApi<Deployment> {
constructor(deps: KubeApiDependencies, opts?: DerivedKubeApiOptions) {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { autoBind } from "../../utils";
import autoBind from "auto-bind";
import type { KubeObjectMetadata, KubeObjectScope, NamespaceScopedMetadata, ObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
@@ -6,7 +6,7 @@
import moment from "moment";
import type { KubeObjectMetadata, KubeObjectScope, ObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import { formatDuration } from "../../utils/formatDuration";
import { formatDuration } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { KubeJsonApiData } from "../kube-json-api";
@@ -3,7 +3,8 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { autoBind, bifurcateArray } from "../../utils";
import { array } from "@k8slens/utilities";
import autoBind from "auto-bind";
import Joi from "joi";
export interface RawHelmChart {
@@ -263,7 +264,7 @@ export class HelmChart implements HelmChartData {
return new HelmChart(result.value);
}
const [actualErrors, unknownDetails] = bifurcateArray(result.error.details, ({ type }) => type === "object.unknown");
const [actualErrors, unknownDetails] = array.bifurcate(result.error.details, ({ type }) => type === "object.unknown");
if (unknownDetails.length > 0) {
console.warn("HelmChart data has unexpected fields", { original: data, unknownFields: unknownDetails.flatMap(d => d.path) });
@@ -5,7 +5,7 @@
import { getInjectable } from "@ogre-tools/injectable";
import type { RawHelmChart } from "../helm-charts.api";
import { HelmChart } from "../helm-charts.api";
import { isDefined } from "../../../utils";
import { isDefined } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestHelmCharts = () => Promise<HelmChart[]>;
@@ -3,13 +3,13 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { AsyncResult } from "../../../utils/async-result";
import { urlBuilderFor } from "../../../utils/buildUrl";
import type { AsyncResult } from "@k8slens/utilities";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
const requestReadmeEndpoint = urlBuilderFor("/v2/charts/:repo/:name/readme");
export type RequestHelmChartReadme = (repo: string, name: string, version?: string) => Promise<AsyncResult<string>>;
export type RequestHelmChartReadme = (repo: string, name: string, version?: string) => AsyncResult<string>;
const requestHelmChartReadmeInjectable = getInjectable({
id: "request-helm-chart-readme",
@@ -3,13 +3,13 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { AsyncResult } from "../../../utils/async-result";
import { urlBuilderFor } from "../../../utils/buildUrl";
import type { AsyncResult } from "@k8slens/utilities";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
const requestValuesEndpoint = urlBuilderFor("/v2/charts/:repo/:name/values");
export type RequestHelmChartValues = (repo: string, name: string, version: string) => Promise<AsyncResult<string>>;
export type RequestHelmChartValues = (repo: string, name: string, version: string) => AsyncResult<string>;
const requestHelmChartValuesInjectable = getInjectable({
id: "request-helm-chart-values",
@@ -3,10 +3,9 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor, isDefined } from "@k8slens/utilities";
import { HelmChart } from "../helm-charts.api";
import type { RawHelmChart } from "../helm-charts.api";
import { isDefined } from "../../../utils";
import apiBaseInjectable from "../../api-base.injectable";
const requestVersionsEndpoint = urlBuilderFor("/v2/charts/:repo/:name/versions");
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../../../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import requestHelmReleaseConfigurationInjectable from "./request-configuration.injectable";
export default getGlobalOverride(requestHelmReleaseConfigurationInjectable, () => () => {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestHelmReleaseConfiguration = (
@@ -5,7 +5,7 @@
import yaml from "js-yaml";
import { getInjectable } from "@ogre-tools/injectable";
import type { HelmReleaseUpdateDetails } from "../helm-releases.api";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
interface HelmReleaseCreatePayload {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestDeleteHelmRelease = (name: string, namespace: string) => Promise<void>;
@@ -4,7 +4,7 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { KubeJsonApiData } from "../../kube-json-api";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
export interface HelmReleaseDetails {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
export interface HelmReleaseRevision {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
import type { HelmReleaseDto } from "../helm-releases.api";
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestHelmReleaseRollback = (name: string, namespace: string, revision: number) => Promise<void>;
@@ -3,8 +3,8 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import type { AsyncResult } from "../../../utils/async-result";
import { urlBuilderFor } from "@k8slens/utilities";
import type { AsyncResult } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
interface HelmReleaseUpdatePayload {
@@ -18,7 +18,7 @@ export type RequestHelmReleaseUpdate = (
name: string,
namespace: string,
payload: HelmReleaseUpdatePayload
) => Promise<AsyncResult<void, unknown>>;
) => AsyncResult<void, unknown>;
const requestUpdateEndpoint = urlBuilderFor("/v2/releases/:namespace/:name");
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestHelmReleaseValues = (name: string, namespace: string, all?: boolean) => Promise<string>;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { OptionVarient } from "../../utils";
import type { OptionVariant } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { BaseKubeObjectCondition, LabelSelector, NamespaceScopedMetadata } from "../kube-object";
@@ -46,7 +46,7 @@ export interface V2Beta1ContainerResourceMetricSource {
targetAverageValue?: string;
}
export type ContainerResourceMetricSource =
export type ContainerResourceMetricSource =
| V2ContainerResourceMetricSource
| V2Beta1ContainerResourceMetricSource;
@@ -74,7 +74,7 @@ export interface V2Beta1ExternalMetricSource {
};
}
export type ExternalMetricSource =
export type ExternalMetricSource =
| V2Beta1ExternalMetricSource
| V2ExternalMetricSource;
@@ -152,11 +152,11 @@ export interface BaseHorizontalPodAutoscalerMetricSpec {
}
export type HorizontalPodAutoscalerMetricSpec =
| OptionVarient<HpaMetricType.Resource, BaseHorizontalPodAutoscalerMetricSpec, "resource">
| OptionVarient<HpaMetricType.External, BaseHorizontalPodAutoscalerMetricSpec, "external">
| OptionVarient<HpaMetricType.Object, BaseHorizontalPodAutoscalerMetricSpec, "object">
| OptionVarient<HpaMetricType.Pods, BaseHorizontalPodAutoscalerMetricSpec, "pods">
| OptionVarient<HpaMetricType.ContainerResource, BaseHorizontalPodAutoscalerMetricSpec, "containerResource">;
| OptionVariant<HpaMetricType.Resource, BaseHorizontalPodAutoscalerMetricSpec, "resource">
| OptionVariant<HpaMetricType.External, BaseHorizontalPodAutoscalerMetricSpec, "external">
| OptionVariant<HpaMetricType.Object, BaseHorizontalPodAutoscalerMetricSpec, "object">
| OptionVariant<HpaMetricType.Pods, BaseHorizontalPodAutoscalerMetricSpec, "pods">
| OptionVariant<HpaMetricType.ContainerResource, BaseHorizontalPodAutoscalerMetricSpec, "containerResource">;
interface HorizontalPodAutoscalerBehavior {
scaleUp?: HPAScalingRules;
@@ -294,11 +294,11 @@ export interface BaseHorizontalPodAutoscalerMetricStatus {
}
export type HorizontalPodAutoscalerMetricStatus =
| OptionVarient<HpaMetricType.Resource, BaseHorizontalPodAutoscalerMetricStatus, "resource">
| OptionVarient<HpaMetricType.External, BaseHorizontalPodAutoscalerMetricStatus, "external">
| OptionVarient<HpaMetricType.Object, BaseHorizontalPodAutoscalerMetricStatus, "object">
| OptionVarient<HpaMetricType.Pods, BaseHorizontalPodAutoscalerMetricStatus, "pods">
| OptionVarient<HpaMetricType.ContainerResource, BaseHorizontalPodAutoscalerMetricStatus, "containerResource">;
| OptionVariant<HpaMetricType.Resource, BaseHorizontalPodAutoscalerMetricStatus, "resource">
| OptionVariant<HpaMetricType.External, BaseHorizontalPodAutoscalerMetricStatus, "external">
| OptionVariant<HpaMetricType.Object, BaseHorizontalPodAutoscalerMetricStatus, "object">
| OptionVariant<HpaMetricType.Pods, BaseHorizontalPodAutoscalerMetricStatus, "pods">
| OptionVariant<HpaMetricType.ContainerResource, BaseHorizontalPodAutoscalerMetricStatus, "containerResource">;
export interface HorizontalPodAutoscalerSpec {
scaleTargetRef: CrossVersionObjectReference;
@@ -5,7 +5,7 @@
import type { NamespaceScopedMetadata, TypedLocalObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import { hasTypedProperty, isString, iter } from "../../utils";
import { hasTypedProperty, isString, iter } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { RequireExactlyOne } from "type-fest";
@@ -6,7 +6,7 @@
// Metrics api
import moment from "moment";
import { isDefined, object } from "../../utils";
import { isDefined, object } from "@k8slens/utilities";
export interface MetricData {
status: string;
@@ -5,7 +5,7 @@
import type { BaseKubeObjectCondition, ClusterScopedMetadata } from "../kube-object";
import { KubeObject } from "../kube-object";
import { cpuUnitsToNumber, unitsToBytes, isObject } from "../../../renderer/utils";
import { cpuUnitsToNumber, unitsToBytes, isObject } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import { TypedRegEx } from "typed-regex";
@@ -8,7 +8,7 @@ import { KubeObject } from "../kube-object";
import type { Pod } from "./pod.api";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import { object } from "../../utils";
import { object } from "@k8slens/utilities";
import type { ResourceRequirements } from "./types/resource-requirements";
export class PersistentVolumeClaimApi extends KubeApi<PersistentVolumeClaim> {
@@ -5,7 +5,7 @@
import type { ClusterScopedMetadata, LabelSelector, ObjectReference, TypedLocalObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import { unitsToBytes } from "../../utils";
import { unitsToBytes } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { ResourceRequirements } from "./types/resource-requirements";
@@ -10,7 +10,7 @@ import type { KubeObjectMetadata, LocalObjectReference, Affinity, Toleration, Na
import type { SecretReference } from "./secret.api";
import type { PersistentVolumeClaimSpec } from "./persistent-volume-claim.api";
import { KubeObject } from "../kube-object";
import { isDefined } from "../../utils";
import { isDefined } from "@k8slens/utilities";
import type { PodSecurityContext } from "./types/pod-security-context";
import type { Probe } from "./types/probe";
import type { Container } from "./types/container";
@@ -5,10 +5,10 @@
import { getInjectable } from "@ogre-tools/injectable";
import type { Patch } from "rfc6902";
import apiBaseInjectable from "../../api-base.injectable";
import type { AsyncResult } from "../../../utils/async-result";
import type { AsyncResult, Result } from "@k8slens/utilities";
import type { KubeJsonApiData } from "../../kube-json-api";
export type RequestKubeObjectPatch = (name: string, kind: string, ns: string | undefined, patch: Patch) => Promise<AsyncResult<KubeJsonApiData, string>>;
export type RequestKubeObjectPatch = (name: string, kind: string, ns: string | undefined, patch: Patch) => AsyncResult<KubeJsonApiData, string>;
const requestKubeObjectPatchInjectable = getInjectable({
id: "request-kube-object-patch",
@@ -23,7 +23,7 @@ const requestKubeObjectPatchInjectable = getInjectable({
ns,
patch,
},
}) as AsyncResult<string, string>;
}) as Result<string, string>;
if (!result.callWasSuccessful) {
return result;
@@ -4,10 +4,10 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import apiBaseInjectable from "../../api-base.injectable";
import type { AsyncResult } from "../../../utils/async-result";
import type { AsyncResult, Result } from "@k8slens/utilities";
import type { KubeJsonApiData } from "../../kube-json-api";
export type RequestKubeObjectCreation = (resourceDescriptor: string) => Promise<AsyncResult<KubeJsonApiData, string>>;
export type RequestKubeObjectCreation = (resourceDescriptor: string) => AsyncResult<KubeJsonApiData, string>;
const requestKubeObjectCreationInjectable = getInjectable({
id: "request-kube-object-creation",
@@ -15,7 +15,7 @@ const requestKubeObjectCreationInjectable = getInjectable({
const apiBase = di.inject(apiBaseInjectable);
return async (data) => {
const result = await apiBase.post("/stack", { data }) as AsyncResult<string, string>;
const result = await apiBase.post("/stack", { data }) as Result<string, string>;
if (!result.callWasSuccessful) {
return result;
@@ -6,9 +6,9 @@
import type { KubeObjectMetadata, KubeObjectScope, NamespaceScopedMetadata } from "../kube-object";
import { KubeObject } from "../kube-object";
import type { KubeJsonApiData } from "../kube-json-api";
import { autoBind } from "../../utils";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import autoBind from "auto-bind";
export enum SecretType {
Opaque = "Opaque",
@@ -3,12 +3,12 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { autoBind } from "../../utils";
import type { ClusterScopedMetadata, KubeObjectMetadata, KubeObjectScope } from "../kube-object";
import { KubeObject } from "../kube-object";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { KubeJsonApiData } from "../kube-json-api";
import autoBind from "auto-bind";
export interface TopologySelectorLabelRequirement {
key: string;
+16 -15
View File
@@ -15,8 +15,8 @@ import type { PartialDeep, ValueOf } from "type-fest";
import { EventEmitter } from "../../common/event-emitter";
import type { Logger } from "../../common/logger";
import type { Fetch } from "../fetch/fetch.injectable";
import type { Defaulted } from "../utils";
import { json } from "../utils";
import type { Defaulted } from "@k8slens/utilities";
import { isObject, isString, json } from "@k8slens/utilities";
export interface JsonApiData {}
@@ -184,20 +184,17 @@ export class JsonApi<Data = JsonApiData, Params extends JsonApiParams<Data> = Js
const res = await this.dependencies.fetch(reqUrl, reqInit);
return this.parseResponse<OutData>(res, infoLog);
return await this.parseResponse(res, infoLog) as OutData;
}
protected async parseResponse<OutData>(res: Response, log: JsonApiLog): Promise<OutData> {
protected async parseResponse(res: Response, log: JsonApiLog): Promise<Data> {
const { status } = res;
const text = await res.text();
let data: any;
try {
data = text ? json.parse(text) : ""; // DELETE-requests might not have response-body
} catch (e) {
data = text;
}
const parseResponse = json.parse(text || "{}");
const data = parseResponse.callWasSuccessful
? parseResponse.response as Data
: text as Data;
if (status >= 200 && status < 300) {
this.onData.emit(data, res);
@@ -211,7 +208,7 @@ export class JsonApi<Data = JsonApiData, Params extends JsonApiParams<Data> = Js
throw data;
}
const error = new JsonApiErrorParsed(data, this.parseError(data, res));
const error = new JsonApiErrorParsed(data as JsonApiError, this.parseError(data, res));
this.onError.emit(error, res);
this.writeLog({ ...log, error });
@@ -219,16 +216,20 @@ export class JsonApi<Data = JsonApiData, Params extends JsonApiParams<Data> = Js
throw error;
}
protected parseError(error: JsonApiError | string, res: Response): string[] {
if (typeof error === "string") {
protected parseError(error: unknown, res: Response): string[] {
if (isString(error)) {
return [error];
}
if (!isObject(error)) {
return [];
}
if (Array.isArray(error.errors)) {
return error.errors.map(error => error.title);
}
if (error.message) {
if (isString(error.message)) {
return [error.message];
}
@@ -5,7 +5,7 @@
// Parse kube-api path and get api-version, group, etc.
import { splitArray } from "../utils";
import { array } from "@k8slens/utilities";
export interface IKubeApiLinkRef {
apiPrefix?: string;
@@ -26,7 +26,7 @@ export function parseKubeApi(path: string): IKubeApiParsed {
const apiPath = new URL(path, "https://localhost").pathname;
const [, prefix, ...parts] = apiPath.split("/");
const apiPrefix = `/${prefix}`;
const [left, right, namespaced] = splitArray(parts, "namespaces");
const [left, right, namespaced] = array.split(parts, "namespaces");
let apiGroup!: string;
let apiVersion!: string;
let namespace!: string;
+2 -2
View File
@@ -13,8 +13,8 @@ import { KubeObject, KubeStatus, isKubeStatusData } from "./kube-object";
import byline from "byline";
import type { IKubeWatchEvent } from "./kube-watch-event";
import type { KubeJsonApiData, KubeJsonApi } from "./kube-json-api";
import type { Disposer } from "../utils";
import { isDefined, noop, WrappedAbortController } from "../utils";
import type { Disposer } from "@k8slens/utilities";
import { isDefined, noop, WrappedAbortController } from "@k8slens/utilities";
import type { RequestInit, Response } from "@k8slens/node-fetch";
import type { Patch } from "rfc6902";
import assert from "assert";
@@ -4,8 +4,8 @@
*/
import { action, computed, makeObservable, observable, reaction } from "mobx";
import type { Disposer } from "../utils";
import { waitUntilDefined, autoBind, includes, rejectPromiseBy } from "../utils";
import type { Disposer } from "@k8slens/utilities";
import { waitUntilDefined, includes, rejectPromiseBy, object } from "@k8slens/utilities";
import type { KubeJsonApiDataFor, KubeObject } from "./kube-object";
import { KubeStatus } from "./kube-object";
import type { IKubeWatchEvent } from "./kube-watch-event";
@@ -17,9 +17,9 @@ import type { Patch } from "rfc6902";
import type { Logger } from "../logger";
import assert from "assert";
import type { PartialDeep } from "type-fest";
import { entries } from "../utils/objects";
import AbortController from "abort-controller";
import type { ClusterContext } from "../../renderer/cluster-frame-context/cluster-frame-context";
import autoBind from "auto-bind";
export type OnLoadFailure = (error: unknown) => void;
@@ -179,7 +179,7 @@ export abstract class KubeObjectStore<
return this.items.filter((item: K) => {
const itemLabels = item.metadata.labels || {};
return entries(labels)
return object.entries(labels)
.every(([key, value]) => itemLabels[key] === value);
});
}
@@ -7,7 +7,7 @@
import moment from "moment";
import type { KubeJsonApiData, KubeJsonApiDataList, KubeJsonApiListMetadata } from "./kube-json-api";
import { autoBind, formatDuration, hasOptionalTypedProperty, hasTypedProperty, isObject, isString, isNumber, bindPredicate, isTypedArray, isRecord, json } from "../utils";
import { formatDuration, hasOptionalTypedProperty, hasTypedProperty, isObject, isString, isNumber, bindPredicate, isTypedArray, isRecord } from "@k8slens/utilities";
import type { ItemObject } from "../item.store";
import type { Patch } from "rfc6902";
import assert from "assert";
@@ -17,6 +17,7 @@ import { apiKubeInjectionToken } from "./api-kube";
import requestKubeObjectCreationInjectable from "./endpoints/resource-applier.api/request-update.injectable";
import { dump } from "js-yaml";
import { getLegacyGlobalDiForExtensionApi } from "../../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import autoBind from "auto-bind";
export type KubeJsonApiDataFor<K> = K extends KubeObject<infer Metadata, infer Status, infer Spec>
? KubeJsonApiData<Metadata, Status, Spec>
@@ -624,7 +625,7 @@ export class KubeObject<
}
toPlainObject() {
return json.parse(JSON.stringify(this)) as JsonObject;
return JSON.parse(JSON.stringify(this)) as JsonObject;
}
/**
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import windowLocationInjectable from "./window-location.injectable";
export default getGlobalOverride(windowLocationInjectable, () => ({
@@ -7,13 +7,13 @@ import type { KubernetesCluster } from "../catalog-entities";
import yaml from "js-yaml";
import { getLegacyGlobalDiForExtensionApi } from "../../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import productNameInjectable from "../vars/product-name.injectable";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { Logger } from "../logger";
import type { KubectlApplyAll, KubectlDeleteAll } from "../kube-helpers/channels";
import type { ReadDirectory } from "../fs/read-directory.injectable";
import type { JoinPaths } from "../path/join-paths.injectable";
import type { ReadFile } from "../fs/read-file.injectable";
import { hasTypedProperty, isObject } from "../utils";
import { hasTypedProperty, isObject } from "@k8slens/utilities";
export interface ResourceApplyingStack {
kubectlApplyFolder(folderPath: string, templateContext?: any, extraArgs?: string[]): Promise<string>;
@@ -72,7 +72,7 @@ export class ResourceStack {
return "";
}
protected async applyResources(resources: string[], extraArgs: string[] = []): Promise<AsyncResult<string, string>> {
protected async applyResources(resources: string[], extraArgs: string[] = []): AsyncResult<string, string> {
const kubectlArgs = [...extraArgs, ...this.getAdditionalArgs(extraArgs)];
return this.dependencies.kubectlApplyAll({
@@ -82,7 +82,7 @@ export class ResourceStack {
});
}
protected async deleteResources(resources: string[], extraArgs: string[] = []): Promise<AsyncResult<string, string>> {
protected async deleteResources(resources: string[], extraArgs: string[] = []): AsyncResult<string, string> {
const kubectlArgs = [...extraArgs, ...this.getAdditionalArgs(extraArgs)];
return this.dependencies.kubectlDeleteAll({
+1 -1
View File
@@ -7,7 +7,7 @@ import { KubeConfig } from "@kubernetes/client-node";
import yaml from "js-yaml";
import type { Cluster, Context, User } from "@kubernetes/client-node/dist/config_types";
import { newClusters, newContexts, newUsers } from "@kubernetes/client-node/dist/config_types";
import { isDefined } from "./utils";
import { isDefined } from "@k8slens/utilities";
import Joi from "joi";
import type { PartialDeep } from "type-fest";
@@ -7,7 +7,7 @@ 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 "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
export interface KubectlApplyAllArgs {
@@ -2,7 +2,7 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "./test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "@k8slens/test-utils";
import logErrorInjectable from "./log-error.injectable";
// Note: this should remain as it is, and throw if called. Logging error is something
@@ -4,13 +4,12 @@
*/
import loggerInjectable from "./logger.injectable";
import { getGlobalOverride } from "./test-utils/get-global-override";
import { noop } from "./utils";
import { getGlobalOverride } from "@k8slens/test-utils";
export default getGlobalOverride(loggerInjectable, () => ({
warn: noop,
debug: noop,
error: noop,
info: noop,
silly: noop,
warn: () => {},
debug: () => {},
error: () => {},
info: () => {},
silly: () => {},
}));
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import tempDirectoryPathInjectable from "./temp-directory-path.injectable";
export default getGlobalOverride(tempDirectoryPathInjectable, () => "/some-temp-directory");
@@ -4,7 +4,7 @@
*/
import path from "path";
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import getAbsolutePathInjectable from "./get-absolute-path.injectable";
export default getGlobalOverride(getAbsolutePathInjectable, () => path.posix.resolve);
@@ -4,7 +4,7 @@
*/
import path from "path";
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import getBasenameOfPathInjectable from "./get-basename.injectable";
export default getGlobalOverride(getBasenameOfPathInjectable, () => path.posix.basename);
@@ -4,7 +4,7 @@
*/
import path from "path";
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import getDirnameOfPathInjectable from "./get-dirname.injectable";
export default getGlobalOverride(getDirnameOfPathInjectable, () => path.posix.dirname);
@@ -4,7 +4,7 @@
*/
import path from "path";
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import getRelativePathInjectable from "./get-relative-path.injectable";
export default getGlobalOverride(getRelativePathInjectable, () => path.posix.relative);
@@ -4,7 +4,7 @@
*/
import path from "path";
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import joinPathsInjectable from "./join-paths.injectable";
export default getGlobalOverride(joinPathsInjectable, () => path.posix.join);
@@ -4,7 +4,7 @@
*/
import path from "path";
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import parsePathInjectable from "./parse.injectable";
export default getGlobalOverride(parsePathInjectable, () => path.posix.parse);
@@ -4,7 +4,7 @@
*/
import path from "path";
import { getGlobalOverride } from "../test-utils/get-global-override";
import { getGlobalOverride } from "@k8slens/test-utils";
import fileSystemSeparatorInjectable from "./separator.injectable";
export default getGlobalOverride(fileSystemSeparatorInjectable, () => path.posix.sep);
@@ -6,7 +6,7 @@
import type { match } from "react-router";
import { matchPath } from "react-router";
import { countBy } from "lodash";
import { isDefined, iter } from "../utils";
import { isDefined, iter } from "@k8slens/utilities";
import { pathToRegexp } from "path-to-regexp";
import type Url from "url-parse";
import { RoutingError, RoutingErrorType } from "./error";
@@ -1,660 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { AsyncFnMock } from "@async-fn/jest";
import asyncFn from "@async-fn/jest";
import { createContainer, getInjectable, getInjectionToken } from "@ogre-tools/injectable";
import type { Runnable } from "./run-many-for";
import { runManyFor } from "./run-many-for";
import { getPromiseStatus } from "../test-utils/get-promise-status";
import { runInAction } from "mobx";
import { flushPromises } from "../test-utils/flush-promises";
describe("runManyFor", () => {
describe("given no hierarchy, when running many", () => {
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
let actualPromise: Promise<void>;
beforeEach(() => {
const rootDi = createContainer("irrelevant");
runMock = asyncFn();
const someInjectionTokenForRunnables = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const someInjectable = getInjectable({
id: "some-injectable",
instantiate: () => ({
id: "some-injectable",
run: () => runMock("some-call"),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someOtherInjectable = getInjectable({
id: "some-other-injectable",
instantiate: () => ({
id: "some-other-injectable",
run: () => runMock("some-other-call"),
}),
injectionToken: someInjectionTokenForRunnables,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManyFor(rootDi)(someInjectionTokenForRunnables);
actualPromise = runMany() as Promise<void>;
});
it("runs all runnables at the same time", () => {
expect(runMock.mock.calls).toEqual([
["some-call"],
["some-other-call"],
]);
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
it("when all runnables resolve, resolves", async () => {
await Promise.all([runMock.resolve(), runMock.resolve()]);
expect(await actualPromise).toBe(undefined);
});
});
describe("given hierarchy that is three levels deep, when running many", () => {
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
let actualPromise: Promise<void>;
beforeEach(() => {
const di = createContainer("irrelevant");
runMock = asyncFn();
const someInjectionTokenForRunnables = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const someInjectable1 = getInjectable({
id: "some-injectable-1",
instantiate: (di) => ({
id: "some-injectable-1",
run: () => runMock("third-level-run"),
runAfter: di.inject(someInjectable2),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someInjectable2 = getInjectable({
id: "some-injectable-2",
instantiate: (di) => ({
id: "some-injectable-2",
run: () => runMock("second-level-run"),
runAfter: di.inject(someInjectable3),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someInjectable3 = getInjectable({
id: "some-injectable-3",
instantiate: () => ({
id: "some-injectable-3",
run: () => runMock("first-level-run"),
}),
injectionToken: someInjectionTokenForRunnables,
});
di.register(someInjectable1, someInjectable2, someInjectable3);
const runMany = runManyFor(di)(someInjectionTokenForRunnables);
actualPromise = runMany() as Promise<void>;
});
it("runs first level runnables", () => {
expect(runMock.mock.calls).toEqual([["first-level-run"]]);
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
describe("when first level runnables resolve", () => {
beforeEach(async () => {
runMock.mockClear();
await runMock.resolveSpecific(["first-level-run"]);
});
it("runs second level runnables", async () => {
expect(runMock.mock.calls).toEqual([["second-level-run"]]);
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
describe("when second level runnables resolve", () => {
beforeEach(async () => {
runMock.mockClear();
await runMock.resolveSpecific(["second-level-run"]);
});
it("runs final third level runnables", async () => {
expect(runMock.mock.calls).toEqual([["third-level-run"]]);
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
describe("when final third level runnables resolve", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["third-level-run"]);
});
it("resolves", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(true);
});
});
});
});
});
it("given invalid hierarchy, when running runnables, throws", () => {
const rootDi = createContainer("irrelevant");
const runMock = asyncFn<(...args: unknown[]) => void>();
const someInjectionToken = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const someOtherInjectionToken = getInjectionToken<Runnable>({
id: "some-other-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: (di) => ({
id: "some-runnable-1",
run: () => runMock("some-runnable-1"),
runAfter: di.inject(someOtherInjectable),
}),
injectionToken: someInjectionToken,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: () => runMock("some-runnable-2"),
}),
injectionToken: someOtherInjectionToken,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManyFor(rootDi)(
someInjectionToken,
);
return expect(() => runMany()).rejects.toThrow(
/Runnable "some-runnable-1" is unreachable for injection token "some-injection-token": run afters "some-runnable-2" are a part of different injection tokens./,
);
});
it("given partially incorrect hierarchy, when running runnables, throws", () => {
const rootDi = createContainer("irrelevant");
const runMock = asyncFn<(...args: unknown[]) => void>();
const someInjectionToken = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const someOtherInjectionToken = getInjectionToken<Runnable>({
id: "some-other-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: (di) => ({
id: "some-runnable-1",
run: () => runMock("some-runnable-1"),
runAfter: [
di.inject(someOtherInjectable),
di.inject(someSecondInjectable),
],
}),
injectionToken: someInjectionToken,
});
const someSecondInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: () => runMock("some-runnable-2"),
}),
injectionToken: someInjectionToken,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-3",
instantiate: () => ({
id: "some-runnable-3",
run: () => runMock("some-runnable-3"),
}),
injectionToken: someOtherInjectionToken,
});
rootDi.register(someInjectable, someOtherInjectable, someSecondInjectable);
const runMany = runManyFor(rootDi)(
someInjectionToken,
);
return expect(() => runMany()).rejects.toThrow(
/Runnable "some-runnable-3" is not part of the injection token "some-injection-token"/,
);
});
describe("when running many with parameter", () => {
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
beforeEach(() => {
const rootDi = createContainer("irrelevant");
runMock = asyncFn();
const someInjectionTokenForRunnablesWithParameter = getInjectionToken<
Runnable<string>
>({
id: "some-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: () => ({
id: "some-runnable-1",
run: (parameter) => runMock("run-of-some-runnable-1", parameter),
}),
injectionToken: someInjectionTokenForRunnablesWithParameter,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: (parameter) => runMock("run-of-some-runnable-2", parameter),
}),
injectionToken: someInjectionTokenForRunnablesWithParameter,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManyFor(rootDi)(
someInjectionTokenForRunnablesWithParameter,
);
runMany("some-parameter");
});
it("runs all runnables using the parameter", () => {
expect(runMock.mock.calls).toEqual([
["run-of-some-runnable-1", "some-parameter"],
["run-of-some-runnable-2", "some-parameter"],
]);
});
});
describe("given multiple runAfters", () => {
let runMock: AsyncFnMock<(...args: unknown[]) => void>;
let finishingPromise: Promise<void>;
beforeEach(async () => {
const rootDi = createContainer("irrelevant");
runMock = asyncFn<(...args: unknown[]) => void>();
const someInjectionToken = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const runnableOneInjectable = getInjectable({
id: "runnable-1",
instantiate: () => ({
id: "runnable-1",
run: () => runMock("runnable-1"),
}),
injectionToken: someInjectionToken,
});
const runnableTwoInjectable = getInjectable({
id: "runnable-2",
instantiate: () => ({
id: "runnable-2",
run: () => runMock("runnable-2"),
runAfter: [], // shouldn't block being called
}),
injectionToken: someInjectionToken,
});
const runnableThreeInjectable = getInjectable({
id: "runnable-3",
instantiate: (di) => ({
id: "runnable-3",
run: () => runMock("runnable-3"),
runAfter: di.inject(runnableOneInjectable),
}),
injectionToken: someInjectionToken,
});
const runnableFourInjectable = getInjectable({
id: "runnable-4",
instantiate: (di) => ({
id: "runnable-4",
run: () => runMock("runnable-4"),
runAfter: [di.inject(runnableThreeInjectable)], // should be the same as an single item
}),
injectionToken: someInjectionToken,
});
const runnableFiveInjectable = getInjectable({
id: "runnable-5",
instantiate: (di) => ({
id: "runnable-5",
run: () => runMock("runnable-5"),
runAfter: di.inject(runnableThreeInjectable),
}),
injectionToken: someInjectionToken,
});
const runnableSixInjectable = getInjectable({
id: "runnable-6",
instantiate: (di) => ({
id: "runnable-6",
run: () => runMock("runnable-6"),
runAfter: [
di.inject(runnableFourInjectable),
di.inject(runnableFiveInjectable),
],
}),
injectionToken: someInjectionToken,
});
const runnableSevenInjectable = getInjectable({
id: "runnable-7",
instantiate: (di) => ({
id: "runnable-7",
run: () => runMock("runnable-7"),
runAfter: [
di.inject(runnableFiveInjectable),
di.inject(runnableSixInjectable),
],
}),
injectionToken: someInjectionToken,
});
runInAction(() => {
rootDi.register(
runnableOneInjectable,
runnableTwoInjectable,
runnableThreeInjectable,
runnableFourInjectable,
runnableFiveInjectable,
runnableSixInjectable,
runnableSevenInjectable,
);
});
const runMany = runManyFor(rootDi);
const runSome = runMany(someInjectionToken);
finishingPromise = runSome();
await flushPromises();
});
it("should run 'runnable-1'", () => {
expect(runMock).toBeCalledWith("runnable-1");
});
it("should run 'runnable-2'", () => {
expect(runMock).toBeCalledWith("runnable-2");
});
it("should not run 'runnable-3'", () => {
expect(runMock).not.toBeCalledWith("runnable-3");
});
describe("when 'runnable-1' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-1"]);
});
it("should run 'runnable-3'", () => {
expect(runMock).toBeCalledWith("runnable-3");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(3);
});
});
describe("when 'runnable-3' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-3"]);
});
it("should run 'runnable-4'", () => {
expect(runMock).toBeCalledWith("runnable-4");
});
it("should run 'runnable-5'", () => {
expect(runMock).toBeCalledWith("runnable-5");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
});
describe("when 'runnable-4' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-4"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
});
describe("when 'runnable-5' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-5"]);
});
it("should run 'runnable-6'", () => {
expect(runMock).toBeCalledWith("runnable-6");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(6);
});
});
describe("when 'runnable-6' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-6"]);
});
it("should run 'runnable-7'", () => {
expect(runMock).toBeCalledWith("runnable-7");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(7);
});
describe("when 'runnable-7' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-7"]);
});
it("should resolve the runMany promise call", async () => {
await finishingPromise;
});
});
});
});
});
});
describe("when 'runnable-5' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-5"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
});
describe("when 'runnable-4' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-4"]);
});
it("should run 'runnable-6'", () => {
expect(runMock).toBeCalledWith("runnable-6");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(6);
});
});
describe("when 'runnable-6' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-6"]);
});
it("should run 'runnable-7'", () => {
expect(runMock).toBeCalledWith("runnable-7");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(7);
});
describe("when 'runnable-7' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-7"]);
});
it("should resolve the runMany promise call", async () => {
await finishingPromise;
});
});
});
});
});
});
});
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(2);
});
});
});
});
@@ -1,140 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { DiContainerForInjection, InjectionToken } from "@ogre-tools/injectable";
import type { SingleOrMany } from "../utils";
import { getOrInsert, getOrInsertSetFor, isDefined } from "../utils";
import * as uuid from "uuid";
import assert from "assert";
import type { Asyncify } from "type-fest";
import type TypedEventEmitter from "typed-emitter";
import EventEmitter from "events";
export interface Runnable<TParameter = void> {
id: string;
run: Run<TParameter>;
runAfter?: SingleOrMany<Runnable<TParameter>>;
}
type Run<Param> = (parameter: Param) => Promise<void> | void;
export type RunMany = <Param>(injectionToken: InjectionToken<Runnable<Param>, void>) => Asyncify<Run<Param>>;
const computedNextEdge = (traversed: string[], graph: Map<string, Set<string>>, currentId: string, seenIds: Set<string>) => {
seenIds.add(currentId);
const currentNode = graph.get(currentId);
assert(currentNode, `Runnable graph does not contain node with id="${currentId}"`);
for (const nextId of currentNode.values()) {
if (traversed.includes(nextId)) {
throw new Error(`Cycle in runnable graph: "${traversed.join(`" -> "`)}" -> "${nextId}"`);
}
computedNextEdge([...traversed, nextId], graph, nextId, seenIds);
}
};
const verifyRunnablesAreDAG = <Param>(injectionToken: InjectionToken<Runnable<Param>, void>, runnables: Runnable<Param>[]) => {
const rootId = uuid.v4();
const runnableGraph = new Map<string, Set<string>>();
const seenIds = new Set<string>();
const addRunnableId = getOrInsertSetFor(runnableGraph);
// Build the Directed graph
for (const runnable of runnables) {
addRunnableId(runnable.id);
if (!runnable.runAfter || (Array.isArray(runnable.runAfter) && runnable.runAfter.length === 0)) {
addRunnableId(rootId).add(runnable.id);
} else if (Array.isArray(runnable.runAfter)) {
for (const parentRunnable of runnable.runAfter) {
addRunnableId(parentRunnable.id).add(runnable.id);
}
} else {
addRunnableId(runnable.runAfter.id).add(runnable.id);
}
}
addRunnableId(rootId);
// Do a DFS to find any cycles
computedNextEdge([], runnableGraph, rootId, seenIds);
for (const id of runnableGraph.keys()) {
if (!seenIds.has(id)) {
const runnable = runnables.find(runnable => runnable.id === id);
if (!runnable) {
throw new Error(`Runnable "${id}" is not part of the injection token "${injectionToken.id}"`);
}
const runAfters = [runnable.runAfter]
.flat()
.filter(isDefined)
.map(runnable => runnable.id)
.join('", "');
throw new Error(`Runnable "${id}" is unreachable for injection token "${injectionToken.id}": run afters "${runAfters}" are a part of different injection tokens.`);
}
}
};
interface BarrierEvent {
finish: (id: string) => void;
}
class DynamicBarrier {
private readonly finishedIds = new Map<string, Promise<void>>();
private readonly events: TypedEventEmitter<BarrierEvent> = new EventEmitter();
private initFinishingPromise(id: string): Promise<void> {
return getOrInsert(this.finishedIds, id, new Promise(resolve => {
const handler = (finishedId: string) => {
if (finishedId === id) {
resolve();
this.events.removeListener("finish", handler);
}
};
this.events.addListener("finish", handler);
}));
}
setFinished(id: string): void {
void this.initFinishingPromise(id);
this.events.emit("finish", id);
}
async blockOn(id: string): Promise<void> {
await this.initFinishingPromise(id);
}
}
const executeRunnableWith = <Param>(param: Param) => {
const barrier = new DynamicBarrier();
return async (runnable: Runnable<Param>): Promise<void> => {
const parentRunnables = [runnable.runAfter].flat().filter(isDefined);
for (const parentRunnable of parentRunnables) {
await barrier.blockOn(parentRunnable.id);
}
await runnable.run(param);
barrier.setFinished(runnable.id);
};
};
export function runManyFor(di: DiContainerForInjection): RunMany {
return <Param>(injectionToken: InjectionToken<Runnable<Param>, void>) => async (param: Param) => {
const executeRunnable = executeRunnableWith(param);
const allRunnables = di.injectMany(injectionToken);
verifyRunnablesAreDAG(injectionToken, allRunnables);
await Promise.all(allRunnables.map(executeRunnable));
};
}
@@ -1,212 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { createContainer, getInjectable, getInjectionToken } from "@ogre-tools/injectable";
import type { RunnableSync } from "./run-many-sync-for";
import { runManySyncFor } from "./run-many-sync-for";
describe("runManySyncFor", () => {
describe("given hierarchy, when running many", () => {
let runMock: jest.Mock;
beforeEach(() => {
const rootDi = createContainer("irrelevant");
runMock = jest.fn();
const someInjectionTokenForRunnables = getInjectionToken<RunnableSync>({
id: "some-injection-token",
});
const someInjectable = getInjectable({
id: "some-injectable",
instantiate: () => ({
id: "some-injectable",
run: () => runMock("some-call"),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someOtherInjectable = getInjectable({
id: "some-other-injectable",
instantiate: () => ({
id: "some-other-injectable",
run: () => runMock("some-other-call"),
}),
injectionToken: someInjectionTokenForRunnables,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManySyncFor(rootDi)(someInjectionTokenForRunnables);
runMany();
});
it("runs all runnables at the same time", () => {
expect(runMock.mock.calls).toEqual([
["some-call"],
["some-other-call"],
]);
});
});
describe("given hierarchy that is three levels deep, when running many", () => {
let runMock: jest.Mock<(arg: string) => void>;
beforeEach(() => {
const di = createContainer("irrelevant");
runMock = jest.fn();
const someInjectionTokenForRunnables = getInjectionToken<RunnableSync>({
id: "some-injection-token",
});
const someInjectable1 = getInjectable({
id: "some-injectable-1",
instantiate: (di) => ({
id: "some-injectable-1",
run: () => void runMock("third-level-run"),
runAfter: di.inject(someInjectable2),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someInjectable2 = getInjectable({
id: "some-injectable-2",
instantiate: (di) => ({
id: "some-injectable-2",
run: () => void runMock("second-level-run"),
runAfter: di.inject(someInjectable3),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someInjectable3 = getInjectable({
id: "some-injectable-3",
instantiate: () => ({
id: "some-injectable-3",
run: () => void runMock("first-level-run"),
}),
injectionToken: someInjectionTokenForRunnables,
});
di.register(someInjectable1, someInjectable2, someInjectable3);
const runMany = runManySyncFor(di)(someInjectionTokenForRunnables);
runMany();
});
it("runs runnables in order", () => {
expect(runMock.mock.calls).toEqual([["first-level-run"], ["second-level-run"], ["third-level-run"]]);
});
});
it("given invalid hierarchy, when running runnables, throws", () => {
const rootDi = createContainer("irrelevant");
const runMock = jest.fn();
const someInjectionToken = getInjectionToken<RunnableSync>({
id: "some-injection-token",
});
const someOtherInjectionToken = getInjectionToken<RunnableSync>({
id: "some-other-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: (di) => ({
id: "some-runnable-1",
run: () => runMock("some-runnable-1"),
runAfter: di.inject(someOtherInjectable),
}),
injectionToken: someInjectionToken,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: () => runMock("some-runnable-2"),
}),
injectionToken: someOtherInjectionToken,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManySyncFor(rootDi)(
someInjectionToken,
);
return expect(() => runMany()).toThrow(
/Tried to get a composite but encountered missing parent ids: "some-runnable-2".\n\nAvailable parent ids are:\n"[0-9a-z-]+",\n"some-runnable-1"/,
);
});
describe("when running many with parameter", () => {
let runMock: jest.Mock<(arg: string, arg2: string) => undefined>;
beforeEach(() => {
const rootDi = createContainer("irrelevant");
runMock = jest.fn();
const someInjectionTokenForRunnablesWithParameter = getInjectionToken<
RunnableSync<string>
>({
id: "some-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: () => ({
id: "some-runnable-1",
run: (parameter) => void runMock("run-of-some-runnable-1", parameter),
}),
injectionToken: someInjectionTokenForRunnablesWithParameter,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: (parameter) => void runMock("run-of-some-runnable-2", parameter),
}),
injectionToken: someInjectionTokenForRunnablesWithParameter,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManySyncFor(rootDi)(
someInjectionTokenForRunnablesWithParameter,
);
runMany("some-parameter");
});
it("runs all runnables using the parameter", () => {
expect(runMock.mock.calls).toEqual([
["run-of-some-runnable-1", "some-parameter"],
["run-of-some-runnable-2", "some-parameter"],
]);
});
});
});
@@ -1,55 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { DiContainerForInjection, InjectionToken } from "@ogre-tools/injectable";
import type { Composite } from "../utils/composite/get-composite/get-composite";
import { getCompositeFor } from "../utils/composite/get-composite/get-composite";
import * as uuid from "uuid";
export interface RunnableSync<TParameter = void> {
id: string;
run: RunSync<TParameter>;
runAfter?: RunnableSync<TParameter>;
}
/**
* NOTE: this is the worse of two evils. This makes sure that `RunnableSync` always is sync.
* If the return type is `void` instead then async functions (those return `Promise<T>`) can
* coerce to it.
*/
type RunSync<Param> = (parameter: Param) => undefined;
export type RunManySync = <Param>(injectionToken: InjectionToken<RunnableSync<Param>, void>) => RunSync<Param>;
function runCompositeRunnableSyncs<Param>(param: Param, composite: Composite<RunnableSync<Param>>): undefined {
composite.value.run(param);
composite.children.map(composite => runCompositeRunnableSyncs(param, composite));
return undefined;
}
export function runManySyncFor(di: DiContainerForInjection): RunManySync {
return <Param>(injectionToken: InjectionToken<RunnableSync<Param>, void>) => (param: Param): undefined => {
const allRunnables = di.injectMany(injectionToken);
const rootId = uuid.v4();
const getCompositeRunnables = getCompositeFor<RunnableSync<Param>>({
getId: (runnable) => runnable.id,
getParentId: (runnable) => (
runnable.id === rootId
? undefined
: runnable.runAfter?.id ?? rootId
),
});
const composite = getCompositeRunnables([
// This is a dummy runnable to conform to the requirements of `getCompositeFor` to only have one root
{
id: rootId,
run: () => undefined,
},
...allRunnables,
]);
return runCompositeRunnableSyncs(param, composite);
};
}
@@ -1,7 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { setImmediate } from "timers";
export const flushPromises = () => new Promise(setImmediate);
@@ -1,25 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { Injectable } from "@ogre-tools/injectable";
import { getGlobalOverride } from "./get-global-override";
import { camelCase } from "lodash/fp";
export const getGlobalOverrideForFunction = (
injectable: Injectable<Function, any, any>,
) =>
getGlobalOverride(injectable, () => (...args: any[]) => {
console.warn(
`Tried to invoke a function "${injectable.id}" without override. The args were:`,
args,
);
throw new Error(
`Tried to invoke a function "${
injectable.id
}" without override. Add eg. "di.override(${camelCase(
injectable.id,
)}Mock)" to the unit test interested in this.`,
);
});
@@ -1,18 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { Injectable } from "@ogre-tools/injectable";
export interface GlobalOverride {
injectable: Injectable<any, any, any>;
overridingInstantiate: any;
}
export const getGlobalOverride = <T extends Injectable<any, any, any>>(
injectable: T,
overridingInstantiate: T["instantiate"],
) => ({
injectable,
overridingInstantiate,
});
Loaded 100 of 754 files, more files were not shown because too many files have changed in this diff. Show more