
    `i$                     B   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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# d dl$m%Z% e%r0d 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.  ej/        d          Z0dZ1 G d de          Z2ddde3fdZ4ddde3fdZ5e j6        	 	 dddddd dd!d"d#e3d$e3d%e7dd&fd'            Z8	 	 	 	 	 	 dd,Z9dd/Z:d0e3d1d"d2d3d4d3d5d"d6d"de3fd7Z;	 	 	 	 	 	 	 	 	 	 dd8Z<dd9Z=dd:Z>	 	 	 	 dd=Z?ddd>e7dd"fd?Z@ G d@ dA          ZA G dB dC          ZBdDdEdFe7de3fdGZCddJZDdddejE        f	 	 	 	 	 	 	 	 	 ddQZFdddTZGdddUZHdVdWdXd"dYdZdeIfd[ZJ	 	 	 	 	 	 dd`ZKdaddbe7ddcfddZL	 ddOdedMe7dfdde7fdgZMdOdede7fdhZNdOdedie3djdkdfdlddlf
dmZOddoZPdOdedie3dpdddlfdqZQd*drdOdedie3dMe7dsddjdkdfdlddfdtZRd*drdOdedie3dpdddf
duZSdvdwde3fdxZTdydzd{e7ddfd|ZUd d}lVmWZWmXZXmYZY e%rd d~lVmZZZ dS dS )    N)MappingMutableMapping)	timedelta)Random)quoteunquote)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_external_source_is_in_project_root_module_in_list)TYPE_CHECKING)Any)Dict)	Generator)Optional)Union)Iterator)Tuple)	FrameTypez5^[ 	]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ 	]*$z(([a-zA-Z0-9+/]{4})*([a-zA-Z0-9+/]{2,3})?c                   J    e Zd Z	 ddddeddfdZdedd	fd
ZdefdZddZdS )EnvironHeadersHTTP_environzMapping[str, str]prefixreturnNc                 "    || _         || _        d S N)r%   r&   )selfr%   r&   s      l/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/sentry_sdk/tracing_utils.py__init__zEnvironHeaders.__init__B   s    
     keyOptional[Any]c                 x    | j         | j        |                    dd                                          z            S N-_)r%   r&   replaceupper)r*   r.   s     r+   __getitem__zEnvironHeaders.__getitem__J   s0    |DK#++c3*?*?*E*E*G*GGHHr-   c                 N    t          d t          |           D                       S )Nc              3      K   | ]}d V  dS )   N ).0r3   s     r+   	<genexpr>z)EnvironHeaders.__len__.<locals>.<genexpr>N   s"      ))1))))))r-   )sumiterr*   s    r+   __len__zEnvironHeaders.__len__M   s%    ))d4jj))))))r-   Generator[str, None, None]c              #     K   | j         D ]y}t          |t                    s|                    dd                                          }|                    | j                  s[|t          | j                  d          V  zd S r1   )r%   
isinstancestrr4   r5   
startswithr&   len)r*   ks     r+   __iter__zEnvironHeaders.__iter__P   s       	( 	(Aa%% 		#s##))++A<<,, C$$&&'''''	( 	(r-   )r$   )r'   rA   )	__name__
__module____qualname__rD   r,   r6   intr@   rH   r:   r-   r+   r#   r#   A   s          $  
	   Is I I I I I* * * * *	( 	( 	( 	( 	( 	(r-   r#   optionsOptional[Dict[str, Any]]r'   c                     | 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rM   s    r+   has_tracing_enabledrV   \   si    
 u$%%U2 	
KK,--T9 9{{+,,D8	  r-   Optional[dict[str, Any]]c                 f    | dS |                      d          pi                      d          dk    S )NF_experimentstrace_lifecyclestream)rT   rU   s    r+   has_span_streaming_enabledr\   m   s7    uKK''-2223DEEQQr-   Fmanualcursorr   queryparams_list
paramstyleOptional[str]executemanyrecord_cursor_reprspan_originz.Generator[sentry_sdk.tracing.Span, None, None]c              #   T  K   t          j                    j        d                             dd          r|r|d gk    rd }|dk    rd}nd }d }t	          | |          }i }|||d<   |||d<   |rd|d	<   |r| | |d
<   t                      5  t          j        |d|           d d d            n# 1 swxY w Y   t          j        t          j	        ||          5 }|
                                D ]\  }	}
|                    |	|
           |V  d d d            d S # 1 swxY w Y   d S )NrY   record_sql_paramsFpyformatformatz	db.paramszdb.paramstyleTzdb.executemanyz	db.cursorr_   )messagecategorydata)opnameorigin)
sentry_sdk
get_clientrM   rT   _format_sqlr   add_breadcrumb
start_spanr	   DBitemsset_data)r^   r_   r`   ra   rc   rd   re   rl   spanrG   vs              r+   record_sql_queriesrz   t   s      &~6::;NPUVV  	kdV33K##!J
&&ED'[ *_ &!% #f0"[	$	&	& N N!%'MMMMN N N N N N N N N N N N N N N 
	5
 
 
  
JJLL 	  	 DAqMM!Q


                 s$   B//B36B35DD!$D!scopesentry_sdk.Scoperx   sentry_sdk.tracing.Spanc                     |j         t          j        k    r%|                     |j        dd|j                   d S |j         t          j        k    rd }|j                            t          j
                  }|r%d|cxk    rdk    rn nd}nd|cxk    rdk    rn nd}|r |                     d	d
|j        |           d S |                     d	d
|j                   d S |j         dk    r%|                     dd|j        |j                   d S d S )Nredis)rj   typerk   rl   i  iW  errori  i  warninghttphttplib)r   rk   rl   level)r   rk   rl   
subprocess)r   rk   rj   rl   )rm   r	   DB_REDISrs   description_tagsHTTP_CLIENT_datarT   r
   HTTP_STATUS_CODE)r{   rx   r   status_codes       r+   "maybe_create_breadcrumbs_from_spanr      sy    w"+$7W4: 	 	
 	
 	
 	
 	
 
BN	"	"jnnX%>?? 	"k((((S(((((****s*****! 	S  idj !        fytz RRRRR	L	 	 !$	 	 	
 	
 	
 	
 	
 
!	 r-   framer!   c                 >    	 | j         j        S # t          $ r Y d S w xY wr)   )f_codeco_filename	Exception)r   s    r+   _get_frame_module_abs_pathr      s4    |''   tts    
is_sentry_sdk_frame	namespacein_app_includeOptional[list[str]]in_app_excludeabs_pathproject_rootc                     t          ||          }t          |          pt          ||          }|  o|pt          ||          o| S r)   )r   r   r   )r   r   r   r   r   r   should_be_includedshould_be_excludeds           r+   _should_be_includedr      si     )NCC,X66 />; ; #"  	T,77R@R<Rr-   c                    t          j                    }|wt          |          }	 |j                            d          }n# t
          $ r d}Y nw xY w|duo|                    d          }t          ||||||          }|rn|j        }|wd}|q	 |j	        }	n# t
          $ r d}	Y nw xY w|	%| 
                    t          j        |j	                   	 |j                            d          }n# t
          $ r d}Y nw xY w| | 
                    t          j        |           t          |          }
|
|t          ||
          }nM|I|
                    |          r4|
                    |d                              t"          j                  }n|
}| 
                    t          j        |           	 |j        j        }n# t
          $ r d}Y nw xY w|.| 
                    t          j        |j        j                   dS dS dS )zB
    Adds OTel compatible source code information to the span
    NrI   zsentry_sdk.)r   r   r   r   r   r    )sys	_getframer   	f_globalsrT   r   rE   r   f_backf_linenorw   r
   CODE_LINENOCODE_NAMESPACEr   r4   lstripossepCODE_FILEPATHr   co_nameCODE_FUNCTION)rx   r   r   r   r   r   r   r   r   linenofilepathin_app_pathcode_functions                r+   
add_sourcer      s    '*mooE

-e44	).)<)<Z)H)HII 	 	 	III	 (t3 
	8L8L9
 9
 1 3))%
 
 
  	/ 
2  	^FF 	 	 	FFF	MM(.???	++J77II 	 	 	III	 MM(19===-e44$1)XFF)h.A.A,.O.O)&..|R@@GGOO&MM(0+>>>	!!L0MM 	! 	! 	! MMM	! $MM(0%,2FGGGGG? < %$sG   A AAB B*)B*C0 0C?>C?6G GGc                    t          j                    }|                                sdS | j        | j        dS |j                            dd          }|sdS | j        | j        z
  }|j                            dd          }|t          d          z  |k    }|sdS t          | |j        d         |j                            d	          |j                            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   r9   millisecondsr   r   r   rx   r   r   r   	rp   rq   	is_active	timestampstart_timestamprM   rT   r   r   )rx   clientshould_add_query_sourceduration	threshold
slow_querys         r+   add_query_sourcer   &  s
    "$$F ~!5!=$n001I4PP" ~ 44H""#A1EEII15555	AJ ^N3~))*:;;~))*:;;	     r-   c                    t          j                    }|                                sdS | j        | j        dS |j                            dd          }|sdS | j        | j        z
  }|j                            dd          }|t          d          z  |k    }|sdS t          | |j        d         |j                            d	          |j                            d
                     dS )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   r9   r   r   r   r   r   r   )rx   r   should_add_request_sourcer   r   r   s         r+   add_http_request_sourcer   D  s    "$$F ~!5!= & 2 23OQU V V$ ~ 44H""#EqIIII15555	AJ ^N3~))*:;;~))*:;;	     r-   header+Optional[Dict[str, Union[str, bool, None]]]c                    | sdS |                      d          r|                     d          r
| dd         } t                              |           }|sdS |                                \  }}}d}|r#d                    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)rE   endswithSENTRY_TRACE_REGEXmatchgroupsri   rL   )r   r   r   r   sampled_strr   s         r+   extract_sentrytrace_datar   b  s      t FOOE$:$: "$$V,,E t,1LLNN)HnkN 7##C"$5$566 C"))#nb*A*ABB ,$+ ((  r-   sqlc                    d }	 t          | d          rI|                     |          }t          |t                    r|                    | j        j                  }n# t          $ r d }Y nw xY w|pt          |          S )Nmogrify)	hasattrr   rC   bytesdecode
connectionencodingr   r   )r^   r   real_sqls      r+   rr   rr     s    H69%% 	G~~c**H(E** G#??6+<+EFF    %y~~%s   AA A-,A-c                   J   e Zd ZdZdZ	 	 	 	 	 	 d$	 	 	 	 	 	 	 	 	 	 	 	 	 d%dZe	 	 	 	 d&d            Zede	fd            Z
e
j        de	ddfd            Z
ede	fd            Zej        de	ddfd            Zed'd            Zde	fdZd(dZd)dZd*d Zde	fd!Zd+d"Zd,d#ZdS )-PropagationContextzJ
    The PropagationContext represents the data of a trace in Sentry.
    )	_trace_id_span_idr   r   baggageNr   rb   span_idr   r   Optional[bool]dynamic_sampling_contextOptional[Dict[str, str]]r   Optional[Baggage]r'   c                     || _         	 || _        	 || _        	 || _        	 || _        	 	 ||t          |          | _        d S d S d S r)   )r   r   r   r   r   Baggage)r*   r   r   r   r   r   r   s          r+   r,   zPropagationContext.__init__  sq     "/:,	H -	Q PN?7C"#;<<DLLL ?CCr-   incoming_dataDict[str, Any]c                    t                      }t          |          }|                    t                    }t	          |          }||S |                    t
                    }|rt                              |          nd }t          |          s|S |	                    |           |r||_
        |                                 |S r)   )r   normalize_incoming_datarT   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   s           r+   from_incoming_dataz%PropagationContext.from_incoming_data  s     1221-@@-112JKK34GHH #&&(,,-@AA<JTG((888PT 	 &g.. 	'&&""#3444 	2*1'--///""r-   c                 X    | j         st          j                    j        | _         | j         S )z!The trace id of the Sentry trace.)r   uuiduuid4hexr?   s    r+   r   zPropagationContext.trace_id  s&     ~ 	.!Z\\-DN~r-   valuec                     || _         d S r)   )r   r*   r  s     r+   r   zPropagationContext.trace_id  s    r-   c                 h    | j         s%t          j                    j        dd         | _         | j         S )z+The span id of the currently executed span.r   N)r   r   r  r  r?   s    r+   r   zPropagationContext.span_id  s/     } 	2 JLL,RSS1DM}r-   c                     || _         d S r)   )r   r  s     r+   r   zPropagationContext.span_id  s    r-   rN   c                 N    |                                                                  S r)   )get_baggager   r?   s    r+   r   z+PropagationContext.dynamic_sampling_context  s     !!::<<<r-   c                 $    | j          d| j         S )Nr2   )r   r   r?   s    r+   to_traceparentz!PropagationContext.to_traceparent  s    -00$,000r-   r   c                 \    | j         t                              |           | _         | j         S r)   )r   r   !populate_from_propagation_contextr?   s    r+   r	  zPropagationContext.get_baggage  s'    <"DDTJJDL|r-   Iterator[Tuple[str, str]]c              #      K   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   s     r+   iter_headerszPropagationContext.iter_headers  sk       '(;(;(=(=====""$$..00 	/%w......	/ 	/r-   
other_dictc                 ~    |                                 D ]'\  }}	 t          | ||           # t          $ r Y $w xY wdS )zU
        Updates the PropagationContext with data from the given dictionary.
        N)rv   setattrAttributeError)r*   r  r.   r  s       r+   r   zPropagationContext.update  sg     %**,, 	 	JCc5))))!   	 	s   -
::c                 f    d                     | j        | j        | j        | j        | j                  S )Nz\<PropagationContext _trace_id={} _span_id={} parent_span_id={} parent_sampled={} baggage={}>)ri   r   r   r   r   r   r?   s    r+   __repr__zPropagationContext.__repr__  s5    mttNML
 
 	
r-   c                    | j         dS t          t          | j         j                            d                    }|d|cxk    rdk     rn ndS t          t          | j         j                            d                    }t          | j        |          \  }}	 t          | j        ||f          }n1# t          $ r$ t          j        d| j         d| d	           Y dS w xY 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   r9   sample_rateintervalz5Could not backfill sample_rand, since parent_sampled=z and sample_rate=..6f)r   r   floatsentry_itemsrT   _sample_rand_ranger   _generate_sample_randr   
ValueErrorr   debug)r*   r  r  lowerr5   s        r+   r   z$PropagationContext._fill_sample_rand!  s7   & <F!%)B)F)F})U)UVV"qK';';';';!';';';';';F "%)B)F)F})U)UVV)$*={KKu	/PUWWWKK 		 		 		
 L2H[ 2 2#.2 2 2   FF		 7B3G3G!-000s   B4 4*C"!C"c                 R    | j         dS | j         j                            d          S )zAConvenience method to get the sample_rand value from the baggage.Nr  )r   r   rT   r?   s    r+   _sample_randzPropagationContext._sample_randP  s(    <4|(,,];;;r-   )NNNNNN)r   rb   r   rb   r   rb   r   r   r   r   r   r   r'   N)r   r   r'   r   )r'   rN   )r'   r   )r'   r  )r  r   r'   Nr'   N)r'   rb   )rI   rJ   rK   __doc__	__slots__r,   classmethodr   propertyrD   r   setterr   r   r  r	  r  r   r  r   r'  r:   r-   r+   r   r     s.        I %)#'*.+/?C'+=!= != (	=
 )= #== %= 
= = = => #,#	# # # [#: #    X _c d    _     X ^S T    ^ = = = X=1 1 1 1 1   
/ / / /   
# 
 
 
 
-H -H -H -H^< < < < < <r-   r   c                   *   e Zd ZdZdZdZ ej        d          Z	 	 d&ddd	e	d
e
fdZedd	 	 	 	 	 d'd            Zed(d            Ze	 	 	 	 d)d            Ze	 	 	 	 d*d            Zd+dZd,dZd-d e
de	fd!Zede	de	fd"            Zd.d$Zde	fd%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]r0  r1  c                 0    || _         || _        || _        d S r)   r/  )r*   r   r0  r1  s       r+   r,   zBaggage.__init__f  s     )!2r-   N)r'  r   rb   r'  r'   c                   i }d}d}|r|                     d          D ]}d|vrt                      5  |                                }|                     d          \  }}t          j                            |          r=t          |                     d          d                   }	t          |          ||	<   d}n||rdnd|z   z  }ddd           n# 1 swxY w Y   |t          |          |d	<   d}t          |||          S )
zF
        freeze if incoming header already has sentry baggage
        r   T,=r2   r9   FNr  )splitr   stripr   SENTRY_PREFIX_REGEXr   r   rD   )
r   r   r'  r   r0  r1  itemr.   valbaggage_keys
             r+   r   zBaggage.from_incoming_headerp  ss     	WS)) W Wd??022 W W::<<D#zz#HC288== W&-ciinnQ.?&@&@4;CLL[1"')5F.NccBRV-VV)W W W W W W W W W W W W W W W #*-l*;*;L'G|%6@@@s   BCC	C	r{   sentry_sdk.scope.Scoper   c                 l    |j         t          i           S t                              |j                   S )zC
        Deprecated: use populate_from_propagation_context
        )_propagation_contextr   r  )r   r{   s     r+   from_optionszBaggage.from_options  s0    
 %-2;;889STTTr-   r   r   c                    i }d}d}t          j                    }|                                st          |          S |j        }|j        |d<   |                    d          r|d         |d<   |                    d          r|d         |d<   |j        r*|j        j        |d<   |j        j	        r|j        j	        |d<   |                    d          rt          |d                   |d	<   t          |||          S )
Nr   Fr   environmentrelease
public_keyorg_idrQ   r  )rp   rq   r   r   rM   r   rT   
parsed_dsnrD  rE  rD   )r   r   r   r0  r1  r   rM   s          r+   r  z)Baggage.populate_from_propagation_context  s    *,&((!! 	)<(((.#6#?Z ;;}%% 	A*1-*@L';;y!! 	9&-i&8L# 	B)/):)EL& ' B)/):)AX&;;+,, 	M*-g6J.K*L*LL'|%6@@@r-   transactionsentry_sdk.tracing.Transactionc                    t          j                    }i }|                                st          |          S |j        pi }|j        |d<   |j        d|d<   |                    d          r|d         |d<   |                    d          r|d         |d<   |j        r*|j        j	        |d<   |j        j
        r|j        j
        |d<   |j        r|j        t          vr
|j        |d<   |j        t          |j                  |d
<   |j        |j        rdnd|d<   |j        r+|j        j        r|                    |j        j                   t          |d          S )z
        Populate fresh baggage entry with sentry_items and make it immutable
        if this is the head SDK which originates traces.
        r   r  r  rB  rC  rD  rE  rG  Nr  truefalsesampledFr1  )rp   rq   r   r   rM   r   r'  rT   rF  rD  rE  rn   sourceLOW_QUALITY_TRANSACTION_SOURCESr  rD   rL  _baggager   r   )r   rG  r   r   rM   s        r+   populate_from_transactionz!Baggage.populate_from_transaction  s    &(()+!! 	)<(((.&B#.#7Z )4)A&G&G]#;;}%% 	A*1-*@L';;y!! 	9&-i&8L# 	B)/):)EL& ' B)/):)AX& 	;"*III*5*:L'".*-k.E*F*FL'*0;0C&PffL#
  	CK$8$E 	C 4 ABBB|U3333r-   c                     d| _         d S )NFrM  r?   s    r+   freezezBaggage.freeze  s    r-   c                 R    i }| j                                         D ]
\  }}|||<   |S r)   )r   rv   )r*   r   r.   r:  s       r+   r   z Baggage.dynamic_sampling_context  s9    *0022 	 	ICF3KKr-   Finclude_third_partyc                    g }| j                                         D ]|\  }}t                      5  t          j        t          |          z   dz   t          t          |                    z   }|                    |           d d d            n# 1 swxY w Y   }|r|                    | j                   d	                    |          S )Nr6  r5  )
r   rv   r   r   SENTRY_PREFIXr   rD   appendr0  join)r*   rU  rv   r.   r;  r:  s         r+   r  zBaggage.serialize  s    )//11 	# 	#HC,.. # #,uSzz9C?%C//QT"""# # # # # # # # # # # # # # #  	1LL/000xxs   ABB	B	c                 f    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.
        r5  c              3   |   K   | ]7}t           j                            |                                          3|V  8d S r)   )r   r9  r   r8  )r;   r:  s     r+   r<   z/Baggage.strip_sentry_baggage.<locals>.<genexpr>  sU        288FF     r-   )rY  r7  )r   s    r+   strip_sentry_baggagezBaggage.strip_sentry_baggage  sB     xx "LL--  
 
 	
r-   Optional[float]c                     t          t          | j                            d                    }|d|cxk    rdk     rn n|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   rT   )r*   r  s     r+   r'  zBaggage._sample_rand  sV     "%):)>)>})M)MNN"sk'?'?'?'?C'?'?'?'?'?tr-   c                 F    d|                      d           d| j         dS )Nz
<Baggage "T)rU  z", mutable=>)r  r1  r?   s    r+   r  zBaggage.__repr__#  s-    `DNNtNDD``QUQ]````r-   )r   T)r   rb   r'  rb   r'   r   )r{   r=  r'   r   )r   r   r'   r   )rG  rH  r'   r   r(  )r'   r2  )F)r'   r]  )rI   rJ   rK   r)  r*  rW  recompiler9  rD   rS   r,   r+  r   r@  r  rQ  rS  r   r  staticmethodr\  r'  r  r:   r-   r+   r   r   X  s         AIM$"*Z00
 "$	 &  	    
 )-	 A  A A &	 A
 
 A  A  A [ AD U U U [U A"6A	A A A [A@ /4:/4	/4 /4 /4 [/4b       T c     
S 
S 
 
 
 \
   a# a a a a a ar-   r   r   zsentry_sdk.client.BaseClienturlc                 d    | j         d         }t          | |          rdS t          ||d          S )zy
    Returns True if url matches trace_propagation_targets configured in the given client. Otherwise, returns False.
    trace_propagation_targetsFT)substring_matching)rM   r   r   )r   rf  rh  s      r+   should_propagate_tracerj  '  s?     !'/J KVS!! uC!:tTTTTr-   r   r   c                     i }|                                  D ]Q\  }}|                    d          r
|dd         }|                    dd                                          }|||<   R|S )z
    Normalizes incoming data so the keys are all lowercase with dashes instead of underscores and stripped from known prefixes.
    r$      Nr3   r2   )rv   rE   r4   r%  )r   rl   r.   r  s       r+   r   r   3  sx     D#))++  
U>>'"" 	abb'Ckk#s##))++S		Kr-   rm   Optional[Union[str, OP]]rn   
attributestemplater   c                 0     ddl m d f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                 v    t          j                   d fd            }	 t          j                   |_        n# t
          $ r Y nw xY wt          j                   d fd            }	 t          j                   |_        n# t
          $ r Y nw xY wt          j                   r|S |S )	zD
        Decorator to create a span for the given function.
        argsr   kwargsr'   c            
        K   t                      }|0t          j        dt          
                      
| i | d {V S pt	                    }pt          
          pd}t          ||          }             }|                    ||          5 }|                    	pi            t          |||
| |            
| i | d {V }t          |||           |cd d d            S # 1 swxY w Y   d S NzbCannot create a child span for %s. Please start a Sentry transaction before calling this function.r   )rm   rn   
get_current_spanr   r$  r   _get_span_op_get_span_namestart_childupdate_data_set_input_attributes_set_output_attributesrt  ru  current_spanspan_opfunction_name	span_namesend_piirx   resultrn  rr  rn   rm   rq  ro  s            r+   async_wrapperzDcreate_span_decorator.<locals>.span_decorator.<locals>.async_wrapper_  s     +--L#V*1--  
 Q//////////2L22G C$:1$=$=CM&xGGI..00H)) *      !1r222%(HmQf    !q$1&11111111&tXxHHH                 s   AC55C9<C9c            
         t                      }|*t          j        dt          
                      
| i |S pt	                    }pt          
          pd}t          ||          }             }|                    ||          5 }|                    	pi            t          |||
| |            
| i |}t          |||           |cd d d            S # 1 swxY w Y   d S rw  rx  r  s            r+   sync_wrapperzCcreate_span_decorator.<locals>.span_decorator.<locals>.sync_wrapper  s   +--L#V*1--  
 q$)&)))2L22G C$:1$=$=CM&xGGI..00H)) *      !1r222%(HmQf   D+F++&tXxHHH                 s   AC''C+.C+N)rt  r   ru  r   r'   r   )	functoolswrapsinspect	signature__signature__r   iscoroutinefunction)rr  r  r  rn  rn   rm   rq  ro  s   `  r+   span_decoratorz-create_span_decorator.<locals>.span_decoratorZ  s7   
 
			 	 	 	 	 	 	 	 	 	 
		>	*1*;A*>*>M'' 	 	 	D	 
			 	 	 	 	 	 	 	 	 	 
		>	)0):1)=)=L&& 	 	 	D	 &q)) 	   s#   A 
AA9B 
B B )rr  r   r'   r   )sentry_sdk.scoperq  )rm   rn   rn  ro  r  rq  s   ```` @r+   create_span_decoratorr  B  s`    , 988888R  R  R  R  R  R  R  R  R  R h r-   Optional[sentry_sdk.Scope]Optional[Span]c                 >    | pt          j                    } | j        }|S )zU
    Returns the currently active span if there is one running, otherwise `None`
    )rp   get_current_scoperx   )r{   r  s     r+   ry  ry    s$     3Z133E:Lr-   c                     | pt                      } | L|                     t          j                   | j        (| j                            t          j                   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.
    N)ry  
set_statusr   INTERNAL_ERRORcontaining_transaction)rx   s    r+   set_span_erroredr    sg    
 %#%%D
1222&2'22:3LMMMMM 22r-   r_  r`  r  r   r  tuple[float, float]c                    |\  }}||k     st          d          t          |           }t          |dz            }t          |dz            }	 |                    ||          }n# t           $ r |}Y nw xY w|dz  S )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   rL   	randrange)r   r  r%  r5   rnglower_scaledupper_scaledsample_rand_scaleds           r+   r"  r"    s     LE55==JKKK


Cuy())Luy())L* ]]<FF * * * **
 	))s   A& &A54A5r   r   r  r]  c                 &    | |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  Tr_  r`  r:   )r   r  s     r+   r!  r!    s5     !4x	4		KCr-   rN  r.   r/   c                     d}t          | t                    r|                     |          }n4t          | |          r$	 t	          | |          }n# t
          $ r d}Y nw xY 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)rC   dictrT   r   getattrr   )rN  r.   r  s      r+   
_get_valuer    s}    
 E&$ 

363 	,,   Ls   A AAzUnion[str, SPANTEMPLATE]ru  c                    |}| t           j        k    rMd}|r?dD ]<}|                    |          r%t          ||         t                    r
||         } n=|rd| nd}n+| t           j        k    rd| }n| t           j        k    rd| }|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_CHATrT   rC   rD   AI_AGENTAI_TOOL)ro  rn   ru  r  r  r.   s         r+   r{  r{    s     I<''' 	.  ::c?? z&+s'C'C "3KEE',8OEOOO&			\*	*	**D**			\)	)	)*D**	r-   c                     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_TOOLrT   FUNCTIONrD   )ro  mappingrm   s      r+   rz  rz  #  sN    
 	bnr5b4AG
 
Xr{	+	+Br77Nr-   r  rt  ztuple[Any, ...]dict[str, Any]c                 p   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}t!          |                                          D ]\  }}|dk    rLt%          |t                    r7                    t          j        g                               d	|d
           W|dk    rLt%          |t                    r7                    t          j        g                               d|d
            |||           | t           j        k    r!|rt-          ||d          t          j        <   t          j        v r,t-          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                 `    | v r$|          \  }}|t          ||          r||<   d S d S d S d S r)   )rC   )r.   r  	attribute	data_typern  r  s       r+   _set_from_keyz,_get_input_attributes.<locals>._set_from_keyJ  sR    g~~)0&I$E9)E)E$,1Jy))) ~$$$$r-   promptuser)rolecontentsystem_promptsystem)rt  ru  )r   r  r  r  r
   GEN_AI_REQUEST_MODELrD   GEN_AI_AGENT_NAMEGEN_AI_REQUEST_MAX_TOKENSrL    GEN_AI_REQUEST_FREQUENCY_PENALTYr  GEN_AI_REQUEST_PRESENCE_PENALTYGEN_AI_REQUEST_TEMPERATUREGEN_AI_REQUEST_TOP_PGEN_AI_REQUEST_TOP_Klistrv   rC   
setdefaultGEN_AI_REQUEST_MESSAGESrX  r   GEN_AI_TOOL_INPUT)	ro  r  rt  ru  r  r.   r  rn  r  s	          @@r+   _get_input_attributesr  1  s(    $&JL)<+?AUVVV3S9#8#>0#6#5s;#=sC"*"KU!S!)!I5 Q$?G3U;3S9
 
	2s 	25 	2T 	2 	2 	2 	2 	2 	2 	2 v||~~.. 	& 	&JCh:eS#9#9%%h&FKKRR#66   o%%*UC*@*@%%%h&FKKRR%%88   M#u%%%%<'''H'1:V,,2
 2

8-.
 ':557@x788
 8

834 r-   usagec                      i dt           ddddf fd} |t          j        d            |t          j        d            |t          j        d	           S )
z
    Get usage attributes.
    r  keysztuple[str, ...]r'   Nc                 j    |D ].}t          |          }|t          |t                    r|| <   /d S r)   )r  rC   rL   )r  r  r.   r  rn  r  s       r+   _set_from_keysz-_get_usage_attributes.<locals>._set_from_keyss  sK     	. 	.Cuc**E Zs%;%; (-
9%	. 	.r-   )prompt_tokensinput_tokens)completion_tokensoutput_tokens)total_tokens)rD   r
   GEN_AI_USAGE_INPUT_TOKENSGEN_AI_USAGE_OUTPUT_TOKENSGEN_AI_USAGE_TOTAL_TOKENS)r  r  rn  s   ` @r+   _get_usage_attributesr  m  s     J.# .-> .4 . . . . . . . N*)   N+.   N*  
 r-   r  c                    i }| t           j        t           j        t           j        fv rt	                      5  |g}t          |d          }|                    |           t          |d          }t          |d          }|                    |           |D ]&}|"|                    t          |                     't          |d          }|$t          |t                    r||t          j        <   t          |d          }|$t          |t                    r||t          j        <   ddd           n# 1 swxY w 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  rX  r   r  rC   rD   r
   GEN_AI_RESPONSE_MODELr   GEN_AI_TOOL_OUTPUT)	ro  r  r  rn  usage_candidatesr  metausage_candidater  s	            r+   _get_output_attributesr    s    $&JL)<+?AUVVV(** 	H 	H &xvw//E##E***fj11DtW--E##E***#3 N N".%%&;O&L&LMMM $FG44J%*Z*E*E%=G
89:#FL99J%*Z*E*E%=G
89:-	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H2 <'''H'2;F2C2C
8./s   C3D66D:=D:Spanrr  c                    i }|t           j        k    rt          j        dt          j        |i}na|t           j        k    rt          j        di}nB|t           j        k    r2t          j        dt          j        |i}|j        }|||t          j	        <   |
                    t          ||||                     |                     |pi            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  r}  )	rx   ro  r  rn   rr  rt  ru  rn  	docstrings	            r+   r~  r~    s    & $&J<(((*N&


 
\)	)	)*F


 
\)	)	)*N%t


 I	 ;DJx78+HhfMMNNNZ%2&&&&&r-   c                 R    |                      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)r}  r  )rx   ro  r  r  s       r+   r  r    s0     	+HhGGM2NNNNNr-   r   r   c                 ^   t          j                    }|j        }|r|j        nd}| r| j                            d          nd}|%|#||k    rt          j        d| d| d           dS |j                            dd          }|r%||||t          j        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
    NrE  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)	rp   rq   rF  rE  r   rT   r   r$  rM   )r   r   rF  client_org_idbaggage_org_idr  s         r+   r   r     s=    "$$F"J)3=J%%M;BLW)--h777N 	!&^++ IZh  I  I  yF  I  I  I	
 	
 	
 u&,n&8&8#U' ' ! &=+@"}'@L x  JX  x  x  hu  x  x  x   54r-   headerszMutableMapping[str, str]sentry_baggagec                     |                      t          d          }t                              |          }t	          |          dk    rdnd}||z   |z   | 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   r5  N)rT   r   r   r\  rF   )r  r  existing_baggagestripped_existing_baggage	separators        r+   add_sentry_baggage_to_headersr    sj     {{#6;; ' < <=M N N45599rI 	"I->    r-   )r   rO  r   )r  )Fr]   )r{   r|   rx   r}   r'   N)r   r!   r'   rb   )
rx   r}   r   rb   r   r   r   r   r'   N)rx   r}   r'   N)r   rb   r'   r   )r   r   r'   r   )
rm   rm  rn   rb   rn  rW   ro  r   r'   r   r)   )r{   r  r'   r  )rx   r  r'   N)r   r   r  r]  r'   r  )r  r   r'   r  )[
contextlibr  r  r   rc  r   collections.abcr   r   datetimer   randomr   urllib.parser   r   r   rp   sentry_sdk.constsr	   r
   r   r   sentry_sdk.utilsr   r   r   r   r   r   r   r   r   r   r   r   typingr   r   r   r   r   r   r   r    typesr!   rd  r   base64_strippedr#   rS   rV   r\   contextmanagerrD   rz   r   r   r   r   r   r   r   rr   r   r   rj  r   DEFAULTr  ry  r  r  r"  r!  r  r{  rz  r  r  r  r~  r  r   r  sentry_sdk.tracingr   rO  r   r  r:   r-   r+   <module>r     s            				 				 



 3 3 3 3 3 3 3 3             ' ' ' ' ' ' ' '      D D D D D D D D D D D D                            !           	         RZ   ( ( ( ( (W ( ( (6!;     "R(B Rt R R R R   %* *** *  	*
 * * * 6* * * *Z

%>
	
 
 
 
B    * *	
  " 
   &FH
#FH!FH *FH *	FH
 
FH FH FH FHR   <   <2   B& &C &O & & & &$@< @< @< @< @< @< @< @<FLa La La La La La La La^	U#A 	U 	UPT 	U 	U 	U 	U     &* -1+3	l"l
l +l 	l
 l l l l^    	N 	N 	N 	N 	N '1* * ** $* 	* * * *> $ 3D         u 3 ?    ( *. (
 ' 		   :5 #    9(99 9 	9
 9 9 9 9x   8%(%48%BG%% % % %P)'
)'()' )' 	)'
 )' )' )' 
)' )' )' )'XO
O6OBFOPUO	O O O O!$7 !D ! ! ! !H'9<	   (           (''''''''( (r-   