UNPKG

@aws-lambda-powertools/metrics

Version:
93 lines (92 loc) 3.34 kB
import '@aws/lambda-invoke-store'; import { shouldUseInvokeStore } from '@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 (!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 (!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 (!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 }; } } export { DimensionsStore };