
    j                        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	 d dlm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'm(Z( d d	lm)Z) e)r6d 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jj                  d      Z6dZ7 G d de      Z8ddde9fdZ:ddde9fdZ;e jx                  	 	 duddddd dd!d"d#e9d$e9d%e=dd&fd'       Z>	 	 	 	 	 	 dvd+Z?dwd,Z@d-e9d.d"d/d0d1d0d2d"d3d"de9fd4ZA	 	 	 	 	 	 	 	 	 	 dxd5ZBdyd6ZCdyd7ZD	 	 	 	 dzd8ZEddd9e=dd"fd:ZF G d; d<      ZG G d= d>      ZHd?d@dAe=de9fdBZId{dCZJdddej                  f	 	 	 	 	 	 	 	 	 d|dGZL	 	 	 d}dDd"dEddHe9ddfdIZM	 d~	 	 	 ddJZNd~ddKZOdLdMdNd"dOdPdePfdQZQ	 	 	 	 	 	 ddRZRdSddTe=ddUfdVZS	 d~dFdWdDe=dXdde=fdYZTdFdWde=fdZZUdFdWd[e9d\d]dXd^dd^f
d_ZVdd`ZWdFdWd[e9daddd^fdbZXd*dcdFdWd[e9dDe=dddd\d]dXd^ddfdeZYd*dcdFdWd[e9dadddf
dfZZdgdhde9fdiZ[djdkdle=ddfdmZ\dDe=dEdnd(d)ddofdpZ]dDe=dEdnde9fdqZ^d drl_m`Z`maZambZbmcZc d dsldmeZemfZfmgZh e)rd dtl_mcZc yy# e$ r
 d dlmZ Y 2w xY w)    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                   H    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y)EnvironHeadersenvironzMapping[str, str]prefixreturnNc                      || _         || _        y N)r'   r(   )selfr'   r(   s      q/Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/sentry_sdk/tracing_utils.py__init__zEnvironHeaders.__init__L   s    
     keyOptional[Any]c                 v    | j                   | j                  |j                  dd      j                         z      S N-_)r'   r(   replaceupper)r,   r0   s     r-   __getitem__zEnvironHeaders.__getitem__T   s.    ||DKK#++c3*?*E*E*GGHHr/   c                 8    t        d t        |       D              S )Nc              3       K   | ]  }d   yw)   N ).0r5   s     r-   	<genexpr>z)EnvironHeaders.__len__.<locals>.<genexpr>X   s     )j1js   )sumiterr,   s    r-   __len__zEnvironHeaders.__len__W   s    )d4j)))r/   c              #      K   | j                   D ]i  }t        |t              s|j                  dd      j	                         }|j                  | j                        sP|t        | j                        d   k y wr3   )r'   
isinstancestrr6   r7   
startswithr(   len)r,   ks     r-   __iter__zEnvironHeaders.__iter__Z   sd     Aa%		#s#))+A<<,C$&'' s   A:A<)HTTP_)r)   zGenerator[str, None, None])	__name__
__module____qualname__rE   r.   r8   intrB   rI   r<   r/   r-   r&   r&   K   sO     $  
	Is I I* *	(r/   r&   optionsOptional[Dict[str, Any]]r)   c                     | yt        | j                  d      duxr( | j                  d      duxs | j                  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rO   s    r-   has_tracing_enabledrX   f   sY    
 $%U2 	
KK,-T9 9{{+,D8	 r/   Optional[dict[str, Any]]c                 V    | y| j                  d      xs i j                  d      dk(  S )NF_experimentstrace_lifecyclestream)rV   rW   s    r-   has_span_streaming_enabledr^   w   s/    KK'-2223DEQQr/   cursorr   queryparams_list
paramstyleOptional[str]executemanyrecord_cursor_reprspan_originz.Generator[sentry_sdk.tracing.Span, None, None]c              #   2  K   t        j                         j                  d   j                  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        t        j                  t        j                  ||      5 }|j                         D ]  \  }	}
|j                  |	|
        | d d d        y # 1 sw Y   gxY w# 1 sw Y   y xY ww)Nr[   record_sql_paramsFpyformatformatz	db.paramszdb.paramstyleTzdb.executemanyz	db.cursorr`   )messagecategorydata)opnameorigin)
sentry_sdk
get_clientrO   rV   _format_sqlr   add_breadcrumb
start_spanr
   DBitemsset_data)r_   r`   ra   rb   rd   re   rf   rm   spanrH   vs              r-   record_sql_queriesr{   ~   s*     &&~6::;NPUVkdV3K#!J
&ED'[ *_!%f0"[	$	&!!%'M 
' 
		55
 
JJLDAqMM!Q !

 
 
'	&
 
s6   A>D C?.D/D6	D?DDDDscopesentry_sdk.Scopery   c                 \   |j                   t        j                  k(  r*| j                  |j                  dd|j
                         y |j                   t        j                  k(  rd }|j                  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 | j                  d	d
|j                  |       y | j                  d	d
|j                         y |j                   dk(  r*| j                  dd|j                  |j                         y y )Nredis)rk   typerl   rm   i  iW  errori  i  warninghttphttplib)r   rl   rm   level)r   rl   rm   
subprocess)r   rl   rk   rm   )rn   r
   DB_REDISrt   description_tagsHTTP_CLIENT_datarV   r   HTTP_STATUS_CODE)r|   ry   r   status_codes       r-   "maybe_create_breadcrumbs_from_spanr      s    ww"++$$7W4:: 	 	
 
BNN	"jjnnX%>%>?k(S(*s*!  idjj !    fytzz R	L	 !$$	 	 	
 
!r/   c                 N    	 | j                   j                  S # t        $ r Y y w xY wr+   )f_codeco_filename	Exception)frames    r-   _get_frame_module_abs_pathr      s)    ||''' s    	$$is_sentry_sdk_frame	namespacein_app_includeOptional[list[str]]in_app_excludeabs_pathproject_rootc                     t        ||      }t        |      xs t        ||      }|  xr |xs t        ||      xr | S r+   )r   r   r   )r   r   r   r   r   r   should_be_includedshould_be_excludeds           r-   _should_be_includedr      s[     )NC,X6 />; #"  	T,7R@R<Rr/   c                    t        j                         }|at        |      }	 |j                  j	                  d      }|duxr |j                  d      }t        ||||||      }|rn|j                  }|ad}|G	 |j                  }	|	*| j                  t        j                  |j                         	 |j                  j	                  d      }| | j                  t        j                  |       t        |      }
|
t|t        ||
      }nE|A|
j                  |      r0|
j                  |d      j!                  t"        j$                        }n|
}| j                  t        j&                  |       	 |j(                  j*                  }|5| j                  t        j,                  |j(                  j*                         yyy# t
        $ r d}Y w xY w# t
        $ r d}	Y [w xY w# t
        $ r d}Y %w xY w# t
        $ r d}Y |w xY w)zB
    Adds OTel compatible source code information to the span
    NrK   zsentry_sdk.)r   r   r   r   r   r    )sys	_getframer   	f_globalsrV   r   rF   r   f_backf_linenorx   r   CODE_LINENOCODE_NAMESPACEr   r6   lstripossepCODE_FILEPATHr   co_nameCODE_FUNCTION)ry   r   r   r   r   r   r   r   r   linenofilepathin_app_pathcode_functions                r-   
add_sourcer      s    '*mmoE

-e4	).)<)<Z)HI (t3 
	8L8L9
 1 3))%
 / 
2  	^^F MM(..?	++J7I  MM(119=-e4$1)XF)h.A.A,.O&..|R@GGO&MM(00+>	!!LL00M $MM(00%,,2F2FG %= /  	I	4  	F	  	I	"  	! M	!sG   G >G 7G) 6G; GGG&%G&)G87G8;H	H	c                    t        j                         }|j                         sy| j                  | j                  y|j
                  j                  dd      }|sy| j                  | j                  z
  }|j
                  j                  dd      }|t        d      z  |kD  }|syt        | |j
                  d   |j
                  j                  d	      |j
                  j                  d
             y)zO
    Adds OTel compatible source code information to a database query span
    Nenable_db_query_sourceTdb_query_source_threshold_msr   r;   millisecondsr   r   r   ry   r   r   r   	rq   rr   	is_active	timestampstart_timestamprO   rV   r   r   )ry   clientshould_add_query_sourceduration	threshold
slow_querys         r-   add_query_sourcer   0  s     ""$F~~!5!5!=$nn001I4P"~~ 4 44H""#A1EII155	AJ^^N3~~))*:;~~))*:;	r/   c                    t        j                         }|j                         sy| j                  | j                  y|j
                  j                  dd      }|sy| j                  | j                  z
  }|j
                  j                  dd      }|t        d      z  |kD  }|syt        | |j
                  d   |j
                  j                  d	      |j
                  j                  d
             y)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   r;   r   r   r   r   r   r   )ry   r   should_add_request_sourcer   r   r   s         r-   add_http_request_sourcer   N  s     ""$F~~!5!5!= & 2 23OQU V$~~ 4 44H""#EqIII155	AJ^^N3~~))*:;~~))*:;	r/   c                 @   | sy| j                  d      r| j                  d      r| dd } t        j                  |       }|sy|j	                         \  }}}d}|rdj                  t        |d            }|rdj                  t        |d            }|r|d	k7  }|||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)rF   endswithSENTRY_TRACE_REGEXmatchgroupsrj   rN   )headerr   r   r   sampled_strr   s         r-   extract_sentrytrace_datar   l  s     FOOE$:"$$V,E,1LLN)HnkN##C"$56"))#nb*AB$+ (( r/   sqlc                     d }	 t        | d      rF| j                  |      }t        |t              r%|j	                  | j
                  j                        }|xs t        |      S # t        $ r d }Y w xY w)Nmogrify)	hasattrr   rD   bytesdecode
connectionencodingr   r   )r_   r   real_sqls      r-   rs   rs     so    H69%~~c*H(E*#??6+<+<+E+EF %y~%  s   AA% %A32A3c                   H   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dZde	fdZddZddZy)PropagationContextzJ
    The PropagationContext represents the data of a trace in Sentry.
    )	_trace_id_span_idr   r   baggagecustom_sampling_contextNr)   c                     || _         	 || _        	 || _        	 || _        	 || _        	 	 ||t        |      | _        d | _        y r+   )r   r   r   r   r   Baggager   )r,   r   span_idr   r   dynamic_sampling_contextr   s          r-   r.   zPropagationContext.__init__  se     "/:,	H -	Q PN?7C"#;<DLCG$r/   c                 B   t               }t        |      }|j                  t              }t	        |      }||S |j                  t
              }|rt        j                  |      nd }t        |      s|S |j                  |       |r||_
        |j                          |S r+   )r   normalize_incoming_datarV   SENTRY_TRACE_HEADER_NAMEr   BAGGAGE_HEADER_NAMEr   from_incoming_header_should_continue_traceupdater   _fill_sample_rand)clsincoming_datapropagation_contextnormalized_datasentry_trace_headersentrytrace_databaggage_headerr   s           r-   from_incoming_dataz%PropagationContext.from_incoming_data  s     121-@-112JK34GH #&&(,,-@A<JG((8PT 	 &g.&&""#34*1'--/""r/   c                 x    | j                   s#t        j                         j                  | _         | j                   S )z!The trace id of the Sentry trace.)r   uuiduuid4hexrA   s    r-   r   zPropagationContext.trace_id  s(     ~~!ZZ\--DN~~r/   valuec                     || _         y r+   )r   r,   r   s     r-   r   zPropagationContext.trace_id  s	    r/   c                 ~    | j                   s&t        j                         j                  dd | _         | j                   S )z+The span id of the currently executed span.r   N)r   r   r   r   rA   s    r-   r   zPropagationContext.span_id  s/     }} JJL,,RS1DM}}r/   c                     || _         y r+   )r   r  s     r-   r   zPropagationContext.span_id  s	    r/   c                 >    | j                         j                         S r+   )get_baggager   rA   s    r-   r   z+PropagationContext.dynamic_sampling_context  s    !::<<r/   c                 8    | j                    d| j                   S )Nr4   )r   r   rA   s    r-   to_traceparentz!PropagationContext.to_traceparent	  s    --$,,00r/   c                 f    | j                   t        j                  |       | _         | j                   S r+   )r   r   !populate_from_propagation_contextrA   s    r-   r  zPropagationContext.get_baggage  s(    <<"DDTJDL||r/   c              #      K   t         | j                         f | j                         j                         }|rt        |f yyw)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  sF      '(;(;(===""$..0%w.. s   AAc                 n    |j                         D ]  \  }}	 t        | ||        y# t        $ r Y "w xY w)zU
        Updates the PropagationContext with data from the given dictionary.
        N)rw   setattrAttributeError)r,   
other_dictr0   r   s       r-   r   zPropagationContext.update  s@     %**,JCc5) - " s   (	44c                     || _         y r+   )r   )r,   r   s     r-   _set_custom_sampling_contextz/PropagationContext._set_custom_sampling_context%  s     (?$r/   c                     dj                  | j                  | j                  | j                  | j                  | j
                        S )Nz\<PropagationContext _trace_id={} _span_id={} parent_span_id={} parent_sampled={} baggage={}>)rj   r   r   r   r   r   rA   s    r-   __repr__zPropagationContext.__repr__*  s<    mttNNMMLL
 	
r/   c                    | j                   yt        t        | j                   j                  j	                  d            }|d|cxk  rdk  ry t        t        | j                   j                  j	                  d            }t        | j                  |      \  }}	 t        | j                  ||f      }|d
| j                   j                  d<   y# t        $ r) t        j                  d| j                   d| d	       Y yw xY w)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   r;   sample_rateintervalz5Could not backfill sample_rand, since parent_sampled=z and sample_rate=..6f)r   r   floatsentry_itemsrV   _sample_rand_ranger   _generate_sample_randr   
ValueErrorr   debug)r,   r  r  lowerr7   s        r-   r   z$PropagationContext._fill_sample_rand3  s    & <<!%)B)B)F)F})UV"qK';!'; (< "%)B)B)F)F})UV)$*=*={Ku	/PUWK 7B#5F!!-0  		
 LLGH[H[G\ ]##.-q2 		s   C /DDc                 f    | j                   y| j                   j                  j                  d      S )zAConvenience method to get the sample_rand value from the baggage.Nr  )r   r  rV   rA   s    r-   _sample_randzPropagationContext._sample_randb  s*    <<||((,,];;r/   )NNNNNN)r   rc   r   rc   r   rc   r   Optional[bool]r   zOptional[Dict[str, str]]r   Optional[Baggage]r)   N)r   Dict[str, Any]r)   r   )r)   rP   )r)   r   )r)   zIterator[Tuple[str, str]])r  r'  r)   N)r   dict[str, Any]r)   Nr)   N)r)   rc   )rK   rL   rM   __doc__	__slots__r.   classmethodr   propertyrE   r   setterr   r   r  r  r  r   r  r  r   r$  r<   r/   r-   r   r     sv   I %)#'*.+/?C'+H!H !H (	H
 )H #=H %H 
HB #,#	# #: #   __c d      ^^S T   = =1 1
/?'7?	?

# 
-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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y
)$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  Dict[str, str]r1  r2  c                 .    || _         || _        || _        y r+   r0  )r,   r  r1  r2  s       r-   r.   zBaggage.__init__x  s     )!2r/   N)r$  r   r)   c                   i }d}d}|r|j                  d      D ]  }d|vrt               5  |j                         }|j                  d      \  }}t        j                  j                  |      r.t        |j                  d      d         }	t        |      ||	<   d}n||rdnd|z   z  }ddd        |t        |      |d	<   d}t        |||      S # 1 sw Y   xY w)
zF
        freeze if incoming header already has sentry baggage
        r   T,=r4   r;   FNr  )splitr   stripr   SENTRY_PREFIX_REGEXr   r   rE   )
r   r   r$  r  r1  r2  itemr0   valbaggage_keys
             r-   r   zBaggage.from_incoming_header  s     S)d?02::<D#zz#HC2288=&-ciinQ.?&@4;CL[1"')5FcBRV-VV) 32	 * #*-l*;L'G|%6@@ 32s   A>CC	c                 n    |j                   t        i       S t        j                  |j                         S )zC
        Deprecated: use populate_from_propagation_context
        )_propagation_contextr   r	  )r   r|   s     r-   from_optionszBaggage.from_options  s1    
 %%-2;889S9STTr/   c                    i }d}d}t        j                         }|j                         st        |      S |j                  }|j
                  |d<   |j                  d      r|d   |d<   |j                  d      r|d   |d<   |j                  rH|j                  j                  |d<   |j                  j                  r|j                  j                  |d<   |j                  d      rt        |d         |d	<   t        |||      S )
Nr   Fr   environmentrelease
public_keyorg_idrS   r  )rq   rr   r   r   rO   r   rV   
parsed_dsnrD  rE  rE   )r   r   r  r1  r2  r   rO   s          r-   r	  z)Baggage.populate_from_propagation_context  s     *,&&(!<((..#6#?#?Z ;;}%*1-*@L';;y!&-i&8L#)/):):)E)EL&  '')/):):)A)AX&;;+,*-g6J.K*LL'|%6@@r/   c                 X   t        j                         }i }|j                         st        |      S |j                  xs i }|j
                  |d<   |j                  d|d<   |j                  d      r|d   |d<   |j                  d      r|d   |d<   |j                  rH|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"                  j$                         t        |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  rB  rC  rD  rE  transactionr  truefalsesampledFr2  )rq   rr   r   r   rO   r   r$  rV   rF  rD  rE  ro   sourceLOW_QUALITY_TRANSACTION_SOURCESr  rE   rL  _baggager  r   )r   rI  r   r  rO   s        r-   populate_from_transactionz!Baggage.populate_from_transaction  s    &&()+!<((..&B#.#7#7Z )4)A)A#(F]#;;}%*1-*@L';;y!&-i&8L#)/):):)E)EL&  '')/):):)A)AX& ""*II*5*:*:L'"".*-k.E.E*FL'*0;0C0CfL#
 K$8$8$E$E 4 4 A AB|U33r/   c                 ~   t        j                         }i }|j                         st        |      S |j                  xs i }|j
                  |d<   |j                  d|d<   |j                  d      r|d   |d<   |j                  d      r|d   |d<   |j                  rH|j                  j                  |d<   |j                  j                  r|j                  j                  |d<   |j                         j                  d      t        vr|j                  r|j                  |d	<   |j                  t        |j                        |d
<   |j                   |j                   rdnd|d<   |j"                  r;|j"                  j$                  r%|j'                  |j"                  j$                         t        |d      S )rH  r   r  r  rB  rC  rD  rE  zsentry.span.sourcerI  r  rJ  rK  rL  FrM  )rq   rr   r   r   rO   r   r$  rV   rF  rD  rE  get_attributesLOW_QUALITY_SEGMENT_SOURCES_name_sample_raterE   rL  rP  r  r   )r   segmentr   r  rO   s        r-   populate_from_segmentzBaggage.populate_from_segment  s    &&()+!<((..&B#*#3#3Z )0)=)=c(B]#;;}%*1-*@L';;y!&-i&8L#)/):):)E)EL&  '')/):):)A)AX& ""$(()=>./mm*1--L'+*-g.B.B*CL'??&07fWL#  0 0 = = 0 0 = =>|U33r/   c                     d| _         y NFrM  rA   s    r-   freezezBaggage.freeze3  s	    r/   c                 X    i }| j                   j                         D ]
  \  }}|||<    |S r+   )r  rw   )r,   r   r0   r;  s       r-   r   z Baggage.dynamic_sampling_context6  s4    **002ICF3K 3 r/   include_third_partyc                 n   g }| j                   j                         D ]]  \  }}t               5  t        j                  t        |      z   dz   t        t        |            z   }|j                  |       d d d        _ |r|j                  | j                         dj                  |      S # 1 sw Y   xY w)Nr7  r6  )
r  rw   r   r   SENTRY_PREFIXr   rE   appendr1  join)r,   r]  rw   r0   r<  r;  s         r-   r  zBaggage.serialize>  s    ))//1HC,.,,uSz9C?%C/QT" /. 2
 LL//0xx /.s   AB++B4	c                 P    dj                  d | j                  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.
        r6  c              3   z   K   | ]3  }t         j                  j                  |j                               s| 5 y wr+   )r   r:  r   r9  )r=   r;  s     r-   r>   z/Baggage.strip_sentry_baggage.<locals>.<genexpr>R  s2      -D2288F -s   9;)ra  r8  )r   s    r-   strip_sentry_baggagezBaggage.strip_sentry_baggageK  s+     xx"LL-
 	
r/   c                 x    t        t        | j                  j                  d            }|d|cxk  rdk  r|S  yy)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  rV   )r,   r  s     r-   r$  zBaggage._sample_randY  sD     "%):):)>)>})MN"sk'?C'? (@ r/   c                 H    d| j                  d       d| j                   dS )Nz
<Baggage "T)r]  z", mutable=>)r  r2  rA   s    r-   r  zBaggage.__repr__f  s,    DNNtNDE[QUQ]Q]P^^_``r/   )r   T)r   rc   r$  rc   r)   r   )r|   zsentry_sdk.scope.Scoper)   r&  )r   r   r)   r   )rI  zsentry_sdk.tracing.Transactionr)   r   )rW  StreamedSpanr)   r   r)  )r)   r3  )F)r)   Optional[float])rK   rL   rM   r*  r+  r_  recompiler:  rE   rU   r.   r,  r   r@  r	  rQ  rX  r[  r   r  staticmethodrd  r$  r  r<   r/   r-   r   r   j  sT    AIM$"**Z0
 "$	&  	 
 )-	 A A &	 A
 
 A  AD U U A"6A	A A@ /4:/4	/4 /4b .4 .4`T c  
S 
S 
 
a# ar/   r   r   zsentry_sdk.client.BaseClienturlc                 V    | j                   d   }t        | |      ry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)rO   r   r   )r   ro  rq  s      r-   should_propagate_tracers  j  s1     !'/J KVS!C!:tTTr/   c                     i }| j                         D ]@  \  }}|j                  d      r|dd }|j                  dd      j                         }|||<   B |S )z
    Normalizes incoming data so the keys are all lowercase with dashes instead of underscores and stripped from known prefixes.
    rJ      Nr5   r4   )rw   rF   r6   r"  )r   rm   r0   r   s       r-   r   r   v  s`     D#))+
U>>'"ab'Ckk#s#))+S	 , Kr/   ro   
attributestemplatec                 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_piic                 l    t        j                         d fd       }	 t        j                         |_        t        j                         d fd       }	 t        j                         |_        t        j                         r|S |S # t
        $ r Y bw xY w# t
        $ r Y 3w xY w)D
        Decorator to create a span for the given function.
        c            
      P  K   t               }|/t        j                  dt        
              
| i | d {   S t	        |t
              r,t        j                  dt        d        
| i | d {   S xs t              }xs t        
      xs d}t        ||      }        }|j                  ||      5 }|j                  	xs i        t        |||
| |        
| i | d {   }t        |||       |cd d d        S 7 7 7 !# 1 sw Y   y xY ww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   )rn   ro   get_current_spanr   r!  r   rD   rj  warningswarnDeprecationWarning_get_span_op_get_span_namestart_childupdate_data_set_input_attributes_set_output_attributesargskwargscurrent_spanspan_opfunction_name	span_namesend_piiry   resultrv  fro   rn   ry  rw  s            r-   async_wrapperzDcreate_span_decorator.<locals>.span_decorator.<locals>.async_wrapper  sE    +-L#V*1-
 ////,5X& 
 ////2L2G C$:1$=CM&xGI.0H)) *    !1r2%(HmQf  !$1&11&tXxH  0 0  2 sL   7D&D;D&6D7AD&2D6D7D
D&D&DD#D&c            
         t               }|'t        j                  dt        
              
| i |S t	        |t
              r$t        j                  dt        d        
| i |S xs t              }xs t        
      xs d}t        ||      }        }|j                  ||      5 }|j                  	xs i        t        |||
| |        
| i |}t        |||       |cd d d        S # 1 sw Y   y xY wr}  r  r  s            r-   sync_wrapperzCcreate_span_decorator.<locals>.span_decorator.<locals>.sync_wrapper  s"   +-L#V*1-
 $)&)),5X& 
 $)&))2L2G C$:1$=CM&xGI.0H)) *    !1r2%(HmQf D+F+&tXxH  s   2>C::Dr  r   r  r   r)   r   	functoolswrapsinspect	signature__signature__r   iscoroutinefunction)r  r  r  rv  ro   rn   ry  rw  s   `  r-   span_decoratorz-create_span_decorator.<locals>.span_decorator  s    
 
	%	 %	 
%	N	*1*;*;A*>M' 
	%	 %	 
%	N	)0):):1)=L& &&q)  g  		Z  		s#   B %B' 	B$#B$'	B32B3r  r   r)   r   )sentry_sdk.scopery  )rn   ro   rv  rw  r  ry  s   ```` @r-   create_span_decoratorr    s    , 9b  b H r/   activec                      d fd}|S )zW
    Create a span creating decorator that can wrap both sync and async functions.
    c                 d    t        j                         d fd       }	 t        j                         |_        t        j                         d fd       }	 t        j                         |_        t        j                         r|S |S # t
        $ r Y `w xY w# t
        $ r Y 3w xY w)r{  c                  "  K   t        j                         }t        |j                        st	        j
                  dd       xs t              xs d}t        |      5   | i | d {   }|cd d d        S 7 # 1 sw Y   y xY wwNzSUsing span streaming API in non-span-streaming mode. Use @sentry_sdk.trace instead.r~  r  r   )ro   rv  r  rq   rr   r^   rO   r  r  r   start_streaming_span)	r  r  r   r  r  r  rv  r  ro   s	        r-   r  zNcreate_streaming_span_decorator.<locals>.span_decorator.<locals>.async_wrapper  s     **,F-fnn=1  ? 6q 9?RI%:f  !$1&11	  2 s0   A"B%B1B2B7
BBBBc                     t        j                         }t        |j                        st	        j
                  dd       xs t              xs d}t        |      5   | i |cd d d        S # 1 sw Y   y xY wr  r  )r  r  r   r  r  rv  r  ro   s       r-   r  zMcreate_streaming_span_decorator.<locals>.span_decorator.<locals>.sync_wrapper)  sv    **,F-fnn=1  ? 6q 9?RI%:f $)&)  s   #A55A>r  r  )r  r  r  r  rv  ro   s   `  r-   r  z7create_streaming_span_decorator.<locals>.span_decorator  s    
 
		 
	"	*1*;*;A*>M' 
		* 
	* 	)0):):1)=L& &&q)  9  		,  		s#   B !B# 	B B #	B/.B/r  r<   )ro   rv  r  r  s   ``` r-   create_streaming_span_decoratorr    s    5 n r/   c                 N    | xs t        j                         } | j                  }|S )zU
    Returns the currently active span if there is one running, otherwise `None`
    )rq   get_current_scopery   )r|   r  s     r-   r  r  G  s&     3Z113E::Lr/   c                    ddl m}m} | xs
 t               } | t	        | t
              rV| j                  t        j                         | j                  *| j                  j                  t        j                         yyt	        | |      r:|j                  | _        | j                  |j                  | j                  _        yyyy)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   )rj  
SpanStatusN)sentry_sdk.tracesrj  r  r  rD   Span
set_statusr   INTERNAL_ERRORcontaining_transactionERRORstatus_segment)ry   rj  r  s      r-   set_span_erroredr  R  s    
 ;%#%DdD!OOJ556**6++66z7P7PQ 7l+$**DK}}('1'7'7$ ) , r/   rf  rg  r  r   r  tuple[float, float]c                    |\  }}||k  st        d      t        |       }t        |dz        }t        |dz        }	 |j                  ||      }|dz  S # t         $ r	 |}Y |dz  S w xY 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   rN   	randrange)r   r  r"  r7   rnglower_scaledupper_scaledsample_rand_scaleds           r-   r  r  f  s     LE55=JKK

Cuy()Luy()L* ]]<F 	))  * *	))*s   A A'&A'c                 $    | |y| 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.
    r  Trf  rg  r<   )r   r  s     r-   r  r    s0     !4	4	KCr/   rN  r0   r1   c                     d}t        | t              r| j                  |      }|S t        | |      r	 t	        | |      }|S |S # t
        $ r d}Y |S w xY w)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)rD   dictrV   r   getattrr   )rN  r0   r   s      r-   
_get_valuer    sj    
 E&$

3 L 63, L5L  Ls   A AAzUnion[str, SPANTEMPLATE]r  c                    |}| t         j                  k(  rDd}|r3dD ].  }|j                  |      st        ||   t              s)||   } n |rd| }|S d}|S | t         j
                  k(  rd| }|S | 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_CHATrV   rD   rE   AI_AGENTAI_TOOL)rw  ro   r  r  r  r0   s         r-   r  r    s     I<'''.::c?z&+s'C"3KE /
 (-eE7O	  39	  
\**	*#D6*	
  
\))	)#D6*	r/   c                    t         j                  t        j                  t         j                  t        j
                  t         j                  t        j                  i}|j                  | 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_TOOLrV   FUNCTIONrE   )rw  mappingrn   s      r-   r  r    s\    
 	bnnr55b44AG
 
Xr{{	+Br7Nr/   r  r  ztuple[Any, ...]r(  c                    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!        |j#                               D ]  \  }}|dk(  rCt%        |t              r3j'                  t        j(                  g       j+                  d	|d
       N|dk(  rCt%        |t              r3j'                  t        j(                  g       j+                  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_kr0   r   r   r)   Nc                 J    | v r|    \  }}|t        ||      r||<   y y y y r+   )rD   )r0   r   	attribute	data_typerv  r  s       r-   _set_from_keyz,_get_input_attributes.<locals>._set_from_key  s?    g~)0&I$E9)E,1Jy) *F$ r/   promptuser)rolecontentsystem_promptsystem)r  r  )r   r  r  r  r   GEN_AI_REQUEST_MODELrE   GEN_AI_AGENT_NAMEGEN_AI_REQUEST_MAX_TOKENSrN    GEN_AI_REQUEST_FREQUENCY_PENALTYr  GEN_AI_REQUEST_PRESENCE_PENALTYGEN_AI_REQUEST_TEMPERATUREGEN_AI_REQUEST_TOP_PGEN_AI_REQUEST_TOP_Klistrw   rD   
setdefaultGEN_AI_REQUEST_MESSAGESr`  r   GEN_AI_TOOL_INPUT)	rw  r  r  r  r  r0   r   rv  r  s	          @@r-   _get_input_attributesr    s    $&JL))<+?+?AUAUVV33S9#88#>00#6#55s;#==sC"*"K"KU!S!)!I!I5 Q$??G33U;33S9
	2s 	25 	2T 	2 v||~.JCh:eS#9%%h&F&FKRR#6 o%*UC*@%%h&F&FKRR%%8 #u% / <'''H1:V,2

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

8334 r/   c                      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                 ^    |D ]'  }t        |      }|t        |t              s#|| <   ) y r+   )r  rD   rN   )r  r  r0   r   rv  usages       r-   _set_from_keysz-_get_usage_attributes.<locals>._set_from_keys  s2    Cuc*E Zs%;(-
9% r/   )prompt_tokensinput_tokens)completion_tokensoutput_tokens)total_tokens)rE   r   GEN_AI_USAGE_INPUT_TOKENSGEN_AI_USAGE_OUTPUT_TOKENSGEN_AI_USAGE_TOTAL_TOKENS)r  r  rv  s   ` @r-   _get_usage_attributesr    so     J.# .-> .4 . **) ++. **
 r/   r  c                    i }| t         j                  t         j                  t         j                  fv rt	               5  |g}t        |d      }|j                  |       t        |d      }t        |d      }|j                  |       |D ]  }||j                  t        |             ! t        |d      }|#t        |t              r||t        j                  <   t        |d      }|#t        |t              r||t        j                  <   ddd       | t         j                  k(  r|rt        |      |t        j                  <   |S # 1 sw Y   <xY w)z<
    Get output attributes for the given span template.
    r  metadataNr  r  )r   r  r  r  r   r  r`  r   r  rD   rE   r   GEN_AI_RESPONSE_MODELr   GEN_AI_TOOL_OUTPUT)	rw  r  r  rv  usage_candidatesr  metausage_candidater  s	            r-   _get_output_attributesr
  )  s/    $&JL))<+?+?AUAUVV(* &xvw/E##E*fj1DtW-E##E*#3".%%&;O&LM $4
 $FG4J%*Z*E=G
899:#FL9J%*Z*E=G
899:- +2 <'''H2;F2C
8../9 +*s   AE	A>E		Er  r  c                    i }|t         j                  k(  r#t        j                  dt        j                  |i}n||t         j
                  k(  rt        j                  di}nV|t         j                  k(  rCt        j                  dt        j                  |i}|j                  }|||t        j                  <   |j                  t        ||||             | j                  |xs i        y)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  )	ry   rw  r  ro   r  r  r  rv  	docstrings	            r-   r  r  Q  s    & $&J<(((**N&&

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

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


 II	 ;DJx778+HhfMNZ%2&r/   c                 D    | j                  t        |||      xs i        y)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
  )ry   rw  r  r  s       r-   r  r  }  s!     	+HhGM2Nr/   r   r&  c                 t   t        j                         }|j                  }|r|j                  nd}| r| j                  j                  d      nd}|$|"||k7  rt        j                  d| d| d       y|j                  j                  dd      }|r%||||t        j                  d| d| d       yy	)
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)	rq   rr   rF  rE  r  rV   r   r!  rO   )r   r   rF  client_org_idbaggage_org_idr  s         r-   r   r     s    ""$F""J)3J%%M;BW))--h7N 	!&^+YZhYiiw  yF  xG  GH  I	
 &,nn&8&8#U' !&=+@"}'@LL I  JX  IY  Yg  hu  gv  vw  x r/   headerszMutableMapping[str, str]sentry_baggagec                     | j                  t        d      }t        j                  |      }t	        |      dkD  rdnd}||z   |z   | t        <   y)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   r6  N)rV   r   r   rd  rG   )r  r  existing_baggagestripped_existing_baggage	separators        r-   add_sentry_baggage_to_headersr    sV     {{#6; ' < <=M N459rI 	"I->  r/   zOptional[Attributes]z<tuple[bool, Optional[float], Optional[float], Optional[str]]c                 6   t        j                         }t        |j                        sy|j	                         }d}|j
                  |j
                  j                         }|t        |j                        }t        |j                  j                  d            }|rrd| |j                  |j                  |j                  |rt        |      ni di}|j                  r|j                  |j                          |j                  d   |      }n(|j                  |j                  }n|j                  d   }t!        |d      st#        j$                  d	|  d
       yt'        |      }|s#|rd}	nd}	t#        j(                  d	|  d|	        y|j*                  r8|d|j*                  j,                  z  z  }|st#        j(                  d	|  d       y||k  }
|
rt#        j(                  d|         d}nt#        j(                  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
    )FNNNNrT   span_context)ro   r   r   r   rv  rS   Tracing)rN  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 )Frf  Nr  r~  z because backpressure)Frf  Nbackpressurez[Tracing] Starting zA because it's not included in the random sample (sampling rate = r  r  )rq   rr   rX   rO   get_active_propagation_contextr   r$  r  r   callablerV   r   r   r  r   r   r   r   r   r  r!  monitordownsample_factor)ro   rv  r|   r   r   r  traces_sampler_definedsampling_contextr  reasonrL  outcomes               r-   _make_sampling_decisionr+    s    ""$Fv~~.&>>@K"".)11>>@+,?,H,HI &fnn&8&89I&JK/88"5"D"D"5"D"D2<d:."
 66##$7$O$OP6fnn%567GH--9-<<K ..)=>K  I>.tf4TUV/$K!9F5F,TF)F8DE. ~~q&..::::LL06KLM3K'G*4&12#D6)jkvjwwxy	
  Kg55r/   c                    t        j                         }|j                  j                  d      xs i j                  d      }|sydddddt        fd}|D ]  }t        |t        t        f      r |||       s# y	t        |t              s6d
|v sd|v s?d	}d	}|xs i }d
|v r ||d
   |       }d|v r/|d   j                         D ]  \  }}	||vs ||	||         rd} n |s|s y	 y)z:Determine if a span fits one of the rules in ignore_spans.r[   ignore_spansFruler   r   r)   c                     t        | t              r+t        |t              rt        | j	                  |            S y| |k(  S rZ  )rD   r	   rE   rU   	fullmatch)r.  r   s     r-   _matchesz!is_ignored_span.<locals>._matches"  s7    dG$%%DNN5122u}r/   Tro   rv  )
rq   rr   rO   rV   rU   rD   rE   r	   r  rw   )
ro   rv  r   r-  r1  r.  name_matchesattributes_matchr  r   s
             r-   is_ignored_spanr4    s   ""$FNN&&~6<"AA.QLu U t  dS'N+d#d#4<4;OL##)rJ~'Vd;t#(,\(:(@(@(B$Iu 
2(z)4; ,1( )C  0/ 2 r/   )r   rO  r   r  )rT  rj  ru   )r  )Fmanual)r|   r}   ry   sentry_sdk.tracing.Spanr)   N)r   r#   r)   rc   )
ry   r6  r   rc   r   r   r   r   r)   N)ry   r6  r)   N)r   rc   r)   z+Optional[Dict[str, Union[str, bool, None]]])r   r'  r)   r'  )
rn   zOptional[Union[str, OP]]ro   rc   rv  rY   rw  r   r)   r   )NNTr+   )r|   zOptional[sentry_sdk.Scope]r)   #Optional[Union[Span, StreamedSpan]])ry   r7  r)   N)r   r%  r  rk  r)   r  )r  r   r)   r(  )i
contextlibr  r  r   rl  r   r  collections.abcr   r   datetimer   randomr   urllib.parser   r   r   r	   ImportErrortypingrq   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$   rm  r   base64_strippedr&   rU   rX   r^   contextmanagerrE   r{   r   r   r   r   r   r   r   rs   r   r   rs  r   DEFAULTr  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r   r  r+  r4  sentry_sdk.tracingr   rO  r   r  r  rT  rj  ru   r  r<   r/   r-   <module>rG     sA      	 	 
  3   ' 
  D D     ! ,  RZZ  (W (6!;  "R(B Rt R   %*** *  	*
 * * * 6* *Z

%>
	
B * *	
  " 
&FH
#FH!FH *FH *	FH
 
FHR<<2B& &C &O &$H< H<V}a }a@	U#A 	U 	UPT 	U  &* -1+33	|"|
| +| 	|
 |@ !-1@
@*@ @ 	@H +/'*8. '1** $* 	*> $ 3D   u 3 ? ( *.(
 ' 		:5 # 9(99 9 	9
 9x8%(%48%BG%%P)'
)'()' )' 	)'
 )' )' )' 
)'XO
O6OBFOPUO	O!$7 !D !H'9<	&U6
U6&U6 U6 D	U6p*# *+A *d *\   ' I2  s   I( (I76I7