All files / builtins/sci-embodied index.ts

100% Statements 29/29
100% Branches 4/4
100% Functions 6/6
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 1324x     4x   4x   4x   4x 1x       1x                       1x 8x 11x   7x                     1x 7x 7x 7x   7x 7x   7x                   1x 22x                                       11x                             11x                             11x       11x         11x       11x     1x          
import {z} from 'zod';
import {ExecutePlugin, PluginParams} from '@grnsft/if-core/types';
 
import {validate, allDefined} from '../../util/validations';
 
import {STRINGS} from '../../config';
 
const {SCI_EMBODIED_ERROR} = STRINGS;
 
export const SciEmbodied = (): ExecutePlugin => {
  const metadata = {
    kind: 'execute',
  };
 
  const METRICS = [
    'device/emissions-embodied',
    'device/expected-lifespan',
    'resources-reserved',
    'vcpus-allocated',
    'resources-total',
    'vcpus-total',
  ];
 
  /**
   * Calculate the Embodied carbon for a list of inputs.
   */
  const execute = (inputs: PluginParams[]) => {
    return inputs.map(input => {
      const safeInput = validateInput(input);
 
      return {
        ...input,
        'carbon-embodied': calculateEmbodiedCarbon(safeInput),
      };
    });
  };
 
  /**
   * Calculate the Embodied carbon for the input.
   * M = totalEmissions * (duration/ExpectedLifespan) * (resourcesReserved/totalResources)
   */
  const calculateEmbodiedCarbon = (input: PluginParams) => {
    const totalEmissions = input['device/emissions-embodied'];
    const duration = input['duration'];
    const expectedLifespan = input['device/expected-lifespan'];
    const resourcesReserved =
      input['vcpus-allocated'] || input['resources-reserved'];
    const totalResources = input['vcpus-total'] || input['resources-total'];
 
    return (
      totalEmissions *
      (duration / expectedLifespan) *
      (resourcesReserved / totalResources)
    );
  };
 
  /**
   * Checks for required fields in input.
   */
  const validateInput = (input: PluginParams) => {
    const commonSchemaPart = (errorMessage: (unit: string) => string) => ({
      'device/emissions-embodied': z
        .number({
          invalid_type_error: errorMessage('gCO2e'),
        })
        .gte(0)
        .min(0),
      'device/expected-lifespan': z
        .number({
          invalid_type_error: errorMessage('gCO2e'),
        })
        .gte(0)
        .min(0),
      duration: z
        .number({
          invalid_type_error: errorMessage('seconds'),
        })
        .gte(1),
    });
 
    const vcpusSchemaPart = {
      'vcpus-allocated': z
        .number({
          invalid_type_error: SCI_EMBODIED_ERROR('count'),
        })
        .gte(0)
        .min(0),
      'vcpus-total': z
        .number({
          invalid_type_error: SCI_EMBODIED_ERROR('count'),
        })
        .gte(0)
        .min(0),
    };
 
    const resourcesSchemaPart = {
      'resources-reserved': z
        .number({
          invalid_type_error: SCI_EMBODIED_ERROR('count'),
        })
        .gte(0)
        .min(0),
      'resources-total': z
        .number({
          invalid_type_error: SCI_EMBODIED_ERROR('count'),
        })
        .gte(0)
        .min(0),
    };
 
    const schemaWithVcpus = z.object({
      ...commonSchemaPart(SCI_EMBODIED_ERROR),
      ...vcpusSchemaPart,
    });
    const schemaWithResources = z.object({
      ...commonSchemaPart(SCI_EMBODIED_ERROR),
      ...resourcesSchemaPart,
    });
 
    const schema = schemaWithVcpus.or(schemaWithResources).refine(allDefined, {
      message: `All ${METRICS} should be present.`,
    });
 
    return validate<z.infer<typeof schema>>(schema, input);
  };
 
  return {
    metadata,
    execute,
  };
};