o
    ai                     @   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mZm	Z	 d dl
mZ d dlmZ d dlmZmZ d dlZzd dlmZ W n eyS   d dlmZ Y nw d dlZd dlmZmZmZmZ d dlmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$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m0Z0 d dl1m2Z2 d dl3m4Z4 e5dZ6dZ7G dd deZ8ddde9fddZ:ddde9fddZ;e j<		 dd!d"d#d"d$d"d%d&d'e9d(e9d)e=dd*fd+d,Z>	-	.	/	0		dd1d2Z?dd5d6Z@d7e9d8d&d9d:d;d:d<d&d=d&de9fd>d?ZA	/	0	=	&	9	:	;	:		dd@dAZBddBdCZCddDdEZD	F	&		GddHdIZEd!d"dJe=dd&fdKdLZFG dMdN dNZGG dOdP dPZHdQdRdSe=de9fdTdUZIddXdYZJdddejKf	[	\	&	]		^	_		"dd`daZL			bdd\d&d]ddce9dd"fdddeZM	d	f		gddhdiZNdddjdkZOdldmdnd&dodpdePfdqdrZQ	s	t	u	v		pddwdxZRdyd"dze=dd{fd|d}ZS	dd^d~d\e=ddde=fddZTd^d~de=fddZUd^d~de9ddddddf
ddZVdddZWd^d~de9dd"ddfddZXd/dd^d~de9d\e=dd"ddddddfddZYd/dd^d~de9dd"ddf
ddZZddde9fddZ[ddde=ddfddZ\d\e=d]dd-d.ddfddZ]d\e=d]dde9fddZ^d dl_m`Z`maZambZbmcZc d dldmeZemfZfmgZh e)rmd dl_mcZc dS dS )    N)MappingMutableMapping)	timedelta)Random)quoteunquote)Pattern)OPSPANDATA
SPANSTATUSSPANTEMPLATE)capture_internal_exceptionsfilename_for_moduleloggermatch_regex_listqualname_from_function	safe_repr	to_stringtry_convertis_sentry_urlis_valid_sample_rate_is_external_source_is_in_project_root_module_in_list)TYPE_CHECKING)Any)Dict)	Generator)Optional)Union)Iterator)Tuple)	FrameType)
Attributesz5^[ 	]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ 	]*$z(([a-zA-Z0-9+/]{4})*([a-zA-Z0-9+/]{2,3})?c                   @   sP   e Zd Z	ddddeddfddZd	edd
fddZdefddZdddZdS )EnvironHeadersHTTP_environzMapping[str, str]prefixreturnNc                 C   s   || _ || _d S N)r&   r'   )selfr&   r'    r+   V/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/sentry_sdk/tracing_utils.py__init__L   s   
zEnvironHeaders.__init__keyOptional[Any]c                 C   s   | j | j|dd   S N-_)r&   r'   replaceupper)r*   r.   r+   r+   r,   __getitem__T      zEnvironHeaders.__getitem__c                 C   s   t dd t| D S )Nc                 s   s    | ]}d V  qdS )   Nr+   ).0r2   r+   r+   r,   	<genexpr>X   s    z)EnvironHeaders.__len__.<locals>.<genexpr>)sumiterr*   r+   r+   r,   __len__W   s   zEnvironHeaders.__len__Generator[str, None, None]c                 c   sP    | j D ]!}t|tsq|dd }|| jsq|t| jd  V  qd S r0   )r&   
isinstancestrr3   r4   
startswithr'   len)r*   kr+   r+   r,   __iter__Z   s   

zEnvironHeaders.__iter__)r%   )r(   r>   )	__name__
__module____qualname__r@   r-   r5   intr=   rD   r+   r+   r+   r,   r$   K   s    
r$   optionsOptional[Dict[str, Any]]r(   c                 C   s:   | du rdS t | dduo| ddup| dduS )z}
    Returns True if either traces_sample_rate or traces_sampler is
    defined and enable_tracing is set and not false.
    NFenable_tracingtraces_sample_ratetraces_sampler)boolgetrI   r+   r+   r,   has_tracing_enabledf   s   rQ   Optional[dict[str, Any]]c                 C   s$   | d u rdS |  dpi  ddkS )NF_experimentstrace_lifecyclestream)rO   rP   r+   r+   r,   has_span_streaming_enabledw   s   rV   Fmanualcursorr   queryparams_list
paramstyleOptional[str]executemanyrecord_cursor_reprspan_originz.Generator[sentry_sdk.tracing.Span, None, None]c                 c   s    t  jd ddr|r|d gkrd }|dkrd}nd }d }t| |}i }|d ur/||d< |d ur7||d< |r=d|d	< |rG| d urG| |d
< t  t j|d|d W d    n1 s]w   Y  t jtj	||d}|
 D ]
\}	}
||	|
 qp|V  W d    d S 1 sw   Y  d S )NrS   record_sql_paramsFpyformatformatz	db.paramszdb.paramstyleTzdb.executemanyz	db.cursorrY   )messagecategorydata)opnameorigin)
sentry_sdk
get_clientrI   rO   _format_sqlr   add_breadcrumb
start_spanr	   DBitemsset_data)rX   rY   rZ   r[   r]   r^   r_   re   spanrC   vr+   r+   r,   record_sql_queries~   s@   
"rs   scopesentry_sdk.Scoperq   sentry_sdk.tracing.Spanc                 C   s   |j tjkr| j|jdd|jd d S |j tjkrZd }|jt	j
}|rAd|  kr.dkr3n nd}nd|  kr=dkrAn nd}|rO| jd	d
|j|d d S | jd	d
|jd d S |j dkrl| jdd|j|jd d S d S )Nredis)rc   typerd   re   i  iW  errori  i  warninghttphttplib)rx   rd   re   level)rx   rd   re   
subprocess)rx   rd   rc   re   )rf   r	   DB_REDISrl   description_tagsHTTP_CLIENT_datarO   r
   HTTP_STATUS_CODE)rt   rq   r}   status_coder+   r+   r,   "maybe_create_breadcrumbs_from_span   s2   




r   framer"   c                 C   s    z| j jW S  ty   Y d S w r)   )f_codeco_filename	Exception)r   r+   r+   r,   _get_frame_module_abs_path   s
   
r   is_sentry_sdk_frame	namespacein_app_includeOptional[list[str]]in_app_excludeabs_pathproject_rootc                 C   s6   t ||}t|pt ||}|  o|pt||o| S r)   )r   r   r   )r   r   r   r   r   r   should_be_includedshould_be_excludedr+   r+   r,   _should_be_included   s   
	
r   c                 C   s  t  }|dur=t|}z|jd}W n ty   d}Y nw |duo(|d}t||||||d}|r6n	|j}|dusd}|durz|j	}	W n tyS   d}	Y nw |	dur`| 
tj|j	 z|jd}W n tys   d}Y nw |dur| 
tj| t|}
|
dur|durt||
}n|dur|
|r|
|dtj}n|
}| 
tj| z|jj}W n ty   d}Y nw |dur| 
tj|jj dS dS dS )zB
    Adds OTel compatible source code information to the span
    NrE   zsentry_sdk.)r   r   r   r   r   r    )sys	_getframer   	f_globalsrO   r   rA   r   f_backf_linenorp   r
   CODE_LINENOCODE_NAMESPACEr   r3   lstripossepCODE_FILEPATHr   co_nameCODE_FUNCTION)rq   r   r   r   r   r   r   r   r   linenofilepathin_app_pathcode_functionr+   r+   r,   
add_source   sp   

r   c                 C      t  }| s
dS | jdu s| jdu rdS |jdd}|s!dS | j| j }|jdd}|tdd |k}|s;dS t| |jd |jd	|jd
d dS )zO
    Adds OTel compatible source code information to a database query span
    Nenable_db_query_sourceTdb_query_source_threshold_msr   r7   millisecondsr   r   r   rq   r   r   r   	ri   rj   	is_active	timestampstart_timestamprI   rO   r   r   )rq   clientshould_add_query_sourceduration	threshold
slow_queryr+   r+   r,   add_query_source0  &   


r   c                 C   r   )z]
    Adds OTel compatible source code information to a span for an outgoing HTTP request
    Nenable_http_request_sourceT http_request_source_threshold_msr   r7   r   r   r   r   r   r   )rq   r   should_add_request_sourcer   r   r   r+   r+   r,   add_http_request_sourceN  r   r   header+Optional[Dict[str, Union[str, bool, None]]]c                 C   s   | sdS |  dr| dr| dd } t| }|sdS | \}}}d}|r0dt|d}|r:dt|d}|r@|d	k}|||d
S )zL
    Given a `sentry-trace` header string, return a dictionary of data.
    Nz00-z-00   z{:032x}   z{:016x}0)trace_idparent_span_idparent_sampled)rA   endswithSENTRY_TRACE_REGEXmatchgroupsrb   rH   )r   r   r   r   sampled_strr   r+   r+   r,   extract_sentrytrace_datal  s&   
r   sqlc                 C   sX   d }zt | dr| |}t|tr|| jj}W n ty%   d }Y nw |p+t|S )Nmogrify)	hasattrr   r?   bytesdecode
connectionencodingr   r   )rX   r   real_sqlr+   r+   r,   rk     s   


rk   c                   @   s  e Zd ZdZdZ						d4									
					d5ddZe				 d6ddZede	fddZ
e
jde	ddfddZ
ede	fddZejde	ddfddZed7ddZde	fdd Zd8d"d#Zd9d%d&Zd:d(d)Z	*	+		d;d,d-Zde	fd.d/Zd<d0d1Zd=d2d3ZdS )>PropagationContextzJ
    The PropagationContext represents the data of a trace in Sentry.
    )	_trace_id_span_idr   r   baggagecustom_sampling_contextNr   r\   span_idr   r   Optional[bool]dynamic_sampling_contextOptional[Dict[str, str]]r   Optional[Baggage]r(   c                 C   sN   || _ 	 || _	 || _	 || _	 || _	 	 |d u r"|d ur"t|| _d | _d S r)   )r   r   r   r   r   Baggager   )r*   r   r   r   r   r   r   r+   r+   r,   r-     s   	

zPropagationContext.__init__incoming_dataDict[str, Any]c                 C   st   t  }t|}|t}t|}|d u r|S |t}|r"t|nd }t|s*|S |	| |r4||_
|  |S r)   )r   normalize_incoming_datarO   SENTRY_TRACE_HEADER_NAMEr   BAGGAGE_HEADER_NAMEr   from_incoming_header_should_continue_traceupdater   _fill_sample_rand)clsr   propagation_contextnormalized_datasentry_trace_headersentrytrace_databaggage_headerr   r+   r+   r,   from_incoming_data  s    


z%PropagationContext.from_incoming_datac                 C   s   | j s	t j| _ | j S )z!The trace id of the Sentry trace.)r   uuiduuid4hexr<   r+   r+   r,   r     s   zPropagationContext.trace_idvaluec                 C   
   || _ d S r)   )r   r*   r   r+   r+   r,   r        
c                 C   s    | j st jdd | _ | j S )z+The span id of the currently executed span.r   N)r   r   r   r   r<   r+   r+   r,   r     s   zPropagationContext.span_idc                 C   r   r)   )r   r   r+   r+   r,   r     r   rJ   c                 C   s   |    S r)   )get_baggager   r<   r+   r+   r,   r     s   z+PropagationContext.dynamic_sampling_contextc                 C   s   | j  d| j S )Nr1   )r   r   r<   r+   r+   r,   to_traceparent	  s   z!PropagationContext.to_traceparentr   c                 C   s   | j d u rt| | _ | j S r)   )r   r   !populate_from_propagation_contextr<   r+   r+   r,   r     s   
zPropagationContext.get_baggageIterator[Tuple[str, str]]c                 c   s2    t |  fV  |   }|rt|fV  dS dS )zw
        Creates a generator which returns the propagation_context's ``sentry-trace`` and ``baggage`` headers.
        N)r   r   r   	serializer   )r*   r   r+   r+   r,   iter_headers  s   zPropagationContext.iter_headers
other_dictc              	   C   s8   |  D ]\}}zt| || W q ty   Y qw dS )zU
        Updates the PropagationContext with data from the given dictionary.
        N)ro   setattrAttributeError)r*   r   r.   r   r+   r+   r,   r     s   zPropagationContext.updater   dict[str, Any]c                 C   r   r)   )r   )r*   r   r+   r+   r,   _set_custom_sampling_context%  s   
z/PropagationContext._set_custom_sampling_contextc                 C   s   d | j| j| j| j| jS )Nz\<PropagationContext _trace_id={} _span_id={} parent_span_id={} parent_sampled={} baggage={}>)rb   r   r   r   r   r   r<   r+   r+   r,   __repr__*  s   zPropagationContext.__repr__c              
   C   s   | j du rdS tt| j jd}|dur!d|  kr dk r!dS  tt| j jd}t| j|\}}zt| j||fd}W n t	yU   t
d| j d| d	 Y dS w |d
| j jd< dS )a  
        Ensure that there is a valid sample_rand value in the baggage.

        If there is a valid sample_rand value in the baggage, we keep it.
        Otherwise, we generate a sample_rand value according to the following:

          - If we have a parent_sampled value and a sample_rate in the DSC, we compute
            a sample_rand value randomly in the range:
                - [0, sample_rate) if parent_sampled is True,
                - or, in the range [sample_rate, 1) if parent_sampled is False.

          - If either parent_sampled or sample_rate is missing, we generate a random
            value in the range [0, 1).

        The sample_rand is deterministically generated from the trace_id, if present.

        This function does nothing if there is no baggage.
        Nsample_randr   r7   sample_rateintervalz5Could not backfill sample_rand, since parent_sampled=z and sample_rate=..6f)r   r   floatsentry_itemsrO   _sample_rand_ranger   _generate_sample_randr   
ValueErrorr   debug)r*   r  r  lowerr4   r+   r+   r,   r   3  s&   

z$PropagationContext._fill_sample_randc                 C   s   | j du rdS | j jdS )zAConvenience method to get the sample_rand value from the baggage.Nr  )r   r
  rO   r<   r+   r+   r,   _sample_randb  s   
zPropagationContext._sample_rand)NNNNNN)r   r\   r   r\   r   r\   r   r   r   r   r   r   r(   N)r   r   r(   r   )r(   rJ   )r(   r   )r(   r   )r   r   r(   N)r   r   r(   Nr(   N)r(   r\   )rE   rF   rG   __doc__	__slots__r-   classmethodr   propertyr@   r   setterr   r   r   r   r   r   r  r  r   r  r+   r+   r+   r,   r     sh    
!






	/r   c                   @   s   e Zd ZdZdZdZedZ		d5ddd	e	d
e
fddZedd					 d6ddZed7ddZe				 d8ddZe				 d9d d!Zed:d$d%Zd;d&d'Zd<d(d)Zd=d+e
de	fd,d-Zede	de	fd.d/Zd>d1d2Zde	fd3d4ZdS )?r   aF  
    The W3C Baggage header information (see https://www.w3.org/TR/baggage/).

    Before mutating a `Baggage` object, calling code must check that `mutable` is `True`.
    Mutating a `Baggage` object that has `mutable` set to `False` is not allowed, but
    it is the caller's responsibility to enforce this restriction.
    r
  third_party_itemsmutablezsentry-z^sentry-r   Tr
  Dict[str, str]r  r  c                 C   s   || _ || _|| _d S r)   r  )r*   r
  r  r  r+   r+   r,   r-   x  s   
zBaggage.__init__N)r  r   r\   r  r(   c          
   	   C   s   i }d}d}|rU| dD ]G}d|vrqt 5 | }| d\}}tj|r;t| dd }	t|||	< d}n
||r@dnd| 7 }W d   n1 sOw   Y  q|durat||d	< d}t|||S )
zF
        freeze if incoming header already has sentry baggage
        r   T,=r1   r7   FNr  )splitr   stripr   SENTRY_PREFIX_REGEXr   r   r@   )
r   r   r  r
  r  r  itemr.   valbaggage_keyr+   r+   r,   r     s,   

zBaggage.from_incoming_headerrt   sentry_sdk.scope.Scoper   c                 C   s   |j du r	ti S t|j S )zC
        Deprecated: use populate_from_propagation_context
        N)_propagation_contextr   r   )r   rt   r+   r+   r,   from_options  s   
zBaggage.from_optionsr   r   c                 C   s   i }d}d}t  }| st|S |j}|j|d< |dr%|d |d< |dr0|d |d< |jrC|jj|d< |jj	rC|jj	|d< |drPt
|d |d	< t|||S )
Nr   Fr   environmentrelease
public_keyorg_idrL   r  )ri   rj   r   r   rI   r   rO   
parsed_dsnr(  r)  r@   )r   r   r
  r  r  r   rI   r+   r+   r,   r     s&   



z)Baggage.populate_from_propagation_contexttransactionsentry_sdk.tracing.Transactionc                 C   s  t  }i }| st|S |jpi }|j|d< |jd|d< |dr*|d |d< |dr5|d |d< |jrH|jj	|d< |jj
rH|jj
|d< |jrU|jtvrU|j|d< |jd	urat|j|d
< |jd	uro|jrkdnd|d< |jr}|jjr}||jj t|ddS )
        Populate fresh baggage entry with sentry_items and make it immutable
        if this is the head SDK which originates traces.
        r   r  r  r&  r'  r(  r)  r+  Nr  truefalsesampledFr  )ri   rj   r   r   rI   r   r  rO   r*  r(  r)  rg   sourceLOW_QUALITY_TRANSACTION_SOURCESr  r@   r0  _baggager
  r   )r   r+  r   r
  rI   r+   r+   r,   populate_from_transaction  s4   







z!Baggage.populate_from_transactionsegmentStreamedSpanc                 C   s  t  }i }| st|S |jpi }|j|d< |jd|d< |dr*|d |d< |dr5|d |d< |jrH|jj	|d< |jj
rH|jj
|d< | dtvrY|jrY|j|d	< |jd
uret|j|d< |jd
urs|jrodnd|d< |jr|jjr||jj t|ddS )r-  r   r  r  r&  r'  r(  r)  zsentry.span.sourcer+  Nr  r.  r/  r0  Fr1  )ri   rj   r   r   rI   r   r  rO   r*  r(  r)  get_attributesLOW_QUALITY_SEGMENT_SOURCES_name_sample_rater@   r0  r4  r
  r   )r   r6  r   r
  rI   r+   r+   r,   populate_from_segment  s8   






zBaggage.populate_from_segmentc                 C   s
   d| _ d S NFr1  r<   r+   r+   r,   freeze3  s   
zBaggage.freezec                 C   s$   i }| j  D ]\}}|||< q|S r)   )r
  ro   )r*   r   r.   r   r+   r+   r,   r   6  s   
z Baggage.dynamic_sampling_contextFinclude_third_partyc              	   C   s   g }| j  D ]+\}}t  tjt| d tt| }|| W d    n1 s-w   Y  q|r;|| j d	|S )Nr  r  )
r
  ro   r   r   SENTRY_PREFIXr   r@   appendr  join)r*   r?  ro   r.   r!  r   r+   r+   r,   r   >  s   
zBaggage.serializec                 C   s   d dd | dD S )zRemove Sentry baggage from the given header.

        Given a Baggage header, return a new Baggage header with all Sentry baggage items removed.
        r  c                 s   s$    | ]}t j| s|V  qd S r)   )r   r  r   r  )r8   r   r+   r+   r,   r9   R  s    
z/Baggage.strip_sentry_baggage.<locals>.<genexpr>)rB  r  )r   r+   r+   r,   strip_sentry_baggageK  s
   zBaggage.strip_sentry_baggageOptional[float]c                 C   s:   t t| jd}|durd|  krdk r|S  dS dS )zConvenience method to get the sample_rand value from the sentry_items.

        We validate the value and parse it as a float before returning it. The value is considered
        valid if it is a float in the range [0, 1).
        r  N              ?)r   r	  r
  rO   )r*   r  r+   r+   r,   r  Y  s
   zBaggage._sample_randc                 C   s   d| j dd d| j dS )Nz
<Baggage "T)r?  z", mutable=>)r   r  r<   r+   r+   r,   r  f  r6   zBaggage.__repr__)r   T)r   r\   r  r\   r(   r   )rt   r#  r(   r   )r   r   r(   r   )r+  r,  r(   r   )r6  r7  r(   r   r  )r(   r  )F)r(   rD  )rE   rF   rG   r  r  r@  recompiler  r@   rN   r-   r  r   r%  r   r5  r<  r>  r   r   staticmethodrC  r  r  r+   r+   r+   r,   r   j  s\    


"	 1
0

r   r   zsentry_sdk.client.BaseClienturlc                 C   s&   | j d }t| |rdS t||ddS )zy
    Returns True if url matches trace_propagation_targets configured in the given client. Otherwise, returns False.
    trace_propagation_targetsFT)substring_matching)rI   r   r   )r   rK  rL  r+   r+   r,   should_propagate_tracej  s   

rN  r   r   c                 C   sH   i }|   D ]\}}|dr|dd }|dd }|||< q|S )z
    Normalizes incoming data so the keys are all lowercase with dashes instead of underscores and stripped from known prefixes.
    r%      Nr2   r1   )ro   rA   r3   r  )r   re   r.   r   r+   r+   r,   r   v  s   

r   rf   Optional[Union[str, OP]]rg   
attributestemplater   c                    s&   ddl m d	 fdd}|S )
a  
    Create a span decorator that can wrap both sync and async functions.

    :param op: The operation type for the span.
    :type op: str or :py:class:`sentry_sdk.consts.OP` or None
    :param name: The name of the span.
    :type name: str or None
    :param attributes: Additional attributes to set on the span.
    :type attributes: dict or None
    :param template: The type of span to create. This determines what kind of
        span instrumentation and data collection will be applied. Use predefined
        constants from :py:class:`sentry_sdk.consts.SPANTEMPLATE`.
        The default is `SPANTEMPLATE.DEFAULT` which is the right choice for most
        use cases.
    :type template: :py:class:`sentry_sdk.consts.SPANTEMPLATE`
    r   )should_send_default_piifr   r(   c                    s   t  d
 fdd}zt |_W n	 ty"   Y nw t  d
 fdd}zt |_W n	 tyE   Y nw t rM|S |S )D
        Decorator to create a span for the given function.
        argsr   kwargsr(   c            	   	      s
  t  }|d u rtdt | i |I d H S t|tr1tjdtdd | i |I d H S p6t	}p>tp>d}t
||} }|j||d,}| pUi  t|||| | | i |I d H }t||| |W  d    S 1 s~w   Y  d S NzbCannot create a child span for %s. Please start a Sentry transaction before calling this function.zBUse the @sentry_sdk.traces.trace decorator in span streaming mode.   
stacklevelr   )rf   rg   get_current_spanr   r  r   r?   r7  warningswarnDeprecationWarning_get_span_op_get_span_namestart_childupdate_data_set_input_attributes_set_output_attributes	rV  rW  current_spanspan_opfunction_name	span_namesend_piirq   resultrQ  rT  rg   rf   rS  rR  r+   r,   async_wrapper  s@   
$zDcreate_span_decorator.<locals>.span_decorator.<locals>.async_wrapperc            	   	      s   t  }|d u rtdt | i |S t|tr*tjdtdd | i |S p/t	}p7tp7d}t
||} }|j||d)}| pNi  t|||| | | i |}t||| |W  d    S 1 stw   Y  d S rX  r\  rg  rn  r+   r,   sync_wrapper  s>   
$zCcreate_span_decorator.<locals>.span_decorator.<locals>.sync_wrapperNrV  r   rW  r   r(   r   	functoolswrapsinspect	signature__signature__r   iscoroutinefunctionrT  ro  rp  rQ  rg   rf   rS  rR  rT  r,   span_decorator  s"   ''
z-create_span_decorator.<locals>.span_decoratorNrT  r   r(   r   )sentry_sdk.scoperS  )rf   rg   rQ  rR  r|  r+   rz  r,   create_span_decorator  s   dr  Tactivec                    s   d fdd}|S )zW
    Create a span creating decorator that can wrap both sync and async functions.
    rT  r   r(   c                    s   t  d
 fdd}zt |_W n	 ty    Y nw t  d
 fdd}zt |_W n	 tyA   Y nw t rI|S |S )rU  rV  r   rW  r(   c                     s|   t  }t|jstjddd ptpd}t| d | i |I d H }|W  d    S 1 s7w   Y  d S NzSUsing span streaming API in non-span-streaming mode. Use @sentry_sdk.trace instead.rY  rZ  r   )rg   rQ  r  ri   rj   rV   rI   r^  r_  r   start_streaming_span)rV  rW  r   rk  rm  r  rQ  rT  rg   r+   r,   ro    s   
$zNcreate_streaming_span_decorator.<locals>.span_decorator.<locals>.async_wrapperc                     sp   t  }t|jstjddd ptpd}t| d | i |W  d    S 1 s1w   Y  d S r  r  )rV  rW  r   rk  r  r+   r,   rp  )  s   
$zMcreate_streaming_span_decorator.<locals>.span_decorator.<locals>.sync_wrapperNrq  rr  ry  r  rQ  rg   r{  r,   r|    s"   
z7create_streaming_span_decorator.<locals>.span_decoratorNr}  r+   )rg   rQ  r  r|  r+   r  r,   create_streaming_span_decorator  s   	7r  Optional[sentry_sdk.Scope]#Optional[Union[Span, StreamedSpan]]c                 C   s   | pt  } | j}|S )zU
    Returns the currently active span if there is one running, otherwise `None`
    )ri   get_current_scoperq   )rt   rh  r+   r+   r,   r]  G  s   r]  c                 C   s   ddl m}m} | pt } | durAt| tr,| tj | j	dur*| j	tj dS dS t| |rC|j
| _| jdurE|j
| j_dS dS dS dS )z
    Set the status of the current or given span to INTERNAL_ERROR.
    Also sets the status of the transaction (root span) to INTERNAL_ERROR.
    r   )r7  
SpanStatusN)sentry_sdk.tracesr7  r  r]  r?   Span
set_statusr   INTERNAL_ERRORcontaining_transactionERRORstatus_segment)rq   r7  r  r+   r+   r,   set_span_erroredR  s   




r  rE  rF  r  r   r  tuple[float, float]c                C   sl   |\}}||k st dt| }t|d }t|d }z|||}W |d S  t y5   |}Y |d S w )a  Generate a sample_rand value from a trace ID.

    The generated value will be pseudorandomly chosen from the provided
    interval. Specifically, given (lower, upper) = interval, the generated
    value will be in the range [lower, upper). The value has 6-digit precision,
    so when printing with .6f, the value will never be rounded up.

    The pseudorandom number generator is seeded with the trace ID.
    z/Invalid interval: lower must be less than upperi@B )r  r   rH   	randrange)r   r  r  r4   rnglower_scaledupper_scaledsample_rand_scaledr+   r+   r,   r  f  s   r  r   r   r  rD  c                 C   s,   | du s|du r
dS | du rd|fS |dfS )z
    Compute the lower (inclusive) and upper (exclusive) bounds of the range of values
    that a generated sample_rand value must fall into, given the parent_sampled and
    sample_rate values.
    Nr  TrE  rF  r+   )r   r  r+   r+   r,   r    s
   r  r2  r.   r/   c                 C   sT   d}t | tr| |}|S t| |r(zt| |}W |S  ty'   d}Y |S w |S )z
    Gets a value from a source object. The source can be a dict or an object.
    It is checked for dictionary keys and object attributes.
    N)r?   dictrO   r   getattrr   )r2  r.   r   r+   r+   r,   
_get_value  s   


r  zUnion[str, SPANTEMPLATE]rW  c                 C   s   |}| t jkr/d}|r"dD ]}||r!t|| tr!|| } nq|r+d| }|S d}|S | t jkr;d| }|S | t jkrEd| }|S )zF
    Get the name of the span based on the template and the name.
    N)model
model_namezchat chatzinvoke_agent zexecute_tool )r   AI_CHATrO   r?   r@   AI_AGENTAI_TOOL)rR  rg   rW  rk  r  r.   r+   r+   r,   rb    s&   




rb  c                 C   s2   t jtjt jtjt jtji}|| tj	}t
|S )z>
    Get the operation of the span based on the template.
    )r   r  r	   GEN_AI_CHATr  GEN_AI_INVOKE_AGENTr  GEN_AI_EXECUTE_TOOLrO   FUNCTIONr@   )rR  mappingrf   r+   r+   r,   ra    s   ra  rl  rV  ztuple[Any, ...]r   c                    sJ  i  | t jt jt jfv rtjtftjtftjtftjtftjt	ftj
tftjtftjtftjtftjt	fd
dtddddf fdd}t| D ]7\}}|d	krft|trf tjg d
|d qK|dkr}t|tr} tjg d|d qK||| qK| t jkr|rt||d tj< tj v rt tj  tj<  S )z;
    Get input attributes for the given span template.
    )
r  r  agent
agent_name
max_tokensfrequency_penaltypresence_penaltytemperaturetop_ptop_kr.   r   r   r(   Nc                    s>   | v r|  \}}|d urt ||r| |< d S d S d S d S r)   )r?   )r.   r   	attribute	data_typerQ  r  r+   r,   _set_from_key  s   z,_get_input_attributes.<locals>._set_from_keypromptuser)rolecontentsystem_promptsystem)rV  rW  )r   r  r  r  r
   GEN_AI_REQUEST_MODELr@   GEN_AI_AGENT_NAMEGEN_AI_REQUEST_MAX_TOKENSrH    GEN_AI_REQUEST_FREQUENCY_PENALTYr	  GEN_AI_REQUEST_PRESENCE_PENALTYGEN_AI_REQUEST_TEMPERATUREGEN_AI_REQUEST_TOP_PGEN_AI_REQUEST_TOP_Klistro   r?   
setdefaultGEN_AI_REQUEST_MESSAGESrA  r   GEN_AI_TOOL_INPUT)rR  rl  rV  rW  r  r.   r   r+   r  r,   _get_input_attributes  sF   	


r  usagec                    sH   i  dt ddddf fdd}|tjd |tjd	 |tjd
  S )z
    Get usage attributes.
    r  keysztuple[str, ...]r(   Nc                    s2   |D ]}t |}|d urt|tr| | < qd S r)   )r  r?   rH   )r  r  r.   r   rQ  r  r+   r,   _set_from_keys  s   
z-_get_usage_attributes.<locals>._set_from_keys)prompt_tokensinput_tokens)completion_tokensoutput_tokens)total_tokens)r@   r
   GEN_AI_USAGE_INPUT_TOKENSGEN_AI_USAGE_OUTPUT_TOKENSGEN_AI_USAGE_TOTAL_TOKENS)r  r  r+   r  r,   _get_usage_attributes  s   r  rm  c           	      C   s  i }| t jt jt jfv rqt Z |g}t|d}|| t|d}t|d}|| |D ]}|dur;|t| q.t|d}|durOt	|t
rO||tj< t|d}|durbt	|t
rb||tj< W d   n1 slw   Y  | t jkr|rt||tj< |S )z<
    Get output attributes for the given span template.
    r  metadataNr  r  )r   r  r  r  r   r  rA  r   r  r?   r@   r
   GEN_AI_RESPONSE_MODELr   GEN_AI_TOOL_OUTPUT)	rR  rl  rm  rQ  usage_candidatesr  metausage_candidater  r+   r+   r,   _get_output_attributes)  s0   








r  r  rT  c           	      C   s   i }|t jkrtjdtj|i}n$|t jkrtjdi}n|t jkr4tjdtj|i}|j}|dur4||tj	< |
t|||| | |pCi  dS )a  
    Set span input attributes based on the given span template.

    :param span: The span to set attributes on.
    :param template: The template to use to set attributes on the span.
    :param send_pii: Whether to send PII data.
    :param f: The wrapped function.
    :param args: The arguments to the wrapped function.
    :param kwargs: The keyword arguments to the wrapped function.
    invoke_agentr  execute_toolN)r   r  r
   GEN_AI_OPERATION_NAMEr  r  r  GEN_AI_TOOL_NAMEr  GEN_AI_TOOL_DESCRIPTIONr   r  rd  )	rq   rR  rl  rg   rT  rV  rW  rQ  	docstringr+   r+   r,   re  Q  s"   



re  c                 C   s   |  t|||p	i  dS )a%  
    Set span output attributes based on the given span template.

    :param span: The span to set attributes on.
    :param template: The template to use to set attributes on the span.
    :param send_pii: Whether to send PII data.
    :param result: The result of the wrapped function.
    N)rd  r  )rq   rR  rl  rm  r+   r+   r,   rf  }  s   rf  r   r   c                 C   s   t  }|j}|r|jnd}| r| jdnd}|dur2|dur2||kr2td| d| d dS |jdd}|rY|durC|du sK|du rY|durYtd| d| d dS d	S )
z
    Check if we should continue the incoming trace according to the strict_trace_continuation spec.
    https://develop.sentry.dev/sdk/telemetry/traces/#stricttracecontinuation
    Nr)  zKStarting a new trace because org IDs don't match (incoming baggage org_id: z, SDK org_id: )Fstrict_trace_continuationzvStarting a new trace because strict trace continuation is enabled and one org ID is missing (incoming baggage org_id: T)	ri   rj   r*  r)  r
  rO   r   r  rI   )r   r   r*  client_org_idbaggage_org_idr  r+   r+   r,   r     s,   r   headerszMutableMapping[str, str]sentry_baggagec                 C   s>   |  td}t|}t|dkrdnd}|| | | t< dS )zAdd the Sentry baggage to the headers.

    This function directly mutates the provided headers. The provided sentry_baggage
    is appended to the existing baggage. If the baggage already contains Sentry items,
    they are stripped out first.
    r   r   r  N)rO   r   r   rC  rB   )r  r  existing_baggagestripped_existing_baggage	separatorr+   r+   r,   add_sentry_baggage_to_headers  s
   	


r  zOptional[Attributes]z<tuple[bool, Optional[float], Optional[float], Optional[str]]c                 C   s  t  }t|jsdS | }d}|jdur|j }|du r$t|j}t	|j
d}|rRd| |j|j|j|r<t|ni di}|jrJ||j |jd |}n|jdur[|j}n|jd }t|ddsqtd	|  d
 dS t|}|s|r|d}	nd}	td	|  d|	  dS |jr|d|jj  }|std	|  d dS ||k }
|
rtd|   d}ntd	|  d| d d}|
|||fS )z
    Decide whether a span should be sampled.

    Returns a tuple with:
    1. the sampling decision
    2. the effective sample rate
    3. the sample rand
    4. the reason for not sampling the span, if unsampled
    )FNNNNrM   span_context)rg   r   r   r   rQ  rL   Tracing)r2  z[Tracing] Discarding z  because of invalid sample rate.)FNNr  z"traces_sampler returned 0 or Falseztraces_sample_rate is set to 0z	 because )FrE  Nr  rY  z because backpressure)FrE  Nbackpressurez[Tracing] Starting zA because it's not included in the random sample (sampling rate = r  r  )ri   rj   rQ   rI   get_active_propagation_contextr   r  r  r   callablerO   r   r   r  r   r   r   r   rz   r	  r  monitordownsample_factor)rg   rQ  rt   r   r   r  traces_sampler_definedsampling_contextr  reasonr0  outcomer+   r+   r,   _make_sampling_decision  sb   






r  c           
      C   s   t  }|jdpi d}|sdS dddddtfdd	}|D ]W}t|ttfr2||| r1 d
S q t|trwd|v s?d|v rwd
}d
}|pFi }d|v rR||d | }d|v rp|d 	 D ]\}}	||vsk||	|| sod} nq\|rw|rw d
S q dS )z:Determine if a span fits one of the rules in ignore_spans.rS   ignore_spansFruler   r   r(   c                 S   s.   t | trt |trt| |S dS | |kS r=  )r?   r   r@   rN   	fullmatch)r  r   r+   r+   r,   _matches"  s
   

z!is_ignored_span.<locals>._matchesTrg   rQ  )
ri   rj   rI   rO   rN   r?   r@   r   r  ro   )
rg   rQ  r   r  r  r  name_matchesattributes_matchr  r   r+   r+   r,   is_ignored_span  s8   	

r  )r   r3  r   r  )r9  r7  rm   )r  )FrW   )rt   ru   rq   rv   r(   N)r   r"   r(   r\   )
rq   rv   r   r\   r   r   r   r   r(   N)rq   rv   r(   N)r   r\   r(   r   )r   r   r(   r   )
rf   rP  rg   r\   rQ  rR   rR  r   r(   r   )NNTr)   )rt   r  r(   r  )rq   r  r(   N)r   r   r  rD  r(   r  )r  r   r(   r   )i
contextlibrs  ru  r   rH  r   r^  collections.abcr   r   datetimer   randomr   urllib.parser   r   r   r   ImportErrortypingri   sentry_sdk.constsr	   r
   r   r   sentry_sdk.utilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   typesr"   sentry_sdk._typesr#   rI  r   base64_strippedr$   rN   rQ   rV   contextmanagerr@   rs   r   r   r   r   r   r   r   rk   r   r   rN  r   DEFAULTr  r  r]  r  r	  r  r  r  rb  ra  r  r  r  re  rf  r   r  r  r  sentry_sdk.tracingr   r3  r   r  r  r9  r7  rm   r  r+   r+   r+   r,   <module>   s   <
-

!


I

! L  

 
D





<
(
,
$

X.