UNPKG

@aws-lambda-powertools/metrics

Version:
96 lines (95 loc) 3.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DimensionsStore = void 0; require("@aws/lambda-invoke-store"); const env_1 = require("@aws-lambda-powertools/commons/utils/env"); /** * Manages storage of metrics dimensions with automatic context detection. * * This class abstracts the storage mechanism for metrics, automatically * choosing between AsyncLocalStorage (when in async context) and a fallback * object (when outside async context). The decision is made at runtime on * every method call to support Lambda's transition to async contexts. */ class DimensionsStore { #dimensionsKey = Symbol('powertools.metrics.dimensions'); #dimensionSetsKey = Symbol('powertools.metrics.dimensionSets'); #fallbackDimensions = {}; #fallbackDimensionSets = []; #defaultDimensions = {}; #getDimensions() { if (!(0, env_1.shouldUseInvokeStore)()) { return this.#fallbackDimensions; } if (globalThis.awslambda?.InvokeStore === undefined) { throw new Error('InvokeStore is not available'); } const store = globalThis.awslambda.InvokeStore; let stored = store.get(this.#dimensionsKey); if (stored == null) { stored = {}; store.set(this.#dimensionsKey, stored); } return stored; } #getDimensionSets() { if (!(0, env_1.shouldUseInvokeStore)()) { return this.#fallbackDimensionSets; } if (globalThis.awslambda?.InvokeStore === undefined) { throw new Error('InvokeStore is not available'); } const store = globalThis.awslambda.InvokeStore; let stored = store.get(this.#dimensionSetsKey); if (stored == null) { stored = []; store.set(this.#dimensionSetsKey, stored); } return stored; } addDimension(name, value) { this.#getDimensions()[name] = value; return value; } addDimensionSet(dimensionSet) { this.#getDimensionSets().push({ ...dimensionSet }); return dimensionSet; } getDimensions() { return { ...this.#getDimensions() }; } getDimensionSets() { return this.#getDimensionSets().map((set) => ({ ...set })); } clearRequestDimensions() { if (!(0, env_1.shouldUseInvokeStore)()) { this.#fallbackDimensions = {}; this.#fallbackDimensionSets = []; return; } if (globalThis.awslambda?.InvokeStore === undefined) { throw new Error('InvokeStore is not available'); } const store = globalThis.awslambda.InvokeStore; store.set(this.#dimensionsKey, {}); store.set(this.#dimensionSetsKey, []); } clearDefaultDimensions() { this.#defaultDimensions = {}; } getDimensionCount() { const dimensions = this.#getDimensions(); const dimensionSets = this.#getDimensionSets(); const dimensionSetsCount = dimensionSets.reduce((total, dimensionSet) => total + Object.keys(dimensionSet).length, 0); return (Object.keys(dimensions).length + Object.keys(this.#defaultDimensions).length + dimensionSetsCount); } setDefaultDimensions(dimensions) { this.#defaultDimensions = { ...dimensions }; } getDefaultDimensions() { return { ...this.#defaultDimensions }; } } exports.DimensionsStore = DimensionsStore;