{"version":3,"file":"PeriodicExportingMetricReader.mjs","names":[],"sources":["../../src/export/PeriodicExportingMetricReader.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n  internal,\n  ExportResultCode,\n  globalErrorHandler,\n} from '@opentelemetry/core';\nimport { MetricReader } from './MetricReader';\nimport type { PushMetricExporter } from './MetricExporter';\nimport { callWithTimeout, TimeoutError } from '../utils';\nimport { InstrumentType } from './MetricData';\nimport { splitMetricData } from './MetricDataSplitter';\nimport type { MetricProducer } from './MetricProducer';\nimport { OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER } from '../semconv';\n\nexport type PeriodicExportingMetricReaderOptions = {\n  /**\n   * The backing exporter for the metric reader.\n   */\n  exporter: PushMetricExporter;\n  /**\n   * An internal milliseconds for the metric reader to initiate metric\n   * collection.\n   */\n  exportIntervalMillis?: number;\n  /**\n   * Milliseconds for the async observable callback to timeout.\n   */\n  exportTimeoutMillis?: number;\n  /**\n   * **Note, this option is experimental**. Additional MetricProducers to use as a source of\n   * aggregated metric data in addition to the SDK's metric data. The resource returned by\n   * these MetricProducers is ignored; the SDK's resource will be used instead.\n   * @experimental\n   */\n  metricProducers?: MetricProducer[];\n  /**\n   * Cardinality limits for the metric reader, applied per instrument. If not configured, defaults to 2000 time series per instrument. These are wrapped in a cardinalitySelector function that returns limits based on the instrument type, so they can be configured differently per type if desired.\n   *\n   */\n  cardinalityLimits?: {\n    counter?: number;\n    gauge?: number;\n    histogram?: number;\n    upDownCounter?: number;\n    observableCounter?: number;\n    observableGauge?: number;\n    observableUpDownCounter?: number;\n    default?: number;\n  };\n  /**\n   * The maximum number of metric data points in a batch that are provided to a\n   * single export. If configured, the reader will split batches larger than\n   * this size into smaller batches.\n   */\n  maxExportBatchSize?: number;\n};\n\n/**\n * {@link MetricReader} which collects metrics based on a user-configurable time interval, and passes the metrics to\n * the configured {@link PushMetricExporter}\n */\nexport class PeriodicExportingMetricReader extends MetricReader {\n  private _interval?: ReturnType<typeof setInterval>;\n  private _exporter: PushMetricExporter;\n  private readonly _exportInterval: number;\n  private readonly _exportTimeout: number;\n  private readonly _maxExportBatchSize?: number;\n  private _ongoingExportPromise: Promise<void> | null = null;\n\n  constructor(options: PeriodicExportingMetricReaderOptions) {\n    const {\n      exporter,\n      exportIntervalMillis = 60000,\n      metricProducers,\n      cardinalityLimits,\n      maxExportBatchSize,\n    } = options;\n    let { exportTimeoutMillis = 30000 } = options;\n\n    super({\n      aggregationSelector: exporter.selectAggregation?.bind(exporter),\n      aggregationTemporalitySelector:\n        exporter.selectAggregationTemporality?.bind(exporter),\n      otelComponentType: OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER,\n      metricProducers,\n      cardinalitySelector: (instrumentType: InstrumentType) => {\n        const limits = {\n          default: 2000,\n          ...cardinalityLimits,\n        };\n\n        switch (instrumentType) {\n          case InstrumentType.COUNTER:\n            return limits.counter ?? limits.default;\n          case InstrumentType.GAUGE:\n            return limits.gauge ?? limits.default;\n          case InstrumentType.HISTOGRAM:\n            return limits.histogram ?? limits.default;\n          case InstrumentType.OBSERVABLE_COUNTER:\n            return limits.observableCounter ?? limits.default;\n          case InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:\n            return limits.observableUpDownCounter ?? limits.default;\n          case InstrumentType.OBSERVABLE_GAUGE:\n            return limits.observableGauge ?? limits.default;\n          case InstrumentType.UP_DOWN_COUNTER:\n            return limits.upDownCounter ?? limits.default;\n          default:\n            return limits.default;\n        }\n      },\n    });\n\n    if (exportIntervalMillis <= 0) {\n      throw Error('exportIntervalMillis must be greater than 0');\n    }\n\n    if (exportTimeoutMillis <= 0) {\n      throw Error('exportTimeoutMillis must be greater than 0');\n    }\n\n    if (\n      maxExportBatchSize !== undefined &&\n      (!Number.isInteger(maxExportBatchSize) || maxExportBatchSize <= 0)\n    ) {\n      throw Error('maxExportBatchSize must be a positive integer');\n    }\n\n    if (exportIntervalMillis < exportTimeoutMillis) {\n      if (\n        'exportIntervalMillis' in options &&\n        'exportTimeoutMillis' in options\n      ) {\n        // An invalid combination of values was explicitly provided.\n        throw Error(\n          'exportIntervalMillis must be greater than or equal to exportTimeoutMillis'\n        );\n      } else {\n        // An invalid combination of value was implicitly provided.\n        api.diag.info(\n          `Timeout of ${exportTimeoutMillis} exceeds the interval of ${exportIntervalMillis}. Clamping timeout to interval duration.`\n        );\n        exportTimeoutMillis = exportIntervalMillis;\n      }\n    }\n\n    this._exportInterval = exportIntervalMillis;\n    this._exportTimeout = exportTimeoutMillis;\n    this._exporter = exporter;\n    this._maxExportBatchSize = maxExportBatchSize;\n  }\n\n  private async _runOnce(): Promise<void> {\n    try {\n      await this._doRun();\n    } catch (err) {\n      globalErrorHandler(err);\n    }\n  }\n\n  private async _doRun(): Promise<void> {\n    if (this._ongoingExportPromise) {\n      api.diag.debug(\n        'PeriodicExportingMetricReader: export already in progress, skipping'\n      );\n      return;\n    }\n\n    const currentRun = async () => {\n      const { resourceMetrics, errors } = await this.collect({\n        timeoutMillis: this._exportTimeout,\n      });\n\n      if (errors.length > 0) {\n        api.diag.error(\n          'PeriodicExportingMetricReader: metrics collection errors',\n          ...errors\n        );\n      }\n\n      if (resourceMetrics.resource.asyncAttributesPending) {\n        try {\n          await resourceMetrics.resource.waitForAsyncAttributes?.();\n        } catch (e) {\n          api.diag.debug(\n            'Error while resolving async portion of resource: ',\n            e\n          );\n          globalErrorHandler(e);\n        }\n      }\n\n      if (resourceMetrics.scopeMetrics.length === 0) {\n        return;\n      }\n\n      const batches = this._maxExportBatchSize\n        ? splitMetricData(resourceMetrics, this._maxExportBatchSize)\n        : [resourceMetrics];\n\n      let anyErr: Error | null = null;\n      for (const batch of batches) {\n        try {\n          const result = await callWithTimeout(\n            internal._export(this._exporter, batch),\n            this._exportTimeout\n          );\n          if (result.code !== ExportResultCode.SUCCESS) {\n            const err = new Error(\n              `PeriodicExportingMetricReader: metrics export failed (error ${result.error})`\n            );\n            anyErr = err;\n          }\n        } catch (e) {\n          if (e instanceof TimeoutError) {\n            api.diag.error(\n              `PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`\n            );\n            break;\n          } else {\n            api.diag.error(\n              'PeriodicExportingMetricReader: metrics export threw error',\n              e\n            );\n            anyErr = e instanceof Error ? e : new Error(String(e));\n          }\n        }\n      }\n      if (anyErr) {\n        throw anyErr;\n      }\n    };\n\n    this._ongoingExportPromise = currentRun();\n    try {\n      await this._ongoingExportPromise;\n    } finally {\n      this._ongoingExportPromise = null;\n    }\n  }\n\n  protected override onInitialized(): void {\n    // start running the interval as soon as this reader is initialized and keep handle for shutdown.\n    this._interval = setInterval(() => {\n      // this._runOnce never rejects. Using void operator to suppress @typescript-eslint/no-floating-promises.\n      void this._runOnce();\n    }, this._exportInterval);\n    unrefTimer(this._interval);\n  }\n\n  protected async onForceFlush(): Promise<void> {\n    // Wait for any in-progress export to finish first so that we never run\n    // collect + export concurrently with it.\n    await this._awaitOngoingExport();\n    // forceFlush SHOULD collect and export the latest metrics. If a concurrent\n    // caller already started a fresh export while we were waiting above, await\n    // that one instead of starting yet another collect + export cycle;\n    // otherwise run our own.\n    if (this._ongoingExportPromise) {\n      await this._awaitOngoingExport();\n    } else {\n      await this._runOnce();\n    }\n    await this._exporter.forceFlush();\n  }\n\n  /**\n   * Helper function to wait for an ongoing export to complete.\n   * Errors are swallowed and handled by the original _runOnce().\n   */\n  private async _awaitOngoingExport(): Promise<void> {\n    if (this._ongoingExportPromise) {\n      api.diag.debug(\n        'PeriodicExportingMetricReader: export already in progress, awaiting ongoing export'\n      );\n      try {\n        await this._ongoingExportPromise;\n      } catch {\n        // Error is handled by the _runOnce() that initiated the export.\n      }\n    }\n  }\n\n  protected async onShutdown(): Promise<void> {\n    if (this._interval) {\n      clearInterval(this._interval);\n    }\n    await this.onForceFlush();\n    await this._exporter.shutdown();\n  }\n}\n\n// Node.js timers keep the process alive unless unref'd; browsers return a number.\nfunction unrefTimer(timer: ReturnType<typeof setInterval>): void {\n  const handle = timer as number | { unref?: () => void };\n  if (typeof handle !== 'number') handle.unref?.();\n}\n"],"mappings":";;;;;;;;;;;;AAkEA,IAAa,gCAAb,cAAmD,aAAa;CAC9D;CACA;CACA;CACA;CACA;CACA,wBAAsD;CAEtD,YAAY,SAA+C;EACzD,MAAM,EACJ,UACA,uBAAuB,KACvB,iBACA,mBACA,uBACE;EACJ,IAAI,EAAE,sBAAsB,QAAU;EAEtC,MAAM;GACJ,qBAAqB,SAAS,mBAAmB,KAAK,QAAQ;GAC9D,gCACE,SAAS,8BAA8B,KAAK,QAAQ;GACtD,mBAAmB;GACnB;GACA,sBAAsB,mBAAmC;IACvD,MAAM,SAAS;KACb,SAAS;KACT,GAAG;IACL;IAEA,QAAQ,gBAAR;KACE,KAAA,WACE,OAAO,OAAO,WAAW,OAAO;KAClC,KAAA,SACE,OAAO,OAAO,SAAS,OAAO;KAChC,KAAA,aACE,OAAO,OAAO,aAAa,OAAO;KACpC,KAAA,sBACE,OAAO,OAAO,qBAAqB,OAAO;KAC5C,KAAA,8BACE,OAAO,OAAO,2BAA2B,OAAO;KAClD,KAAA,oBACE,OAAO,OAAO,mBAAmB,OAAO;KAC1C,KAAA,mBACE,OAAO,OAAO,iBAAiB,OAAO;KACxC,SACE,OAAO,OAAO;IAClB;GACF;EACF,CAAC;EAED,IAAI,wBAAwB,GAC1B,MAAM,MAAM,6CAA6C;EAG3D,IAAI,uBAAuB,GACzB,MAAM,MAAM,4CAA4C;EAG1D,IACE,uBAAuB,KAAA,MACtB,CAAC,OAAO,UAAU,kBAAkB,KAAK,sBAAsB,IAEhE,MAAM,MAAM,+CAA+C;EAG7D,IAAI,uBAAuB,qBAAqB;GAC9C,IACE,0BAA0B,WAC1B,yBAAyB,SAGzB,MAAM,MACJ,2EACF;QACK;IAEL,IAAI,KAAK,KACP,cAAc,oBAAoB,2BAA2B,qBAAqB,yCACpF;IACA,sBAAsB;GACxB;EACF;EAEA,KA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