{"version":3,"file":"TemporalMetricProcessor.cjs","names":["AttributeHashMap"],"sources":["../../src/state/TemporalMetricProcessor.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime } from '@opentelemetry/api';\nimport type {\n  Accumulation,\n  AccumulationRecord,\n  Aggregator,\n} from '../aggregator/types';\nimport type { MetricData } from '../export/MetricData';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { Maybe } from '../utils';\nimport type { MetricCollectorHandle } from './MetricCollector';\nimport { AttributeHashMap } from './HashMap';\n\n/**\n * Remembers what was presented to a specific exporter.\n */\ninterface LastReportedHistory<T extends Maybe<Accumulation>> {\n  /**\n   * The last accumulation of metric data.\n   */\n  accumulations: AttributeHashMap<T>;\n  /**\n   * The timestamp the data was reported.\n   */\n  collectionTime: HrTime;\n  /**\n   * The AggregationTemporality used to aggregate reports.\n   */\n  aggregationTemporality: AggregationTemporality;\n}\n\n/**\n * Internal interface.\n *\n * Provides unique reporting for each collector. Allows synchronous collection\n * of metrics and reports given temporality values.\n */\nexport class TemporalMetricProcessor<T extends Maybe<Accumulation>> {\n  private _aggregator: Aggregator<T>;\n  private _unreportedAccumulations = new Map<\n    MetricCollectorHandle,\n    AttributeHashMap<T>[]\n  >();\n  private _reportHistory = new Map<\n    MetricCollectorHandle,\n    LastReportedHistory<T>\n  >();\n\n  constructor(\n    aggregator: Aggregator<T>,\n    collectorHandles: MetricCollectorHandle[]\n  ) {\n    this._aggregator = aggregator;\n    collectorHandles.forEach(handle => {\n      this._unreportedAccumulations.set(handle, []);\n    });\n  }\n\n  /**\n   * Builds the {@link MetricData} streams to report against a specific MetricCollector.\n   * @param collector The information of the MetricCollector.\n   * @param collectors The registered collectors.\n   * @param instrumentDescriptor The instrumentation descriptor that these metrics generated with.\n   * @param currentAccumulations The current accumulation of metric data from instruments.\n   * @param collectionTime The current collection timestamp.\n   * @returns The {@link MetricData} points or `null`.\n   */\n  buildMetrics(\n    collector: MetricCollectorHandle,\n    instrumentDescriptor: InstrumentDescriptor,\n    currentAccumulations: AttributeHashMap<T>,\n    collectionTime: HrTime\n  ): Maybe<MetricData> {\n    this._stashAccumulations(currentAccumulations);\n    const unreportedAccumulations =\n      this._getMergedUnreportedAccumulations(collector);\n\n    let result = unreportedAccumulations;\n    let aggregationTemporality: AggregationTemporality;\n    // Check our last report time.\n    if (this._reportHistory.has(collector)) {\n      const last = this._reportHistory.get(collector)!;\n      const lastCollectionTime = last.collectionTime;\n      aggregationTemporality = last.aggregationTemporality;\n\n      // Use aggregation temporality + instrument to determine if we do a merge or a diff of\n      // previous. We have the following four scenarios:\n      // 1. Cumulative Aggregation (temporality) + Delta recording (sync instrument).\n      //    Here we merge with our last record to get a cumulative aggregation.\n      // 2. Cumulative Aggregation + Cumulative recording (async instrument).\n      //    Cumulative records are converted to delta recording with DeltaMetricProcessor.\n      //    Here we merge with our last record to get a cumulative aggregation.\n      // 3. Delta Aggregation + Delta recording\n      //    Calibrate the startTime of metric streams to be the reader's lastCollectionTime.\n      // 4. Delta Aggregation + Cumulative recording.\n      //    Cumulative records are converted to delta recording with DeltaMetricProcessor.\n      //    Calibrate the startTime of metric streams to be the reader's lastCollectionTime.\n      if (aggregationTemporality === AggregationTemporality.CUMULATIVE) {\n        // We need to make sure the current delta recording gets merged into the previous cumulative\n        // for the next cumulative recording.\n        result = TemporalMetricProcessor.merge(\n          last.accumulations,\n          unreportedAccumulations,\n          this._aggregator\n        );\n      } else {\n        result = TemporalMetricProcessor.calibrateStartTime(\n          last.accumulations,\n          unreportedAccumulations,\n          lastCollectionTime\n        );\n      }\n    } else {\n      // Call into user code to select aggregation temporality for the instrument.\n      aggregationTemporality = collector.selectAggregationTemporality(\n        instrumentDescriptor.type\n      );\n    }\n\n    // Update last reported (cumulative) accumulation.\n    this._reportHistory.set(collector, {\n      accumulations: result,\n      collectionTime,\n      aggregationTemporality,\n    });\n\n    const accumulationRecords = AttributesMapToAccumulationRecords(result);\n\n    // do not convert to metric data if there is nothing to convert.\n    if (accumulationRecords.length === 0) {\n      return undefined;\n    }\n\n    return this._aggregator.toMetricData(\n      instrumentDescriptor,\n      aggregationTemporality,\n      accumulationRecords,\n      /* endTime */ collectionTime\n    );\n  }\n\n  private _stashAccumulations(currentAccumulation: AttributeHashMap<T>) {\n    const registeredCollectors = this._unreportedAccumulations.keys();\n    for (const collector of registeredCollectors) {\n      let stash = this._unreportedAccumulations.get(collector);\n      if (stash === undefined) {\n        stash = [];\n        this._unreportedAccumulations.set(collector, stash);\n      }\n      stash.push(currentAccumulation);\n    }\n  }\n\n  private _getMergedUnreportedAccumulations(collector: MetricCollectorHandle) {\n    let result = new AttributeHashMap<T>();\n    const unreportedList = this._unreportedAccumulations.get(collector);\n    this._unreportedAccumulations.set(collector, []);\n    if (unreportedList === undefined) {\n      return result;\n    }\n    for (const it of unreportedList) {\n      result = TemporalMetricProcessor.merge(result, it, this._aggregator);\n    }\n    return result;\n  }\n\n  static merge<T extends Maybe<Accumulation>>(\n    last: AttributeHashMap<T>,\n    current: AttributeHashMap<T>,\n    aggregator: Aggregator<T>\n  ) {\n    const result = last;\n    const iterator = current.entries();\n    let next = iterator.next();\n    while (next.done !== true) {\n      const [key, record, hash] = next.value;\n      if (last.has(key, hash)) {\n        const lastAccumulation = last.get(key, hash);\n        // last.has() returned true, lastAccumulation is present.\n        const accumulation = aggregator.merge(lastAccumulation!, record);\n        result.set(key, accumulation, hash);\n      } else {\n        result.set(key, record, hash);\n      }\n\n      next = iterator.next();\n    }\n    return result;\n  }\n\n  /**\n   * Calibrate the reported metric streams' startTime to lastCollectionTime. Leaves\n   * the new stream to be the initial observation time unchanged.\n   */\n  static calibrateStartTime<T extends Maybe<Accumulation>>(\n    last: AttributeHashMap<T>,\n    current: AttributeHashMap<T>,\n    lastCollectionTime: HrTime\n  ) {\n    for (const [key, hash] of last.keys()) {\n      const currentAccumulation = current.get(key, hash);\n      currentAccumulation?.setStartTime(lastCollectionTime);\n    }\n    return current;\n  }\n}\n\n// TypeScript complains about converting 3 elements tuple to AccumulationRecord<T>.\nfunction AttributesMapToAccumulationRecords<T>(\n  map: AttributeHashMap<T>\n): AccumulationRecord<T>[] {\n  return Array.from(map.entries()) as unknown as AccumulationRecord<T>[];\n}\n"],"mappings":";;;;;;;;;AA0CA,IAAa,0BAAb,MAAa,wBAAuD;CAClE;CACA,2CAAmC,IAAI,IAGrC;CACF,iCAAyB,IAAI,IAG3B;CAEF,YACE,YACA,kBACA;EACA,KAAK,cAAc;EACnB,iBAAiB,SAAQ,WAAU;GACjC,KAAK,yBAAyB,IAAI,QAAQ,CAAC,CAAC;EAC9C,CAAC;CACH;;;;;;;;;;CAWA,aACE,WACA,sBACA,sBACA,gBACmB;EACnB,KAAK,oBAAoB,oBAAoB;EAC7C,MAAM,0BACJ,KAAK,kCAAkC,SAAS;EAElD,IAAI,SAAS;EACb,IAAI;EAEJ,IAAI,KAAK,eAAe,IAAI,SAAS,GAAG;GACtC,MAAM,OAAO,KAAK,eAAe,IAAI,SAAS;GAC9C,MAAM,qBAAqB,KAAK;GAChC,yBAAyB,KAAK;GAc9B,IAAI,2BAAA,GAGF,SAAS,wBAAwB,MAC/B,KAAK,eACL,yBACA,KAAK,WACP;QAEA,SAAS,wBAAwB,mBAC/B,KAAK,eACL,yBACA,kBACF;EAEJ,OAEE,yBAAyB,UAAU,6BACjC,qBAAqB,IACvB;EAIF,KAAK,eAAe,IAAI,WAAW;GACjC,eAAe;GACf;GACA;EACF,CAAC;EAED,MAAM,sBAAsB,mCAAmC,MAAM;EAGrE,IAAI,oBAAoB,WAAW,GACjC;EAGF,OAAO,KAAK,YAAY,aACtB,sBACA,wBACA,qBACc,cAChB;CACF;CAEA,oBAA4B,qBAA0C;EACpE,MAAM,uBAAuB,KAAK,yBAAyB,KAAK;EAChE,KAAK,MAAM,aAAa,sBAAsB;GAC5C,IAAI,QAAQ,KAAK,yBAAyB,IAAI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