Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate multiply plugin to builtins #709

Merged
merged 17 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions src/__tests__/unit/builtins/multiply.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import {Multiply} from '../../../builtins/multiply';

import {ERRORS} from '../../../util/errors';

const {InputValidationError} = ERRORS;

describe('lib/multiply: ', () => {
describe('Multiply: ', () => {
const globalConfig = {
'input-parameters': ['cpu/energy', 'network/energy', 'memory/energy'],
'output-parameter': 'energy',
};
const multiply = Multiply(globalConfig);

describe('init: ', () => {
it('successfully initalized.', () => {
expect(multiply).toHaveProperty('metadata');
expect(multiply).toHaveProperty('execute');
});
});

describe('execute(): ', () => {
it('successfully applies Multiply strategy to given input.', async () => {
expect.assertions(1);

const expectedResult = [
{
duration: 3600,
'cpu/energy': 2,
'network/energy': 2,
'memory/energy': 2,
energy: 8,
timestamp: '2021-01-01T00:00:00Z',
},
];

const result = await multiply.execute([
{
duration: 3600,
'cpu/energy': 2,
'network/energy': 2,
'memory/energy': 2,
timestamp: '2021-01-01T00:00:00Z',
},
]);

expect(result).toStrictEqual(expectedResult);
});

it('throws an error on missing params in input.', async () => {
const expectedMessage =
'Multiply: cpu/energy is missing from the input array.';

expect.assertions(1);

try {
await multiply.execute([
{
duration: 3600,
timestamp: '2021-01-01T00:00:00Z',
},
]);
} catch (error) {
expect(error).toStrictEqual(
new InputValidationError(expectedMessage)
);
}
});

it('returns a result with input params not related to energy.', async () => {
expect.assertions(1);
const newConfig = {
'input-parameters': ['carbon', 'other-carbon'],
'output-parameter': 'carbon-product',
};
const multiply = Multiply(newConfig);

const data = [
{
duration: 3600,
timestamp: '2021-01-01T00:00:00Z',
carbon: 3,
'other-carbon': 2,
},
];
const response = await multiply.execute(data);

const expectedResult = [
{
duration: 3600,
carbon: 3,
'other-carbon': 2,
'carbon-product': 6,
timestamp: '2021-01-01T00:00:00Z',
},
];

expect(response).toEqual(expectedResult);
});
});
});
});
1 change: 1 addition & 0 deletions src/builtins/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export {GroupBy} from './group-by';
export {TimeSync} from './time-sync';
export {Multiply} from './multiply';
95 changes: 95 additions & 0 deletions src/builtins/multiply/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Multiply

`multiply` is a generic plugin for multiplying two or more values in an `input` array.

You provide the names of the values you want to multiply, and a name to use to append the product to the output array.

For example, you could multiply `cpu/energy` and `network/energy` and name the result `energy-product`. `energy-product` would then be added to every observation in your input array as the product of `cpu/energy` and `network/energy`.

## Parameters

### Plugin config

Two parameters are required in global config: `input-parameters` and `output-parameter`.

`input-parameters`: an array of strings. Each string should match an existing key in the `inputs` array
`output-parameter`: a string defining the name to use to add the product of the input parameters to the output array.

### Inputs

All of `input-parameters` must be available in the input array.

## Returns

- `output-parameter`: the product of all `input-parameters` with the parameter name defined by `output-parameter` in global config.

## Calculation

```pseudocode
output = input0 * input1 * input2 ... inputN
```

## Implementation

To run the plugin, you must first create an instance of `Multiply`. Then, you can call `execute()`.

```typescript
import {Multiply} from 'builtins';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this part for builtin plugins?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think so... ?


const config = {
inputParameters: ['cpu/energy', 'network/energy'],
outputParameter: 'energy-product',
};

const mult = Multiply(config);
const result = await mult.execute([
{
duration: 3600,
timestamp: '2021-01-01T00:00:00Z',
'cpu/energy': 0.001,
'memory/energy': 0.0005,
},
]);
```

## Example manifest

IF users will typically call the plugin as part of a pipeline defined in a manifest file. In this case, instantiating the plugin is handled by `ie` and does not have to be done explicitly by the user. The following is an example manifest that calls `multiply`:

```yaml
name: multiply-demo
description:
tags:
initialize:
outputs:
- yaml
plugins:
multiply:
method: Multiply
path: 'builtins'
jmcook1186 marked this conversation as resolved.
Show resolved Hide resolved
global-config:
input-parameters: ['cpu/energy', 'network/energy']
output-parameter: 'energy-product'
tree:
children:
child:
pipeline:
- multiply
config:
multiply:
inputs:
- timestamp: 2023-08-06T00:00
duration: 3600
cpu/energy: 0.001
network/energy: 0.001
```

You can run this example by saving it as `./examples/manifests/test/multiply.yml` and executing the following command from the project root:

```sh
npm i -g @grnsft/if
npm i -g @grnsft/if-plugins
jmcook1186 marked this conversation as resolved.
Show resolved Hide resolved
ie --manifest ./examples/manifests/test/multiply.yml --output ./examples/outputs/multiply.yml
```

The results will be saved to a new `yaml` file in `./examples/outputs`
87 changes: 87 additions & 0 deletions src/builtins/multiply/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import {z} from 'zod';

import {buildErrorMessage} from '../../util/helpers';
import {ERRORS} from '../../util/errors';
import {validate} from '../../util/validations';

import {ExecutePlugin, PluginParams} from '../../types/interface';
import {MultiplyConfig} from './types';

const {InputValidationError} = ERRORS;

export const Multiply = (globalConfig: MultiplyConfig): ExecutePlugin => {
const errorBuilder = buildErrorMessage(Multiply.name);
const metadata = {
kind: 'execute',
};

/**
* Checks global config value are valid.
*/
const validateGlobalConfig = () => {
const globalConfigSchema = z.object({
'input-parameters': z.array(z.string()),
'output-parameter': z.string().min(1),
});

return validate<z.infer<typeof globalConfigSchema>>(
globalConfigSchema,
globalConfig
);
};

/**
* Checks for required fields in input.
*/
const validateSingleInput = (
input: PluginParams,
inputParameters: string[]
) => {
inputParameters.forEach(metricToMultiply => {
if (
input[metricToMultiply] === undefined ||
isNaN(input[metricToMultiply])
) {
throw new InputValidationError(
errorBuilder({
message: `${metricToMultiply} is missing from the input array`,
})
);
}
});

return input;
};

/**
* Calculate the product of each input parameter.
*/
const execute = (inputs: PluginParams[]): PluginParams[] => {
const safeGlobalConfig = validateGlobalConfig();
const inputParameters = safeGlobalConfig['input-parameters'];
const outputParameter = safeGlobalConfig['output-parameter'];

return inputs.map(input => {
const safeInput = validateSingleInput(input, inputParameters);

return {
...input,
[outputParameter]: calculateProduct(safeInput, inputParameters),
};
});
};

/**
* Calculates the product of the energy components.
*/
const calculateProduct = (input: PluginParams, inputParameters: string[]) =>
inputParameters.reduce(
(accumulator, metricToMultiply) => accumulator * input[metricToMultiply],
1
);

return {
metadata,
execute,
};
};
4 changes: 4 additions & 0 deletions src/builtins/multiply/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type MultiplyConfig = {
'input-parameters': string[];
'output-parameter': string;
};
4 changes: 4 additions & 0 deletions src/types/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type ErrorFormatParams = {
scope?: string;
message: string;
};
12 changes: 11 additions & 1 deletion src/util/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,21 @@ import {promisify} from 'node:util';

import {ERRORS} from './errors';
import {logger} from './logger';

import {ErrorFormatParams} from '../types/helpers';
import {STRINGS} from '../config';

const {ISSUE_TEMPLATE} = STRINGS;

/**
* Formats given error according to class instance, scope and message.
*/
export const buildErrorMessage =
(classInstanceName: string) => (params: ErrorFormatParams) => {
const {scope, message} = params;

return `${classInstanceName}${scope ? `(${scope})` : ''}: ${message}.`;
};

/**
* Impact engine error handler. Logs errors and appends issue template if error is unknown.
*/
Expand Down