{"version":3,"file":"Histogram.cjs","names":["binarySearchUB"],"sources":["../../src/aggregator/Histogram.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Accumulation, AccumulationRecord, Aggregator } from './types';\nimport { AggregatorKind } from './types';\nimport type { HistogramMetricData } from '../export/MetricData';\nimport { DataPointType, InstrumentType } from '../export/MetricData';\nimport type { HrTime } from '@opentelemetry/api';\nimport type { Maybe } from '../utils';\nimport { binarySearchUB } from '../utils';\nimport type { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\n\n/**\n * Internal value type for HistogramAggregation.\n * Differs from the exported type as undefined sum/min/max complicate arithmetic\n * performed by this aggregation, but are required to be undefined in the exported types.\n */\ninterface InternalHistogram {\n  buckets: {\n    boundaries: number[];\n    counts: number[];\n  };\n  sum: number;\n  count: number;\n  hasMinMax: boolean;\n  min: number;\n  max: number;\n}\n\nfunction createNewEmptyCheckpoint(boundaries: number[]): InternalHistogram {\n  const counts = boundaries.map(() => 0);\n  counts.push(0);\n  return {\n    buckets: {\n      boundaries,\n      counts,\n    },\n    sum: 0,\n    count: 0,\n    hasMinMax: false,\n    min: Infinity,\n    max: -Infinity,\n  };\n}\n\nexport class HistogramAccumulation implements Accumulation {\n  public startTime;\n  private readonly _boundaries;\n  private _recordMinMax;\n  private _current;\n\n  constructor(\n    startTime: HrTime,\n    boundaries: number[],\n    recordMinMax = true,\n    current: InternalHistogram = createNewEmptyCheckpoint(boundaries)\n  ) {\n    this.startTime = startTime;\n    this._boundaries = boundaries;\n    this._recordMinMax = recordMinMax;\n    this._current = current;\n  }\n\n  record(value: number): void {\n    // NaN does not fall into any bucket, is not zero and should not be counted,\n    // NaN is never greater than max nor less than min, therefore return as there's nothing for us to do.\n    if (Number.isNaN(value)) {\n      return;\n    }\n\n    this._current.count += 1;\n    this._current.sum += value;\n\n    if (this._recordMinMax) {\n      this._current.min = Math.min(value, this._current.min);\n      this._current.max = Math.max(value, this._current.max);\n      this._current.hasMinMax = true;\n    }\n\n    const idx = binarySearchUB(this._boundaries, value);\n    this._current.buckets.counts[idx] += 1;\n  }\n\n  setStartTime(startTime: HrTime): void {\n    this.startTime = startTime;\n  }\n\n  toPointValue(): InternalHistogram {\n    return this._current;\n  }\n}\n\n/**\n * Basic aggregator which observes events and counts them in pre-defined buckets\n * and provides the total sum and count of all observations.\n */\nexport class HistogramAggregator implements Aggregator<HistogramAccumulation> {\n  public kind: AggregatorKind.HISTOGRAM = AggregatorKind.HISTOGRAM;\n  private readonly _boundaries: number[];\n  private readonly _recordMinMax: boolean;\n\n  /**\n   * @param _boundaries sorted upper bounds of recorded values.\n   * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded.\n   */\n  constructor(boundaries: number[], recordMinMax: boolean) {\n    this._boundaries = boundaries;\n    this._recordMinMax = recordMinMax;\n  }\n\n  createAccumulation(startTime: HrTime) {\n    return new HistogramAccumulation(\n      startTime,\n      this._boundaries,\n      this._recordMinMax\n    );\n  }\n\n  /**\n   * Return the result of the merge of two histogram accumulations. As long as one Aggregator\n   * instance produces all Accumulations with constant boundaries we don't need to worry about\n   * merging accumulations with different boundaries.\n   */\n  merge(\n    previous: HistogramAccumulation,\n    delta: HistogramAccumulation\n  ): HistogramAccumulation {\n    const previousValue = previous.toPointValue();\n    const deltaValue = delta.toPointValue();\n\n    const previousCounts = previousValue.buckets.counts;\n    const deltaCounts = deltaValue.buckets.counts;\n\n    const mergedCounts = new Array(previousCounts.length);\n    for (let idx = 0; idx < previousCounts.length; idx++) {\n      mergedCounts[idx] = previousCounts[idx] + deltaCounts[idx];\n    }\n\n    let min = Infinity;\n    let max = -Infinity;\n\n    if (this._recordMinMax) {\n      if (previousValue.hasMinMax && deltaValue.hasMinMax) {\n        min = Math.min(previousValue.min, deltaValue.min);\n        max = Math.max(previousValue.max, deltaValue.max);\n      } else if (previousValue.hasMinMax) {\n        min = previousValue.min;\n        max = previousValue.max;\n      } else if (deltaValue.hasMinMax) {\n        min = deltaValue.min;\n        max = deltaValue.max;\n      }\n    }\n\n    return new HistogramAccumulation(\n      previous.startTime,\n      previousValue.buckets.boundaries,\n      this._recordMinMax,\n      {\n        buckets: {\n          boundaries: previousValue.buckets.boundaries,\n          counts: mergedCounts,\n        },\n        count: previousValue.count + deltaValue.count,\n        sum: previousValue.sum + deltaValue.sum,\n        hasMinMax:\n          this._recordMinMax &&\n          (previousValue.hasMinMax || deltaValue.hasMinMax),\n        min: min,\n        max: max,\n      }\n    );\n  }\n\n  /**\n   * Returns a new DELTA aggregation by comparing two cumulative measurements.\n   */\n  diff(\n    previous: HistogramAccumulation,\n    current: HistogramAccumulation\n  ): HistogramAccumulation {\n    const previousValue = previous.toPointValue();\n    const currentValue = current.toPointValue();\n\n    const previousCounts = previousValue.buckets.counts;\n    const currentCounts = currentValue.buckets.counts;\n\n    const diffedCounts = new Array(previousCounts.length);\n    for (let idx = 0; idx < previousCounts.length; idx++) {\n      diffedCounts[idx] = currentCounts[idx] - previousCounts[idx];\n    }\n\n    return new HistogramAccumulation(\n      current.startTime,\n      previousValue.buckets.boundaries,\n      this._recordMinMax,\n      {\n        buckets: {\n          boundaries: previousValue.buckets.boundaries,\n          counts: diffedCounts,\n        },\n        count: currentValue.count - previousValue.count,\n        sum: currentValue.sum - previousValue.sum,\n        hasMinMax: false,\n        min: Infinity,\n        max: -Infinity,\n      }\n    );\n  }\n\n  toMetricData(\n    descriptor: InstrumentDescriptor,\n    aggregationTemporality: AggregationTemporality,\n    accumulationByAttributes: AccumulationRecord<HistogramAccumulation>[],\n    endTime: HrTime\n  ): Maybe<HistogramMetricData> {\n    return {\n      descriptor,\n      aggregationTemporality,\n      dataPointType: DataPointType.HISTOGRAM,\n      dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {\n        const pointValue = accumulation.toPointValue();\n\n        // determine if instrument allows negative values.\n        const allowsNegativeValues =\n          descriptor.type === InstrumentType.GAUGE ||\n          descriptor.type === InstrumentType.UP_DOWN_COUNTER ||\n          descriptor.type === InstrumentType.OBSERVABLE_GAUGE ||\n          descriptor.type === InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;\n\n        return {\n          attributes,\n          startTime: accumulation.startTime,\n          endTime,\n          value: {\n            min: pointValue.hasMinMax ? pointValue.min : undefined,\n            max: pointValue.hasMinMax ? pointValue.max : undefined,\n            sum: !allowsNegativeValues ? pointValue.sum : undefined,\n            buckets: pointValue.buckets,\n            count: pointValue.count,\n          },\n        };\n      }),\n    };\n  }\n}\n"],"mappings":";;;AAgCA,SAAS,yBAAyB,YAAyC;CACzE,MAAM,SAAS,WAAW,UAAU,CAAC;CACrC,OAAO,KAAK,CAAC;CACb,OAAO;EACL,SAAS;GACP;GACA;EACF;EACA,KAAK;EACL,OAAO;EACP,WAAW;EACX,KAAK;EACL,KAAK;CACP;AACF;AAEA,IAAa,wBAAb,MAA2D;CACzD;CACA;CACA;CACA;CAEA,YACE,WACA,YACA,eAAe,MACf,UAA6B,yBAAyB,UAAU,GAChE;EACA,KAAK,YAAY;EACjB,KAAK,cAAc;EACnB,KAAK,gBAAgB;EACrB,KAAK,WAAW;CAClB;CAEA,OAAO,OAAqB;EAG1B,IAAI,OAAO,MAAM,KAAK,GACpB;EAGF,KAAK,SAAS,SAAS;EACvB,KAAK,SAAS,OAAO;EAErB,IAAI,KAAK,eAAe;GACtB,KAAK,SAAS,MAAM,KAAK,IAAI,OAAO,KAAK,SAAS,GAAG;GACrD,KAAK,SAAS,MAAM,KAAK,IAAI,OAAO,KAAK,SAAS,GAAG;GACrD,KAAK,SAAS,YAAY;EAC5B;EAEA,MAAM,MAAMA,cAAAA,eAAe,KAAK,aAAa,KAAK;EAClD,KAAK,SAAS,QAAQ,OAAO,QAAQ;CACvC;CAEA,aAAa,WAAyB;EACpC,KAAK,YAAY;CACnB;CAEA,eAAkC;EAChC,OAAO,KAAK;CACd;AACF;;;;;AAMA,IAAa,sBAAb,MAA8E;CAC5E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