Skip to content

Commit

Permalink
Synchronize access race in HistogramMetric
Browse files Browse the repository at this point in the history
  • Loading branch information
angelo-ebay committed Oct 1, 2024
1 parent 4d973a1 commit 1a0c7a6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
14 changes: 9 additions & 5 deletions Sources/OpenTelemetrySdk/Metrics/HistogramMetricSdk.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,23 @@ internal class HistogramMetricSdk<T: SignedNumeric & Comparable>: HistogramMetri
public private(set) var boundInstruments = [LabelSet: BoundHistogramMetricSdkBase<T>]()
let metricName: String
let explicitBoundaries: Array<T>?
let bindUnbindLock = Lock()

init(name: String, explicitBoundaries: Array<T>? = nil) {
metricName = name
self.explicitBoundaries = explicitBoundaries
}

func bind(labelset: LabelSet) -> BoundHistogramMetric<T> {
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<T> {
Expand Down
18 changes: 11 additions & 7 deletions Sources/OpenTelemetrySdk/Metrics/MeterSdk.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down

0 comments on commit 1a0c7a6

Please sign in to comment.