Skip to content

chore(maintenance): migrate metrics utility to biome #2816

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

Merged
merged 6 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
22 changes: 5 additions & 17 deletions packages/metrics/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
"build:cjs": "tsc --build tsconfig.json && echo '{ \"type\": \"commonjs\" }' > lib/cjs/package.json",
"build:esm": "tsc --build tsconfig.esm.json && echo '{ \"type\": \"module\" }' > lib/esm/package.json",
"build": "npm run build:esm & npm run build:cjs",
"lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .",
"lint-fix": "eslint --fix --ext .ts,.js --no-error-on-unmatched-pattern .",
"lint": "biome lint .",
"lint:fix": "biome check --write .",
"prepack": "node ../../.github/scripts/release_patch_package_json.js ."
},
"homepage": "https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/packages/metrics#readme",
Expand Down Expand Up @@ -52,10 +52,7 @@
"lib/cjs/middleware/middy.d.ts",
"lib/esm/middleware/middy.d.ts"
],
"types": [
"lib/cjs/types/index.d.ts",
"lib/esm/types/index.d.ts"
]
"types": ["lib/cjs/types/index.d.ts", "lib/esm/types/index.d.ts"]
}
},
"types": "./lib/cjs/index.d.ts",
Expand All @@ -74,9 +71,7 @@
"optional": true
}
},
"files": [
"lib"
],
"files": ["lib"],
"repository": {
"type": "git",
"url": "git+https://github.com/aws-powertools/powertools-lambda-typescript.git"
Expand All @@ -87,12 +82,5 @@
"dependencies": {
"@aws-lambda-powertools/commons": "^2.5.0"
},
"keywords": [
"aws",
"lambda",
"powertools",
"metrics",
"serverless",
"nodejs"
]
"keywords": ["aws", "lambda", "powertools", "metrics", "serverless", "nodejs"]
}
44 changes: 19 additions & 25 deletions packages/metrics/src/Metrics.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
import type { Callback, Context, Handler } from 'aws-lambda';
import { Console } from 'node:console';
import { Utility } from '@aws-lambda-powertools/commons';
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { Callback, Context, Handler } from 'aws-lambda';
import { EnvironmentVariablesService } from './config/EnvironmentVariablesService.js';
import {
COLD_START_METRIC,
DEFAULT_NAMESPACE,
MAX_DIMENSION_COUNT,
MAX_METRICS_SIZE,
DEFAULT_NAMESPACE,
COLD_START_METRIC,
MAX_METRIC_VALUES_SIZE,
MetricUnit as MetricUnits,
MetricResolution as MetricResolutions,
MetricUnit as MetricUnits,
} from './constants.js';
import {
type MetricsOptions,
type Dimensions,
type EmfOutput,
type StoredMetrics,
type ExtraOptions,
type MetricDefinition,
type ConfigServiceInterface,
type MetricsInterface,
type MetricUnit,
type MetricResolution,
import type {
ConfigServiceInterface,
Dimensions,
EmfOutput,
ExtraOptions,
MetricDefinition,
MetricResolution,
MetricUnit,
MetricsInterface,
MetricsOptions,
StoredMetrics,
} from './types/index.js';

/**
Expand Down Expand Up @@ -167,9 +167,9 @@ class Metrics extends Utility implements MetricsInterface {
*/
public addDimensions(dimensions: { [key: string]: string }): void {
const newDimensions = { ...this.dimensions };
Object.keys(dimensions).forEach((dimensionName) => {
for (const dimensionName of Object.keys(dimensions)) {
newDimensions[dimensionName] = dimensions[dimensionName];
});
}
if (Object.keys(newDimensions).length > MAX_DIMENSION_COUNT) {
throw new RangeError(
`Unable to add ${
Expand Down Expand Up @@ -337,10 +337,7 @@ class Metrics extends Utility implements MetricsInterface {
}

return (_target, _propertyKey, descriptor) => {
/**
* The descriptor.value is the method this decorator decorates, it cannot be undefined.
*/
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
// biome-ignore lint/style/noNonNullAssertion: The descriptor.value is the method this decorator decorates, it cannot be undefined.
const originalMethod = descriptor.value!;

// eslint-disable-next-line @typescript-eslint/no-this-alias
Expand All @@ -359,8 +356,6 @@ class Metrics extends Utility implements MetricsInterface {
let result: unknown;
try {
result = await originalMethod.apply(this, [event, context, callback]);
} catch (error) {
throw error;
} finally {
metricsRef.publishStoredMetrics();
}
Expand Down Expand Up @@ -598,9 +593,8 @@ class Metrics extends Utility implements MetricsInterface {
}

return false;
} else {
return true;
}
return true;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/metrics/src/config/EnvironmentVariablesService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ConfigServiceInterface } from '../types/ConfigServiceInterface.js';
import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons';
import type { ConfigServiceInterface } from '../types/ConfigServiceInterface.js';

class EnvironmentVariablesService
extends CommonEnvironmentVariablesService
Expand Down
14 changes: 7 additions & 7 deletions packages/metrics/src/middleware/middy.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { METRICS_KEY } from '@aws-lambda-powertools/commons';
import type { Metrics } from '../Metrics.js';
import type { ExtraOptions } from '../types/Metrics.js';
import type {
MiddlewareLikeObj,
MiddyLikeRequest,
} from '@aws-lambda-powertools/commons/types';
import type { Metrics } from '../Metrics.js';
import type { ExtraOptions } from '../types/Metrics.js';

/**
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
Expand Down Expand Up @@ -38,7 +38,7 @@ const logMetrics = (
target: Metrics | Metrics[],
options: ExtraOptions = {}
): MiddlewareLikeObj => {
const metricsInstances = target instanceof Array ? target : [target];
const metricsInstances = Array.isArray(target) ? target : [target];

/**
* Set the cleanup function to be called in case other middlewares return early.
Expand All @@ -53,7 +53,7 @@ const logMetrics = (
};

const logMetricsBefore = async (request: MiddyLikeRequest): Promise<void> => {
metricsInstances.forEach((metrics: Metrics) => {
for (const metrics of metricsInstances) {
metrics.setFunctionName(request.context.functionName);
const { throwOnEmptyMetrics, defaultDimensions, captureColdStartMetric } =
options;
Expand All @@ -66,15 +66,15 @@ const logMetrics = (
if (captureColdStartMetric) {
metrics.captureColdStartMetric();
}
});
}

setCleanupFunction(request);
};

const logMetricsAfterOrError = async (): Promise<void> => {
metricsInstances.forEach((metrics: Metrics) => {
for (const metrics of metricsInstances) {
metrics.publishStoredMetrics();
});
}
};

return {
Expand Down
9 changes: 6 additions & 3 deletions packages/metrics/src/types/Metrics.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type {
MetricResolution as MetricResolutionList,
MetricUnit as MetricUnitList,
} from '../constants.js';
import type { ConfigServiceInterface } from './ConfigServiceInterface.js';
import { MetricResolution, MetricUnit } from '../constants.js';

type Dimensions = Record<string, string>;

Expand Down Expand Up @@ -49,9 +52,9 @@ type ExtraOptions = {
};

type MetricResolution =
(typeof MetricResolution)[keyof typeof MetricResolution];
(typeof MetricResolutionList)[keyof typeof MetricResolutionList];

type MetricUnit = (typeof MetricUnit)[keyof typeof MetricUnit];
type MetricUnit = (typeof MetricUnitList)[keyof typeof MetricUnitList];

type StoredMetric = {
name: string;
Expand Down
6 changes: 3 additions & 3 deletions packages/metrics/src/types/MetricsInterface.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { Metrics } from '../Metrics.js';
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { Metrics } from '../Metrics.js';
import type {
EmfOutput,
Dimensions,
MetricsOptions,
EmfOutput,
MetricResolution,
MetricUnit,
MetricsOptions,
} from './Metrics.js';

interface MetricsInterface {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Metrics, MetricUnit } from '../../src/index.js';
import type { MetricUnit as MetricUnitType } from '../../src/types/index.js';
import type { Context } from 'aws-lambda';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import type { Context } from 'aws-lambda';
import { MetricUnit, Metrics } from '../../src/index.js';
import type { MetricUnit as MetricUnitType } from '../../src/types/index.js';

const namespace = process.env.EXPECTED_NAMESPACE ?? 'CdkExample';
const serviceName =
Expand Down Expand Up @@ -35,7 +35,7 @@ class Lambda implements LambdaInterface {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
public async handler(_event: unknown, _context: Context): Promise<void> {
metrics.addMetric(metricName, metricUnit, parseInt(metricValue));
metrics.addMetric(metricName, metricUnit, Number.parseInt(metricValue));
metrics.addDimension(
Object.entries(JSON.parse(extraDimension))[0][0],
Object.entries(JSON.parse(extraDimension))[0][1] as string
Expand All @@ -54,7 +54,7 @@ class Lambda implements LambdaInterface {
metricWithItsOwnDimensions.addMetric(
singleMetricName,
singleMetricUnit,
parseInt(singleMetricValue)
Number.parseInt(singleMetricValue)
);
}
}
Expand Down
10 changes: 5 additions & 5 deletions packages/metrics/tests/e2e/basicFeatures.decorators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,27 @@
*
* @group e2e/metrics/decorator
*/
import { join } from 'node:path';
import {
invokeFunction,
TestStack,
invokeFunction,
} from '@aws-lambda-powertools/testing-utils';
import {
CloudWatchClient,
GetMetricStatisticsCommand,
} from '@aws-sdk/client-cloudwatch';
import { join } from 'node:path';
import { getMetrics, sortDimensions } from '../helpers/metricsUtils.js';
import { MetricsTestNodejsFunction } from '../helpers/resources.js';
import {
commonEnvironmentVars,
ONE_MINUTE,
RESOURCE_NAME_PREFIX,
SETUP_TIMEOUT,
TEARDOWN_TIMEOUT,
TEST_CASE_TIMEOUT,
commonEnvironmentVars,
} from './constants.js';

describe(`Metrics E2E tests, basic features decorator usage`, () => {
describe('Metrics E2E tests, basic features decorator usage', () => {
const testStack = new TestStack({
stackNameProps: {
stackNamePrefix: RESOURCE_NAME_PREFIX,
Expand Down Expand Up @@ -205,7 +205,7 @@ describe(`Metrics E2E tests, basic features decorator usage`, () => {
? metricStat.Datapoints[0]
: {};
expect(singleDataPoint?.Sum).toBeGreaterThanOrEqual(
parseInt(expectedMetricValue) * invocations
Number.parseInt(expectedMetricValue) * invocations
);
},
TEST_CASE_TIMEOUT
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Metrics, MetricUnit } from '../../src/index.js';
import type { MetricUnit as MetricUnitType } from '../../src/types/index.js';
import type { Context } from 'aws-lambda';
import { MetricUnit, Metrics } from '../../src/index.js';
import type { MetricUnit as MetricUnitType } from '../../src/types/index.js';

const namespace = process.env.EXPECTED_NAMESPACE ?? 'CdkExample';
const serviceName =
Expand Down Expand Up @@ -32,7 +32,7 @@ export const handler = async (
metrics.captureColdStartMetric();
metrics.throwOnEmptyMetrics();
metrics.setDefaultDimensions(JSON.parse(defaultDimensions));
metrics.addMetric(metricName, metricUnit, parseInt(metricValue));
metrics.addMetric(metricName, metricUnit, Number.parseInt(metricValue));
metrics.addDimension(
Object.entries(JSON.parse(extraDimension))[0][0],
Object.entries(JSON.parse(extraDimension))[0][1] as string
Expand All @@ -46,7 +46,7 @@ export const handler = async (
metricWithItsOwnDimensions.addMetric(
singleMetricName,
singleMetricUnit,
parseInt(singleMetricValue)
Number.parseInt(singleMetricValue)
);

metrics.publishStoredMetrics();
Expand Down
10 changes: 5 additions & 5 deletions packages/metrics/tests/e2e/basicFeatures.manual.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,27 @@
*
* @group e2e/metrics/standardFunctions
*/
import { join } from 'node:path';
import {
invokeFunction,
TestStack,
invokeFunction,
} from '@aws-lambda-powertools/testing-utils';
import {
CloudWatchClient,
GetMetricStatisticsCommand,
} from '@aws-sdk/client-cloudwatch';
import { join } from 'node:path';
import { getMetrics, sortDimensions } from '../helpers/metricsUtils.js';
import { MetricsTestNodejsFunction } from '../helpers/resources.js';
import {
commonEnvironmentVars,
ONE_MINUTE,
RESOURCE_NAME_PREFIX,
SETUP_TIMEOUT,
TEARDOWN_TIMEOUT,
TEST_CASE_TIMEOUT,
commonEnvironmentVars,
} from './constants.js';

describe(`Metrics E2E tests, manual usage`, () => {
describe('Metrics E2E tests, manual usage', () => {
const testStack = new TestStack({
stackNameProps: {
stackNamePrefix: RESOURCE_NAME_PREFIX,
Expand Down Expand Up @@ -191,7 +191,7 @@ describe(`Metrics E2E tests, manual usage`, () => {
? metricStat.Datapoints[0]
: {};
expect(singleDataPoint.Sum).toBeGreaterThanOrEqual(
parseInt(expectedMetricValue) * invocations
Number.parseInt(expectedMetricValue) * invocations
);
},
TEST_CASE_TIMEOUT
Expand Down
16 changes: 7 additions & 9 deletions packages/metrics/tests/helpers/metricsUtils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import promiseRetry from 'promise-retry';
import { Metrics, MetricUnit } from '../../src/index.js';
import { ExtraOptions } from '../../src/types/index.js';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import {
CloudWatchClient,
type CloudWatchClient,
type Dimension,
ListMetricsCommand,
} from '@aws-sdk/client-cloudwatch';
import type {
Dimension,
ListMetricsCommandOutput,
type ListMetricsCommandOutput,
} from '@aws-sdk/client-cloudwatch';
import type { Context, Handler } from 'aws-lambda';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import promiseRetry from 'promise-retry';
import { MetricUnit, type Metrics } from '../../src/index.js';
import type { ExtraOptions } from '../../src/types/index.js';

const getMetrics = async (
cloudWatchClient: CloudWatchClient,
Expand Down
Loading