1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/src/main/cluster-detectors/detect-cluster-metadata.injectable.ts
Sebastian Malton 8e65a0acd6
Improve the injectability of cluster metadata detection (#6910)
* Improve the injectability of cluster metadata detection

- Remove unnecessary and complex base class

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

* Remove dead code

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

* Remove dead code

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

Signed-off-by: Sebastian Malton <sebastian@malton.name>
2023-01-19 16:34:31 +02:00

52 lines
1.8 KiB
TypeScript

/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { pipeline } from "@ogre-tools/fp";
import { getInjectable } from "@ogre-tools/injectable";
import { groupBy, reduce } from "lodash";
import { filter, map } from "lodash/fp";
import type { ClusterMetadata } from "../../common/cluster-types";
import type { Cluster } from "../../common/cluster/cluster";
import { hasDefinedTupleValue, isDefined, object } from "../../common/utils";
import type { ClusterDetectionResult, ClusterMetadataDetector } from "./token";
import { clusterMetadataDetectorInjectionToken } from "./token";
export type DetectClusterMetadata = (cluster: Cluster) => Promise<ClusterMetadata>;
const pickHighestAccuracy = (prev: ClusterDetectionResult, curr: ClusterDetectionResult) => (
prev.accuracy > curr.accuracy
? prev
: curr
);
const detectMetadataWithFor = (cluster: Cluster) => async (clusterMetadataDetector: ClusterMetadataDetector) => {
try {
return await clusterMetadataDetector.detect(cluster);
} catch {
return null;
}
};
const detectClusterMetadataInjectable = getInjectable({
id: "detect-cluster-metadata",
instantiate: (di): DetectClusterMetadata => {
const clusterMetadataDetectors = di.injectMany(clusterMetadataDetectorInjectionToken);
return async (cluster) => {
const entries = pipeline(
await Promise.all(clusterMetadataDetectors.map(detectMetadataWithFor(cluster))),
filter(isDefined),
(arg) => groupBy(arg, "key"),
(arg) => object.entries(arg),
map(([ key, results ]) => [key, reduce(results, pickHighestAccuracy)] as const),
filter(hasDefinedTupleValue),
);
return object.fromEntries(entries);
};
},
});
export default detectClusterMetadataInjectable;