o
    hr                  	   @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
mZ d dlmZmZmZ d dlmZ d dlZd dlmZmZmZ d dlmZmZmZmZmZ d dlmZmZ d d	lm Z m!Z!m"Z"m#Z# d d
l$m%Z% e%rd dl&m'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, d dl&m-Z- d dl&m.Z. d dl&m/Z/ d dl&m0Z0 d dl$m1Z1 d dl$m2Z2 d dl$m3Z3 d dl$m4Z4 d dl$m5Z5 d dl$m6Z6 d dl$m7Z7 d dl$m8Z8 d dl$m9Z9 d dl$m:Z: e; Z<ee=dj>d Z?ee=d!ej@j>d ZAeBZCeDe e!e"e#gZEd"d# ZFed$d% ZGd&d' ZHG d(d) d)eIZJG d*d+ d+eJZKG d,d- d-eJZLG d.d/ d/eJZMG d0d1 d1eJZNd2d3 ZOd4d5 ZPeKeLeMeNd6ZQed7d8 d9d8 ed:d8 d;d8 d<d8 d=d8 d>ZRG d?d@ d@eIZSG dAdB dBeIZTdCdD ZUdEdF ZVdGdH ZWdIdJ ZX	K	L			 dZdMdNZYG dOdP dPeIZZ		Q			 d[dRdSZ[	L			 d\dTdUZ\	L			 d\dVdWZB	L			 d\dXdYZ]dS )]    N)datetime)wrapspartial)EventLockThread)contextmanager)	text_typeutc_from_timestamp	iteritems)nownanosecond_timeto_timestampserialize_frame
json_dumps)EnvelopeItem)TRANSACTION_SOURCE_ROUTETRANSACTION_SOURCE_VIEWTRANSACTION_SOURCE_COMPONENTTRANSACTION_SOURCE_TASK)TYPE_CHECKING)Any)Callable)Dict)	Generator)Iterable)List)Optional)Set)Tuple)Union)	BucketKey)DurationUnit)FlushedMetricValue)MeasurementUnit)MetricMetaKey)MetricTagValue)
MetricTags)MetricTagsInternal)
MetricType)MetricValuez[^a-zA-Z0-9_/.-]+_z[^\w\d_:/@\.{}\[\]$-]+c                 C   s2   zt | }W n
 ty   Y d S w t|dddS )NFT)include_local_variablesinclude_source_context)sys	_getframe	Exceptionr   )
stacklevelfrm r4   U/var/www/html/aiguide_backend/venv/lib/python3.10/site-packages/sentry_sdk/metrics.pyget_code_locationG   s   r6   c                  c   sF    zt j} W n ty   d} Y nw dt _z	| V  W | t _dS | t _w )z5Enters recursion protection and returns the old flag.FTN)_thread_local
in_metricsAttributeError)r8   r4   r4   r5   recursion_protectionS   s   
r:   c                    s   t   fdd}|S )zYConvenient decorator that uses `recursion_protection` to
    make a function a noop.
    c                     sL   t  }|s | i |W  d    S W d    d S 1 sw   Y  d S N)r:   )argskwargsr8   funcr4   r5   new_funch   s   "zmetrics_noop.<locals>.new_func)r   )r?   r@   r4   r>   r5   metrics_noopb   s   rA   c                   @   s,   e Zd ZdZedd Zdd Zdd ZdS )	Metricr4   c                 C      t  r;   NotImplementedErrorselfr4   r4   r5   weightu   s   zMetric.weightc                 C   rC   r;   rD   rG   valuer4   r4   r5   addz   s   z
Metric.addc                 C   rC   r;   rD   rF   r4   r4   r5   serialize_value      zMetric.serialize_valueN)__name__
__module____qualname__	__slots__propertyrH   rK   rL   r4   r4   r4   r5   rB   r   s    
rB   c                   @   4   e Zd ZdZdd Zedd Zdd Zdd	 Zd
S )CounterMetricrJ   c                 C   s   t || _d S r;   floatrJ   rG   firstr4   r4   r5   __init__   s   zCounterMetric.__init__c                 C      dS N   r4   rF   r4   r4   r5   rH      s   zCounterMetric.weightc                 C   s   |  j t|7  _ d S r;   )rJ   rW   rI   r4   r4   r5   rK      s   zCounterMetric.addc                 C   s   | j fS r;   rU   rF   r4   r4   r5   rL      s   zCounterMetric.serialize_valueN	rN   rO   rP   rQ   rZ   rR   rH   rK   rL   r4   r4   r4   r5   rT          
rT   c                   @   rS   )GaugeMetriclastminmaxsumcountc                 C   s*   t |}|| _|| _|| _|| _d| _d S r\   rW   rb   rc   rd   re   rf   rX   r4   r4   r5   rZ      s   
zGaugeMetric.__init__c                 C   r[   )N   r4   rF   r4   r4   r5   rH      s   zGaugeMetric.weightc                 C   sJ   t |}|| _t| j|| _t| j|| _|  j|7  _|  jd7  _d S r\   rg   rI   r4   r4   r5   rK      s   zGaugeMetric.addc                 C   s   | j | j| j| j| jfS r;   ra   rF   r4   r4   r5   rL      s   zGaugeMetric.serialize_valueNr^   r4   r4   r4   r5   r`      s    
r`   c                   @   rS   )DistributionMetricrU   c                 C   s   t |g| _d S r;   rV   rX   r4   r4   r5   rZ         zDistributionMetric.__init__c                 C   
   t | jS r;   lenrJ   rF   r4   r4   r5   rH         
zDistributionMetric.weightc                 C   s   | j t| d S r;   )rJ   appendrW   rI   r4   r4   r5   rK      s   zDistributionMetric.addc                 C   s   | j S r;   rU   rF   r4   r4   r5   rL      rM   z"DistributionMetric.serialize_valueNr^   r4   r4   r4   r5   ri      r_   ri   c                   @   rS   )	SetMetricrU   c                 C   s   |h| _ d S r;   rU   rX   r4   r4   r5   rZ      s   zSetMetric.__init__c                 C   rk   r;   rl   rF   r4   r4   r5   rH      rn   zSetMetric.weightc                 C   s   | j | d S r;   )rJ   rK   rI   r4   r4   r5   rK      rj   zSetMetric.addc                    s   dd   fdd| j D S )Nc                 S   s&   t | trt| dd@ S t| S )Nutf-8l    )
isinstancestrzlibcrc32encodeint)xr4   r4   r5   _hash   s   
z(SetMetric.serialize_value.<locals>._hashc                 3   s    | ]} |V  qd S r;   r4   ).0rJ   ry   r4   r5   	<genexpr>  s    z,SetMetric.serialize_value.<locals>.<genexpr>rU   rF   r4   r{   r5   rL      s   zSetMetric.serialize_valueNr^   r4   r4   r4   r5   rp      r_   rp   c                 C   s4  t  }|j}| D ]\}}t|D ]\}}|\}}}	}
t|}||d |d ||	d | D ]}|d |t|d q5|d ||d |
r|d d}|
D ](\}}t|}|seqZ|rjd}n|d	 ||d |d |t|d qZ|d
 |t|d |d qq	|	 S )Nrq      @   :   |asciis   |#TF   ,s   |T   
)
ioBytesIOwriter   _sanitize_keyrv   rL   rs   _sanitize_valuegetvalue)flushable_bucketsout_write	timestampbuckets
bucket_keymetricmetric_typemetric_namemetric_unitmetric_tagsserialized_valuerY   tag_key	tag_valuer4   r4   r5   _encode_metrics  s@   
!r   c           	      C   sV   i }|D ]\}}|\}}}d |t||}d|d< ||g | qt| |dS )Nz{}:{}@{}locationtype)r   mapping)formatr   
setdefaultro   r   )	r   code_locationsr   keylocr   nameunitmrir4   r4   r5   _encode_locations5  s   
r   )cgdsc                   C   
   t  d S )Ng     @@r   r4   r4   r4   r5   <lambda>M     
 r   c                   C   r   )Ng    .Ar   r4   r4   r4   r5   r   N  r   c                   C   r   )Ng      N@r   r4   r4   r4   r5   r   P  r   c                   C   r   )N      @r   r4   r4   r4   r5   r   Q  r   c                   C   s   t  d d S )Nr         8@r   r4   r4   r4   r5   r   R  s    c                   C   s   t  d d d S )Nr   r   g      @r   r4   r4   r4   r5   r   S  s    )
nanosecondmicrosecondmillisecondsecondminutehourdayweekc                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	LocalAggregator_measurementsc                 C   s
   i | _ d S r;   r   rF   r4   r4   r5   rZ   Z  s   zLocalAggregator.__init__c                 C   s   d|||f }||f}| j |}|d ur.|\}	}
}}t|	|}	t|
|}
|d7 }||7 }n| }	 }
}d}|	|
||f| j |< d S )Nz%s:%s@%sr]   )r   getrc   rd   )rG   tyr   rJ   r   tags
export_keyr   oldv_minv_maxv_countv_sumr4   r4   r5   rK   `  s   	


zLocalAggregator.addc              	   C   sJ   i }| j  D ]\\}}\}}}}||g t|||||d q|S )N)r   rc   rd   rf   re   )r   itemsr   ro   _tags_to_dict)rG   rvr   r   r   r   r   r   r4   r4   r5   to_jsonx  s    	zLocalAggregator.to_jsonN)rN   rO   rP   rQ   rZ   rK   r   r4   r4   r4   r5   r   W  s
    r   c                   @   s   e Zd ZdZdZdZ	d!ddZdd Zd	d
 Zdd Z	dd Z
dd Ze			d"ddZ	d#ddZedd Zdd Zedd Zdd Zdd  ZdS )$MetricsAggregatorg      $@i g      @Fc                 C   sj   i | _ || _t | _i | _d| _|| _t | _d| _	t
 | _d| _t | j | _d | _d | _|   d S )Nr   TF)r   _enable_code_locations_set_seen_locations_pending_locations_buckets_total_weight_capture_funcr   _lock_runningr   _flush_event_force_flushrandomROLLUP_IN_SECONDS_flush_shift_flusher_flusher_pid_ensure_thread)rG   capture_funcenable_code_locationsr4   r4   r5   rZ     s   zMetricsAggregator.__init__c              	   C   s   | j sdS t }| j|krdS | j2 || _t| jd| _d| j_z| j	  W n t
y<   d| _ Y W d   dS w W d   dS 1 sHw   Y  dS )zFor forking processes we might need to restart this thread.
        This ensures that our process actually has that thread running.
        FT)targetN)r   osgetpidr   r   r   _flush_loopr   daemonstartRuntimeError)rG   pidr4   r4   r5   r     s*   

z MetricsAggregator._ensure_threadc                 C   sB   dt _| js	| jr|   | jr| j| j | js	| js	d S d S NT)r7   r8   r   r   _flushr   waitFLUSHER_SLEEP_TIMErF   r4   r4   r5   r     s   zMetricsAggregator._flush_loopc                 C   s   |  |  |   d S r;   )_emit_flushable_buckets_flushable_locationsrF   r4   r4   r5   r     s   zMetricsAggregator._flushc           	      C   s   | j j | j}t | j | j }d}d}|r&| j }i | _d| _d| _n?g }t| jD ]\}}||kr<|	||f q-|D ]\}}t|D ]	\}}||j
7 }qG| j|= q?|  j|8  _W d    |S W d    |S 1 spw   Y  |S )Nr4   r   F)r   r   timer   r   r   r   r   r   ro   rH   )	rG   force_flushcutoffr   weight_to_removebuckets_timestampr   r,   r   r4   r4   r5   r     s6   



z$MetricsAggregator._flushable_bucketsc                 C   s8   | j  | j}i | _W d    |S 1 sw   Y  |S r;   )r   r   )rG   	locationsr4   r4   r5   r     s   
z&MetricsAggregator._flushable_locationsNr   c	                 C   s8  |   r	| jd u rd S |d u rt }n	t|trt|}t|| j | j }	t|}
||||
f}| j	A | j
|	i }||}|d urN|j}|| nt| | }||< d}|j| }|d urn| ||||d | W d    n1 sxw   Y  |   |d urt|dkr|n|}||||||
 d S d S )Nr      r   )r   r   r   rr   r   r   rw   r   _serialize_tagsr   r   r   r   rH   rK   METRIC_TYPESrecord_code_location_consider_force_flushrW   )rG   r   r   rJ   r   r   r   local_aggregatorr2   bucket_timestampserialized_tagsr   local_bucketsr   previous_weightaddedlocal_valuer4   r4   r5   rK     sB   



zMetricsAggregator.addc           	      C   s   | j sd S |d u rt }|||f}t|jddddd d}tt|}||f| jvrK| j||f t|d }|d urM| j	
|g ||f d S d S d S )Nr   r   r   r   r   tzinfo   )r   r   r
   replacerw   r   r   rK   r6   r   r   ro   )	rG   r   r   r   r2   r   meta_keystart_of_dayr   r4   r4   r5   r   -  s$   	

z&MetricsAggregator.record_code_locationc                 C   sF   | j rdS |||f}t|jddddd d}tt|}||f| jvS )NFr   r   )r   r
   r   rw   r   r   )rG   r   r   r   r   r   r   r4   r4   r5   need_code_loationJ  s   	

z#MetricsAggregator.need_code_loationc                 C   s2   | j d u rd S d| _| j  | j   d | _ d S )NF)r   r   r   setjoinrF   r4   r4   r5   kill\  s   



zMetricsAggregator.killc                 C   s   d| _ |   d S r   )r   r   rF   r4   r4   r5   flushf  s   zMetricsAggregator.flushc                 C   s2   t | j| j }|| jkrd| _| j  d S d S r   )rm   r   r   
MAX_WEIGHTr   r   r  )rG   total_weightr4   r4   r5   r   l  s
   
z'MetricsAggregator._consider_force_flushc                 C   sj   t  }|rt|}|t|dd t|D ]\}}t||}|t|dd q|jr3| | |S d S )Nstatsd)payloadr   metric_meta)r   r   add_itemr   r   r   r   r   )rG   r   r   envelopeencoded_metricsr   r   encoded_locationsr4   r4   r5   r   t  s   

zMetricsAggregator._emit)F)NNr   r;   )rN   rO   rP   r   r  r   rZ   r   r   r   r   r   rA   rK   r   r  r  r  r   r   r4   r4   r4   r5   r     s2    
;



r   c                 C   sx   | sdS g }t | D ]+\}}t|ttfr(|D ]}|d ur&||t|f qq
|d ur5||t|f q
tt|S )Nr4   )r   rr   listtuplero   r	   sorted)r   r   r   rJ   inner_valuer4   r4   r5   r     s   r   c                 C   sT   i }| D ]#\}}| |}|d ur#t|tr|| q||g||< q|||< q|S r;   )r   rr   r  ro   )r   r   tag_namer   	old_valuer4   r4   r5   r     s   


r   c                  C   s*   t jj} | j}|d ur|jd ur|jS d S r;   )
sentry_sdkHubcurrentclientmetrics_aggregator)hubr  r4   r4   r5   _get_aggregator  s   r  c                 C   sX  t jj}|j}|d u s|jd u rd d |fS |jdi }t|p d}|d|jd  |d|jd  |j	}d }|j
d}|tv rw|j}	|	rN|d|	 |jd urw|d}
|
d u r^d}
|d	}t |
k rw|d u sr|| |rw|j }|d
}|d urt }|s|| |sd d |fW  d    S W d    n1 sw   Y  |j||fS )N_experimentsr4   releaseenvironmentsourcetransactionmetrics_summary_sample_rate      ?should_summarize_metricbefore_emit_metric)r  r  r  r  r  optionsr   dictr   scope_transaction_infoGOOD_TRANSACTION_SOURCES_transaction_spanr   _get_local_aggregatorr:   )r   r   r  r  experimentsupdated_tagsr'  r   transaction_sourcetransaction_namesample_rate should_summarize_metric_callbackbefore_emit_callbackr8   r4   r4   r5   _get_aggregator_and_update_tags  sJ   





 r4  r"  nonec              
   C   8   t | |\}}}|dur|d| |||||| dS dS )zIncrements a counter.Nr   r4  rK   r   rJ   r   r   r   r2   
aggregatorr   r4   r4   r5   incr     
r:  c                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )_Timingc                 C   s4   || _ || _|| _|| _|| _d | _d | _|| _d S r;   )r   r   r   rJ   r   enteredr+  r2   )rG   r   r   r   rJ   r   r2   r4   r4   r5   rZ     s   

z_Timing.__init__c                 C   s   | j d urtd| d S )Nz0cannot use timing as %s when a value is provided)rJ   	TypeError)rG   contextr4   r4   r5   _validate_invocation  s
   
z_Timing._validate_invocationc                 C   s   t | j  | _| d tjd| jd| _| jr:| j	 D ]\}}t
|ttfr2dttt|}| j|| q| j  t }|d urQ|d| j| j| j | S )Nzcontext-managerzmetric.timing)opdescription,r   )TIMING_FUNCTIONSr   r=  r@  r  
start_spanr   r+  r   r   rr   r  r  r  r  maprs   set_tag	__enter__r  r   r2   )rG   r   rJ   r9  r4   r4   r5   rH    s   

z_Timing.__enter__c              
   C   st   | j sJ dt| j| j\}}}|d ur-t| j  | j }|d| j|| j|| j|d  | j 	||| d | _ d S )Nzdid not enterr   )
r+  r4  r   r   rD  r   r=  rK   r   __exit__)rG   exc_type	exc_valuetbr9  r   r   elapsedr4   r4   r5   rI  )  s$   

z_Timing.__exit__c                    s$    d t  fdd}|S )N	decoratorc                     sR   t jjjjjd d  | i |W  d    S 1 s"w   Y  d S )Nr]   )r   r   r   r   r2   )timingr   r   r   r   r2   )r<   r=   frG   r4   r5   
timed_funcC  s   $z$_Timing.__call__.<locals>.timed_func)r@  r   )rG   rQ  rR  r4   rP  r5   __call__?  s   
z_Timing.__call__N)rN   rO   rP   rZ   r@  rH  rI  rS  r4   r4   r4   r5   r<    s    r<  r   c              
   C   sJ   |durt | |\}}}|dur|d| |||||| t| |||||S )a#  Emits a distribution with the time it takes to run the given code block.

    This method supports three forms of invocation:

    - when a `value` is provided, it functions similar to `distribution` but with
    - it can be used as a context manager
    - it can be used as a decorator
    Nr   )r4  rK   r<  r8  r4   r4   r5   rO  R  s   rO  c              
   C   r6  )zEmits a distribution.Nr   r7  r8  r4   r4   r5   distributionl  r;  rT  c              
   C   r6  )zEmits a set.Nr   r7  r8  r4   r4   r5   r  }  r;  r  c              
   C   r6  )zEmits a gauge.Nr   r7  r8  r4   r4   r5   gauge  r;  rU  )r"  r5  NNr   )Nr   NNr   )r5  NNr   )^r   r   rer/   	threadingr   r   rt   r   	functoolsr   r   r   r   r   
contextlibr   r  sentry_sdk._compatr	   r
   r   sentry_sdk.utilsr   r   r   r   r   sentry_sdk.enveloper   r   sentry_sdk.tracingr   r   r   r   sentry_sdk._typesr   typingr   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   localr7   compilesubr   UNICODEr   r  r   	frozensetr)  r6   r:   rA   objectrB   rT   r`   ri   rp   r   r   r   rD  r   r   r   r   r  r4  r:  r<  rO  rT  rU  r4   r4   r4   r5   <module>   s    

0/	6 ~2
Y


