a
    xdzq                  
   @   sd  d dl Z d dlZd dlZd dlZd dlmZmZ d dlZd dlmZ d dl	m
Z
 d dlmZ erd dl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mZ dZdZdZdZdZdZdZeeeeeeeeed	ZG dd deZ G dd deZ!G dd de!Z"d dl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- dS )    N)datetime	timedelta)has_profiling_enabled)logger)MYPY)Optional)Any)Dict)List)Tuple)Iterator)Sampler)SamplingContextMeasurementUnitZcustomurlZrouteview	componentZtaskunknown)	ZendpointZfunction_nameZhandler_nameZmethod_and_path_patternpathZ
route_nameZroute_patternZuri_templater   c                   @   s$   e Zd ZdZdZdd Zdd ZdS )_SpanRecorderz5Limits the number of spans recorded in a transaction.maxlenspansc                 C   s   |d | _ g | _d S )N   r   selfr    r   J/var/www/html/Ranjet/env/lib/python3.9/site-packages/sentry_sdk/tracing.py__init__9   s    
z_SpanRecorder.__init__c                 C   s(   t | j| jkrd |_n| j| d S N)lenr   r   _span_recorderappend)r   spanr   r   r   addC   s    z_SpanRecorder.addN)__name__
__module____qualname____doc__	__slots__r   r$   r   r   r   r   r   4   s   
r   c                   @   s   e Zd ZdZdd Zd4ddZdd	 Zd
d Zdd Zdd Z	e
dd Zdd Zdd Zedd Zedd Zdd Zedd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd5d.d/Zd0d1 Zd2d3 ZdS )6Span)trace_idspan_idparent_span_idsame_process_as_parentsampledopdescriptionstart_timestamp_start_timestamp_monotonicstatus	timestamp_tags_datar!   hub_context_manager_state_containing_transactionc                 K   s   d|v rt tS t | S )z_
        Backwards-compatible implementation of Span and Transaction
        creation.
        transaction)object__new__Transaction)clskwargsr   r   r   r=   `   s    

zSpan.__new__NTc                 C   s   |pt  j| _|p$t  jdd  | _|| _|| _|| _|| _|| _	|	| _
|| _i | _i | _|| _t | _zt | _W n ty   Y n0 d | _d | _d S )N   )uuiduuid4hexr+   r,   r-   r.   r/   r0   r1   r4   r8   r6   r7   r:   r   utcnowr2   timeperf_counterr3   AttributeErrorr5   r!   )r   r+   r,   r-   r.   r/   r0   r1   r8   r4   r;   containing_transactionr   r   r   r   n   s&    
zSpan.__init__c                 C   s   | j d u rt|| _ d S r   )r!   r   r   r   r   r   init_span_recorder   s    
zSpan.init_span_recorderc                 C   s&   d| j j| j| j| j| j| j| jf S )NzS<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r)>)	__class__r%   r0   r1   r+   r,   r-   r/   r   r   r   r   __repr__   s    zSpan.__repr__c                 C   s8   | j ptjj}|jd \}}|j}| |_|||f| _| S )N)r8   
sentry_sdkHubcurrent_stackr#   r9   )r   r8   _scopeold_spanr   r   r   	__enter__   s    zSpan.__enter__c                 C   s6   |d ur|  d | j\}}}| `| | ||_d S )Ninternal_error)
set_statusr9   finishr#   )r   tyvaluetbr8   rT   rU   r   r   r   __exit__   s    

zSpan.__exit__c                 C   s   | j S r   )r:   rL   r   r   r   rI      s    zSpan.containing_transactionc                 K   sJ   | d| j tf | j| j| jd|}| jo6| jj}|rF|| |S )a  
        Start a sub-span from the current span or transaction.

        Takes the same arguments as the initializer of :py:class:`Span`. The
        trace id, sampling decision, transaction pointer, and span recorder are
        inherited from the current span/transaction.
        r/   )r+   r-   rI   )
setdefaultr/   r*   r+   r,   rI   r!   r$   )r   r@   childZspan_recorderr   r   r   start_child   s    	
zSpan.start_childc                 K   s   t d | jf i |S )z$Deprecated: use start_child instead.z:Deprecated: use Span.start_child instead of Span.new_span.)r   warningr`   )r   r@   r   r   r   new_span   s    
zSpan.new_spanc                 K   s(   | t u rtd tjt|fi |S )a  
        Create a Transaction with the given params, then add in data pulled from
        the 'sentry-trace', 'baggage' and 'tracestate' headers from the environ (if any)
        before returning the Transaction.

        This is different from `continue_from_headers` in that it assumes header
        names in the form "HTTP_HEADER_NAME" - such as you would get from a wsgi
        environ - rather than the form "header-name".
        zXDeprecated: use Transaction.continue_from_environ instead of Span.continue_from_environ.)r*   r   ra   r>   continue_from_headersEnvironHeaders)r?   environr@   r   r   r   continue_from_environ   s
    zSpan.continue_from_environc                 K   s   | t u rtd t|d}|d|i t|d}|durX|| |  |t	|d t
f i |}d|_|S )z
        Create a transaction with the given params (including any data pulled from
        the 'sentry-trace', 'baggage' and 'tracestate' headers).
        zXDeprecated: use Transaction.continue_from_headers instead of Span.continue_from_headers.baggagesentry-traceN
tracestateF)r*   r   ra   BaggageZfrom_incoming_headergetupdateextract_sentrytrace_datafreezeextract_tracestate_datar>   r.   )r?   headersr@   rg   Zsentrytrace_kwargsr;   r   r   r   rc     s    
zSpan.continue_from_headersc                 c   s\   d|   fV  t| r|  nd}|r0d|fV  | jrX| jjrX| jj }|rXd|fV  dS )a  
        Creates a generator which returns the span's `sentry-trace`, `baggage` and
        `tracestate` headers.

        If the span's containing transaction doesn't yet have a
        `sentry_tracestate` value, this will cause one to be generated and
        stored.
        rh   Nri   rg   )to_traceparenthas_tracestate_enabledto_tracestaterI   _baggage	serialize)r   ri   rg   r   r   r   iter_headers&  s    

zSpan.iter_headersc                 K   s(   t d |sdS | jd|ifi |S )z
        DEPRECATED: Use Transaction.continue_from_headers(headers, **kwargs)

        Create a Transaction with the given params, then add in data pulled from
        the given 'sentry-trace' header value before returning the Transaction.

        zwDeprecated: Use Transaction.continue_from_headers(headers, **kwargs) instead of from_traceparent(traceparent, **kwargs)Nrh   )r   ra   rc   )r?   Ztraceparentr@   r   r   r   from_traceparent>  s    zSpan.from_traceparentc                 C   s2   d}| j du rd}| j du r d}d| j| j|f S )N T1F0z%s-%s-%s)r/   r+   r,   )r   r/   r   r   r   rq   V  s    

zSpan.to_traceparentc                 C   s:   |   }| jr| jjnd}|s"dS |}|r6|d | }|S )a  
        Computes the `tracestate` header value using data from the containing
        transaction.

        If the containing transaction doesn't yet have a `sentry_tracestate`
        value, this will cause one to be generated and stored.

        If there is no containing transaction, a value will be generated but not
        stored.

        Returns None if there's no client and/or no DSN.
        N,)get_or_set_sentry_tracestaterI   _third_party_tracestate)r   sentry_tracestatethird_party_tracestateheader_valuer   r   r   rs   _  s    
zSpan.to_tracestatec                 C   s(   | j }|r |jst| |_|jS t| S )z
        Read sentry tracestate off of the span's containing transaction.

        If the transaction doesn't yet have a `_sentry_tracestate` value,
        compute one and store it.
        )rI   _sentry_tracestatecompute_tracestate_entry)r   r;   r   r   r   r|     s    
z!Span.get_or_set_sentry_tracestatec                 C   s   || j |< d S r   )r6   r   keyr[   r   r   r   set_tag  s    zSpan.set_tagc                 C   s   || j |< d S r   )r7   r   r   r   r   set_data  s    zSpan.set_datac                 C   s
   || _ d S r   r4   )r   r[   r   r   r   rX     s    zSpan.set_statusc                 C   s6  |  dt| |dk r&| d nd|  kr:dk rn n|dkrR| d nn|dkrf| d nZ|d	krz| d
 nF|dkr| d n2|dkr| d n|dkr| d n
| d npd|  krdk r(n nL|dkr| d n6|dkr| d n |dkr| d n
| d n
| d d S )Nzhttp.status_codei  oki  i  Zpermission_deniedi  	not_foundi  Zresource_exhaustedi  Zfailed_preconditioni  Zunauthenticatedi  Zalready_existsZinvalid_argumentiX  i  Zdeadline_exceededi  Zunimplementedi  unavailablerW   Zunknown_error)r   strrX   )r   Zhttp_statusr   r   r   set_http_status  s4    

zSpan.set_http_statusc                 C   s
   | j dkS )Nr   r   rL   r   r   r   
is_success  s    zSpan.is_successc                 C   sp   | j d urd S |p| jptjj}z$t | j }| jt	|d | _ W n t
y`   t | _ Y n0 t||  d S )N)seconds)r5   r8   rO   rP   rQ   rF   rG   r3   r2   r   rH   r   rE   "maybe_create_breadcrumbs_from_span)r   r8   Zduration_secondsr   r   r   rY     s    

zSpan.finishc              	   C   s`   | j | j| j| j| j| j| j| jd}| jr8| j| j	d< | j	}|rJ||d< | j
}|r\||d< |S )N)r+   r,   r-   r.   r0   r1   r2   r5   r4   tagsdata)r+   r,   r-   r.   r0   r1   r2   r5   r4   r6   r7   )r   rvr   r   r   r   r   to_json  s$    zSpan.to_jsonc                 C   s`   | j | j| j| j| jd}| jr*| j|d< |  }|r>||d< | jr\| jjr\| jj	 |d< |S )N)r+   r,   r-   r0   r1   r4   ri   dynamic_sampling_context)
r+   r,   r-   r0   r1   r4   r|   rI   rt   r   )r   r   r~   r   r   r   get_trace_context  s"    

zSpan.get_trace_context)NNNTNNNNNNN)N)r%   r&   r'   r)   r=   r   rJ   rM   rV   r]   propertyrI   r`   rb   classmethodrf   rc   rv   rw   rq   rs   r|   r   r   rX   r   r   rY   r   r   r   r   r   r   r*   K   sP              
,



#
	 !
r*   c                       sf   e Zd ZdZdddddefddZdd Zedd	 Zdd
dZ	dddZ
 fddZdd Z  ZS )r>   )namesourceparent_sampledr   r}   _measurements_profilert   rx   Nc                 K   sf   |s d|v r t d |d}tj| fi | || _|| _|| _|| _|| _	i | _
d | _|| _d S )Nr;   z^Deprecated: use Transaction(name=...) to create transactions instead of Span(transaction=...).)r   ra   popr*   r   r   r   r   r   r}   r   r   rt   )r   r   r   r~   r   rg   r   r@   r   r   r   r     s    
zTransaction.__init__c              	   C   s*   d| j j| j| j| j| j| j| j| jf S )NzW<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, source=%r)>)	rK   r%   r   r0   r+   r,   r-   r/   r   rL   r   r   r   rM   @  s    zTransaction.__repr__c                 C   s   | S r   r   rL   r   r   r   rI   P  s    z"Transaction.containing_transactionc                 C   sx  | j d urd S |p| jptjj}|j}|d u r2d S | jd u rjtd |j	rft
|jrf|j	jddd d S | jstd d| _t| | | js| jd u rtd d S dd	 | jjD }d | _d| jd
| jid|  i| j| j | j|d}t|r\|jd ur\| jd ur\t t | jj|jjd dt t j | j! | j"d | jdd d|d< t# rn| j$|d< |%|S )Nz.Discarding transaction because sampled = Falsesample_rater;   )Zdata_categoryzCTransaction has no name, falling back to `<unlabeled transaction>`.z<unlabeled transaction>z1Discarding transaction without sampling decision.c                 S   s   g | ]}|j d ur| qS r   )r5   r   ).0r#   r   r   r   
<listcomp>  s   
z&Transaction.finish.<locals>.<listcomp>r   trace)typer;   Ztransaction_infoZcontextsr   r5   r2   r   environmentpythonrx   )Zdevice_os_nameZdevice_os_versionZduration_nsr   platformplatform_versionZ
profile_idprofiler+   Ztransaction_idZtransaction_nameZversion_codeZversion_namer   Zmeasurements)&r5   r8   rO   rP   rQ   clientr!   r   debug	transporthas_tracing_enabledoptionsZrecord_lost_eventr   ra   r*   rY   r/   r   r   r   r6   r2   r   r   r   systemreleasedurationpython_versionrB   rC   rD   r   r+   has_custom_measurements_enabledr   Zcapture_event)r   r8   r   Zfinished_spanseventr   r   r   rY   Y  sv    









zTransaction.finishc                 C   s(   t  std d S ||d| j|< d S )Nz>[Tracing] Experimental custom_measurements feature is disabled)r[   unit)r   r   r   r   )r   r   r[   r   r   r   r   set_measurement  s    zTransaction.set_measurementc                    s0   t t|  }| j|d< | j|d< | j|d< |S )Nr   r   r/   )superr>   r   r   r   r/   )r   r   rK   r   r   r     s
    


zTransaction.to_jsonc                 C   sB  | j ptjj}|j}|r|jp i }dj| jr:d| j d nd| jd}|rRt	|s\d| _
dS | j
durjdS t|dr|d |n|d	 dur|d	 n|d
 }t|stdj|d d| _
dS |stdj|t|drdndd d| _
dS t t|k | _
| j
r&tdj|d ntdj|t|d dS )aO  
        Sets the transaction's sampling decision, according to the following
        precedence rules:

        1. If a sampling decision is passed to `start_transaction`
        (`start_transaction(name: "my transaction", sampled: True)`), that
        decision will be used, regardless of anything else

        2. If `traces_sampler` is defined, its decision will be used. It can
        choose to keep or ignore any parent sampling decision, or use the
        sampling context data to make its own decision or to choose a sample
        rate for the transaction.

        3. If `traces_sampler` is not defined, but there's a parent sampling
        decision, the parent sampling decision will be used.

        4. If `traces_sampler` is not defined and there's no parent sampling
        decision, `traces_sample_rate` will be used.
        z{op}transaction <{name}><z> rx   )r0   r   FNZtraces_samplerr   Ztraces_sample_ratezN[Tracing] Discarding {transaction_description} because of invalid sample rate.)transaction_descriptionz?[Tracing] Discarding {transaction_description} because {reason}z"traces_sampler returned 0 or Falseztraces_sample_rate is set to 0)r   reasonz,[Tracing] Starting {transaction_description}z}[Tracing] Discarding {transaction_description} because it's not included in the random sample (sampling rate = {sample_rate}))r   r   )r8   rO   rP   rQ   r   r   formatr0   r   r   r/   callablerk   is_valid_sample_rater   ra   r   randomfloat)r   Zsampling_contextr8   r   r   r   r   r   r   r   _set_initial_sampling_decision  sb    



z*Transaction._set_initial_sampling_decision)N)rx   )r%   r&   r'   r)   TRANSACTION_SOURCE_UNKNOWNr   rM   r   rI   rY   r   r   r   __classcell__r   r   r   r   r>     s   
!

[


r>   )
rj   rd   r   rm   ro   rr   r   r   r   r   ).rB   r   rF   r   r   r   rO   Zsentry_sdk.profilerr   Zsentry_sdk.utilsr   Zsentry_sdk._typesr   typingr   r   r	   r
   r   r   r   r   r   ZTRANSACTION_SOURCE_CUSTOMZTRANSACTION_SOURCE_URLZTRANSACTION_SOURCE_ROUTEZTRANSACTION_SOURCE_VIEWZTRANSACTION_SOURCE_COMPONENTZTRANSACTION_SOURCE_TASKr   ZSOURCE_FOR_STYLEr<   r   r*   r>   Zsentry_sdk.tracing_utilsrj   rd   r   rm   ro   rr   r   r   r   r   r   r   r   r   <module>   sX      F  #