{"version":3,"file":"MetricReader.cjs","names":["DEFAULT_AGGREGATION_SELECTOR","DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR","MetricReaderMetrics","api","VERSION","hrTime","hrTimeToSeconds","hrTimeDuration","callWithTimeout"],"sources":["../../src/export/MetricReader.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { AggregationTemporality } from './AggregationTemporality';\nimport type { MetricProducer } from './MetricProducer';\nimport type { CollectionResult, InstrumentType } from './MetricData';\nimport { callWithTimeout } from '../utils';\nimport type {\n  CollectionOptions,\n  ForceFlushOptions,\n  ShutdownOptions,\n} from '../types';\nimport type {\n  AggregationSelector,\n  AggregationTemporalitySelector,\n} from './AggregationSelector';\nimport {\n  DEFAULT_AGGREGATION_SELECTOR,\n  DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,\n} from './AggregationSelector';\nimport type { AggregationOption } from '../view/AggregationOption';\nimport type { CardinalitySelector } from './CardinalitySelector';\nimport { MetricReaderMetrics } from './MetricReaderMetrics';\nimport { VERSION } from '../version';\nimport { hrTime, hrTimeDuration, hrTimeToSeconds } from '@opentelemetry/core';\n\nexport interface MetricReaderOptions {\n  /**\n   * Aggregation selector based on metric instrument types. If no views are\n   * configured for a metric instrument, a per-metric-reader aggregation is\n   * selected with this selector.\n   *\n   * <p> NOTE: the provided function MUST be pure\n   */\n  aggregationSelector?: AggregationSelector;\n  /**\n   * Aggregation temporality selector based on metric instrument types. If\n   * not configured, cumulative is used for all instruments.\n   *\n   * <p> NOTE: the provided function MUST be pure\n   */\n  aggregationTemporalitySelector?: AggregationTemporalitySelector;\n  /**\n   * Cardinality selector based on metric instrument types. If not configured,\n   * a default value is used.\n   *\n   * <p> NOTE: the provided function MUST be pure\n   */\n  cardinalitySelector?: CardinalitySelector;\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   * The component type used for reporting self-observability SDK metrics.\n   * @experimental This option is experimental and is subject to breaking changes in minor releases.\n   */\n  otelComponentType?: string;\n}\n\n/**\n * Reads metrics from the SDK. Implementations MUST follow the Metric Reader Specification as well as the requirements\n * listed in this interface. Consider extending {@link MetricReader} to get a specification-compliant base implementation\n * of this interface\n */\nexport interface IMetricReader {\n  /**\n   * Set the {@link MetricProducer} used by this instance. **This should only be called once by the\n   * SDK and should be considered internal.**\n   *\n   * <p> NOTE: implementations MUST throw when called more than once\n   *\n   * @param metricProducer\n   */\n  setMetricProducer(metricProducer: MetricProducer): void;\n\n  /**\n   * Select the {@link AggregationOption} for the given {@link InstrumentType} for this\n   * reader.\n   *\n   * <p> NOTE: implementations MUST be pure\n   */\n  selectAggregation(instrumentType: InstrumentType): AggregationOption;\n\n  /**\n   * Select the {@link AggregationTemporality} for the given\n   * {@link InstrumentType} for this reader.\n   *\n   * <p> NOTE: implementations MUST be pure\n   */\n  selectAggregationTemporality(\n    instrumentType: InstrumentType\n  ): AggregationTemporality;\n\n  /**\n   * Select the cardinality limit for the given {@link InstrumentType} for this\n   * reader.\n   *\n   * <p> NOTE: implementations MUST be pure\n   */\n  selectCardinalityLimit(instrumentType: InstrumentType): number;\n\n  /**\n   * Collect all metrics from the associated {@link MetricProducer}\n   */\n  collect(options?: CollectionOptions): Promise<CollectionResult>;\n\n  /**\n   * Shuts down the metric reader, the promise will reject after the optional timeout or resolve after completion.\n   *\n   * <p> NOTE: this operation MAY continue even after the promise rejects due to a timeout.\n   * @param options options with timeout.\n   */\n  shutdown(options?: ShutdownOptions): Promise<void>;\n\n  /**\n   * Flushes metrics read by this reader, the promise will reject after the optional timeout or resolve after completion.\n   *\n   * <p> NOTE: this operation MAY continue even after the promise rejects due to a timeout.\n   * @param options options with timeout.\n   */\n  forceFlush(options?: ForceFlushOptions): Promise<void>;\n}\n\n/**\n * A registered reader of metrics that, when linked to a {@link MetricProducer}, offers global\n * control over metrics.\n */\nexport abstract class MetricReader implements IMetricReader {\n  // Tracks the shutdown state.\n  // TODO: use BindOncePromise here once a new version of @opentelemetry/core is available.\n  private _shutdown = false;\n  // Additional MetricProducers which will be combined with the SDK's output\n  private _metricProducers: MetricProducer[];\n  // MetricProducer used by this instance which produces metrics from the SDK\n  private _sdkMetricProducer?: MetricProducer;\n  // Metrics about the MetricReader itself\n  private _selfObsMetrics: MetricReaderMetrics;\n  private readonly _aggregationTemporalitySelector: AggregationTemporalitySelector;\n  private readonly _aggregationSelector: AggregationSelector;\n  private readonly _cardinalitySelector?: CardinalitySelector;\n  private readonly _otelComponentType: string;\n\n  constructor(options?: MetricReaderOptions) {\n    this._aggregationSelector =\n      options?.aggregationSelector ?? DEFAULT_AGGREGATION_SELECTOR;\n    this._aggregationTemporalitySelector =\n      options?.aggregationTemporalitySelector ??\n      DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;\n    this._metricProducers = options?.metricProducers ?? [];\n    this._cardinalitySelector = options?.cardinalitySelector;\n    this._otelComponentType =\n      options?.otelComponentType ?? this.constructor.name;\n    this._selfObsMetrics = new MetricReaderMetrics(\n      this._otelComponentType,\n      api.createNoopMeter()\n    );\n  }\n\n  setMetricProducer(metricProducer: MetricProducer) {\n    if (this._sdkMetricProducer) {\n      // This check ensures the following requirement from the spec\n      // (https://opentelemetry.io/docs/specs/otel/metrics/sdk/#metricreader):\n      // > The SDK MUST NOT allow a `MetricReader` instance to be registered\n      // > on more than one `MeterProvider` instance.\n      //\n      // So while the argument is a `MetricProducer`, the relevant user-level\n      // error message is about the **MeterProvider**.\n      throw new Error(\n        'MetricReader can not be bound to a MeterProvider again.'\n      );\n    }\n    this._sdkMetricProducer = metricProducer;\n    this.onInitialized();\n  }\n\n  _setSelfObsMeterProvider(meterProvider: api.MeterProvider): void {\n    const meter = meterProvider.getMeter('@opentelemetry/sdk-metrics', VERSION);\n    this._selfObsMetrics = new MetricReaderMetrics(\n      this._otelComponentType,\n      meter\n    );\n  }\n\n  selectAggregation(instrumentType: InstrumentType): AggregationOption {\n    return this._aggregationSelector(instrumentType);\n  }\n\n  selectAggregationTemporality(\n    instrumentType: InstrumentType\n  ): AggregationTemporality {\n    return this._aggregationTemporalitySelector(instrumentType);\n  }\n\n  selectCardinalityLimit(instrumentType: InstrumentType): number {\n    return this._cardinalitySelector\n      ? this._cardinalitySelector(instrumentType)\n      : 2000; // default value if no selector is provided\n  }\n\n  /**\n   * Handle once the SDK has initialized this {@link MetricReader}\n   * Overriding this method is optional.\n   */\n  protected onInitialized(): void {\n    // Default implementation is empty.\n  }\n\n  /**\n   * Handle a shutdown signal by the SDK.\n   *\n   * <p> For push exporters, this should shut down any intervals and close any open connections.\n   * @protected\n   */\n  protected abstract onShutdown(): Promise<void>;\n\n  /**\n   * Handle a force flush signal by the SDK.\n   *\n   * <p> In all scenarios metrics should be collected via {@link collect()}.\n   * <p> For push exporters, this should collect and report metrics.\n   * @protected\n   */\n  protected abstract onForceFlush(): Promise<void>;\n\n  async collect(options?: CollectionOptions): Promise<CollectionResult> {\n    if (this._sdkMetricProducer === undefined) {\n      throw new Error('MetricReader is not bound to a MetricProducer');\n    }\n\n    // Subsequent invocations to collect are not allowed. SDKs SHOULD return some failure for these calls.\n    if (this._shutdown) {\n      throw new Error('MetricReader is shutdown');\n    }\n\n    const startTime = hrTime();\n    const [sdkCollectionResults, ...additionalCollectionResults] =\n      await Promise.all([\n        this._sdkMetricProducer.collect({\n          timeoutMillis: options?.timeoutMillis,\n        }),\n        ...this._metricProducers.map(producer =>\n          producer.collect({\n            timeoutMillis: options?.timeoutMillis,\n          })\n        ),\n      ]);\n    const endTime = hrTime();\n\n    // Merge the results, keeping the SDK's Resource\n    const errors = sdkCollectionResults.errors.concat(\n      additionalCollectionResults.flatMap(result => result.errors)\n    );\n\n    const collectDuration = hrTimeToSeconds(hrTimeDuration(startTime, endTime));\n    this._selfObsMetrics.recordCollection(\n      collectDuration,\n      errors.length > 0\n        ? ((errors[0] as Error).name ?? 'collect_error')\n        : undefined\n    );\n\n    const resource = sdkCollectionResults.resourceMetrics.resource;\n    const scopeMetrics =\n      sdkCollectionResults.resourceMetrics.scopeMetrics.concat(\n        additionalCollectionResults.flatMap(\n          result => result.resourceMetrics.scopeMetrics\n        )\n      );\n    return {\n      resourceMetrics: {\n        resource,\n        scopeMetrics,\n      },\n      errors,\n    };\n  }\n\n  async shutdown(options?: ShutdownOptions): Promise<void> {\n    // Do not call shutdown again if it has already been called.\n    if (this._shutdown) {\n      api.diag.error('Cannot call shutdown twice.');\n      return;\n    }\n\n    // No timeout if timeoutMillis is undefined or null.\n    if (options?.timeoutMillis == null) {\n      await this.onShutdown();\n    } else {\n      await callWithTimeout(this.onShutdown(), options.timeoutMillis);\n    }\n\n    this._shutdown = true;\n  }\n\n  async forceFlush(options?: ForceFlushOptions): Promise<void> {\n    if (this._shutdown) {\n      api.diag.warn('Cannot forceFlush on already shutdown MetricReader.');\n      return;\n    }\n\n    // No timeout if timeoutMillis is undefined or null.\n    if (options?.timeoutMillis == null) {\n      await this.onForceFlush();\n      return;\n    }\n\n    await callWithTimeout(this.onForceFlush(), options.timeoutMillis);\n  }\n}\n"],"mappings":";;;;;;;;;;;;;AAsIA,IAAsB,eAAtB,MAA4D;CAG1D,YAAoB;CAEpB;CAEA;CAEA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAA+B;EACzC,KAAK,uBACH,SAAS,uBAAuBA,4BAAAA;EAClC,KAAK,kCACH,SAAS,kCACTC,4BAAAA;EACF,KAAK,mBAAmB,SAAS,mBAAmB,CAAC;EACrD,KAAK,uBAAuB,SAAS;EACrC,KAAK,qBACH,SAAS,qBAAqB,KAAK,YAAY;EACjD,KAAK,kBAAkB,IAAIC,4BAAAA,oBACzB,KAAK,oBACLC,mBAAI,gBAAgB,CACtB;CACF;CAEA,kBAAkB,gBAAgC;EAChD,IAAI,KAAK,oBAQP,MAAM,IAA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