11use core:: fmt;
22use std:: {
33 borrow:: Cow ,
4+ collections:: HashMap ,
45 sync:: {
56 atomic:: { AtomicBool , Ordering } ,
6- Arc ,
7+ Arc , Mutex ,
78 } ,
89} ;
910
1011use opentelemetry:: {
11- metrics:: { noop:: NoopMeterCore , InstrumentProvider , Meter as ApiMeter , MetricsError , Result } ,
12+ metrics:: { noop:: NoopMeterCore , Meter as ApiMeter , MetricsError , Result } ,
1213 KeyValue ,
1314} ;
1415
@@ -26,6 +27,7 @@ use super::{meter::Meter as SdkMeter, pipeline::Pipelines, reader::MetricReader,
2627#[ derive( Clone , Debug ) ]
2728pub struct MeterProvider {
2829 pipes : Arc < Pipelines > ,
30+ meters : Arc < Mutex < HashMap < Scope , Arc < SdkMeter > > > > ,
2931 is_shutdown : Arc < AtomicBool > ,
3032}
3133
@@ -121,15 +123,23 @@ impl opentelemetry::metrics::MeterProvider for MeterProvider {
121123 schema_url : Option < impl Into < Cow < ' static , str > > > ,
122124 attributes : Option < Vec < KeyValue > > ,
123125 ) -> ApiMeter {
124- let inst_provider: Arc < dyn InstrumentProvider + Send + Sync > =
125- if !self . is_shutdown . load ( Ordering :: Relaxed ) {
126- let scope = Scope :: new ( name, version, schema_url, attributes) ;
127- Arc :: new ( SdkMeter :: new ( scope, self . pipes . clone ( ) ) )
128- } else {
129- Arc :: new ( NoopMeterCore :: new ( ) )
130- } ;
126+ if self . is_shutdown . load ( Ordering :: Relaxed ) {
127+ return ApiMeter :: new ( Arc :: new ( NoopMeterCore :: new ( ) ) ) ;
128+ }
129+
130+ let scope = Scope :: new ( name, version, schema_url, attributes) ;
131131
132- ApiMeter :: new ( inst_provider)
132+ if let Ok ( mut meters) = self . meters . lock ( ) {
133+ let meter = meters
134+ . entry ( scope)
135+ . or_insert_with_key ( |scope| {
136+ Arc :: new ( SdkMeter :: new ( scope. clone ( ) , self . pipes . clone ( ) ) )
137+ } )
138+ . clone ( ) ;
139+ ApiMeter :: new ( meter)
140+ } else {
141+ ApiMeter :: new ( Arc :: new ( NoopMeterCore :: new ( ) ) )
142+ }
133143 }
134144}
135145
@@ -184,6 +194,7 @@ impl MeterProviderBuilder {
184194 self . readers ,
185195 self . views ,
186196 ) ) ,
197+ meters : Default :: default ( ) ,
187198 is_shutdown : Arc :: new ( AtomicBool :: new ( false ) ) ,
188199 }
189200 }
0 commit comments