All files / resources/api/v2 metrics.ts

0% Statements 0/516
0% Branches 0/1
0% Functions 0/1
0% Lines 0/516

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 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import {
  CloudWatchClient, GetMetricDataCommand, GetMetricDataCommandInput,
  MetricDataQuery
} from '@aws-sdk/client-cloudwatch';
 
import {
  LambdaApiFunction,
  handleResourceApi
} from './_base';
import {
  parseJsonBody
} from './_utils';
 
import {
  api401Body, api403Body, generateApi400Body
} from '@/types/api/_shared';
import {
  GetMetricsApi, LambdaMetric, MetricToFetch,
  countMetricValidator, getMetricsApiBodyValidator, lambdaMetricValidator, timingMetricValidator
} from '@/types/api/metrics';
import { validateObject } from '@/utils/backend/validation';
import { getLogger } from '@/utils/common/logger';
 
const logger = getLogger('metrics');
const cloudwatch = new CloudWatchClient();
 
function buildMetricKey(metric: MetricToFetch): string {
  let key: string = `${metric.type}_`;
  switch (metric.type) {
    case 'lambda':
      key += `${metric.fn}_${metric.metric}_${metric.stat}`;
      break;
    case 'count':
      key += `${metric.namespace}_${metric.metricName}`;
      if (typeof metric.source !== 'undefined') {
        key += `_${metric.source}`;
      }
      if (typeof metric.action !== 'undefined') {
        key += `_${metric.action}`;
      }
      break;
    case 'timing':
      key += `${metric.namespace}_${metric.metricName}`;
      if (typeof metric.tower !== 'undefined') {
        key += `_${metric.tower}`;
      }
      key += `_${metric.stat}`;
      break;
  }
  return key.replace(/ /g, '_').replace(/[^A-Za-z0-9_]/g, '');
}
 
const lambdaNameEnvRegex = /^(A|I)_([0-9A-Z_]+)_FN_NAME$/;
const lambdaNames: {
  [key: string]: {
    name: string;
    label: string;
  };
} = Object.keys(process.env)
  .filter(key => key.endsWith('_FN_NAME') && lambdaNameEnvRegex.test(key))
  .reduce((agg: typeof lambdaNames, key) => {
    const value = process.env[key];
    const pieces = key.match(lambdaNameEnvRegex);
    if (
      typeof value === 'undefined' ||
      pieces === null
    ) {
      return agg;
    }
 
    agg[key] = {
      name: value === 'self'
        ? process.env.AWS_LAMBDA_FUNCTION_NAME as string
        : value,
      label: pieces[1] === 'I'
        ? pieces[2].toLowerCase()
        : pieces[2].replace(/_/g, '/').toLowerCase(),
    };
 
    return agg;
  }, {});
const specialLambdaNames = {
  all: 'All Functions',
  all_A: 'All API Functions',
  all_I: 'All Infrastructure Functions',
} as const;
 
function buildLambdaMetric(
  metric: LambdaMetric,
  body: Required<Pick<GetMetricsApi['body'], 'period'>>
): [ MetricDataQuery[], string[] ] {
  const key = buildMetricKey(metric);
  const conf = lambdaNames[metric.fn];
  if (typeof conf === 'undefined') {
    console.log(lambdaNames);
    throw new Error(`Invalid fn - ${metric.fn}`);
  }
 
  const metricToPush: MetricDataQuery = {
    Id: key,
    ReturnData: true,
    Label: `${conf.label || metric.fn} ${metric.metric}`,
    MetricStat: {
      Metric: {
        Namespace: 'AWS/Lambda',
        MetricName: metric.metric,
        Dimensions: [ {
          Name: 'FunctionName',
          Value: conf.name,
        }, ],
      },
      Period: body.period,
      Stat: metric.stat,
    },
  };
 
  return [
    [ metricToPush, ],
    [ key, ],
  ];
}
 
function buildSpecialLambdaMetric(
  metric: LambdaMetric,
  body: Required<Pick<GetMetricsApi['body'], 'period'>>
): [ MetricDataQuery[], string[] ] {
  if (!(metric.fn in specialLambdaNames)) {
    return [
      [],
      [],
    ];
  }
 
  const metricsToUse: MetricDataQuery[] = [];
  const keysToUse: string[] = [];
 
  const fnName = metric.fn as keyof typeof specialLambdaNames;
  Object.keys(lambdaNames)
    .filter(name => {
      if (fnName === 'all') {
        return true;
      }
 
      if (fnName === 'all_A' && name.startsWith('A_')) {
        return true;
      }
 
      if (fnName === 'all_I' && name.startsWith('I_')) {
        return true;
      }
 
      return false;
    })
    .forEach(name => {
      const [
        [ metricQuery, ],
        [ metricKey, ],
      ] = buildLambdaMetric(
        {
          ...metric,
          fn: name,
        },
        body
      );
      metricsToUse.push(metricQuery);
      keysToUse.push(metricKey);
    });
 
  return [
    metricsToUse,
    keysToUse,
  ];
}
 
const periodToTime: {
  period: number; // seconds
  timerange: number; // milliseconds
}[] = [
  {
    timerange: 365 * 24 * 60 * 60, // 365 days (1 year)
    period: 24 * 60 * 60, // 24 hours
  },
  {
    timerange: 28 * 24 * 60 * 60, // 28 days (1 month)
    period: 6 * 60 * 60, // 6 hours
  },
  {
    timerange: 7 * 24 * 60 * 60, // 7 days
    period: 60 * 60, // 1 hour
  },
  {
    timerange: 24 * 60 * 60, // 24 hours
    period: 15 * 60, // 15 minutes
  },
  {
    timerange: 6 * 60 * 60, // 6 hours
    period: 5 * 60, // 5 minutes
  },
  {
    timerange: 60 * 60, // 1 hour
    period: 60, // 1 minute
  },
];
 
function getPeriodFromTimerange(timerange: number) {
  return periodToTime.reduce((period, item) => {
    if (timerange <= item.timerange) {
      return item.period;
    }
 
    return period;
  }, periodToTime[0].period);
}
function getTimerangeFromPeriod(period: number) {
  return periodToTime.reduce((timerange, item) => {
    if (period <= item.period) {
      return item.timerange;
    }
 
    return timerange;
  }, periodToTime[0].timerange);
}
 
const ONE_HOUR = 60 * 60 * 1000;
const ONE_DAY = 24 * ONE_HOUR;
 
const POST: LambdaApiFunction<GetMetricsApi> = async function (event, user, userPerms) {
  logger.trace('POST', ...arguments);
 
  // Authorize the user
  if (user === null) {
    return [
      401,
      api401Body,
    ];
  }
  if (!userPerms.isAdmin) {
    return [
      403,
      api403Body,
    ];
  }
 
  // Validate the body (part 1)
  const [
    body,
    bodyErrors,
  ] = parseJsonBody(
    event.body,
    getMetricsApiBodyValidator
  );
  if (
    body === null ||
    bodyErrors.length > 0
  ) {
    return [
      400,
      generateApi400Body(bodyErrors),
    ];
  }
 
  // Validate the individual metrics
  const allErrors: string[] = [];
  body.metrics.forEach((metric, i) => {
    let metricParsed: typeof metric | null = null;
    let metricErrors: string[] = [];
    switch (metric.type) {
      case 'timing':
        [
          metricParsed,
          metricErrors,
        ] = validateObject(
          metric,
          timingMetricValidator
        );
        break;
      case 'count':
        [
          metricParsed,
          metricErrors,
        ] = validateObject(
          metric,
          countMetricValidator
        );
        break;
      case 'lambda':
        [
          metricParsed,
          metricErrors,
        ] = validateObject(
          metric,
          lambdaMetricValidator
        );
 
        // Verify the function is known
        if (
          metricParsed !== null &&
          !(metricParsed.fn in specialLambdaNames) &&
          typeof lambdaNames[metricParsed.fn] === 'undefined'
        ) {
          metricErrors.push('fn');
        }
        break;
    }
 
    if (metricErrors.length > 0) {
      metricErrors.forEach(err => allErrors.push(`${i}-${err}`));
    } else if (metricParsed === null) {
      allErrors.push(`${i}`);
    } else {
      body.metrics[i] = metricParsed;
    }
  });
  if (allErrors.length > 0) {
    return [
      400,
      generateApi400Body(allErrors),
    ];
  }
  if (body.metrics.length === 0) {
    return [
      400,
      generateApi400Body([ 'metrics', ]),
    ];
  }
 
  // Get the timezone information
  const nowDate = new Date();
  const timeZoneOffset = new Date(nowDate.toLocaleString('en-US', { timeZone: 'America/Denver', })).getTime() -
  new Date(nowDate.toLocaleString('en-US', { timeZone: 'UTC', })).getTime();
  const timeZoneHourOffset = timeZoneOffset / 6e4;
  const timeZoneStr = `${timeZoneHourOffset > 0 ? '+' : '-'}${Math.abs(timeZoneHourOffset / 60).toString()
    .padStart(2, '0')}00`;
 
  // Check for a timerange but not period being provided
  if (
    typeof body.timerange !== 'undefined' &&
    typeof body.period === 'undefined'
  ) {
    body.period = getPeriodFromTimerange(body.timerange);
  }
 
  // Build the default time values and direction to expand the values
  const dir = body.live === 'y'
    ? 'ceil'
    : 'floor';
  const defaultPeriod = 60 * 60;
  const defaultTimeRange = getTimerangeFromPeriod(defaultPeriod);
 
  // Modify the body for the actual values we want to use
  if (
    // Overall default
    typeof body.startTime === 'undefined' &&
    typeof body.endTime === 'undefined' &&
    typeof body.period === 'undefined'
  ) {
    const nowHour = (Math[dir](
      (Date.now() + timeZoneOffset) / ONE_HOUR
    ) * ONE_HOUR) - timeZoneOffset;
    body.startTime = nowHour - ONE_DAY;
    body.endTime = nowHour;
    body.period = 3600;
  } else if (
    // Period but one of startTime or endTime is missing
    typeof body.period !== 'undefined' &&
    (
      typeof body.startTime === 'undefined' ||
      typeof body.endTime === 'undefined'
    )
  ) {
    if (typeof body.timerange === 'undefined') {
      body.timerange = getTimerangeFromPeriod(body.period);
    }
 
    if (typeof body.startTime !== 'undefined') {
      body.endTime = body.startTime + (body.timerange * 1000);
    } else if (typeof body.endTime !== 'undefined') {
      body.startTime = body.endTime - (body.timerange * 1000);
    } else {
      const nowTime = (
        Math[dir]((Date.now() + timeZoneOffset) / (body.period * 1000)) *
        (body.period * 1000)
      ) - timeZoneOffset;
      body.endTime = nowTime;
      body.startTime = nowTime - (body.timerange * 1000);
    }
  } else if (
    // Period missing but startTime or endTime (or both) are provided
    typeof body.period === 'undefined' &&
    (
      typeof body.startTime !== 'undefined' ||
      typeof body.endTime !== 'undefined'
    )
  ) {
    if (
      typeof body.startTime === 'undefined' ||
      typeof body.endTime === 'undefined'
    ) {
      body.timerange = defaultTimeRange;
    } else {
      body.timerange = Math.floor((body.endTime - body.startTime) / 1000);
    }
  }
 
  // Make sure we have defined period, startTime, and endTime
  if (
    typeof body.period === 'undefined' ||
    typeof body.startTime === 'undefined' ||
    typeof body.endTime === 'undefined'
  ) {
    return [
      400,
      generateApi400Body([ 'times', ]),
    ];
  }
  const fullBody: Required<Pick<GetMetricsApi['body'], 'startTime' | 'endTime' | 'period'>> = {
    period: body.period,
    startTime: body.startTime,
    endTime: body.endTime,
  };
 
  // Build the metrics request
  const metricRequest: GetMetricDataCommandInput & {
    MetricDataQueries: MetricDataQuery[];
  } = {
    EndTime: new Date(fullBody.endTime),
    StartTime: new Date(fullBody.startTime),
    ScanBy: 'TimestampDescending',
    LabelOptions: {
      Timezone: timeZoneStr,
    },
    MetricDataQueries: [],
  };
  const includedMetrics: string[] = [];
  body.metrics.forEach(metric => {
    const key = buildMetricKey(metric);
 
    // Skip already included metrics
    if (includedMetrics.includes(key)) {
      metricRequest.MetricDataQueries.forEach(m => {
        if (m.Id === key && !m.ReturnData) {
          m.ReturnData = true;
        }
      });
      return;
    }
 
    // Handle each metric type
    switch (metric.type) {
      case 'lambda': {
        let metrics: MetricDataQuery[] | null = null;
        let keys: string[] | null = null;
        if (metric.fn in specialLambdaNames) {
          [
            metrics,
            keys,
          ] = buildSpecialLambdaMetric(metric, fullBody);
        } else {
          [
            metrics,
            keys,
          ] = buildLambdaMetric(metric, fullBody);
        }
        metrics.forEach((m, i) => {
          if (includedMetrics.includes(keys[i])) {
            return;
          }
 
          metricRequest.MetricDataQueries.push(m);
          includedMetrics.push(keys[i]);
        });
        break;
      }
      case 'timing': {
        const key = buildMetricKey(metric);
        if (includedMetrics.includes(key)) {
          return;
        }
        metricRequest.MetricDataQueries.push({
          Label: metric.label,
          Id: key,
          MetricStat: {
            Metric: {
              Namespace: metric.namespace,
              MetricName: metric.metricName,
              Dimensions: metric.tower
                ? [ {
                  Name: 'Tower',
                  Value: metric.tower,
                }, ]
                : undefined,
            },
            Period: fullBody.period,
            Stat: metric.stat,
          },
        });
        includedMetrics.push(key);
        break;
      }
      case 'count': {
        const key = buildMetricKey(metric);
        if (includedMetrics.includes(key)) {
          return;
        }
        metricRequest.MetricDataQueries.push({
          Label: metric.label,
          Id: key,
          MetricStat: {
            Metric: {
              Namespace: metric.namespace,
              MetricName: metric.metricName,
              Dimensions: ([
                'action',
                'source',
                'ApiName',
              ] as const).map(v => {
                if (typeof metric[v] === 'undefined') {
                  return null;
                }
 
                return {
                  Name: v,
                  Value: metric[v],
                };
              }).filter(v => v !== null),
            },
            Period: fullBody.period,
            Stat: 'Sum',
          },
        });
        includedMetrics.push(key);
        break;
      }
    }
  });
 
  const response: GetMetricsApi['responses'][200] = {
    startTime: body.startTime,
    endTime: body.endTime,
    period: body.period,
    labels: {},
    data: [],
  };
  if (metricRequest.MetricDataQueries.length === 0) {
    return [
      200,
      response,
    ];
  }
 
  const data = await cloudwatch.send(new GetMetricDataCommand(metricRequest));
  if (typeof data.MetricDataResults === 'undefined') {
    return [
      200,
      response,
    ];
  }
 
  // Pull out the data labels
  const labelArr: string[] = [];
  response.labels = data.MetricDataResults.reduce((
    agg: typeof response.labels,
    item
  ) => {
    const id = item.Id || 'ERR';
    const label = item.Label || 'ERR';
    if (!labelArr.includes(id)) {
      labelArr.push(id);
    }
    agg[`k${labelArr.indexOf(id)}`] = label;
 
    return agg;
  }, {});
 
  // Pull out the data
  data.MetricDataResults.forEach(item => {
    item.Timestamps?.forEach((ts, index) => {
      const tsString = ts.toISOString();
      const id = `k${labelArr.indexOf(item.Id || 'ERR')}`;
      const val = item.Values?.[index] || 0;
      const elem = response.data.find(v => v.ts === tsString);
      if (elem) {
        elem.values[id] = val;
      } else {
        response.data.push({
          ts: tsString,
          values: {
            [id]: val,
          },
        });
      }
    });
  });
 
  return [
    200,
    response,
  ];
};
 
export const main = handleResourceApi.bind(null, {
  POST,
});