
    ix                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 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"m#Z# d dl$m%Z% e%r$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jZ                  d      Z.dZ/ G d de      Z0d Z1e jd                  	 	 d2d       Z3d Z4d Z5d Z6d Z7d Z8d Z9 G d d      Z: G d d      Z;d Z<d  Z=dddej|                  fd!Z?d3d"Z@d3d#ZAd$d%d&ZBd' ZCd( ZDd3d)ZEd* ZFd+ ZGd, ZHd- ZId. ZJd/ ZKd d0lLmMZMmNZNmOZO e%rd d1lLmPZP yy)4    N)Mapping)	timedelta)Random)quoteunquote)OPSPANDATA
SPANSTATUSSPANTEMPLATE)capture_internal_exceptionsfilename_for_moduleDsn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)	FrameTypez5^[ 	]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ 	]*$z(([a-zA-Z0-9+/]{4})*([a-zA-Z0-9+/]{2,3})?c                   (    e Zd Z	 ddZd Zd Zd Zy)EnvironHeadersc                      || _         || _        y N)environprefix)selfr$   r%   s      x/var/www/html/hwPaymentPortal-be-dev/hw-payment-portal-api/venv/lib/python3.12/site-packages/sentry_sdk/tracing_utils.py__init__zEnvironHeaders.__init__A   s         c                 v    | j                   | j                  |j                  dd      j                         z      S N-_)r$   r%   replaceupper)r&   keys     r'   __getitem__zEnvironHeaders.__getitem__J   s.    ||DKK#++c3*?*E*E*GGHHr)   c                 8    t        d t        |       D              S )Nc              3       K   | ]  }d   yw)   N ).0r-   s     r'   	<genexpr>z)EnvironHeaders.__len__.<locals>.<genexpr>P   s     )1)s   )sumiterr&   s    r'   __len__zEnvironHeaders.__len__N   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r+   )r$   
isinstancestrr.   r/   
startswithr%   len)r&   ks     r'   __iter__zEnvironHeaders.__iter__R   si      	(Aa%		#s#))+A<<,C$&''	(s   A:A<N)HTTP_)__name__
__module____qualname__r(   r1   r;   rB   r5   r)   r'   r!   r!   @   s     I*
(r)   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)optionss    r'   has_tracing_enabledrN   _   sY     $%U2 	
KK,-T9 9{{+,D8	 r)   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)N_experimentsrecord_sql_paramsFpyformatformatz	db.paramszdb.paramstyleTzdb.executemanyz	db.cursorquery)messagecategorydata)opnameorigin)
sentry_sdk
get_clientrM   rL   _format_sqlr   add_breadcrumb
start_spanr   DBitemsset_data)cursorrT   params_list
paramstyleexecutemanyrecord_cursor_reprspan_originrW   spanrA   vs              r'   record_sql_queriesrk   q   s?     &&~6::;NPUVkdV3K#!J
&ED'[ *_!%f0"[	$	& N!!%'MN 
		55
  
JJL 	 DAqMM!Q	 
 N N s6   A>D C?.D/D6	D?DDDD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)rU   typerV   rW   i  iW  errori  i  warninghttphttplib)rn   rV   rW   level)rn   rV   rW   
subprocess)rn   rV   rU   rW   )rX   r   DB_REDISr^   description_tagsHTTP_CLIENT_datarL   r	   HTTP_STATUS_CODE)scoperi   rs   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    	$$c                     t        ||      }t        |      xs t        ||      }|  xr |xs t        ||      xr | S r#   )r   r   r   )is_sentry_sdk_frame	namespacein_app_includein_app_excludeabs_pathproject_rootshould_be_includedshould_be_excludeds           r'   _should_be_includedr      s[     )NC,X6 />; #"  	T,7R@R<R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|j
                  d   }|j
                  j                  d	      }|j
                  j                  d
      }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/                  t0        j2                        }n|}| j#                  t$        j4                  |       	 |	j6                  j8                  }|5| j#                  t$        j:                  |	j6                  j8                         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
    Nenable_db_query_sourceTdb_query_source_threshold_msr   r4   )millisecondsr   r   r   rD   zsentry_sdk.)r   r   r   r   r   r    )r[   r\   	is_active	timestampstart_timestamprM   rL   r   sys	_getframer   	f_globalsr   r?   r   f_backf_linenorb   r	   CODE_LINENOCODE_NAMESPACEr   r.   lstripossepCODE_FILEPATHr   co_nameCODE_FUNCTION)ri   clientshould_add_query_sourceduration	threshold
slow_queryr   r   r   r   r   r   r   r   linenofilepathin_app_pathcode_functions                     r'   add_query_sourcer      s   
 ""$F~~!5!5!=$nn001I4P"~~ 4 44H""#A1EII155	AJ>>.1L^^''(89N^^''(89N MMOE

-e4	++J7I (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	!sH   J1 *K #K "K' 1K ?K KKK$#K$'K54K5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)r?   endswithSENTRY_TRACE_REGEXmatchgroupsrS   int)headerr   r   r   sampled_strr   s         r'   extract_sentrytrace_datar   8  s    
 FOOE$:"$$V,E,1LLN)HnkN##C"$56"))#nb*AB$+ (( r)   c                     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   r=   bytesdecode
connectionencodingr   r   )rc   sqlreal_sqls      r'   r]   r]   X  sq     H69%~~c*H(E*#??6+<+<+E+EF %y~%  s   AA% %A32A3c                       e Zd ZdZdZ	 	 	 	 	 ddZed        Zed        Z	e	j                  d        Z	ed        Zej                  d	        Zd
 Zd Zd Zd Zy)PropagationContextzJ
    The PropagationContext represents the data of a trace in Sentry.
    	_trace_id_span_idr   r   dynamic_sampling_contextNc                 R    || _         	 || _        	 || _        	 || _        	 || _        y r#   r   )r&   r   span_idr   r   r   s         r'   r(   zPropagationContext.__init__y  sD     "/:,	H -	Q )A%?r)   c                 X   d }t        |      }|j                  t              }|r2t               }t        j                  |      j                         |_        |j                  t              }|r*t        |      }||
t               }|j                  |       ||j                          |S r#   )normalize_incoming_datarL   BAGGAGE_HEADER_NAMEr   Baggagefrom_incoming_headerr   SENTRY_TRACE_HEADER_NAMEr   update_fill_sample_rand)clsincoming_datapropagation_contextnormalized_databaggage_headersentry_trace_headersentrytrace_datas          r'   from_incoming_dataz%PropagationContext.from_incoming_data  s     #1-@(,,-@A"4"6;B;W;W<&&(  8 .112JK78KL+&.*<*>'#**+;<*113""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(     ~~!ZZ\--DN~~r)   c                     || _         y r#   )r   r&   values     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   r:   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                 n    |j                         D ]  \  }}	 t        | ||        y# t        $ r Y "w xY w)zU
        Updates the PropagationContext with data from the given dictionary.
        N)ra   setattrAttributeError)r&   
other_dictr0   r   s       r'   r   zPropagationContext.update  sE    
 %**, 	JCc5)	 " s   (	44c                     dj                  | j                  | j                  | j                  | j                  | j
                        S )Nzm<PropagationContext _trace_id={} _span_id={} parent_span_id={} parent_sampled={} dynamic_sampling_context={}>)rS   r   r   r   r   r   r:   s    r'   __repr__zPropagationContext.__repr__  sD    ~  F  FNNMM))
 	
r)   c                    | j                   yt        t        | j                   j                  d            }|d|cxk  rdk  ry t        t        | j                   j                  d            }t	        | j
                  |      \  }}	 t        | j                  ||f      }|d
| j                   d<   y# t        $ r) t        j                  d| j
                   d| d	       Y yw xY w)aJ  
        Ensure that there is a valid sample_rand value in the dynamic_sampling_context.

        If there is a valid sample_rand value in the dynamic_sampling_context, 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 dynamic_sampling_context.
        Nsample_randr   r4   sample_rateintervalz5Could not backfill sample_rand, since parent_sampled=z and sample_rate=..6f)r   r   floatrL   _sample_rand_ranger   _generate_sample_randr   
ValueErrorr   debug)r&   r   r   lowerr/   s        r'   r   z$PropagationContext._fill_sample_rand  s    ( ((0!40044]C
 "qK';!'; (< "40044]C
 *$*=*={Ku	/PUWK ;Fc9J%%m4  		
 LLGH[H[G\ ]##.-q2 		s   	B4 4/C&%C&c                 R    | j                   y| j                   j                  d      S )zRConvenience method to get the sample_rand value from the dynamic_sampling_context.Nr   )r   rL   r:   s    r'   _sample_randzPropagationContext._sample_rand  s*     ((0,,00??r)   )NNNNN)rD   rE   rF   __doc__	__slots__r(   classmethodr   propertyr   setterr   r   r   r   r   r5   r)   r'   r   r   l  s    I !%@6 # #2   __    ^^ 	
2Lh@r)   r   c                       e Zd ZdZdZdZ ej                  d      Z	 	 ddZ	e
ddd       Ze
d	        Ze
d
        Zd Zd ZddZed        Zd Z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.
    sentry_itemsthird_party_itemsmutablezsentry-z^sentry-c                 .    || _         || _        || _        y r#   r  )r&   r  r  r  s       r'   r(   zBaggage.__init__+  s     )!2r)   N)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,=r,   r4   FNr   )splitr   stripr   SENTRY_PREFIX_REGEXr   r   r>   )
r   r   r   r  r  r  itemr0   valbaggage_keys
             r'   r   zBaggage.from_incoming_header5  s     S) Wd?02 W::<D#zz#HC2288=&-ciinQ.?&@4;CL[1"')5FcBRV-VV)W W	W #*-l*;L'G|%6@@W Ws   A>CC	c                    i }d}d}t        j                         }|j                         r|j                  t	        |      S |j
                  }|j                  }||j                  |d<   |j                  d      r|d   |d<   |j                  d      r|d   |d<   |j                  d      rt        |d         j                  |d<   |j                  d      rt        |d         |d	<   t	        |||      S )
Nr   Fr   environmentreleasedsn
public_keyrI   r   )r[   r\   r   _propagation_contextr   rM   r   rL   r   r  r>   )r   r{   r  r  r  r   rM   r   s           r'   from_optionszBaggage.from_optionsY  s     &&(!U%?%?%G<((..#88*':'C'CL$;;}%*1-*@L';;y!&-i&8L#;;u),WU^)<)G)GL&;;+,*-g6J.K*LL'|%6@@r)   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                  d      rt        |d         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 )z
        Populate fresh baggage entry with sentry_items and make it immutable
        if this is the head SDK which originates traces.
        r   r   r   r  r  r  r  transactionr   truefalsesampledFr  )r[   r\   r   r   rM   r   r   rL   r   r  rY   sourceLOW_QUALITY_TRANSACTION_SOURCESr   r>   r  _baggager  r   )r   r  r   r  rM   s        r'   populate_from_transactionz!Baggage.populate_from_transactionz  sg    &&(!<((..&B#.#7#7Z )4)A)A#(F]#;;}%*1-*@L';;y!&-i&8L#;;u),WU^)<)G)GL& ""*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                     d| _         y )NFr  r:   s    r'   freezezBaggage.freeze  s	    r)   c                 X    i }| j                   j                         D ]
  \  }}|||<    |S r#   )r  ra   )r&   r   r0   r  s       r'   r   z Baggage.dynamic_sampling_context  s9    **002 	ICF3K	 r)   c                 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)Nr	  r  )
r  ra   r   r   SENTRY_PREFIXr   r>   appendr  join)r&   include_third_partyra   r0   r  r  s         r'   	serializezBaggage.serialize  s    ))//1 	#HC,. #,,uSz9C?%C/QT"# #	#
 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.
        r  c              3   z   K   | ]3  }t         j                  j                  |j                               s| 5 y wr#   )r   r  r   r  )r6   r  s     r'   r7   z/Baggage.strip_sentry_baggage.<locals>.<genexpr>  s2      2288F s   9;)r'  r
  )r   s    r'   strip_sentry_baggagezBaggage.strip_sentry_baggage  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  rL   )r&   r   s     r'   r   zBaggage._sample_rand  sD     "%):):)>)>})MN"sk'?C'? (@ r)   c                 H    d| j                  d       d| j                   dS )Nz
<Baggage "T)r(  z", mutable=>)r)  r  r:   s    r'   r   zBaggage.__repr__  s,    DNNtNDE[QUQ]Q]P^^_``r)   )r   T)F)rD   rE   rF   r   r   r%  recompiler  r(   r   r   r  r   r"  r   r)  staticmethodr,  r   r   r5   r)   r'   r   r     s     AIM$"**Z0
 	 
 	!A !AF A A@ ,4 ,4\ 
 
ar)   r   c                 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)rM   r   r   )r   urlr6  s      r'   should_propagate_tracer9    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.
    rC      Nr-   r,   )ra   r?   r.   r   )r   rW   r0   r   s       r'   r   r     se    
 D#))+ 
U>>'"ab'Ckk#s#))+S	 Kr)   c                 .     ddl m  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                 h    t        j                          fd       }	 t        j                         |_        t        j                          fd       }	 t        j                         |_        t        j                         r|S |S # t
        $ r Y aw xY w# t
        $ r Y 3w xY w)zD
        Decorator to create a span for the given function.
        c            
        K   t               }|/t        j                  dt        
              
| 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 # 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.r   )rX   rY   
get_current_spanr   r   r   _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_piiri   result
attributesfrY   rX   r=  templates            r'   async_wrapperzDcreate_span_decorator.<locals>.span_decorator.<locals>.async_wrapper  s     ,-L#V*1-
 ////2L2G C$:1$=CM&xGI.0H)) *     !1r2%(HmQf  !$1&11&tXxH  0  2 s:   7C(CAC(2C:C;CC(CC%!C(c            
         t               }|'t        j                  dt        
              
| 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@  rA  rI  s            r'   sync_wrapperzCcreate_span_decorator.<locals>.span_decorator.<locals>.sync_wrapperE  s     ,-L#V*1-
 $)&))2L2G C$:1$=CM&xGI.0H)) *     !1r2%(HmQf D+F+&tXxH  s   >>CC)	functoolswrapsinspect	signature__signature__r   iscoroutinefunction)rS  rU  rW  rR  rY   rX   r=  rT  s   `  r'   span_decoratorz-create_span_decorator.<locals>.span_decorator  s     
		 	 
	@	*1*;*;A*>M' 
		 	 
	@	)0):):1)=L& &&q)  Y  		L  		s#   B #B% 	B"!B"%	B10B1)sentry_sdk.scoper=  )rX   rY   rR  rT  r^  r=  s   ```` @r'   create_span_decoratorr`    s    ( 9U  U n r)   c                 N    | xs t        j                         } | j                  }|S )zU
    Returns the currently active span if there is one running, otherwise `None`
    )r[   get_current_scoperi   )r{   rL  s     r'   rB  rB  s  s&    
 3Z113E::Lr)   c                     | xs
 t               } | V| j                  t        j                         | j                  *| j                  j                  t        j                         yyy)z
    Set the status of the current or given span to ERROR.
    Also sets the status of the transaction (root span) to ERROR.
    N)rB  
set_statusr
   ERRORcontaining_transaction)ri   s    r'   set_span_erroredrg  }  sZ     %#%D
(()&&2''22:3C3CD 3 r)   r.  r/  r   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   r   	randrange)r   r   r   r/   rnglower_scaledupper_scaledsample_rand_scaleds           r'   r   r     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.
    rh  Tr.  r/  r5   )r   r   s     r'   r   r     s0     !4	4	KCr)   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)r=   dictrL   r   getattrr   )r  r0   r   s      r'   
_get_valuers    sj     E&$

3 L 63, L5L  Ls   A AA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_CHATrL   r=   r>   AI_AGENTAI_TOOL)rT  rY   rK  rO  ru  r0   s         r'   rD  rD    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   rx  r   GEN_AI_CHATry  GEN_AI_INVOKE_AGENTrz  GEN_AI_EXECUTE_TOOLrL   FUNCTIONr>   )rT  mappingrX   s      r'   rC  rC    s[     	bnnr55b44G
 
Xr{{	+Br7Nr)   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
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.
    )
ru  rv  agent
agent_name
max_tokensfrequency_penaltypresence_penaltytemperaturetop_ptop_kc                 J    | v r|    \  }}|t        ||      r||<   y y y y r#   )r=   )r0   r   	attribute	data_typerR  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)rJ  rK  )r   ry  rz  rx  r	   GEN_AI_REQUEST_MODELr>   GEN_AI_AGENT_NAMEGEN_AI_REQUEST_MAX_TOKENSr    GEN_AI_REQUEST_FREQUENCY_PENALTYr   GEN_AI_REQUEST_PRESENCE_PENALTYGEN_AI_REQUEST_TEMPERATUREGEN_AI_REQUEST_TOP_PGEN_AI_REQUEST_TOP_Klistra   r=   
setdefaultGEN_AI_REQUEST_MESSAGESr&  r   GEN_AI_TOOL_INPUT)	rT  rP  rJ  rK  r  r0   r   rR  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
	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  fd} |t         j                  d        |t         j                  d        |t         j                  d       S )z
    Get usage attributes.
    c                 ^    |D ]'  }t        |      }|t        |t              s#|| <   ) y r#   )rs  r=   r   )r  keysr0   r   rR  usages       r'   _set_from_keysz-_get_usage_attributes.<locals>._set_from_keys4  s7     	.Cuc*E Zs%;(-
9%	.r)   )prompt_tokensinput_tokens)completion_tokensoutput_tokens)total_tokens)r	   GEN_AI_USAGE_INPUT_TOKENSGEN_AI_USAGE_OUTPUT_TOKENSGEN_AI_USAGE_TOTAL_TOKENS)r  r  rR  s   ` @r'   _get_usage_attributesr  -  sY    
 J. **) ++. **
 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  metadataNru  rv  )r   ry  rz  rx  r   rs  r&  r   r  r=   r>   r	   GEN_AI_RESPONSE_MODELr   GEN_AI_TOOL_OUTPUT)	rT  rP  rQ  rR  usage_candidatesr  metausage_candidaterv  s	            r'   _get_output_attributesr  K  sA   
 JL))<+?+?AUAUVV(* 	H &xvw/E##E*fj1DtW-E##E*#3 N".%%&;O&LMN
 $FG4J%*Z*E=G
899:#FL9J%*Z*E=G
899:-	H2 <'''H2;F2C
8../9	H 	Hs   AE	A>E		E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_agentrw  execute_toolN)r   ry  r	   GEN_AI_OPERATION_NAMEr  rx  rz  GEN_AI_TOOL_NAMEr   GEN_AI_TOOL_DESCRIPTIONr   r  rF  )	ri   rT  rP  rY   rS  rJ  rK  rR  	docstrings	            r'   rG  rG  r  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)rF  r  )ri   rT  rP  rQ  s       r'   rH  rH    s!     	+HhGM2Nr)   )r   r  r   )Span)Fmanualr#   )Q
contextlibrX  rZ  r   r2  r   collections.abcr   datetimer   randomr   urllib.parser   r   r   r[   sentry_sdk.constsr   r	   r
   r   sentry_sdk.utilsr   r   r   r   r   r   r   r   r   r   r   r   r   typingr   r   r   r   r   r   typesr   r3  r   base64_strippedr!   rN   contextmanagerrk   r}   r   r   r   r   r]   r   r   r9  r   DEFAULTr`  rB  rg  r   r   rs  rD  rC  r  r  r  rG  rH  sentry_sdk.tracingr   r  r   r  r5   r)   r'   <module>r     su      	 	 
 #   '   D D     !   RZZ  (W (>$  , ,^
@(XHv@&(n@ n@bFa FaR
U" $4,2F2Fm`
E  *@ $46r<$N"'J
O  ' r)   