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 3.0.1 to 4.0.0

lib/exceptions/InvalidDimensionError.d.ts

6

lib/config/EnvironmentConfigurationProvider.js

@@ -16,5 +16,9 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnvironmentConfigurationProvider = void 0;
const Constants_1 = require("../Constants");
const Environments_1 = require("../environment/Environments");
const Environments_1 = __importDefault(require("../environment/Environments"));
const ENV_VAR_PREFIX = 'AWS_EMF';

@@ -21,0 +25,0 @@ var ConfigKeys;

export declare enum Constants {
MAX_DIMENSION_SET_SIZE = 30,
MAX_DIMENSION_NAME_LENGTH = 250,
MAX_DIMENSION_VALUE_LENGTH = 1024,
MAX_METRIC_NAME_LENGTH = 1024,
MAX_NAMESPACE_LENGTH = 256,
VALID_NAMESPACE_REGEX = "^[a-zA-Z0-9._#:/-]+$",
MAX_TIMESTAMP_PAST_AGE = 1209600000,
MAX_TIMESTAMP_FUTURE_AGE = 7200000,
DEFAULT_NAMESPACE = "aws-embedded-metrics",

@@ -4,0 +11,0 @@ MAX_METRICS_PER_EVENT = 100,

@@ -17,5 +17,13 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Constants = void 0;
var Constants;
(function (Constants) {
Constants[Constants["MAX_DIMENSION_SET_SIZE"] = 30] = "MAX_DIMENSION_SET_SIZE";
Constants[Constants["MAX_DIMENSION_NAME_LENGTH"] = 250] = "MAX_DIMENSION_NAME_LENGTH";
Constants[Constants["MAX_DIMENSION_VALUE_LENGTH"] = 1024] = "MAX_DIMENSION_VALUE_LENGTH";
Constants[Constants["MAX_METRIC_NAME_LENGTH"] = 1024] = "MAX_METRIC_NAME_LENGTH";
Constants[Constants["MAX_NAMESPACE_LENGTH"] = 256] = "MAX_NAMESPACE_LENGTH";
Constants["VALID_NAMESPACE_REGEX"] = "^[a-zA-Z0-9._#:/-]+$";
Constants[Constants["MAX_TIMESTAMP_PAST_AGE"] = 1209600000] = "MAX_TIMESTAMP_PAST_AGE";
Constants[Constants["MAX_TIMESTAMP_FUTURE_AGE"] = 7200000] = "MAX_TIMESTAMP_FUTURE_AGE";
Constants["DEFAULT_NAMESPACE"] = "aws-embedded-metrics";

@@ -22,0 +30,0 @@ Constants[Constants["MAX_METRICS_PER_EVENT"] = 100] = "MAX_METRICS_PER_EVENT";

10

lib/environment/DefaultEnvironment.js

@@ -16,4 +16,8 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Configuration_1 = require("../config/Configuration");
exports.DefaultEnvironment = void 0;
const Configuration_1 = __importDefault(require("../config/Configuration"));
const AgentSink_1 = require("../sinks/AgentSink");

@@ -27,3 +31,3 @@ const Logger_1 = require("../utils/Logger");

if (!Configuration_1.default.serviceName) {
Logger_1.LOG('Unknown ServiceName.');
(0, Logger_1.LOG)('Unknown ServiceName.');
return 'Unknown';

@@ -35,3 +39,3 @@ }

if (!Configuration_1.default.serviceType) {
Logger_1.LOG('Unknown ServiceType.');
(0, Logger_1.LOG)('Unknown ServiceType.');
return 'Unknown';

@@ -38,0 +42,0 @@ }

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

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Configuration_1 = require("../config/Configuration");
exports.EC2Environment = void 0;
const Configuration_1 = __importDefault(require("../config/Configuration"));
const AgentSink_1 = require("../sinks/AgentSink");

@@ -46,9 +50,9 @@ const Fetch_1 = require("../utils/Fetch");

path: tokenPath,
method: "PUT",
headers: { [tokenRequestHeaderKey]: tokenRequestHeaderValue }
method: 'PUT',
headers: { [tokenRequestHeaderKey]: tokenRequestHeaderValue },
};
this.token = yield Fetch_1.fetchString(options);
this.token = yield (0, Fetch_1.fetchString)(options);
}
catch (e) {
Logger_1.LOG(e);
(0, Logger_1.LOG)(e);
return false;

@@ -60,10 +64,10 @@ }

path: metadataPath,
method: "GET",
headers: { [metadataRequestTokenHeaderKey]: this.token }
method: 'GET',
headers: { [metadataRequestTokenHeaderKey]: this.token },
};
this.metadata = yield Fetch_1.fetchJSON(metadataOptions);
this.metadata = yield (0, Fetch_1.fetchJSON)(metadataOptions);
return !!this.metadata;
}
catch (e) {
Logger_1.LOG(e);
(0, Logger_1.LOG)(e);
return false;

@@ -75,3 +79,3 @@ }

if (!Configuration_1.default.serviceName) {
Logger_1.LOG('Unknown ServiceName.');
(0, Logger_1.LOG)('Unknown ServiceName.');
return 'Unknown';

@@ -78,0 +82,0 @@ }

@@ -16,2 +16,25 @@ "use strict";

*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -26,8 +49,12 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Configuration_1 = require("../config/Configuration");
exports.ECSEnvironment = void 0;
const Configuration_1 = __importDefault(require("../config/Configuration"));
const AgentSink_1 = require("../sinks/AgentSink");
const Fetch_1 = require("../utils/Fetch");
const Logger_1 = require("../utils/Logger");
const os = require("os");
const os = __importStar(require("os"));
const Constants_1 = require("../Constants");

@@ -52,15 +79,15 @@ // formats image names into something more readable for a metric name

Configuration_1.default.agentEndpoint = this.fluentBitEndpoint;
Logger_1.LOG(`Using FluentBit configuration. Endpoint: ${this.fluentBitEndpoint}`);
(0, Logger_1.LOG)(`Using FluentBit configuration. Endpoint: ${this.fluentBitEndpoint}`);
}
try {
const options = new URL(process.env.ECS_CONTAINER_METADATA_URI);
this.metadata = yield Fetch_1.fetchJSON(options);
this.metadata = yield (0, Fetch_1.fetchJSON)(options);
if (this.metadata) {
this.metadata.FormattedImageName = formatImageName(this.metadata.Image);
Logger_1.LOG(`Successfully collected ECS Container metadata.`);
(0, Logger_1.LOG)(`Successfully collected ECS Container metadata.`);
}
}
catch (e) {
Logger_1.LOG('Failed to collect ECS Container Metadata.');
Logger_1.LOG(e);
(0, Logger_1.LOG)('Failed to collect ECS Container Metadata.');
(0, Logger_1.LOG)(e);
}

@@ -67,0 +94,0 @@ // return true regardless of whether or not metadata collection

@@ -25,3 +25,7 @@ "use strict";

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanResolveEnvironment = exports.resolveEnvironment = void 0;
const Logger_1 = require("../utils/Logger");

@@ -32,4 +36,4 @@ const DefaultEnvironment_1 = require("./DefaultEnvironment");

const LambdaEnvironment_1 = require("./LambdaEnvironment");
const Configuration_1 = require("../config/Configuration");
const Environments_1 = require("./Environments");
const Configuration_1 = __importDefault(require("../config/Configuration"));
const Environments_1 = __importDefault(require("./Environments"));
const LocalEnvironment_1 = require("./LocalEnvironment");

@@ -65,5 +69,5 @@ const lambdaEnvironment = new LambdaEnvironment_1.LambdaEnvironment();

const discoverEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {
Logger_1.LOG(`Discovering environment`);
(0, Logger_1.LOG)(`Discovering environment`);
for (const envUnderTest of environments) {
Logger_1.LOG(`Testing: ${envUnderTest.constructor.name}`);
(0, Logger_1.LOG)(`Testing: ${envUnderTest.constructor.name}`);
try {

@@ -75,3 +79,3 @@ if (yield envUnderTest.probe()) {

catch (e) {
Logger_1.LOG(`Failed probe: ${envUnderTest.constructor.name}`);
(0, Logger_1.LOG)(`Failed probe: ${envUnderTest.constructor.name}`);
}

@@ -82,3 +86,3 @@ }

const _resolveEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {
Logger_1.LOG('Resolving environment');
(0, Logger_1.LOG)('Resolving environment');
if (environment) {

@@ -88,3 +92,3 @@ return environment;

if (Configuration_1.default.environmentOverride) {
Logger_1.LOG('Environment override supplied', Configuration_1.default.environmentOverride);
(0, Logger_1.LOG)('Environment override supplied', Configuration_1.default.environmentOverride);
// this will be falsy if an invalid configuration value is provided

@@ -96,3 +100,3 @@ environment = getEnvironmentFromOverride();

else {
Logger_1.LOG('Invalid environment provided. Falling back to auto-discovery.', Configuration_1.default.environmentOverride);
(0, Logger_1.LOG)('Invalid environment provided. Falling back to auto-discovery.', Configuration_1.default.environmentOverride);
}

@@ -99,0 +103,0 @@ }

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.LambdaEnvironment = void 0;
const ConsoleSink_1 = require("../sinks/ConsoleSink");

@@ -19,0 +20,0 @@ class LambdaEnvironment {

@@ -16,4 +16,8 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Configuration_1 = require("../config/Configuration");
exports.LocalEnvironment = void 0;
const Configuration_1 = __importDefault(require("../config/Configuration"));
const Logger_1 = require("../utils/Logger");

@@ -30,3 +34,3 @@ const ConsoleSink_1 = require("../sinks/ConsoleSink");

if (!Configuration_1.default.serviceName) {
Logger_1.LOG('Unknown ServiceName.');
(0, Logger_1.LOG)('Unknown ServiceName.');
return 'Unknown';

@@ -38,3 +42,3 @@ }

if (!Configuration_1.default.serviceType) {
Logger_1.LOG('Unknown ServiceType.');
(0, Logger_1.LOG)('Unknown ServiceType.');
return 'Unknown';

@@ -41,0 +45,0 @@ }

"use strict";
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DimensionSetExceededError = void 0;
class DimensionSetExceededError extends Error {

@@ -4,0 +19,0 @@ constructor(msg) {

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

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Configuration = exports.Unit = exports.createMetricsLogger = exports.metricScope = exports.AgentSink = exports.LocalSink = exports.MetricsLogger = void 0;
var MetricsLogger_1 = require("./logger/MetricsLogger");
exports.MetricsLogger = MetricsLogger_1.MetricsLogger;
Object.defineProperty(exports, "MetricsLogger", { enumerable: true, get: function () { return MetricsLogger_1.MetricsLogger; } });
var ConsoleSink_1 = require("./sinks/ConsoleSink");
exports.LocalSink = ConsoleSink_1.ConsoleSink;
Object.defineProperty(exports, "LocalSink", { enumerable: true, get: function () { return ConsoleSink_1.ConsoleSink; } });
var AgentSink_1 = require("./sinks/AgentSink");
exports.AgentSink = AgentSink_1.AgentSink;
Object.defineProperty(exports, "AgentSink", { enumerable: true, get: function () { return AgentSink_1.AgentSink; } });
var MetricScope_1 = require("./logger/MetricScope");
exports.metricScope = MetricScope_1.metricScope;
Object.defineProperty(exports, "metricScope", { enumerable: true, get: function () { return MetricScope_1.metricScope; } });
var MetricsLoggerFactory_1 = require("./logger/MetricsLoggerFactory");
exports.createMetricsLogger = MetricsLoggerFactory_1.createMetricsLogger;
Object.defineProperty(exports, "createMetricsLogger", { enumerable: true, get: function () { return MetricsLoggerFactory_1.createMetricsLogger; } });
var Unit_1 = require("./logger/Unit");
exports.Unit = Unit_1.Unit;
const Configuration_1 = require("./config/Configuration");
Object.defineProperty(exports, "Unit", { enumerable: true, get: function () { return Unit_1.Unit; } });
const Configuration_1 = __importDefault(require("./config/Configuration"));
exports.Configuration = Configuration_1.default;

@@ -43,8 +43,2 @@ import { MetricValues } from './MetricValues';

/**
* Validates dimension set length is not more than Constants.MAX_DIMENSION_SET_SIZE
*
* @param dimensionSet
*/
static validateDimensionSet(dimensionSet: Record<string, string>): void;
/**
* Adds a new set of dimensions. Any time a new dimensions set

@@ -61,4 +55,9 @@ * is added, the set is first prepended by the default dimensions.

*/
setDimensions(dimensionSets: Array<Record<string, string>>): void;
setDimensions(dimensionSets: Array<Record<string, string>>, useDefault?: boolean): void;
/**
* Reset all custom dimensions
* @param useDefault Indicates whether default dimensions should be used
*/
resetDimensions(useDefault: boolean): void;
/**
* Get the current dimensions.

@@ -70,5 +69,7 @@ */

* Creates an independently flushable context.
* Custom dimensions are preserved by default unless preserveDimensions parameter is set.
* @param preserveDimensions Indicates whether custom dimensions should be preserved
*/
createCopyWithContext(): MetricsContext;
createCopyWithContext(preserveDimensions?: boolean): MetricsContext;
}
export {};

@@ -16,8 +16,11 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Configuration_1 = require("../config/Configuration");
exports.MetricsContext = void 0;
const Configuration_1 = __importDefault(require("../config/Configuration"));
const Logger_1 = require("../utils/Logger");
const Validator_1 = require("../utils/Validator");
const MetricValues_1 = require("./MetricValues");
const Constants_1 = require("../Constants");
const DimensionSetExceededError_1 = require("../exceptions/DimensionSetExceededError");
class MetricsContext {

@@ -67,2 +70,3 @@ /**

setNamespace(value) {
(0, Validator_1.validateNamespace)(value);
this.namespace = value;

@@ -74,2 +78,3 @@ }

setTimestamp(timestamp) {
(0, Validator_1.validateTimestamp)(timestamp);
this.timestamp = timestamp;

@@ -84,15 +89,6 @@ this.meta.Timestamp = MetricsContext.resolveMetaTimestamp(timestamp);

setDefaultDimensions(dimensions) {
Logger_1.LOG(`Received default dimensions`, dimensions);
(0, Logger_1.LOG)(`Received default dimensions`, dimensions);
this.defaultDimensions = dimensions;
}
/**
* Validates dimension set length is not more than Constants.MAX_DIMENSION_SET_SIZE
*
* @param dimensionSet
*/
static validateDimensionSet(dimensionSet) {
if (Object.keys(dimensionSet).length > Constants_1.Constants.MAX_DIMENSION_SET_SIZE)
throw new DimensionSetExceededError_1.DimensionSetExceededError(`Maximum number of dimensions per dimension set allowed are ${Constants_1.Constants.MAX_DIMENSION_SET_SIZE}`);
}
/**
* Adds a new set of dimensions. Any time a new dimensions set

@@ -104,3 +100,3 @@ * is added, the set is first prepended by the default dimensions.

putDimensions(incomingDimensionSet) {
MetricsContext.validateDimensionSet(incomingDimensionSet);
(0, Validator_1.validateDimensionSet)(incomingDimensionSet);
// Duplicate dimensions sets are removed before being added to the end of the collection.

@@ -110,3 +106,3 @@ // This ensures the latest dimension key-value is used as a target member on the root EMF node.

const incomingDimensionSetKeys = Object.keys(incomingDimensionSet);
this.dimensions = this.dimensions.filter(existingDimensionSet => {
this.dimensions = this.dimensions.filter((existingDimensionSet) => {
const existingDimensionSetKeys = Object.keys(existingDimensionSet);

@@ -116,3 +112,3 @@ if (existingDimensionSetKeys.length !== incomingDimensionSetKeys.length) {

}
return !existingDimensionSetKeys.every(existingDimensionSetKey => incomingDimensionSetKeys.includes(existingDimensionSetKey));
return !existingDimensionSetKeys.every((existingDimensionSetKey) => incomingDimensionSetKeys.includes(existingDimensionSetKey));
});

@@ -126,8 +122,16 @@ this.dimensions.push(incomingDimensionSet);

*/
setDimensions(dimensionSets) {
this.shouldUseDefaultDimensions = false;
dimensionSets.forEach(dimensionSet => MetricsContext.validateDimensionSet(dimensionSet));
setDimensions(dimensionSets, useDefault = false) {
dimensionSets.forEach((dimensionSet) => (0, Validator_1.validateDimensionSet)(dimensionSet));
this.shouldUseDefaultDimensions = useDefault;
this.dimensions = dimensionSets;
}
/**
* Reset all custom dimensions
* @param useDefault Indicates whether default dimensions should be used
*/
resetDimensions(useDefault) {
this.shouldUseDefaultDimensions = useDefault;
this.dimensions = [];
}
/**
* Get the current dimensions.

@@ -151,3 +155,3 @@ */

// may get updated asynchronously by environment detection
return this.dimensions.map(custom => {
return this.dimensions.map((custom) => {
return Object.assign(Object.assign({}, this.defaultDimensions), custom);

@@ -157,2 +161,3 @@ });

putMetric(key, value, unit) {
(0, Validator_1.validateMetric)(key, value, unit);
const currentMetric = this.metrics.get(key);

@@ -168,7 +173,9 @@ if (currentMetric) {

* Creates an independently flushable context.
* Custom dimensions are preserved by default unless preserveDimensions parameter is set.
* @param preserveDimensions Indicates whether custom dimensions should be preserved
*/
createCopyWithContext() {
return new MetricsContext(this.namespace, Object.assign({}, this.properties), Object.assign([], this.dimensions), this.defaultDimensions, this.shouldUseDefaultDimensions, this.timestamp);
createCopyWithContext(preserveDimensions = true) {
return new MetricsContext(this.namespace, Object.assign({}, this.properties), preserveDimensions ? Object.assign([], this.dimensions) : [], this.defaultDimensions, this.shouldUseDefaultDimensions, this.timestamp);
}
}
exports.MetricsContext = MetricsContext;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.metricScope = void 0;
const Logger_1 = require("../utils/Logger");

@@ -34,3 +35,3 @@ const MetricsLoggerFactory_1 = require("./MetricsLoggerFactory");

const wrappedHandler = (...args) => __awaiter(void 0, void 0, void 0, function* () {
const metrics = MetricsLoggerFactory_1.createMetricsLogger();
const metrics = (0, MetricsLoggerFactory_1.createMetricsLogger)();
try {

@@ -44,3 +45,3 @@ return yield handler(metrics)(...args);

catch (e) {
Logger_1.LOG('Failed to flush metrics', e);
(0, Logger_1.LOG)('Failed to flush metrics', e);
}

@@ -47,0 +48,0 @@ }

@@ -12,2 +12,3 @@ import { EnvironmentProvider } from '../environment/EnvironmentDetector';

private resolveEnvironment;
flushPreserveDimensions: boolean;
constructor(resolveEnvironment: EnvironmentProvider, context?: MetricsContext);

@@ -42,8 +43,18 @@ /**

* Overwrite all dimensions on this MetricsLogger instance.
* @see [CloudWatch Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)
*
* @param dimensionSets
* @see [CloudWatch Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)
* @param {Array<Record<string, string>> | Record<string, string>} dimensionSetOrSets Dimension sets to overwrite with
* @param {boolean} [useDefault=false] whether to use default dimensions
*/
setDimensions(...dimensionSets: Array<Record<string, string>>): MetricsLogger;
setDimensions(dimensionSet: Record<string, string>, useDefault: boolean): MetricsLogger;
setDimensions(dimensionSet: Record<string, string>): MetricsLogger;
setDimensions(dimensionSets: Array<Record<string, string>>, useDefault: boolean): MetricsLogger;
setDimensions(dimensionSets: Array<Record<string, string>>): MetricsLogger;
/**
* Clear all custom dimensions on this MetricsLogger instance
*
* @param useDefault indicates whether default dimensions should be used
*/
resetDimensions(useDefault: boolean): MetricsLogger;
/**
* Put a metric value.

@@ -50,0 +61,0 @@ * This value will be emitted to CloudWatch Metrics asyncronously and does not contribute to your

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

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Configuration_1 = require("../config/Configuration");
exports.MetricsLogger = void 0;
const Configuration_1 = __importDefault(require("../config/Configuration"));
const MetricsContext_1 = require("./MetricsContext");

@@ -49,2 +53,3 @@ /**

this.context = context || MetricsContext_1.MetricsContext.empty();
this.flushPreserveDimensions = true;
}

@@ -65,3 +70,3 @@ /**

yield sink.accept(this.context);
this.context = this.context.createCopyWithContext();
this.context = this.context.createCopyWithContext(this.flushPreserveDimensions);
});

@@ -97,10 +102,18 @@ }

}
setDimensions(dimensionSetOrSets, useDefault = false) {
if (Array.isArray(dimensionSetOrSets)) {
this.context.setDimensions(dimensionSetOrSets, useDefault);
}
else {
this.context.setDimensions([dimensionSetOrSets], useDefault);
}
return this;
}
/**
* Overwrite all dimensions on this MetricsLogger instance.
* Clear all custom dimensions on this MetricsLogger instance
*
* @param dimensionSets
* @see [CloudWatch Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)
* @param useDefault indicates whether default dimensions should be used
*/
setDimensions(...dimensionSets) {
this.context.setDimensions(dimensionSets);
resetDimensions(useDefault) {
this.context.resetDimensions(useDefault);
return this;

@@ -107,0 +120,0 @@ }

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.createMetricsLogger = void 0;
const __1 = require("..");

@@ -23,5 +24,4 @@ const EnvironmentDetector_1 = require("../environment/EnvironmentDetector");

const context = MetricsContext_1.MetricsContext.empty();
const logger = new __1.MetricsLogger(EnvironmentDetector_1.resolveEnvironment, context);
return logger;
return new __1.MetricsLogger(EnvironmentDetector_1.resolveEnvironment, context);
};
exports.createMetricsLogger = createMetricsLogger;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -17,2 +16,4 @@ * Copyright 2019 Amazon.com, Inc. or its affiliates.

*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetricValues = void 0;
class MetricValues {

@@ -19,0 +20,0 @@ constructor(value, unit) {

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.Unit = void 0;
var Unit;

@@ -19,0 +20,0 @@ (function (Unit) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LogSerializer = void 0;
/*

@@ -31,10 +32,4 @@ * Copyright 2019 Amazon.com, Inc. or its affiliates.

let dimensionProperties = {};
context.getDimensions().forEach(d => {
// we can only take the first 9 defined dimensions
// the reason we do this in the serializer is because
// it is possible that other sinks or formats can
// support more dimensions
// in the future it may make sense to introduce a higher-order
// representation for sink-specific validations
const keys = Object.keys(d);
context.getDimensions().forEach(dimensionSet => {
const keys = Object.keys(dimensionSet);
if (keys.length > Constants_1.Constants.MAX_DIMENSION_SET_SIZE) {

@@ -46,3 +41,3 @@ const errMsg = `Maximum number of dimensions allowed are ${Constants_1.Constants.MAX_DIMENSION_SET_SIZE}.` +

dimensionKeys.push(keys);
dimensionProperties = Object.assign(Object.assign({}, dimensionProperties), d);
dimensionProperties = Object.assign(Object.assign({}, dimensionProperties), dimensionSet);
});

@@ -60,3 +55,5 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any

const eventBatches = [];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
let currentBody = createBody();
// eslint-disable-next-line
const currentMetricsInBody = () => currentBody._aws.CloudWatchMetrics[0].Metrics.length;

@@ -67,2 +64,3 @@ const hasMaxMetrics = () => currentMetricsInBody() === Constants_1.Constants.MAX_METRICS_PER_EVENT;

eventBatches.push(JSON.stringify(currentBody));
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
currentBody = createBody();

@@ -84,4 +82,7 @@ };

? metric.values[startIndex]
: metric.values.slice(startIndex, startIndex + Constants_1.Constants.MAX_VALUES_PER_METRIC);
: // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
metric.values.slice(startIndex, startIndex + Constants_1.Constants.MAX_VALUES_PER_METRIC);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
currentBody[metricProgress.name] = metricValue;
// eslint-disable-next-line
currentBody._aws.CloudWatchMetrics[0].Metrics.push({ Name: metricProgress.name, Unit: metric.unit });

@@ -88,0 +89,0 @@ metricProgress.numLeft -= Constants_1.Constants.MAX_VALUES_PER_METRIC;

@@ -27,5 +27,5 @@ "use strict";

default:
throw new Error(`Version '${version}' is not supported.`);
throw new Error(`Unsupported version.`);
}
};
exports.default = { createSerializer, FormatVersion };

@@ -25,5 +25,9 @@ "use strict";

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentSink = void 0;
const url = require("url");
const Configuration_1 = require("../config/Configuration");
const Configuration_1 = __importDefault(require("../config/Configuration"));
const LogSerializer_1 = require("../serializers/LogSerializer");

@@ -47,7 +51,7 @@ const Logger_1 = require("../utils/Logger");

if (!parsedUrl.hostname || !parsedUrl.port || !parsedUrl.protocol) {
Logger_1.LOG(`Failed to parse the provided agent endpoint. Falling back to the default TCP endpoint.`, parsedUrl);
(0, Logger_1.LOG)(`Failed to parse the provided agent endpoint. Falling back to the default TCP endpoint.`, parsedUrl);
return defaultTcpEndpoint;
}
if (parsedUrl.protocol !== TCP && parsedUrl.protocol !== UDP) {
Logger_1.LOG(`The provided agent endpoint protocol '${parsedUrl.protocol}' is not supported. Please use TCP or UDP. Falling back to the default TCP endpoint.`, parsedUrl);
(0, Logger_1.LOG)(`The provided agent endpoint protocol '${parsedUrl.protocol}' is not supported. Please use TCP or UDP. Falling back to the default TCP endpoint.`, parsedUrl);
return defaultTcpEndpoint;

@@ -62,3 +66,3 @@ }

catch (e) {
Logger_1.LOG('Failed to parse the provided agent endpoint', e);
(0, Logger_1.LOG)('Failed to parse the provided agent endpoint', e);
return defaultTcpEndpoint;

@@ -80,3 +84,3 @@ }

this.socketClient = this.getSocketClient(this.endpoint);
Logger_1.LOG('Using socket client', this.socketClient.constructor.name);
(0, Logger_1.LOG)('Using socket client', this.socketClient.constructor.name);
}

@@ -92,3 +96,3 @@ accept(context) {

const events = this.serializer.serialize(context);
Logger_1.LOG(`Sending {} events to socket.`, events.length);
(0, Logger_1.LOG)(`Sending {} events to socket.`, events.length);
for (let index = 0; index < events.length; index++) {

@@ -103,4 +107,5 @@ const event = events[index];

getSocketClient(endpoint) {
Logger_1.LOG('Getting socket client for connection.', endpoint);
(0, Logger_1.LOG)('Getting socket client for connection.', endpoint);
const client = endpoint.protocol === TCP ? new TcpClient_1.TcpClient(endpoint) : new UdpClient_1.UdpClient(endpoint);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
client.warmup();

@@ -107,0 +112,0 @@ return client;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.TcpClient = void 0;
const net = require("net");

@@ -38,4 +39,5 @@ const Logger_1 = require("../../utils/Logger");

.on('end', () => this.disconnect('end'))
.on('data', data => Logger_1.LOG('TcpClient received data.', data));
// Used to create an initial connection on the socket right after creation to avoid socket failures.
.on('data', data => (0, Logger_1.LOG)('TcpClient received data.', data));
// Used to create an initial connection on the socket right after creation to avoid socket failures.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.initialConnect.apply(this);

@@ -61,3 +63,3 @@ }

catch (err) {
Logger_1.LOG('Failed to connect', err);
(0, Logger_1.LOG)('Failed to connect', err);
}

@@ -72,3 +74,3 @@ });

const onSendError = (err) => {
Logger_1.LOG('Failed to write', err);
(0, Logger_1.LOG)('Failed to write', err);
reject(err);

@@ -78,3 +80,3 @@ };

if (!err) {
Logger_1.LOG('Write succeeded');
(0, Logger_1.LOG)('Write succeeded');
resolve();

@@ -87,3 +89,3 @@ }

if (!wasFlushedToKernel) {
Logger_1.LOG('TcpClient data was not flushed to kernel buffer and was queued in memory.');
(0, Logger_1.LOG)('TcpClient data was not flushed to kernel buffer and was queued in memory.');
}

@@ -94,3 +96,3 @@ });

disconnect(eventName) {
Logger_1.LOG('TcpClient disconnected due to:', eventName);
(0, Logger_1.LOG)('TcpClient disconnected due to:', eventName);
this.socket.removeAllListeners();

@@ -116,3 +118,3 @@ this.socket.destroy();

}
Logger_1.LOG('TCP Client received error', e);
(0, Logger_1.LOG)('TCP Client received error', e);
this.disconnect(e.message);

@@ -123,3 +125,3 @@ reject(e);

this.socket.removeListener('error', onError);
Logger_1.LOG('TcpClient connected.', this.endpoint);
(0, Logger_1.LOG)('TcpClient connected.', this.endpoint);
resolve();

@@ -140,3 +142,3 @@ };

default:
Logger_1.LOG('opening connection with socket in state: ', this.socket.readyState);
(0, Logger_1.LOG)('opening connection with socket in state: ', this.socket.readyState);
this.socket.connect(this.endpoint.port, this.endpoint.host, onConnect).once('error', onError);

@@ -143,0 +145,0 @@ break;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.UdpClient = void 0;
const dgram = require("dgram");

@@ -42,3 +43,3 @@ const Logger_1 = require("../../utils/Logger");

if (error) {
Logger_1.LOG(error);
(0, Logger_1.LOG)(error);
}

@@ -45,0 +46,0 @@ client.close();

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.ConsoleSink = void 0;
const LogSerializer_1 = require("../serializers/LogSerializer");

@@ -19,0 +20,0 @@ /**

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchString = exports.fetchJSON = exports.fetch = void 0;
const http_1 = require("http");

@@ -36,9 +37,9 @@ const SOCKET_TIMEOUT = 1000;

return new Promise((resolve, reject) => {
const request = http_1.request(options, (response) => {
const request = (0, http_1.request)(options, (response) => {
if (!response.statusCode) {
reject(`Received undefined response status code from '${options.host}${options.path}'`);
reject(`Received undefined response status code from '${options.host || 'unknown'}/${options.path || 'unknown'}'`);
return;
}
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
reject(new Error(`Failed to load page, status code: ${response.statusCode}`));
return;

@@ -58,4 +59,3 @@ }

});
})
.on('error', (err) => {
}).on('error', (err) => {
reject(err);

@@ -66,3 +66,3 @@ });

request.abort();
reject(`Socket timeout while connecting to '${options.host}${options.path}'`);
reject(`Socket timeout while connecting to '${options.host || 'unknown'}/${options.path || 'unknown'}'`);
});

@@ -69,0 +69,0 @@ socket.setTimeout(SOCKET_TIMEOUT);

@@ -16,4 +16,8 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Configuration_1 = require("../config/Configuration");
exports.LOG = void 0;
const Configuration_1 = __importDefault(require("../config/Configuration"));
const LOG = (...args) => {

@@ -20,0 +24,0 @@ if (Configuration_1.default.debuggingLoggingEnabled) {

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.now = void 0;
const perf_hooks_1 = require("perf_hooks");

@@ -19,0 +20,0 @@ /**

{
"name": "aws-embedded-metrics",
"version": "3.0.1",
"version": "4.0.0",
"description": "AWS Embedded Metrics Client Library",

@@ -36,21 +36,23 @@ "main": "lib/index.js",

"dependencies": {
"@datastructures-js/heap": "^4.0.2"
"@datastructures-js/heap": "^4.0.2",
"@types/validator": "^13.7.6",
"validator": "^13.7.0"
},
"devDependencies": {
"@faker-js/faker": "^7.5.0",
"@types/faker": "^4.1.5",
"@types/jest": "^26.0.22",
"@types/node": "^12.0.8",
"@typescript-eslint/eslint-plugin": "^2.23.0",
"@typescript-eslint/parser": "^2.23.0",
"@typescript-eslint/eslint-plugin": "^5.36.1",
"@typescript-eslint/parser": "^5.36.1",
"aws-sdk": "^2.551.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-prettier": "^3.1.2",
"faker": "^4.1.0",
"eslint": "^8.23.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^26.6.3",
"node-notifier": ">=8.0.1",
"npm-pack-zip": "^1.2.7",
"prettier": "^1.19.1",
"npm-pack-zip": "^1.3.0",
"prettier": "^2.7.1",
"ts-jest": "^26.5.4",
"typescript": "^3.8.0",
"typescript": "^4.8.2",
"y18n": ">=4.0.1"

@@ -57,0 +59,0 @@ },

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

- Values must be in the range of 8.515920e-109 to 1.174271e+108. In addition, special values (for example, NaN, +Infinity, -Infinity) are not supported.
- Units must meet CW Metrics unit requirements, if not it will default to None.
- Metrics must meet CloudWatch Metrics requirements, otherwise a `InvalidMetricError` will be thrown. See [MetricDatum](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html) for valid values.

@@ -153,2 +153,3 @@ Examples:

- ASCII characters only
- Dimensions must meet CloudWatch Dimensions requirements, otherwise a `InvalidDimensionError` or `DimensionSetExceededError` will be thrown. See [Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_Dimension.html) for valid values.

@@ -161,5 +162,5 @@ Examples:

- **setDimensions**(Record<String, String>[] dimensions...)
- **setDimensions**(Record<String, String> | Record<String, String>[] dimensions, boolean useDefault)
Explicitly override all dimensions. This will remove the default dimensions.
Explicitly override all dimensions. This will remove the default dimensions unless the `useDefault` parameter is set to `true` (defaults to false).

@@ -173,2 +174,3 @@ **WARNING**: Every distinct value will result in a new CloudWatch Metric.

- ASCII characters only
- Dimensions must meet CloudWatch Dimensions requirements, otherwise a `InvalidDimensionError` or `DimensionSetExceededError` will be thrown. See [Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_Dimension.html) for valid values.

@@ -178,7 +180,24 @@ Examples:

```js
setDimensions(
// Overwrites custom dimensions - keeps default dimensions
setDimensions({Operation: "Aggregator"}, true)
```
```js
// Overwrites custom dimensions - removes default dimensions
setDimensions([
{ Operation: "Aggregator" },
{ Operation: "Aggregator", DeviceType: "Actuator" })
{ Operation: "Aggregator", DeviceType: "Actuator" }
])
```
- **resetDimensions**(boolean useDefault)
Explicitly clear all custom dimensions. Set `useDefault` to `true` to keep the default dimensions.
Example:
```js
resetDimensions(false) // this will clear all custom dimensions as well as disable default dimensions
```
- **setNamespace**(String value)

@@ -192,4 +211,5 @@

- Name must be ASCII characters only
- Namespaces must meet CloudWatch Namespace requirements, otherwise a `InvalidNamespaceError` will be thrown. See [Namespace](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Namespace) for valid values.
Examples:
Example:

@@ -207,3 +227,3 @@ ```js

Requirements:
* Date or Unix epoch millis, up to two weeks in the past and up to two hours in the future, as enforced by [CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#about_timestamp).
* Date or Unix epoch millis, up to two weeks in the past and up to two hours in the future, as enforced by [CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#about_timestamp). If the timestamp is outside of this range, a `InvalidTimestampError` will be thrown.

@@ -219,4 +239,21 @@ Examples:

Flushes the current MetricsContext to the configured sink and resets all properties, dimensions and metric values. The namespace and default dimensions will be preserved across flushes. Timestamp will be preserved if set explicitly via `setTimestamp()`.
Flushes the current MetricsContext to the configured sink and resets all properties and metric values. The namespace and default dimensions will be preserved across flushes. Custom dimensions are preserved by default, but this behavior can be changed by setting `logger.flushPreserveDimensions = false`. Timestamp will be preserved if set explicitly via `setTimestamp()`.
Examples:
```js
logger.flush() // custom and default dimensions will be preserved after each flush
```
```js
logger.flushPreserveDimensions = false
logger.flush() // only default dimensions will be preserved after flush()
```
```js
logger.flushPreserveDimensions = false
logger.resetDimensions(false)
logger.flush() // default dimensions are disabled - no dimensions will be preserved after flush()
```
## Configuration

@@ -223,0 +260,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