New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

aws-embedded-metrics

Package Overview
Dependencies
Maintainers
2
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

aws-embedded-metrics - npm Package Compare versions

Comparing version 4.0.0 to 4.1.0

lib/logger/StorageResolution.d.ts

1

lib/Constants.d.ts

@@ -8,2 +8,3 @@ export declare enum Constants {

VALID_NAMESPACE_REGEX = "^[a-zA-Z0-9._#:/-]+$",
VALID_DIMENSION_REGEX = "^[\0-]+$",
MAX_TIMESTAMP_PAST_AGE = 1209600000,

@@ -10,0 +11,0 @@ MAX_TIMESTAMP_FUTURE_AGE = 7200000,

@@ -26,2 +26,3 @@ "use strict";

Constants["VALID_NAMESPACE_REGEX"] = "^[a-zA-Z0-9._#:/-]+$";
Constants["VALID_DIMENSION_REGEX"] = "^[\0-]+$";
Constants[Constants["MAX_TIMESTAMP_PAST_AGE"] = 1209600000] = "MAX_TIMESTAMP_PAST_AGE";

@@ -28,0 +29,0 @@ Constants[Constants["MAX_TIMESTAMP_FUTURE_AGE"] = 7200000] = "MAX_TIMESTAMP_FUTURE_AGE";

2

lib/environment/EnvironmentDetector.d.ts
import { IEnvironment } from './IEnvironment';
declare type EnvironmentProvider = () => Promise<IEnvironment>;
type EnvironmentProvider = () => Promise<IEnvironment>;
declare const resolveEnvironment: EnvironmentProvider;
declare const cleanResolveEnvironment: () => Promise<IEnvironment>;
export { EnvironmentProvider, resolveEnvironment, cleanResolveEnvironment };

@@ -7,3 +7,4 @@ export { MetricsLogger } from './logger/MetricsLogger';

export { Unit } from './logger/Unit';
export { StorageResolution } from './logger/StorageResolution';
import Configuration from './config/Configuration';
export { Configuration };

@@ -20,3 +20,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Configuration = exports.Unit = exports.createMetricsLogger = exports.metricScope = exports.AgentSink = exports.LocalSink = exports.MetricsLogger = void 0;
exports.Configuration = exports.StorageResolution = exports.Unit = exports.createMetricsLogger = exports.metricScope = exports.AgentSink = exports.LocalSink = exports.MetricsLogger = void 0;
var MetricsLogger_1 = require("./logger/MetricsLogger");

@@ -34,3 +34,5 @@ Object.defineProperty(exports, "MetricsLogger", { enumerable: true, get: function () { return MetricsLogger_1.MetricsLogger; } });

Object.defineProperty(exports, "Unit", { enumerable: true, get: function () { return Unit_1.Unit; } });
var StorageResolution_1 = require("./logger/StorageResolution");
Object.defineProperty(exports, "StorageResolution", { enumerable: true, get: function () { return StorageResolution_1.StorageResolution; } });
const Configuration_1 = __importDefault(require("./config/Configuration"));
exports.Configuration = Configuration_1.default;
import { MetricValues } from './MetricValues';
import { StorageResolution } from './StorageResolution';
import { Unit } from './Unit';

@@ -6,3 +7,3 @@ interface IProperties {

}
declare type Metrics = Map<string, MetricValues>;
type Metrics = Map<string, MetricValues>;
export declare class MetricsContext {

@@ -21,2 +22,3 @@ /**

private timestamp;
private metricNameAndResolutionMap;
/**

@@ -66,3 +68,3 @@ * Constructor used to create child instances.

getDimensions(): Array<Record<string, string>>;
putMetric(key: string, value: number, unit?: Unit | string): void;
putMetric(key: string, value: number, unit?: Unit | string, storageResolution?: StorageResolution | number): void;
/**

@@ -69,0 +71,0 @@ * Creates an independently flushable context.

@@ -25,4 +25,11 @@ "use strict";

const MetricValues_1 = require("./MetricValues");
const StorageResolution_1 = require("./StorageResolution");
class MetricsContext {
/**
* Use this to create a new, empty context.
*/
static empty() {
return new MetricsContext();
}
/**
* Constructor used to create child instances.

@@ -42,2 +49,3 @@ * You should not use this constructor directly.

this.shouldUseDefaultDimensions = true;
this.metricNameAndResolutionMap = new Map();
this.namespace = namespace || Configuration_1.default.namespace;

@@ -53,8 +61,2 @@ this.properties = properties || {};

}
/**
* Use this to create a new, empty context.
*/
static empty() {
return new MetricsContext();
}
static resolveMetaTimestamp(timestamp) {

@@ -154,4 +156,5 @@ if (timestamp instanceof Date) {

}
putMetric(key, value, unit) {
(0, Validator_1.validateMetric)(key, value, unit);
putMetric(key, value, unit, storageResolution) {
var _a;
(0, Validator_1.validateMetric)(key, value, unit, storageResolution, this.metricNameAndResolutionMap);
const currentMetric = this.metrics.get(key);

@@ -162,4 +165,5 @@ if (currentMetric) {

else {
this.metrics.set(key, new MetricValues_1.MetricValues(value, unit));
this.metrics.set(key, new MetricValues_1.MetricValues(value, unit, storageResolution));
}
(_a = this.metricNameAndResolutionMap) === null || _a === void 0 ? void 0 : _a.set(key, storageResolution || StorageResolution_1.StorageResolution.Standard);
}

@@ -166,0 +170,0 @@ /**

import { EnvironmentProvider } from '../environment/EnvironmentDetector';
import { MetricsContext } from './MetricsContext';
import { Unit } from './Unit';
import { StorageResolution } from './StorageResolution';
/**

@@ -64,4 +65,5 @@ * An async metrics logger.

* @param unit
* @param storageResolution
*/
putMetric(key: string, value: number, unit?: Unit | string): MetricsLogger;
putMetric(key: string, value: number, unit?: Unit | string, storageResolution?: StorageResolution | number): MetricsLogger;
/**

@@ -68,0 +70,0 @@ * Set the CloudWatch namespace that metrics should be published to.

@@ -124,5 +124,6 @@ "use strict";

* @param unit
* @param storageResolution
*/
putMetric(key, value, unit) {
this.context.putMetric(key, value, unit);
putMetric(key, value, unit, storageResolution) {
this.context.putMetric(key, value, unit, storageResolution);
return this;

@@ -129,0 +130,0 @@ }

import { Unit } from '..';
import { StorageResolution } from './StorageResolution';
export declare class MetricValues {
values: number[];
unit: string;
constructor(value: number, unit?: Unit | string);
storageResolution: number;
constructor(value: number, unit?: Unit | string, storageResolution?: StorageResolution | number);
/**

@@ -7,0 +9,0 @@ * Appends the provided value to the current metric

@@ -18,6 +18,8 @@ "use strict";

exports.MetricValues = void 0;
const StorageResolution_1 = require("./StorageResolution");
class MetricValues {
constructor(value, unit) {
constructor(value, unit, storageResolution) {
this.values = [value];
this.unit = unit || 'None';
this.storageResolution = storageResolution || StorageResolution_1.StorageResolution.Standard;
}

@@ -24,0 +26,0 @@ /**

@@ -21,2 +21,3 @@ "use strict";

const DimensionSetExceededError_1 = require("../exceptions/DimensionSetExceededError");
const StorageResolution_1 = require("../logger/StorageResolution");
/**

@@ -33,3 +34,3 @@ * Serializes the provided context to the CWL Structured

let dimensionProperties = {};
context.getDimensions().forEach(dimensionSet => {
context.getDimensions().forEach((dimensionSet) => {
const keys = Object.keys(dimensionSet);

@@ -68,3 +69,3 @@ if (keys.length > Constants_1.Constants.MAX_DIMENSION_SET_SIZE) {

return { name: key, numLeft: value.values.length };
}), metric => metric.numLeft);
}), (metric) => metric.numLeft);
let processedMetrics = [];

@@ -85,4 +86,5 @@ // Batches the metrics with the most number of values first, such that each metric has no more

currentBody[metricProgress.name] = metricValue;
const metricBody = Object.assign({ Name: metricProgress.name, Unit: metric.unit }, (metric.storageResolution == StorageResolution_1.StorageResolution.High ? { StorageResolution: StorageResolution_1.StorageResolution.High } : {}));
// eslint-disable-next-line
currentBody._aws.CloudWatchMetrics[0].Metrics.push({ Name: metricProgress.name, Unit: metric.unit });
currentBody._aws.CloudWatchMetrics[0].Metrics.push(metricBody);
metricProgress.numLeft -= Constants_1.Constants.MAX_VALUES_PER_METRIC;

@@ -95,3 +97,3 @@ if (metricProgress.numLeft > 0) {

// inserts these metrics back in the heap to be processed in the next iteration.
processedMetrics.forEach(processingMetric => remainingMetrics.insert(processingMetric));
processedMetrics.forEach((processingMetric) => remainingMetrics.insert(processingMetric));
processedMetrics = [];

@@ -98,0 +100,0 @@ }

import { Unit } from '../logger/Unit';
import { StorageResolution } from '../logger/StorageResolution';
/**

@@ -17,6 +18,8 @@ * Validates dimension set.

* @param value
* @param unit
* @param storageResolution
*
* @throws {InvalidMetricError} Metric name must be valid.
*/
declare const validateMetric: (key: string, value: number, unit?: Unit | string) => void;
declare const validateMetric: (key: string, value: number, unit?: Unit | string, storageResolution?: StorageResolution, metricNameAndResolutionMap?: Map<string, StorageResolution>) => void;
/**

@@ -23,0 +26,0 @@ * Validates metric namespace.

@@ -16,10 +16,7 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateTimestamp = exports.validateNamespace = exports.validateMetric = exports.validateDimensionSet = void 0;
const validator_1 = __importDefault(require("validator"));
const Constants_1 = require("../Constants");
const Unit_1 = require("../logger/Unit");
const StorageResolution_1 = require("../logger/StorageResolution");
const DimensionSetExceededError_1 = require("../exceptions/DimensionSetExceededError");

@@ -45,6 +42,6 @@ const InvalidDimensionError_1 = require("../exceptions/InvalidDimensionError");

dimensionSet[key] = value = String(value);
if (!validator_1.default.isAscii(key)) {
if (!new RegExp(Constants_1.Constants.VALID_DIMENSION_REGEX).test(key)) {
throw new InvalidDimensionError_1.InvalidDimensionError(`Dimension key ${key} has invalid characters`);
}
if (!validator_1.default.isAscii(value)) {
if (!new RegExp(Constants_1.Constants.VALID_DIMENSION_REGEX).test(value)) {
throw new InvalidDimensionError_1.InvalidDimensionError(`Dimension value ${value} has invalid characters`);

@@ -76,6 +73,8 @@ }

* @param value
* @param unit
* @param storageResolution
*
* @throws {InvalidMetricError} Metric name must be valid.
*/
const validateMetric = (key, value, unit) => {
const validateMetric = (key, value, unit, storageResolution, metricNameAndResolutionMap) => {
if (key.trim().length == 0) {

@@ -102,2 +101,12 @@ throw new InvalidMetricError_1.InvalidMetricError(`Metric key ${key} must include at least one non-whitespace character`);

}
if (storageResolution !== undefined &&
!Object.values(StorageResolution_1.StorageResolution)
.map((s) => s)
.includes(storageResolution)) {
throw new InvalidMetricError_1.InvalidMetricError(`Metric resolution ${storageResolution} is not valid`);
}
if ((metricNameAndResolutionMap === null || metricNameAndResolutionMap === void 0 ? void 0 : metricNameAndResolutionMap.has(key)) &&
metricNameAndResolutionMap.get(key) !== (storageResolution ? storageResolution : StorageResolution_1.StorageResolution.Standard)) {
throw new InvalidMetricError_1.InvalidMetricError(`Resolution for metrics ${key} is already set. A single log event cannot have a metric with two different resolutions.`);
}
};

@@ -119,3 +128,3 @@ exports.validateMetric = validateMetric;

}
if (!validator_1.default.matches(namespace, Constants_1.Constants.VALID_NAMESPACE_REGEX)) {
if (!new RegExp(Constants_1.Constants.VALID_NAMESPACE_REGEX).test(namespace)) {
throw new InvalidNamespaceError_1.InvalidNamespaceError(`Namespace ${namespace} has invalid characters`);

@@ -132,19 +141,16 @@ }

const validateTimestamp = (timestamp) => {
timestamp = timestamp instanceof Date ? timestamp : new Date(timestamp);
let timestampStr;
try {
timestampStr = timestamp.toISOString();
}
catch (e) {
if (!isDate(timestamp)) {
throw new InvalidTimestampError_1.InvalidTimestampError(`Timestamp ${String(timestamp)} is invalid`);
}
const isTooOld = validator_1.default.isBefore(timestampStr, new Date(Date.now() - Constants_1.Constants.MAX_TIMESTAMP_PAST_AGE).toISOString());
const isTooNew = validator_1.default.isAfter(timestampStr, new Date(Date.now() + Constants_1.Constants.MAX_TIMESTAMP_FUTURE_AGE).toISOString());
if (isTooOld) {
throw new InvalidTimestampError_1.InvalidTimestampError(`Timestamp ${timestampStr} must not be older than ${Constants_1.Constants.MAX_TIMESTAMP_PAST_AGE} milliseconds`);
timestamp = new Date(timestamp);
if (timestamp < new Date(Date.now() - Constants_1.Constants.MAX_TIMESTAMP_PAST_AGE)) {
throw new InvalidTimestampError_1.InvalidTimestampError(`Timestamp ${String(timestamp)} must not be older than ${Constants_1.Constants.MAX_TIMESTAMP_PAST_AGE} milliseconds`);
}
if (isTooNew) {
throw new InvalidTimestampError_1.InvalidTimestampError(`Timestamp ${timestampStr} must not be newer than ${Constants_1.Constants.MAX_TIMESTAMP_FUTURE_AGE} milliseconds`);
if (timestamp > new Date(Date.now() + Constants_1.Constants.MAX_TIMESTAMP_FUTURE_AGE)) {
throw new InvalidTimestampError_1.InvalidTimestampError(`Timestamp ${String(timestamp)} must not be newer than ${Constants_1.Constants.MAX_TIMESTAMP_FUTURE_AGE} milliseconds`);
}
};
exports.validateTimestamp = validateTimestamp;
const isDate = (timestamp) => {
return (timestamp instanceof Date && !isNaN(new Date(timestamp).getTime())) || new Date(timestamp).getTime() > 0;
};
{
"name": "aws-embedded-metrics",
"version": "4.0.0",
"version": "4.1.0",
"description": "AWS Embedded Metrics Client Library",

@@ -36,5 +36,3 @@ "main": "lib/index.js",

"dependencies": {
"@datastructures-js/heap": "^4.0.2",
"@types/validator": "^13.7.6",
"validator": "^13.7.0"
"@datastructures-js/heap": "^4.0.2"
},

@@ -41,0 +39,0 @@ "devDependencies": {

@@ -41,3 +41,3 @@ # aws-embedded-metrics

```js
const { metricScope, Unit } = require("aws-embedded-metrics");
const { metricScope, Unit, StorageResolution } = require("aws-embedded-metrics");

@@ -47,3 +47,4 @@ const myFunc = metricScope(metrics =>

metrics.putDimensions({ Service: "Aggregator" });
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds);
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds, StorageResolution.Standard);
metrics.putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High);
metrics.setProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");

@@ -59,3 +60,3 @@ // ...

```js
const { metricScope, Unit } = require("aws-embedded-metrics");
const { metricScope, Unit, StorageResolution } = require("aws-embedded-metrics");

@@ -65,3 +66,4 @@ const myFunc = metricScope(metrics =>

metrics.putDimensions({ Service: "Aggregator" });
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds);
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds, StorageResolution.Standard);
metrics.putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High);
metrics.setProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");

@@ -77,3 +79,3 @@ // ...

```js
const { createMetricsLogger, Unit } = require("aws-embedded-metrics");
const { createMetricsLogger, Unit, StorageResolution } = require("aws-embedded-metrics");

@@ -83,3 +85,4 @@ const myFunc = async () => {

metrics.putDimensions({ Service: "Aggregator" });
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds);
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds, StorageResolution.Standard);
metrics.putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High);
metrics.setProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");

@@ -114,5 +117,5 @@ // ...

- **putMetric**(String name, Double value, Unit? unit)
- **putMetric**(String name, Double value, Unit? unit, StorageResolution? storageResolution)
Adds a new metric to the current logger context. Multiple metrics using the same key will be appended to an array of values. The Embedded Metric Format supports a maximum of 100 values per key. If more metric values are added than are supported by the format, the logger will be flushed to allow for new metric values to be captured.
Adds a new metric to the current logger context. Multiple metrics using the same key will be appended to an array of values. Multiple metrics cannot have same key and different storage resolution. The Embedded Metric Format supports a maximum of 100 values per key. If more metric values are added than are supported by the format, the logger will be flushed to allow for new metric values to be captured.

@@ -125,6 +128,14 @@ Requirements:

##### Storage Resolution
An OPTIONAL value representing the storage resolution for the corresponding metric. Setting this to `High` specifies this metric as a high-resolution metric, so that CloudWatch stores the metric with sub-minute resolution down to one second. Setting this to `Standard` specifies this metric as a standard-resolution metric, which CloudWatch stores at 1-minute resolution. If a value is not provided, then a default value of `Standard` is assumed. See [Cloud Watch High-Resolution metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html#high-resolution-metrics)
Examples:
```js
// Standard Resolution example
putMetric("Latency", 200, Unit.Milliseconds)
putMetric("Latency", 201, Unit.Milliseconds, StorageResolution.Standard)
// High Resolution example
putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High);
```

@@ -131,0 +142,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc