
    R3i6                     d   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZ ddlmZmZmZmZmZmZ ddlmZmZmZmZmZ dd	lmZ dd
lmZmZmZmZm Z  ddlm!Z" ddl#m$Z$m%Z%m!Z!m&Z&m'Z'm(Z(m)Z) ddl*m+Z+  ee,      Z-dZ.dZ/ ede
      Z0 ede
      Z1 ed      Z2i dddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>	Z3d?d@dAdBdCdDdEdFZ4dGe5dHe5fdIZ6dGe5dHe5fdJZ7dKe5dHe5fdLZ8dMe5dHe5fdNZ9dOee:   dPee;   dHeee5e:f      fdQZ< G dR dSe'      Z= G dT dU      Z>yV)Wa  Vendored OpenTelemetry Prometheus exporter.

This module provides a minimal implementation of PrometheusMetricReader
from opentelemetry-exporter-prometheus. Vendoring removes the exact SDK
version pins that the exporter package brings in as transitive dependencies.

Original source: opentelemetry-exporter-prometheus (Apache 2.0)
https://github.com/open-telemetry/opentelemetry-python-contrib

Copyright The OpenTelemetry Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
    )deque)chain)dumps)	getLogger)UNICODEcompile)DequeDictIterableSequenceTupleUnion)REGISTRYCounterMetricFamilyGaugeMetricFamilyHistogramMetricFamilyInfoMetricFamily)Metric)CounterObservableCounterObservableGaugeObservableUpDownCounterUpDownCounter)	Histogram)AggregationTemporalityGauger   HistogramDataPointMetricReaderMetricsDataSum)
AttributestargetzTarget metadataz[^a-zA-Z0-9:]+z[^a-zA-Z0-9]+z{.*}ddayshhoursminminutesssecondsmsmillisecondsusmicrosecondsnsnanosecondsBybytesKiBy	kibibytesMiBy	mebibytesGiBy	gibibytesTiBy	tibibytesKBy	kilobytesMBy	megabytesGBy	gigabytesTBy	terabytesmmetersvoltsamperesjouleswattsgramscelsiushertz percent)	VAJWgCelHz1%secondminutehourdayweekmonthyear)r)   rC   r%   r#   wmoynamereturnc                 .    t         j                  d|       S )z3Sanitize metric name according to Prometheus rules._)_SANITIZE_NAME_REsubra   s    e/mnt/e/genesis-system/.venvs/voice-bridge/lib/python3.12/site-packages/docket/_prometheus_exporter.py_sanitize_nameri   o   s      d++    c                 R    | r| d   j                         rd| dd z   } t        |       S )z.Sanitize metric name including leading digits.r   rd      N)isdigitri   rg   s    rh   sanitize_full_namern   t   s,    Q!T!"X~$rj   keyc                 h    | r| d   j                         rd| dd z   } t        j                  d|       S )z5Sanitize attribute key according to Prometheus rules.r   rd   rl   N)rm   _SANITIZE_ATTRIBUTE_KEY_RErf   )ro   s    rh   sanitize_attributerr   {   s4    
s1v~~CGm%))#s33rj   unitc                 v   t         j                  d|       } | t        v r	t        |    S | j                  dd      }t	        |      dk(  rXt        |d         }|rHt        |d         }t        j                  ||      }t        j                  ||      }|r| d| S d| S t        |       j                  d	      S )
z/Map unit to Prometheus metric name conventions.rL   /rl   )maxsplit   r   _per_per_rd   )	_UNIT_ANNOTATIONrf   _UNIT_MAPPINGSsplitlenri   get_PER_UNIT_MAPPINGSstrip)rs   ratio_unit_subpartsbottomtops       rh   map_unitr      s    D)D~d##**S1*5
1$ 3A 67 !4Q!78C $$S#.C'++FF;F,/cU%x(DtF8_D$%%c**rj   bucket_countsexplicit_boundsc                 ~    g }d}t        t        |dg      |       D ]  \  }}||z  }|j                  | |f         |S )z/Convert histogram buckets to Prometheus format.r   z+Inf)zipr   append)r   r   bucketstotal_countupper_boundcounts         rh   _convert_bucketsr      s\     GK!ox( 8U 	u;-+678 Nrj   c            	       `     e Zd ZdZddeddf fdZ	 ddedededdfd	Z	ddededdfd
Z
 xZS )PrometheusMetricReaderz-Prometheus metric exporter for OpenTelemetry.disable_target_inforb   Nc                    t         |   t        t        j                  t
        t        j                  t        t        j                  t        t        j                  t        t        j                  t        t        j                  i       t        |      | _        t        j                  | j                         | j                  | j                  _        y )N)preferred_temporality)super__init__r   r   
CUMULATIVEr   HistogramInstrumentr   r   r   _CustomCollector
_collectorr   registercollect	_callback)selfr   	__class__s     rh   r   zPrometheusMetricReader.__init__   s    /::5@@#%;%F%F!#9#D#D')?)J)J!7!B!B# 	 		
 ++>?$//*$(LL!rj   metrics_datatimeout_milliskwargsc                 @    |y | j                   j                  |       y N)r   add_metrics_data)r   r   r   r   s       rh   _receive_metricsz'PrometheusMetricReader._receive_metrics   s     ((6rj   c                 B    t        j                  | j                         y r   )r   
unregisterr   )r   r   r   s      rh   shutdownzPrometheusMetricReader.shutdown   s    DOO,rj   F)i'  )i0u  )__name__
__module____qualname____doc__boolr   r   floatobjectr   r   __classcell__)r   s   @rh   r   r      sc    71D 1T 1$ !'7!7 7 	7
 
7-u - -D -rj   r   c                       e Zd ZdZddefdZdeddfdZdee	   fdZ
ded	eee	f   ddfd
Zdeeeeee   f   defdZdedededefdZy)r   zDCustom Prometheus collector that bridges OTel metrics to Prometheus.r   c                 L    d | _         t               | _        || _        d | _        y r   )r   r   _metrics_datas_disable_target_info_target_info)r   r   s     rh   r   z_CustomCollector.__init__   s#    !%27'$7!59rj   r   rb   Nc                 :    | j                   j                  |       y)zAdd metrics to Prometheus data.N)r   r   )r   r   s     rh   r   z!_CustomCollector.add_metrics_data   s    ""<0rj   c              #   <  K   | j                   | j                          i }t        | j                        r| j                  sy| j                  Zi }| j                  d   j
                  D ]  }i ||j                  j                  } | j                  t        t        |      | _        | j                  |t        <   | j                  rR| j                  | j                  j                         |       |r|j                         E d{    | j                  rQyy7 w)z*Collect metrics for Prometheus exposition.Nr   )r   r}   r   r   r   resource_metricsresource
attributes_create_info_metric_TARGET_INFO_NAME_TARGET_INFO_DESCRIPTION_translate_to_prometheuspopleftvalues)r   metric_family_id_metric_familyr   ress       rh   r   z_CustomCollector.collect   s
    >>%NNFH&t""#,,$$,-/J#2215FF O%N
%Ncll6M6M%N
O )-(@(@)+CZ)D% EIDUDU./@A!!))##++-/M .9@@BBB !! Cs   DDDDDr   c                    g }|j                   D ]5  }|j                  D ]$  }|j                  D ]  }|j                  |        & 7 |D ]  }g }g }g }	g }
t	        |j
                        }|j                  xs d}t        |j                        }|j                  j                  D ]!  }g }g }t        |j                  j                               D ]?  \  }}|j                  t        |             |j                  | j                  |             A |
j                  dj!                  ||dj!                  |      |g             |j                  |       |j                  |       t#        |t$              r5|	j                  |j&                  |j(                  |j*                  d       |	j                  |j,                         $ t/        |
|||	      D ]  \  }}}}t#        |j                  t0              xr |j                  j2                  du }t#        |j                  t0              xr' |j                  j4                  t6        j8                  k(  }|xr |}t#        |j                  t0              rP|sNdj!                  |t:        j<                  g      }||vrt;        ||||      ||<   ||   j?                  ||       t#        |j                  t@              s|r]dj!                  |tB        j<                  g      }||jE                         vrtC        ||||      ||<   ||   j?                  ||       it#        |j                  tF              rqdj!                  |tH        j<                  g      }||jE                         vrtI        ||||      ||<   ||   j?                  |tK        |d   |d	         |d
          tL        jO                  dtQ        |j                                 y )NrL   |rV   )r   r   sumF)ra   documentationlabelsrs   r   valuer   r   r   )r   r   	sum_valuezUnsupported metric data. %s))r   scope_metricsmetricsr   rn   ra   descriptionr   rs   datadata_pointssortedr   itemsrr   _check_valuejoin
isinstancer   r   r   r   r   r   r    is_monotonicaggregation_temporalityr   r   r   r   
add_metricr   r   keysr   r   r   _loggerwarningtype)r   r   r   r   r   r   metriclabel_values_data_pointslabel_keys_data_pointsr   per_metric_family_idsmetric_namemetric_descriptionmetric_unitnumber_data_point
label_keyslabel_valuesro   r   per_metric_family_idis_non_monotonic_sumis_cumulativeshould_convert_sum_to_gaugemetric_family_ids                           rh   r   z)_CustomCollector._translate_to_prometheus   s(   
  , = = 	+!1!?!? ++33 +FNN6*++	+
  t	VF')$%'"#%F$&!,V[[9K!'!3!3!9r"6;;/K%+[[%<%< ;!
!"():)E)E)K)K)M"N BJC%%&8&=> ''(9(9%(@AB &,,HH'.HHZ0'		 )//=&--j9/1CDMM->-L-L/@/P/P#4#8#8 MM"3"9"9:=;@ JM%&(	J IVE$j, v{{C0VV[[5M5MQV5V % v{{C0 9;;-889 
 /C.T}+fkk3/8S'*xx-/B/K/KL($ (/MM/%0.@'1%0	 77GH 33CDOO+5 P   U37R'*xx-/@/I/IJ($ (/M/R/R/TT-%0.@'1%0	 77GH 33CDOO+5 P   Y7'*xx-/D/M/MN($ (/M/R/R/TT1%0.@'1%0	 77GH 33CDOO+ 0!/2!"34! #(, P  OO$A4CTUSIVWt	Vrj   r   c                 Z    t        |t              st        |t              S t        |      S )z<Check the label value and return appropriate representation.)default)r   strr   )r   r   s     rh   r   z_CustomCollector._check_valuen  s#    %%,,5zrj   ra   r   r   c           	         |xs i j                         D ci c])  \  }}t        t        |            | j                  |      + }}}t	        |||      }|j                  t        |j                               |       |S c c}}w )z5Create an Info Metric Family with list of attributes.)r   r   )r   rr   r   r   r   r   listr   )r   ra   r   r   ro   r   sanitized_attributesinfos           rh   r   z$_CustomCollector._create_info_metrict  s      */R668 
U s3x($*;*;E*BB 
  
  k:NO,1134<P 	 	
  
s   .Br   )r   r   r   r   r   r   r   r   r   PrometheusMetricr   r
   r   r   r   intr   r   r   r   r!   r   r    rj   rh   r   r      s    N:D :1[ 1T 1C"23 C6@V!@V )-S2B-B(C@V 
	@VD%UC&9I(I"J s &)7A	rj   r   N)?r   collectionsr   	itertoolsr   jsonr   loggingr   rer   r   typingr	   r
   r   r   r   r   prometheus_client.corer   r   r   r   r   r   r   opentelemetry.sdk.metricsr   r   r   r   r   r   r    opentelemetry.sdk.metrics.exportr   r   r   r   r   r    opentelemetry.util.typesr!   r   r   r   r   re   rq   rz   r{   r   r   ri   rn   rr   r   r   r   r   r   r   r   rj   rh   <module>r      s:  0      @ @  >  G   0
H
 ,  -w7 $%5w? 7#  
9 	
 	. 	. 	- 	' K K K K 
; 
; 
;  
;!" #$ 
				
		5< 
				
	 , , ,
 S  S  4C 4C 4+3 +3 +&C=3;E?eCHo-\ -@| |rj   