From 1a0c7a6506437d3311a192164c76e55f7f771e76 Mon Sep 17 00:00:00 2001 From: Angelo Di Paolo Date: Fri, 27 Sep 2024 13:43:48 -0700 Subject: [PATCH] Synchronize access race in HistogramMetric --- .../Metrics/HistogramMetricSdk.swift | 14 +++++++++----- .../OpenTelemetrySdk/Metrics/MeterSdk.swift | 18 +++++++++++------- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/Sources/OpenTelemetrySdk/Metrics/HistogramMetricSdk.swift b/Sources/OpenTelemetrySdk/Metrics/HistogramMetricSdk.swift index 795ec44e..76e8a0c6 100644 --- a/Sources/OpenTelemetrySdk/Metrics/HistogramMetricSdk.swift +++ b/Sources/OpenTelemetrySdk/Metrics/HistogramMetricSdk.swift @@ -10,6 +10,7 @@ internal class HistogramMetricSdk: HistogramMetri public private(set) var boundInstruments = [LabelSet: BoundHistogramMetricSdkBase]() let metricName: String let explicitBoundaries: Array? + let bindUnbindLock = Lock() init(name: String, explicitBoundaries: Array? = nil) { metricName = name @@ -17,12 +18,15 @@ internal class HistogramMetricSdk: HistogramMetri } func bind(labelset: LabelSet) -> BoundHistogramMetric { - var boundInstrument = boundInstruments[labelset] - if boundInstrument == nil { - boundInstrument = createMetric() - boundInstruments[labelset] = boundInstrument! + bindUnbindLock.withLock { + var boundInstrument = boundInstruments[labelset] + if boundInstrument == nil { + boundInstrument = createMetric() + boundInstruments[labelset] = boundInstrument! + } + + return boundInstrument! } - return boundInstrument! } func bind(labels: [String: String]) -> BoundHistogramMetric { diff --git a/Sources/OpenTelemetrySdk/Metrics/MeterSdk.swift b/Sources/OpenTelemetrySdk/Metrics/MeterSdk.swift index 71d2743e..0ad208b0 100644 --- a/Sources/OpenTelemetrySdk/Metrics/MeterSdk.swift +++ b/Sources/OpenTelemetrySdk/Metrics/MeterSdk.swift @@ -194,14 +194,18 @@ class MeterSdk: Meter { let metricName = histogram.key let measureInstrument = histogram.value var metric = Metric(namespace: meterName, name: metricName, desc: meterName + metricName, type: AggregationType.doubleHistogram, resource: resource, instrumentationScopeInfo: instrumentationScopeInfo) - measureInstrument.boundInstruments.forEach { boundInstrument in - let labelSet = boundInstrument.key - let aggregator = boundInstrument.value.getAggregator() - aggregator.checkpoint() - var metricData = aggregator.toMetricData() - metricData.labels = labelSet.labels - metric.data.append(metricData) + + measureInstrument.bindUnbindLock.withLock { + measureInstrument.boundInstruments.forEach { boundInstrument in + let labelSet = boundInstrument.key + let aggregator = boundInstrument.value.getAggregator() + aggregator.checkpoint() + var metricData = aggregator.toMetricData() + metricData.labels = labelSet.labels + metric.data.append(metricData) + } } + metricProcessor.process(metric: metric) }