All files / if-run/builtins time-sync.ts

100% Statements 155/155
100% Branches 42/42
100% Functions 25/25
100% Lines 153/153

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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 4604x   4x 4x 4x                 4x   4x   4x   4x             4x                   4x   4x 22x             22x 21x 15x             15x 14x   12x   12x   54x 52x     52x 41x 41x     41x         2x     39x       39x         39x 3x                   50x 209x   209x     50x         8x 100x     8x     22x 2806x 16x           2790x 3x     2787x 2786x     1x           22x 54x                       54x           22x 21x 1x     20x             20x       20x           22x 14x         22x       209x   209x           22x 209x   209x 635x   635x 209x 209x   209x       426x 209x   209x     217x         217x             22x       142x   142x 430x 142x   142x       288x 142x   142x     146x 4x   4x     142x   142x 127x   127x     15x   15x             22x 14x 14x   14x 2x             22x       15x       14x   14x         14x                   22x 108x 108x   108x 334x 334x   334x 108x   108x     226x 122x   122x     104x 30x   30x             74x       14x   14x     60x     108x           22x 8x 108x 108x 108x   108x     108x 36x     108x           22x         12x 12x   12x 1x                 12x   12x 8x 8x     8x                 12x     22x         12x 12x   12x 142x                     12x           22x       50x 1135x   1135x       1058x     1135x     22x    
import {isDate} from 'node:util/types';
 
import {Settings, DateTime, DateTimeMaybeValid, Interval} from 'luxon';
import {z} from 'zod';
import {ERRORS} from '@grnsft/if-core/utils';
import {
  ExecutePlugin,
  PluginParams,
  PaddingReceipt,
  TimeNormalizerConfig,
  TimeParams,
} from '@grnsft/if-core/types';
 
import {parameterize} from '../lib/parameterize';
 
import {validate} from '../../common/util/validations';
 
import {STRINGS} from '../config';
 
Settings.defaultZone = 'utc';
 
const {
  GlobalConfigError,
  InvalidDateInInputError,
  InvalidPaddingError,
  InvalidInputError,
} = ERRORS;
 
const {
  INVALID_TIME_NORMALIZATION,
  INVALID_OBSERVATION_OVERLAP,
  AVOIDING_PADDING_BY_EDGES,
  INVALID_DATE_TYPE,
  START_LOWER_END,
  TIMESTAMP_REQUIRED,
  INVALID_DATETIME,
} = STRINGS;
 
export const TimeSync = (globalConfig: TimeNormalizerConfig): ExecutePlugin => {
  const metadata = {
    kind: 'execute',
  };
 
  /**
   * Take input array and return time-synchronized input array.
   */
  const execute = (inputs: PluginParams[]): PluginParams[] => {
    const validatedConfig = validateGlobalConfig();
    const timeParams = {
      startTime: DateTime.fromISO(validatedConfig['start-time']),
      endTime: DateTime.fromISO(validatedConfig['end-time']),
      interval: validatedConfig.interval,
      allowPadding: validatedConfig['allow-padding'],
    };
 
    const pad = checkForPadding(inputs, timeParams);
    validatePadding(pad, timeParams);
 
    const paddedInputs = padInputs(inputs, pad, timeParams);
 
    const flattenInputs = paddedInputs.reduce(
      (acc: PluginParams[], input, index) => {
        const safeInput = Object.assign({}, input, validateInput(input, index));
        const currentMoment = parseDate(safeInput.timestamp);
 
        /** Checks if not the first input, then check consistency with previous ones. */
        if (index > 0) {
          const previousInput = paddedInputs[index - 1];
          const previousInputTimestamp = parseDate(previousInput.timestamp);
 
          /** Checks for timestamps overlap. */
          if (
            parseDate(previousInput.timestamp).plus({
              seconds: previousInput.duration,
            }) > currentMoment
          ) {
            throw new InvalidInputError(INVALID_OBSERVATION_OVERLAP);
          }
 
          const compareableTime = previousInputTimestamp.plus({
            seconds: previousInput.duration,
          });
 
          const timelineGapSize = currentMoment
            .diff(compareableTime)
            .as('seconds');
 
          /** Checks if there is gap in timeline. */
          if (timelineGapSize > 1) {
            acc.push(
              ...getZeroishInputPerSecondBetweenRange(
                compareableTime,
                currentMoment,
                safeInput
              )
            );
          }
        }
        /** Break down current observation. */
        for (let i = 0; i < safeInput.duration; i++) {
          const normalizedInput = breakDownInput(safeInput, i);
 
          acc.push(normalizedInput);
        }
 
        return trimInputsByGlobalTimeline(acc, timeParams);
      },
      [] as PluginParams[]
    );
 
    const sortedInputs = flattenInputs.sort((a, b) =>
      parseDate(a.timestamp).diff(parseDate(b.timestamp)).as('seconds')
    );
 
    return resampleInputs(sortedInputs, timeParams) as PluginParams[];
  };
 
  const parseDate = (date: Date | string) => {
    if (!date) {
      return DateTime.invalid('Invalid date');
    }
 
    // dates are passed to time-sync.ts both in ISO 8601 format
    // and as a Date object (from the deserialization of a YAML file)
    // if the YAML parser fails to identify as a date, it passes as a string
    if (isDate(date)) {
      return DateTime.fromJSDate(date);
    }
 
    if (typeof date === 'string') {
      return DateTime.fromISO(date);
    }
 
    throw new InvalidDateInInputError(INVALID_DATE_TYPE(date));
  };
 
  /**
   * Validates input parameters.
   */
  const validateInput = (input: PluginParams, index: number) => {
    const schema = z.object({
      timestamp: z
        .string({
          required_error: TIMESTAMP_REQUIRED(index),
        })
        .datetime({
          message: INVALID_DATETIME(index),
        })
        .or(z.date()),
      duration: z.number(),
    });
 
    return validate<z.infer<typeof schema>>(schema, input);
  };
 
  /**
   * Validates global config parameters.
   */
  const validateGlobalConfig = () => {
    if (globalConfig === undefined) {
      throw new GlobalConfigError(INVALID_TIME_NORMALIZATION);
    }
 
    const schema = z
      .object({
        'start-time': z.string().datetime(),
        'end-time': z.string().datetime(),
        interval: z.number(),
        'allow-padding': z.boolean(),
      })
      .refine(data => data['start-time'] < data['end-time'], {
        message: START_LOWER_END,
      });
 
    return validate<z.infer<typeof schema>>(schema, globalConfig);
  };
 
  /**
   * Calculates minimal factor.
   */
  const convertPerInterval = (value: number, duration: number) =>
    value / duration;
 
  /**
   * Normalize time per given second.
   */
  const normalizeTimePerSecond = (
    currentRoundMoment: Date | string,
    i: number
  ) => {
    const thisMoment = parseDate(currentRoundMoment).startOf('second');
 
    return thisMoment.plus({seconds: i});
  };
 
  /**
   * Breaks down input per minimal time unit.
   */
  const breakDownInput = (input: PluginParams, i: number) => {
    const inputKeys = Object.keys(input);
 
    return inputKeys.reduce((acc, key) => {
      const method = parameterize.getAggregationMethod(key);
 
      if (key === 'timestamp') {
        const perSecond = normalizeTimePerSecond(input.timestamp, i);
        acc[key] = perSecond.toUTC().toISO() ?? '';
 
        return acc;
      }
 
      /** @todo use user defined resolution later */
      if (key === 'duration') {
        acc[key] = 1;
 
        return acc;
      }
 
      acc[key] =
        method === 'sum'
          ? convertPerInterval(input[key], input['duration'])
          : input[key];
 
      return acc;
    }, {} as PluginParams);
  };
 
  /**
   * Populates object to fill the gaps in observational timeline using zeroish values.
   */
  const fillWithZeroishInput = (
    input: PluginParams,
    missingTimestamp: DateTimeMaybeValid
  ) => {
    const metrics = Object.keys(input);
 
    return metrics.reduce((acc, metric) => {
      if (metric === 'timestamp') {
        acc[metric] = missingTimestamp.startOf('second').toUTC().toISO() ?? '';
 
        return acc;
      }
 
      /** @todo later will be changed to user defined interval */
      if (metric === 'duration') {
        acc[metric] = 1;
 
        return acc;
      }
 
      if (metric === 'time-reserved') {
        acc[metric] = acc['duration'];
 
        return acc;
      }
 
      const method = parameterize.getAggregationMethod(metric);
 
      if (method === 'avg' || method === 'sum') {
        acc[metric] = 0;
 
        return acc;
      }
 
      acc[metric] = input[metric];
 
      return acc;
    }, {} as PluginParams);
  };
 
  /**
   * Checks if `error on padding` is enabled and padding is needed. If so, then throws error.
   */
  const validatePadding = (pad: PaddingReceipt, params: TimeParams): void => {
    const {start, end} = pad;
    const isPaddingNeeded = start || end;
 
    if (!params.allowPadding && isPaddingNeeded) {
      throw new InvalidPaddingError(AVOIDING_PADDING_BY_EDGES(start, end));
    }
  };
 
  /**
   * Checks if padding is needed either at start of the timeline or the end and returns status.
   */
  const checkForPadding = (
    inputs: PluginParams[],
    params: TimeParams
  ): PaddingReceipt => {
    const startDiffInSeconds = parseDate(inputs[0].timestamp)
      .diff(params.startTime)
      .as('seconds');
 
    const lastInput = inputs[inputs.length - 1];
 
    const endDiffInSeconds = parseDate(lastInput.timestamp)
      .plus({second: lastInput.duration})
      .diff(params.endTime)
      .as('seconds');
 
    return {
      start: startDiffInSeconds > 0,
      end: endDiffInSeconds < 0,
    };
  };
 
  /**
   * Iterates over given inputs frame, meanwhile checking if aggregation method is `sum`, then calculates it.
   * For methods is `avg` and `none` calculating average of the frame.
   */
  const resampleInputFrame = (inputsInTimeslot: PluginParams[]) =>
    inputsInTimeslot.reduce((acc, input, index, inputs) => {
      const metrics = Object.keys(input);
 
      metrics.forEach(metric => {
        const method = parameterize.getAggregationMethod(metric);
        acc[metric] = acc[metric] ?? 0;
 
        if (metric === 'timestamp') {
          acc[metric] = inputs[0][metric];
 
          return;
        }
 
        if (method === 'sum') {
          acc[metric] += input[metric];
 
          return;
        }
 
        if (method === 'none') {
          acc[metric] = input[metric];
 
          return;
        }
 
        /**
         * If timeslot contains records more than one, then divide each metric by the timeslot length,
         *  so that their sum yields the timeslot average.
         */
        if (
          inputsInTimeslot.length > 1 &&
          index === inputsInTimeslot.length - 1
        ) {
          acc[metric] /= inputsInTimeslot.length;
 
          return;
        }
 
        acc[metric] += input[metric];
      });
 
      return acc;
    }, {} as PluginParams);
 
  /**
   * Takes each array frame with interval length, then aggregating them together as from units.yaml file.
   */
  const resampleInputs = (inputs: PluginParams[], params: TimeParams) =>
    inputs.reduce((acc: PluginParams[], _input, index, inputs) => {
      const frameStart = index * params.interval;
      const frameEnd = (index + 1) * params.interval;
      const inputsFrame = inputs.slice(frameStart, frameEnd);
 
      const resampledInput = resampleInputFrame(inputsFrame);
 
      /** Checks if resampled input is not empty, then includes in result. */
      if (Object.keys(resampledInput).length > 0) {
        acc.push(resampledInput);
      }
 
      return acc;
    }, [] as PluginParams[]);
 
  /**
   * Pads zeroish inputs from the beginning or at the end of the inputs if needed.
   */
  const padInputs = (
    inputs: PluginParams[],
    pad: PaddingReceipt,
    params: TimeParams
  ): PluginParams[] => {
    const {start, end} = pad;
    const paddedFromBeginning = [];
 
    if (start) {
      paddedFromBeginning.push(
        ...getZeroishInputPerSecondBetweenRange(
          params.startTime,
          parseDate(inputs[0].timestamp),
          inputs[0]
        )
      );
    }
 
    const paddedArray = paddedFromBeginning.concat(inputs);
 
    if (end) {
      const lastInput = inputs[inputs.length - 1];
      const lastInputEnd = parseDate(lastInput.timestamp).plus({
        seconds: lastInput.duration,
      });
      paddedArray.push(
        ...getZeroishInputPerSecondBetweenRange(
          lastInputEnd,
          params.endTime.plus({seconds: 1}),
          lastInput
        )
      );
    }
 
    return paddedArray;
  };
 
  const getZeroishInputPerSecondBetweenRange = (
    startDate: DateTimeMaybeValid,
    endDate: DateTimeMaybeValid,
    templateInput: PluginParams
  ) => {
    const array: PluginParams[] = [];
    const dateRange = Interval.fromDateTimes(startDate, endDate);
 
    for (const interval of dateRange.splitBy({second: 1})) {
      array.push(
        fillWithZeroishInput(
          templateInput,
          // as far as I can tell, start will never be null
          // because if we pass an invalid start/endDate to
          // Interval, we get a zero length array as the range
          interval.start || DateTime.invalid('not expected - start is null')
        )
      );
    }
 
    return array;
  };
 
  /*
   * Checks if input's timestamp is included in global specified period then leaves it, otherwise.
   */
  const trimInputsByGlobalTimeline = (
    inputs: PluginParams[],
    params: TimeParams
  ): PluginParams[] =>
    inputs.reduce((acc: PluginParams[], item) => {
      const {timestamp} = item;
 
      if (
        parseDate(timestamp) >= params.startTime &&
        parseDate(timestamp) <= params.endTime
      ) {
        acc.push(item);
      }
 
      return acc;
    }, [] as PluginParams[]);
 
  return {metadata, execute};
};