diff --git a/packages/metrics/src/Metrics.ts b/packages/metrics/src/Metrics.ts index 94d615c108..64f1540945 100644 --- a/packages/metrics/src/Metrics.ts +++ b/packages/metrics/src/Metrics.ts @@ -798,9 +798,13 @@ class Metrics extends Utility implements MetricsInterface { const newDimensions = this.#sanitizeDimensions(dimensions); const currentDefaultDimensions = this.#dimensionsStore.getDefaultDimensions(); - const currentCount = Object.keys(currentDefaultDimensions).length; - const newSetCount = Object.keys(newDimensions).length; - if (currentCount + newSetCount >= MAX_DIMENSION_COUNT) { + const newKeysCount = Object.keys(newDimensions).filter( + (key) => !Object.hasOwn(currentDefaultDimensions, key) + ).length; + if ( + this.#dimensionsStore.getDimensionCount() + newKeysCount >= + MAX_DIMENSION_COUNT + ) { throw new RangeError( `The number of metric dimensions must be lower than ${MAX_DIMENSION_COUNT}` ); diff --git a/packages/metrics/tests/unit/dimensions.test.ts b/packages/metrics/tests/unit/dimensions.test.ts index d7c6febd3c..774a748795 100644 --- a/packages/metrics/tests/unit/dimensions.test.ts +++ b/packages/metrics/tests/unit/dimensions.test.ts @@ -361,6 +361,42 @@ describe('Working with dimensions', () => { ); }); + it('throws when setDefaultDimensions would exceed the limit with existing regular dimensions', () => { + // Prepare + const metrics = new Metrics({ + singleMetric: true, + }); + + // Act + for (let i = 1; i < MAX_DIMENSION_COUNT - 1; i++) { + metrics.addDimension(`regular-${i}`, 'test'); + } + + // Assess + expect(() => + metrics.setDefaultDimensions({ 'new-default': 'test' }) + ).toThrow( + `The number of metric dimensions must be lower than ${MAX_DIMENSION_COUNT}` + ); + }); + + it('allows overriding existing default dimension keys without triggering the limit', () => { + // Prepare + const metrics = new Metrics({ + singleMetric: true, + }); + + // Act + for (let i = 1; i < MAX_DIMENSION_COUNT - 1; i++) { + metrics.setDefaultDimensions({ [`dimension-${i}`]: 'test' }); + } + + // Assess + expect(() => + metrics.setDefaultDimensions({ 'dimension-1': 'updated' }) + ).not.toThrow(); + }); + it('throws when adding dimension sets would exceed the limit', () => { // Prepare const metrics = new Metrics({