{"version":3,"file":"MeterSharedState.mjs","names":[],"sources":["../../src/state/MeterSharedState.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { MetricCollectOptions } from '../export/MetricProducer';\nimport type { MetricData, ScopeMetrics } from '../export/MetricData';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { createInstrumentDescriptorWithView } from '../InstrumentDescriptor';\nimport { Meter } from '../Meter';\nimport type { Maybe } from '../utils';\nimport { AsyncMetricStorage } from './AsyncMetricStorage';\nimport type { MeterProviderSharedState } from './MeterProviderSharedState';\nimport type { MetricCollectorHandle } from './MetricCollector';\nimport { MetricStorageRegistry } from './MetricStorageRegistry';\nimport { MultiMetricStorage } from './MultiWritableMetricStorage';\nimport { ObservableRegistry } from './ObservableRegistry';\nimport { SyncMetricStorage } from './SyncMetricStorage';\nimport type { Accumulation, Aggregator } from '../aggregator/types';\nimport type { IAttributesProcessor } from '../view/AttributesProcessor';\nimport type { MetricStorage } from './MetricStorage';\n\n/**\n * An internal record for shared meter provider states.\n */\nexport class MeterSharedState {\n  metricStorageRegistry = new MetricStorageRegistry();\n  observableRegistry = new ObservableRegistry();\n  meter: Meter;\n  private _meterProviderSharedState: MeterProviderSharedState;\n  private _instrumentationScope: InstrumentationScope;\n\n  constructor(\n    meterProviderSharedState: MeterProviderSharedState,\n    instrumentationScope: InstrumentationScope\n  ) {\n    this.meter = new Meter(this);\n    this._meterProviderSharedState = meterProviderSharedState;\n    this._instrumentationScope = instrumentationScope;\n  }\n\n  registerMetricStorage(descriptor: InstrumentDescriptor) {\n    const storages = this._registerMetricStorage(descriptor, SyncMetricStorage);\n\n    if (storages.length === 1) {\n      return storages[0];\n    }\n    return new MultiMetricStorage(storages);\n  }\n\n  registerAsyncMetricStorage(descriptor: InstrumentDescriptor) {\n    const storages = this._registerMetricStorage(\n      descriptor,\n      AsyncMetricStorage\n    );\n\n    return storages;\n  }\n\n  /**\n   * @param collector opaque handle of {@link MetricCollector} which initiated the collection.\n   * @param collectionTime the HrTime at which the collection was initiated.\n   * @param options options for collection.\n   * @returns the list of metric data collected.\n   */\n  async collect(\n    collector: MetricCollectorHandle,\n    collectionTime: HrTime,\n    options?: MetricCollectOptions\n  ): Promise<ScopeMetricsResult | null> {\n    /**\n     * 1. Call all observable callbacks first.\n     * 2. Collect metric result for the collector.\n     */\n    const errors = await this.observableRegistry.observe(\n      collectionTime,\n      options?.timeoutMillis\n    );\n    const storages = this.metricStorageRegistry.getStorages(collector);\n\n    // prevent more allocations if there are no storages.\n    if (storages.length === 0) {\n      return null;\n    }\n\n    const metricDataList: MetricData[] = [];\n    storages.forEach(metricStorage => {\n      const metricData = metricStorage.collect(collector, collectionTime);\n\n      if (metricData != null) {\n        metricDataList.push(metricData);\n      }\n    });\n\n    // skip this scope if no data was collected (storage created, but no data observed)\n    if (metricDataList.length === 0) {\n      return { errors };\n    }\n\n    return {\n      scopeMetrics: {\n        scope: this._instrumentationScope,\n        metrics: metricDataList,\n      },\n      errors,\n    };\n  }\n\n  private _registerMetricStorage<\n    MetricStorageType extends MetricStorageConstructor,\n    R extends InstanceType<MetricStorageType>,\n  >(\n    descriptor: InstrumentDescriptor,\n    MetricStorageType: MetricStorageType\n  ): R[] {\n    const views = this._meterProviderSharedState.viewRegistry.findViews(\n      descriptor,\n      this._instrumentationScope\n    );\n    let storages = views.map(view => {\n      const viewDescriptor = createInstrumentDescriptorWithView(\n        view,\n        descriptor\n      );\n      const compatibleStorage =\n        this.metricStorageRegistry.findOrUpdateCompatibleStorage<R>(\n          viewDescriptor\n        );\n      if (compatibleStorage != null) {\n        return compatibleStorage;\n      }\n      const aggregator = view.aggregation.createAggregator(viewDescriptor);\n      const viewStorage = new MetricStorageType(\n        viewDescriptor,\n        aggregator,\n        view.attributesProcessor,\n        this._meterProviderSharedState.metricCollectors,\n        view.aggregationCardinalityLimit\n      ) as R;\n      this.metricStorageRegistry.register(viewStorage);\n      return viewStorage;\n    });\n\n    // Fallback to the per-collector aggregations if no view is configured for the instrument.\n    if (storages.length === 0) {\n      const perCollectorAggregations =\n        this._meterProviderSharedState.selectAggregations(descriptor.type);\n      const collectorStorages = perCollectorAggregations.map(\n        ([collector, aggregation]) => {\n          const compatibleStorage =\n            this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage<R>(\n              collector,\n              descriptor\n            );\n          if (compatibleStorage != null) {\n            return compatibleStorage;\n          }\n\n          const aggregator = aggregation.createAggregator(descriptor);\n          const cardinalityLimit = collector.selectCardinalityLimit(\n            descriptor.type\n          );\n          const storage = new MetricStorageType(\n            descriptor,\n            aggregator,\n            undefined,\n            [collector],\n            cardinalityLimit\n          ) as R;\n          this.metricStorageRegistry.registerForCollector(collector, storage);\n          return storage;\n        }\n      );\n      storages = storages.concat(collectorStorages);\n    }\n\n    return storages;\n  }\n}\n\ninterface ScopeMetricsResult {\n  scopeMetrics?: ScopeMetrics;\n  errors: unknown[];\n}\n\ninterface MetricStorageConstructor {\n  new (\n    instrumentDescriptor: InstrumentDescriptor,\n    aggregator: Aggregator<Maybe<Accumulation>>,\n    attributesProcessor: IAttributesProcessor | undefined,\n    collectors: MetricCollectorHandle[],\n    aggregationCardinalityLimit?: number\n  ): MetricStorage;\n}\n"],"mappings":";;;;;;;;;;;AA2BA,IAAa,mBAAb,MAA8B;CAC5B,wBAAwB,IAAI,sBAAsB;CAClD,qBAAqB,IAAI,mBAAmB;CAC5C;CACA;CACA;CAEA,YACE,0BACA,sBACA;EACA,KAAK,QAAQ,IAAI,MAAM,IAAI;EAC3B,KAAK,4BAA4B;EACjC,KAAK,wBAAwB;CAC/B;CAEA,sBAAsB,YAAkC;EACtD,MAAM,WAAW,KAAK,uBAAuB,YAAY,iBAAiB;EAE1E,IAAI,SAAS,WAAW,GACtB,OAAO,SAAS;EAElB,OAAO,IAAI,mBAAmB,QAAQ;CACxC;CAEA,2BAA2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