
    DjrW                        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 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 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jP                  d      Z)dZ* G d de      Z+d Z,e jZ                  	 	 d%d       Z.d Z/d Z0d Z1d Z2d Z3d Z4 G d d      Z5 G d d      Z6d Z7d  Z8d! Z9d&d"Z:d d#l;m<Z<m=Z=m>Z> e rd d$l;m?Z? yy)'    N)Mapping)	timedelta)wraps)quoteunquote)OPSPANDATA)capture_internal_exceptionsfilename_for_moduleDsnloggermatch_regex_listqualname_from_function	to_string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      \C:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\sentry_sdk/tracing_utils.py__init__zEnvironHeaders.__init__=   s         c                 v    | j                   | j                  |j                  dd      j                         z      S N-_)r    r!   replaceupper)r"   keys     r#   __getitem__zEnvironHeaders.__getitem__F   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>L   s     )1)s   )sumiterr"   s    r#   __len__zEnvironHeaders.__len__J   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__N   si      	(Aa%		#s#))+A<<,C$&''	(s   A:A<N)HTTP_)__name__
__module____qualname__r$   r-   r7   r>   r1   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_enabledrJ   [   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_clientrI   rH   _format_sqlr
   add_breadcrumb
start_spanr   DBitemsset_data)cursorrP   params_list
paramstyleexecutemanyrecord_cursor_reprspan_originrS   spanr=   vs              r#   record_sql_queriesrg   m   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(  r| j                  dd|j                         y |j                   dk(  r*| j                  dd|j                  |j                         y y )Nredis)rQ   typerR   rS   httphttplib)rj   rR   rS   
subprocess)rj   rR   rQ   rS   )rT   r   DB_REDISrZ   description_tagsHTTP_CLIENT_data)scopere   s     r#   "maybe_create_breadcrumbs_from_spanrt      s     ww"++$$7W4:: 	 	
 
BNN	"&94::N	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_pathrz      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   r0   )millisecondsr   r~   r   r@   zsentry_sdk.)r|   r}   r~   r   r   r    )rW   rX   	is_active	timestampstart_timestamprI   rH   r   sys	_getframerz   	f_globalsrx   r;   r   f_backf_linenor^   r	   CODE_LINENOCODE_NAMESPACEr   r*   lstripossepCODE_FILEPATHrv   co_nameCODE_FUNCTION)re   clientshould_add_query_sourceduration	threshold
slow_queryr   r~   r   ry   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groupsrO   int)headerr   r   r   sampled_strr   s         r#   extract_sentrytrace_datar   &  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   r9   bytesdecode
connectionencodingrx   r   )r_   sqlreal_sqls      r#   rY   rY   F  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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__g  sD     "/:,	H -	Q )A%?r%   c                 4   d }t        |      }|j                  t              }|r2t               }t        j                  |      j                         |_        |j                  t              }|r*t        |      }||
t               }|j                  |       |S r   )
normalize_incoming_datarH   BAGGAGE_HEADER_NAMEr   Baggagefrom_incoming_headerr   SENTRY_TRACE_HEADER_NAMEr   update)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+&.*<*>'#**+;<""r%   c                 x    | j                   s#t        j                         j                  | _         | j                   S )z!The trace id of the Sentry trace.)r   uuiduuid4hexr6   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   r6   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)r]   setattrAttributeError)r"   
other_dictr,   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={}>)rO   r   r   r   r   r   r6   s    r#   __repr__zPropagationContext.__repr__  sD    ~  F  FNNMM))
 	
r%   )NNNNN)r@   rA   rB   __doc__	__slots__r$   classmethodr   propertyr   setterr   r   r   r1   r%   r#   r   r   Z  s    I !%@6 # #,   __    ^^ 	
r%   r   c                       e Zd ZdZdZdZ ej                  d      Z	 	 ddZ	e
d        Ze
d        Ze
d        Zd	 Zd
 ZddZed        Zy)r   zR
    The W3C Baggage header information (see https://www.w3.org/TR/baggage/).
    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%   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        |||      S # 1 sw Y   xY w)	zF
        freeze if incoming header already has sentry baggage
        r   T,=r(   r0   FN)splitr
   stripr   SENTRY_PREFIX_REGEXr   r   )	r   r   r   r   r   itemr,   valbaggage_keys	            r#   r   zBaggage.from_incoming_header  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 |%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_keyrE   sample_rate)rW   rX   r   _propagation_contextr   rI   r   rH   r   r   r:   )r   rs   r   r   r   r   rI   r   s           r#   from_optionszBaggage.from_options  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      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   transactionr   truefalsesampledFr   )rW   rX   r   r   rI   r   rH   r   r   rU   sourceLOW_QUALITY_TRANSACTION_SOURCESr   r:   r  _baggager   r   )r   r   r   r   rI   s        r#   populate_from_transactionz!Baggage.populate_from_transaction  sR    &&(!<((..&B#.#7#7Z ;;}%*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  r6   s    r#   freezezBaggage.freezeI  s	    r%   c                 X    i }| j                   j                         D ]
  \  }}|||<    |S r   )r   r]   )r"   r   r,   r   s       r#   r   z Baggage.dynamic_sampling_contextM  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   r]   r
   r   SENTRY_PREFIXr   r:   appendr   join)r"   include_third_partyr]   r,   r   r   s         r#   	serializezBaggage.serializeV  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   )r2   r   s     r#   r3   z/Baggage.strip_sentry_baggage.<locals>.<genexpr>l  s2      2288F s   9;)r  r   )r   s    r#   strip_sentry_baggagezBaggage.strip_sentry_baggaged  s+     xx"LL-
 	
r%   N)r   T)F)r@   rA   rB   r   r   r  recompiler   r$   r   r   r   r  r
  r   r  staticmethodr  r1   r%   r#   r   r     s     AIM$"**Z0
 	 A A4 A A@ +4 +4Z 
 
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)rI   r   r   )r   urlr  s      r#   should_propagate_tracer  t  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.
    r?      Nr)   r(   )r]   r;   r*   lower)r   rS   r,   r   s       r#   r   r     se    
 D#))+ 
U>>'"ab'Ckk#s#))+S	 Kr%   c                 .    t        j                         r0t                fd       }	 t        j                         |_        |S t                fd       }	 t        j                         |_        |S # t
        $ r Y |S w xY w# t
        $ r Y |S w xY w)zc
    Decorator to add child spans for functions.

    See also ``sentry_sdk.tracing.trace()``.
    c                  *  K   t               }|/t        j                  dt                      | i | d {   S |j	                  t
        j                  t                    5   | i | d {   cd d d        S 7 H7 # 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.)rT   rU   get_current_spanr   debugr   start_childr   FUNCTIONargskwargsre   funcs      r#   func_with_tracingz5start_child_span_decorator.<locals>.func_with_tracing  s      $%D|V*40
 "426222!!;;+D1 "  3 "42622	3 3 3 3	3 3s9   7BB.B)B5B6B9BBBBc                      t               }|'t        j                  dt                      | i |S |j	                  t
        j                  t                    5   | i |cd d d        S # 1 sw Y   y xY wr"  r#  r(  s      r#   r,  z5start_child_span_decorator.<locals>.func_with_tracing  s     $%D|V*40
 T,V,,!!;;+D1 "  - T,V,	- - -s   A11A:)inspectiscoroutinefunctionr   	signature__signature__rx   )r+  r,  s   ` r#   start_child_span_decoratorr2    s     ""4(	t	3 
	3&	.5.?.?.E+@ 3 
t	- 
	-&	.5.?.?.E+ ?  	< ?	8  		s#   A7 B 7	BB	BBc                 N    | xs t        j                         } | j                  }|S )zU
    Returns the currently active span if there is one running, otherwise `None`
    )rW   get_current_scopere   )rs   current_spans     r#   r$  r$    s&    
 3Z113E::Lr%   )r   r  r   )Span)Fmanualr   )@
contextlibr.  r   r  r   collections.abcr   datetimer   	functoolsr   urllib.parser   r   r   rW   sentry_sdk.constsr   r	   sentry_sdk.utilsr
   r   r   r   r   r   r   r   r   r   r   typingr   r   r   r   r   r   typesr   r  r   base64_strippedr   rJ   contextmanagerrg   rt   rz   r   r   r   rY   r   r   r  r   r2  r$  sentry_sdk.tracingr   r  r   r6  r1   r%   r#   <module>rD     s     	 	 
 #   '   *    !   RZZ  (W (>$  , ,^
$(XHv@&(n
 n
bf
 f
R
U ?D  ' r%   