diff --git a/sdk/include/opentelemetry/sdk/metrics/async_instruments.h b/sdk/include/opentelemetry/sdk/metrics/async_instruments.h index a22ce1f0f8..48c7d14ec5 100644 --- a/sdk/include/opentelemetry/sdk/metrics/async_instruments.h +++ b/sdk/include/opentelemetry/sdk/metrics/async_instruments.h @@ -25,6 +25,7 @@ class ObservableInstrument : public opentelemetry::metrics::ObservableInstrument ObservableInstrument(InstrumentDescriptor instrument_descriptor, std::unique_ptr storage, std::shared_ptr observable_registry); + ~ObservableInstrument() override; void AddCallback(opentelemetry::metrics::ObservableCallbackPtr callback, void *state) noexcept override; diff --git a/sdk/include/opentelemetry/sdk/metrics/state/observable_registry.h b/sdk/include/opentelemetry/sdk/metrics/state/observable_registry.h index 5eb5b6d6ff..b584cc055f 100644 --- a/sdk/include/opentelemetry/sdk/metrics/state/observable_registry.h +++ b/sdk/include/opentelemetry/sdk/metrics/state/observable_registry.h @@ -35,6 +35,8 @@ class ObservableRegistry void *state, opentelemetry::metrics::ObservableInstrument *instrument); + void CleanupCallback(opentelemetry::metrics::ObservableInstrument *instrument); + void Observe(opentelemetry::common::SystemTimestamp collection_ts); private: diff --git a/sdk/src/metrics/async_instruments.cc b/sdk/src/metrics/async_instruments.cc index 082d6713b4..5ca56b3969 100644 --- a/sdk/src/metrics/async_instruments.cc +++ b/sdk/src/metrics/async_instruments.cc @@ -21,6 +21,11 @@ ObservableInstrument::ObservableInstrument(InstrumentDescriptor instrument_descr {} +ObservableInstrument::~ObservableInstrument() +{ + observable_registry_->CleanupCallback(this); +} + void ObservableInstrument::AddCallback(opentelemetry::metrics::ObservableCallbackPtr callback, void *state) noexcept { diff --git a/sdk/src/metrics/state/observable_registry.cc b/sdk/src/metrics/state/observable_registry.cc index 0296167b05..41b8e86067 100644 --- a/sdk/src/metrics/state/observable_registry.cc +++ b/sdk/src/metrics/state/observable_registry.cc @@ -38,6 +38,16 @@ void ObservableRegistry::RemoveCallback(opentelemetry::metrics::ObservableCallba callbacks_.erase(new_end, callbacks_.end()); } +void ObservableRegistry::CleanupCallback(opentelemetry::metrics::ObservableInstrument *instrument) +{ + std::lock_guard lock_guard{callbacks_m_}; + auto iter = std::remove_if(callbacks_.begin(), callbacks_.end(), + [instrument](const std::unique_ptr &record) { + return record->instrument == instrument; + }); + callbacks_.erase(iter, callbacks_.end()); +} + void ObservableRegistry::Observe(opentelemetry::common::SystemTimestamp collection_ts) { std::lock_guard lock_guard{callbacks_m_};