nope/lib/dispatcher/RpcManager/selectors.ts
2022-01-04 12:42:44 +01:00

94 lines
2.5 KiB
TypeScript

/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2022-01-03 13:46:51
* @modify date 2022-01-03 13:46:51
* @desc [description]
*/
import { maxOfArray, minOfArray } from "../helpers/arrayMethods";
import {
INopeDispatcher,
ValidDefaultSelectors,
ValidSelectorFunction
} from "../types/nope";
/**
* A Helper Function, to generate the Basic selector Functions.
*
* @author M.Karkowski
* @export
* @param {ValidDefaultSelectors} selector
* @param {INopeDispatcher} dispatcher
* @return {*}
*/
export function generateSelector(
selector: ValidDefaultSelectors,
dispatcher: INopeDispatcher
): ValidSelectorFunction {
switch (selector) {
default:
case "first":
return async () => {
const data = dispatcher.externalDispatchers.getContent();
if (data.length) {
return data[0].id;
}
throw Error("No matching dispatcher present.");
};
case "dispatcher":
// Our selector compares the dispatcher - id
return async () => {
const ids = dispatcher.externalDispatchers
.getContent()
.map((item) => item.id);
if (ids.includes(dispatcher.id)) {
return dispatcher.id;
}
throw Error("No matching dispatcher present.");
};
case "host":
// Our selector compares the host-name:
// 1. Get the current Host name of our dispatcher
const host = dispatcher.info.host.name;
return async () => {
const dispatchers = dispatcher.externalDispatchers.getContent();
for (const item of dispatchers) {
if (host == item.host.name) {
return item.id;
}
}
throw Error("No matching dispatcher present.");
};
case "cpu-usage":
return async () => {
// Now we find the Min CPU usage:
const dispatchers = dispatcher.externalDispatchers.getContent();
const bestOption = minOfArray(dispatchers, "host.cpu.usage");
if (bestOption.index >= 0) {
return dispatchers[bestOption.index].id;
}
throw Error("No matching dispatcher present.");
};
case "free-ram":
return async () => {
// Now we find the Min CPU usage:
const dispatchers = dispatcher.externalDispatchers.getContent();
const bestOption = maxOfArray(dispatchers, "host.ram.free");
if (bestOption.index >= 0) {
return dispatchers[bestOption.index].id;
}
throw Error("No matching dispatcher present.");
};
}
}