|
| 1 | +import { InvokeStore } from '@aws/lambda-invoke-store'; |
| 2 | +import type { Dimensions } from './types/Metrics.js'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Manages storage of metrics dimensions with automatic context detection. |
| 6 | + * |
| 7 | + * This class abstracts the storage mechanism for metrics, automatically |
| 8 | + * choosing between AsyncLocalStorage (when in async context) and a fallback |
| 9 | + * object (when outside async context). The decision is made at runtime on |
| 10 | + * every method call to support Lambda's transition to async contexts. |
| 11 | + */ |
| 12 | +class DimensionsStore { |
| 13 | + #fallbackDimensions: Dimensions = {}; |
| 14 | + #fallbackDimensionSets: Dimensions[] = []; |
| 15 | + |
| 16 | + #getDimensions(): Dimensions { |
| 17 | + if (InvokeStore.getContext() === undefined) { |
| 18 | + return this.#fallbackDimensions; |
| 19 | + } |
| 20 | + |
| 21 | + let stored = InvokeStore.get('dimensions') as Dimensions | undefined; |
| 22 | + if (stored == null) { |
| 23 | + stored = {}; |
| 24 | + InvokeStore.set('dimensions', stored); |
| 25 | + } |
| 26 | + return stored; |
| 27 | + } |
| 28 | + |
| 29 | + #getDimensionSets(): Dimensions[] { |
| 30 | + if (InvokeStore.getContext() !== undefined) { |
| 31 | + let stored = InvokeStore.get('dimensionSets') as Dimensions[] | undefined; |
| 32 | + if (stored == null) { |
| 33 | + stored = []; |
| 34 | + InvokeStore.set('dimensionSets', stored); |
| 35 | + } |
| 36 | + return stored; |
| 37 | + } |
| 38 | + return this.#fallbackDimensionSets; |
| 39 | + } |
| 40 | + |
| 41 | + addDimension(name: string, value: string): void { |
| 42 | + this.#getDimensions()[name] = value; |
| 43 | + } |
| 44 | + |
| 45 | + addDimensionSet(dimensionSet: Dimensions): void { |
| 46 | + this.#getDimensionSets().push({ ...dimensionSet }); |
| 47 | + } |
| 48 | + |
| 49 | + getDimensions(): Dimensions { |
| 50 | + return { ...this.#getDimensions() }; |
| 51 | + } |
| 52 | + |
| 53 | + getDimensionSets(): Dimensions[] { |
| 54 | + return this.#getDimensionSets().map((set) => ({ ...set })); |
| 55 | + } |
| 56 | + |
| 57 | + clear(): void { |
| 58 | + if (InvokeStore.getContext() !== undefined) { |
| 59 | + InvokeStore.set('dimensions', {}); |
| 60 | + InvokeStore.set('dimensionSets', []); |
| 61 | + } else { |
| 62 | + this.#fallbackDimensions = {}; |
| 63 | + this.#fallbackDimensionSets = []; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +export { DimensionsStore }; |
0 commit comments