o
    i;                     @   s
  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dl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mZ d dlmZ d dlmZmZmZ d dlmZ d dlmZmZmZmZmZ zd dlm Z  W n e!yy   dZ Y nw d d	l"m#Z# d dl$Z$d d
l%m&Z& d dl'm(Z(m)Z)m*Z* d dl+m,Z,m-Z-m.Z.m/Z/ e#rd dl0m1Z1m2Z2 d dl"m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZC d dlDmEZE d dl'mFZFmGZGmHZHmIZImJZJmKZKmLZL e<dZMe@dZNedddZOePdZQdaReSdZTeUdZVeUdZWdZX	 dddMd"d#ZYd$dd eZfd%d&Z[dNd(d)Z\dNd*d+Z]d,d-d e^fd.d/Z_G d0d1 d1Z`e` ZadOd3d4ZbdPd7d8Zcdd9d edfd:d;Zedd9d e^fd<d=ZfeUd>Zgde^d d9fd?d@Zh	dQ	A	 	BdRdCdDZiG dEdF dFejZkG dGdH dHZlG dIdJ dJZmdSdMdNZndSdOdPZodQdRd epfdSdTZqdTdXdYZr			dUdZe^d[esd\d]d^d_d`d'd dafdbdcZt	dQ	R	d	]	e	]	 	adVdfdgZuddd e^fdhdiZvddd e^fdjdkZw	`	'	l	'	 	'dWdmdnZx		o	o		dXdQdRddd]dpepdqepded]drdsd dtfdudvZy	o	o	dYdpepdqepded]d dtfdwdxZzdye{d d_fdzd{Z|dyd|d e^fd}d~Z}						dZ	L	y	|	U	V						]		]		'			 	td[ddZ~eedZerXd\ddZnd\ddZ			 	 		d]ddLdyd|dUdVdddddesdesdd'ddd dfddZ			dU	6							 	d^ddZde^d e^fddZd_ddZd`ddZ			dU							'	 	daddZ	dQ							'	 	_dbddZdcddZ							 	ddddZ		de						 	dfddZdd'ddd epfddZdld'd epfddZdld'dd'd epfddZde^desd e^fddZde^d d]fddZ	dQde^d\d]d dfddZde^d dfddńZd epfddǄZded efddʄZdgdd̈́Ze \ZZdZdhdd҄ZdhddԄZedՃZG ddׄ deZG ddل dejZde^d d'fdd܄Zde^d d'fdd߄Zedg dZ	o	o	dide^depdepdepd df
ddZedg dZdjde^depd dfddZddde^d epfddZ		dkde^dddepd epfddZddde^d epfddZdlddZde^d e^fddZde^d e^fdd ZdmddZde^d dfddZ	dQ			|	U	_	 		dnd
dZdoddZe#rUeC					 	dpddZeC			 	dqddZef				 	drddZe&rud esfddZn	d esfddZd edfddZzd d lmZ d d!lmZ W n e!y   dsd#d$Zd%e^d epfd&d'ZY nw d epfd(d)Z	dQ	+	 	,dtd-d.Zd/dddd epfd0d1Ze#re@d2Zdud6d7Zd$dd e^fd8d9Zd:d;d epfd<d=Z	:	;	 	>dvd?d@Zd:d;d epfdAdBZ	:	;	 	CdwdDdEZdxdHdIZÐdydKdLZdS (z      N)
namedtuple)datetimetimezone)Decimal)partialpartialmethodwraps)Real)parse_qsunquote	urlencodeurlsplit
urlunsplit)BaseExceptionGroup)TYPE_CHECKING)PY37)SENSITIVE_DATA_SUBSTITUTE	AnnotatedAnnotatedValue)DEFAULT_ADD_FULL_STACKDEFAULT_MAX_STACK_FRAMESDEFAULT_MAX_VALUE_LENGTHEndpointType)	FrameTypeTracebackType)AnyCallableContextManagerDictIteratorListLiteralNoReturnOptional	ParamSpecSetTupleTypeTypeVarUnioncastoverload)Hub)AttributeValueSerializedAttributeValueEventExcInfoHintLogMetricPRi     zsentry_sdk.errorsz^[a-zA-Z0-9/+=]*$)falsefnnooff0)truetyyeson1i  F)strictvaluer   rC   Optional[bool]returnbool | Nonec                C   s@   | dur
t |  nd}|tv rdS |tv rdS |rdS t| S )zCasts an ENV variable value to boolean using the constants defined above.
    In strict mode, it may return None if the value doesn't match any of the predefined values.
    NFT)strlowerFALSY_ENV_VALUESTRUTHY_ENV_VALUESbool)rD   rC   
normalized rN   M/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/sentry_sdk/utils.pyenv_to_boold   s   rP   datac                 C   s   t j| ddddS )zCSerialize data into a compact JSON representation encoded as UTF-8.F),:)	allow_nan
separatorsutf-8)jsondumpsencode)rQ   rN   rN   rO   
json_dumpss   s   rZ   Optional[str]c               
   C   s   zJt tjjd8} d }tjdkstjdkr!t }| jtj	O  _tj
g d|tj| | d d  d}W d    W |S 1 sCw   Y  W |S  tttfyW   Y d S w )Nzw+win32cygwin)gitz	rev-parseHEAD)startupinfostdoutstderrstdinr   rV   )openospathdevnullsysplatform
subprocessSTARTUPINFOdwFlagsSTARTF_USESHOWWINDOWPopenPIPEcommunicatestripdecodeOSErrorIOErrorFileNotFoundError)nullr`   revisionrN   rN   rO   get_git_revisionx   s2   rx   c                  C   sH   t jd} | r
| S t } | r| S dD ]}t j|} | r!|   S qdS )zTry to guess a default release.SENTRY_RELEASE)HEROKU_SLUG_COMMITSOURCE_VERSION!CODEBUILD_RESOLVED_SOURCE_VERSIONCIRCLE_SHA1GAE_DEPLOYMENT_ID
K_REVISIONN)re   environgetrx   )releasevarrN   rN   rO   get_default_release   s   r   installed_integrationsz	List[str]c                 C   s,   g d}|D ]}|| v rd |  S qdS )zAReturn the SDK name including the name of the used web framework.)djangoflaskfastapibottlefalconquartsanic	starlettelitestarstarlitechalice
serverlesspyramidtornadoaiohttp
aws_lambdagcpbeamasgiwsgizsentry.python.{}zsentry.python)format)r   framework_integrationsintegrationrN   rN   rO   get_sdk_name   s   r   c                   @   s4   e Zd ZdZdddZdddd	d
ddefddZdS )CaptureInternalExceptionrN   rF   ContextManager[Any]c                 C   s   | S NrN   selfrN   rN   rO   	__enter__      z"CaptureInternalException.__enter__tyOptional[Type[BaseException]]rD   Optional[BaseException]tbOptional[TracebackType]c                 C   s"   |d ur|d urt |||f dS )NT)capture_internal_exception)r   r   rD   r   rN   rN   rO   __exit__   s   z!CaptureInternalException.__exit__NrF   r   )__name__
__module____qualname__	__slots__r   rL   r   rN   rN   rN   rO   r      s    
r   r   c                   C   s   t S r   )_CAPTURE_INTERNAL_EXCEPTIONrN   rN   rN   rO   capture_internal_exceptions   r   r   exc_infor0   c                 C   s"   t   rtjd| d dS dS )z
    Capture an exception that is likely caused by a bug in the SDK
    itself.

    These exceptions do not end up in Sentry and are just logged instead.
    zInternal error in sentry_sdkr   N)
sentry_sdk
get_client	is_activeloggererrorr   rN   rN   rO   r      s   r   r   c                 C   s   | t   S r   )epochtotal_secondsrD   rN   rN   rO   to_timestamp      r   c                 C   s   |  tj}|dS )zFormats a timestamp in RFC 3339 format.

    Any datetime objects with a non-UTC timezone are converted to UTC, so that all timestamps are formatted in UTC.
    z%Y-%m-%dT%H:%M:%S.%fZ)
astimezoner   utcstrftime)rD   utctimerN   rN   rO   format_timestamp   s   
r   )+-c              	   C   s   zt | }W nG ttfyN   d| v rdnd}| dr%| d d d } | d tv r<|d7 }| d d	 | d
d   } n
| d tv rF|d7 }t | |}Y nw |tj	S )N.z%Y-%m-%dT%H:%M:%S.%fz%Y-%m-%dT%H:%M:%SZz+0000iz%z)
r   fromisoformatAttributeError
ValueErrorendswithISO_TZ_SEPARATORSstrptimer   r   r   )rD   resulttimestamp_formatrN   rN   rO   datetime_from_isoformat  s   
r   Optional[ExcInfo]Dict[str, Optional[ExcInfo]]c                 C   s2   | du r	t  } nt| } | d du rd} d| iS )z+Creates a hint with the exc info filled in.Nr   r   )rh   r   exc_info_from_errorr   rN   rN   rO   event_hint_with_exc_info  s   
r   c                   @      e Zd ZdZdS )BadDsnzRaised on invalid DSNs.Nr   r   r   __doc__rN   rN   rN   rO   r   '  s    r   c                   @   s^   e Zd ZdZedZ	d					dd	d
Zede	fddZ
ddddZde	fddZdS )DsnzRepresents a DSN.z	^o(\d+)\.NrD   Union[Dsn, str]org_idr[   rF   c              	   C   s>  t |trt|j| _d S tt|}|jdvrtd|j |j| _|jd u r,td|j| _	|d ur8|| _
ntj| j	}|rF|dnd | _
|jd u rY| jdkrUdpVd| _n|j| _|jsdtd|j| _|j| _|jd	d}ztt| | _W n ttfy   td
|jpddd   w d	|d	 | _d S )N)httphttpszUnsupported scheme %rzMissing hostnamer6   r     P   zMissing public key/zInvalid project in DSN (%r) )
isinstancer   dict__dict__r   rH   schemer   hostnamehostr   ORG_ID_REGEXmatchgroupportusername
public_keypassword
secret_keyrf   rsplitintpop
project_idr   	TypeErrorjoin)r   rD   r   partsorg_id_matchrf   rN   rN   rO   __init__0  s8   



zDsn.__init__c                 C   s(   | j }| j| jfdvrd|| jf }|S )zThe netloc part of a DSN.))r   r   )r   r   z%s:%s)r   r   r   r   rvrN   rN   rO   netloc[  s   z
Dsn.netlocclientOptional[Any]Authc              	   C   s"   t | j| j| j| j| j| j|dS )z*Returns the auth info object for this dsn.)r   r   rf   r   r   r   r   )r  r   r   rf   r   r   r   )r   r   rN   rN   rO   to_authc  s   zDsn.to_authc                 C   s.   d| j | j| jrd| j pd| j| j| jf S )Nz%s://%s%s@%s%s%s@r   )r   r   r   r   rf   r   r   rN   rN   rO   __str__o  s   zDsn.__str__r   )rD   r   r   r[   rF   N)r   r  rF   r  )r   r   r   r   recompiler   r   propertyrH   r   r  r  rN   rN   rN   rO   r   +  s    

+r   c                   @   sn   e Zd ZdZ				ddedededed	d
dedddeddfddZejfdddefddZ	defddZ
dS )r  z,Helper object that represents the auth info.N   r   r   r   r   r   r   r[   versionr   r  rf   rF   c	           	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _d S r   )r   r   rf   r   r   r   r
  r   )	r   r   r   r   r   r   r
  r   rf   rN   rN   rO   r   }  s   
zAuth.__init__typer   c                 C   s   d| j | j| j| j|jf S )z'Returns the API url for storing events.z%s://%s%sapi/%s/%s/)r   r   rf   r   rD   )r   r  rN   rN   rO   get_api_url  s   zAuth.get_api_urlc                 C   s`   d| j fd| jfg}| jdur|d| jf | jdur$|d| jf dddd	 |D  S )
z!Returns the auth header a string.
sentry_keysentry_versionNsentry_clientsentry_secretzSentry z, c                 s   s     | ]\}}d ||f V  qdS )z%s=%sNrN   ).0keyrD   rN   rN   rO   	<genexpr>  s    z!Auth.to_header.<locals>.<genexpr>)r   r
  r   appendr   r   r   rN   rN   rO   	to_header  s   

zAuth.to_header)Nr	  Nr   )r   r   r   r   rH   r   r   r   ENVELOPEr  r  rN   rN   rN   rO   r  z  s@    	


r  clsOptional[type]c                 C   s   t | dd pt | dd S )Nr   r   getattr)r  rN   rN   rO   get_type_name  s   r  c                 C   s   t | dd }|dvr|S d S )Nr   )Nbuiltins__builtins__r  )r  modrN   rN   rO   get_type_module  s   r  framer   c              	   C   sl   z| j d }|drW dS W n ttfy   Y nw dD ]}z| j| r)W  dS W q ty3   Y qw dS )Nr   zsentry_sdk.T)__traceback_hide____tracebackhide__F)	f_globals
startswithr   KeyErrorf_locals	Exception)r   r  	flag_namerN   rN   rO   should_hide_frame  s"   


r)  r   r   Iterator[TracebackType]c                 c   s4    | }|d urt |js|V  |j}|d usd S d S r   )r)  tb_frametb_next)r   tb_rN   rN   rO   iter_stacks  s   
r.  filenamelineno
max_lengthOptional[int]loaderr  moduleKTuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]]c              	      s6  d}d }|d ur*t |dr*z||}W n ttfy!   d }Y nw |d ur*| }|d u rFzt| }W n ttfyE   g d g f Y S w |sMg d g fS td|| }t	|d | t
|}	z- fdd||| D }
t|| d d} fd	d||d |	 D }|
||fW S  ty   g d g f Y S w )
N   
get_sourcer   r6   c                       g | ]}t |d  dqS 
r1  strip_stringrq   r  liner;  rN   rO   
<listcomp>      z'get_lines_from_file.<locals>.<listcomp>r:  r;  c                    r8  r9  r<  r>  r;  rN   rO   r@    rA  )hasattrr7  ImportErrorrt   
splitlines	linecachegetlinesrs   maxminlenr=  rq   
IndexError)r/  r0  r1  r3  r4  context_linessource
source_strlower_boundupper_boundpre_contextcontext_linepost_contextrN   r;  rO   get_lines_from_file  s@   



rS  	tb_linenomax_value_lengthc                 C   s   z| j j}W n ty   d }Y nw z| jd }W n ty'   g d g f Y S w z| jd }W n ty:   d }Y nw |d urN|rN|d }t|||||dS g d g fS )Nr   
__loader__r6   )r3  r4  )f_codeco_filenamer'  r#  rS  )r   rT  rU  abs_pathr4  r3  r0  rN   rN   rO   get_source_context  s*   

rZ  c                 C   s&   zt | W S  ty   t|  Y S w r   )rH   r'  	safe_reprr   rN   rN   rO   safe_str  s
   
r\  c                 C   s    zt | W S  ty   Y dS w )Nz<broken repr>)reprr'  r   rN   rN   rO   r[    s
   
r[  rY  c                 C   s   |r| s|S z=| dr|d d }| ddd }|| kr%tj|W S tj| j}|s0|W S ||tj	dd dd 
tj	W S  tyN   | Y S w )Nz.pycr   r   r6   r      )r   splitre   rf   basenamerh   modules__file__r   seplstripr'  )r4  rY  base_modulebase_module_pathrN   rN   rO   filename_for_module#  s"   
rg  Tinclude_local_variablesinclude_source_contextcustom_reprz&Optional[Callable[..., Optional[str]]]Dict[str, Any]c                 C   s   t | dd }|sd }d }n| jj}| jj}z| jd }	W n ty'   d }	Y nw |d u r/| j}z|r8tj	|nd }
W n tyF   d }
Y nw t
|	|pMd |
|pQd|	|d}|rgt| ||\|d< |d< |d< |r{dd	lm} |t| jd
|d|d< |S )NrW  r   z	<unknown>)r/  rY  functionr4  r0  rP  rQ  rR  r   )	serializeT)is_varsrj  vars)r  rW  rX  co_namer#  r'  f_linenore   rf   abspathrg  rZ  sentry_sdk.serializerrm  r   r&  )r   rT  rh  ri  rU  rj  rW  rY  rl  r4  os_abs_pathr   rm  rN   rN   rO   serialize_frame<  sD   
ru  c                 C   sT   d}g }t  }|d ur"t|s|t|| ||d |j}|d us|  d|iS )NT)rh  ri  rU  frames)rh   	_getframer)  r  ru  f_backreverse)rh  ri  rU  r"  rv  r8   rN   rN   rO   current_stacktraceo  s"   rz  	exc_valuec                 C   s   t | dd S )Nerrnor  )r{  rN   rN   rO   	get_errno  r   r}  r   c                 C   sf   t t| ddpt| ddpt | }t| dd }t|tr1t|dkr1|dddd |D  7 }|S )	Nmessager   detail	__notes__r   
c                 s   s    | ]
}t |tr|V  qd S r   )r   rH   )r  noterN   rN   rO   r    s    z$get_error_message.<locals>.<genexpr>)r\  r  r   listrI  r   )r{  r~  notesrN   rN   rO   get_error_message  s   

r  exc_typeclient_optionsOptional[Dict[str, Any]]	mechanismexception_id	parent_idrL  
full_stackOptional[list[dict[str, Any]]]c	                    s  i }	|r|  nddd|	d< |dur||	d d< |dur"t|}
nd}
|
dur8|	d di di d	|
 |durB||	d d
< |dk}|sX|durX||	d d< d|	d d< |rfd|	d vrfd|	d d< tduont|t}|rwd|	d d< t| |	d< t| |	d< t||	d< |du rddtd n|d |d |d |	d  fddt
t|ttd D }t|tkrtjdd|	d< |	S |r|s|}nt|||}d|i|	d< |	S )z
    Creates a dict that goes into the events `exception.values` list and is ingestible by Sentry.

    See the Exception Interface documentation for more details:
    https://develop.sentry.dev/sdk/event-payloads/exception/
    genericTr  handledr  Nr  metar|  numberrL  r   r  chainedr  is_exception_groupr4  rD   rh  ri  rU  rj  c              
      s(   g | ]\}}t |j|j d qS ))rT  rh  ri  rU  rj  )ru  r+  rT  )r  r   _rj  rh  ri  rU  rN   rO   r@    s    z5single_exception_from_error_tuple.<locals>.<listcomp>r6   r   
stacktracerv  )copyr}  
setdefaultr   r   r  r  r  r   r   zipr.  rangeMAX_STACK_FRAMESrI  r   removed_because_over_size_limitmerge_stack_frames)r  r{  r   r  r  r  r  rL  r  exception_valuer|  is_root_exceptionr  rv  
new_framesrN   r  rO   !single_exception_from_error_tuple  sh   




r  __suppress_context__Iterator[ExcInfo]c                 c   s    | \}}}g }t  }|d urW|d urYt||vr[|||fV  || |t| |jr2|j}n|j}|d u r;d S t|}|}t|dd }|d ur]|d ur_t||vsd S d S d S d S d S d S )N__traceback__)	setidr  addr  	__cause____context__r  r  )r   r  r{  r   seen_exceptionsseen_exception_idscauserN   rN   rO   walk_exception_chain	  s4   

r  c                 c   s    | V  d S r   rN   r   rN   rN   rO   r  (  s   
z Tuple[int, List[Dict[str, Any]]]c	                 C   sP  t | ||||||||d	}	|	g}
|}|d7 }t|do|j}|rK|o+t|do+|jdu}|rJ|j}tt||t|dd|||d|d\}}|
| n*|oVt|doV|jdu}|ru|j}tt||t|dd|||d|d\}}|
| |o{t|d	}|rt	|j
D ] \}}tt||t|dd||||d
| |d	\}}|
| q||
fS )z
    Creates the list of exceptions.
    This can include chained exceptions and exceptions from an ExceptionGroup.

    See the Exception Interface documentation for more details:
    https://develop.sentry.dev/sdk/event-payloads/exception/
    )	r  r{  r   r  r  r  r  rL  r  r6   r  r  Nr  )r  r{  r   r  r  r  rL  r  r  
exceptionszexceptions[%s])r  rB  r  r  exceptions_from_errorr  r  extendr  	enumerater  )r  r{  r   r  r  r  r  rL  r  parentr  should_supress_contextexception_has_causer  child_exceptionsexception_has_contentcontextr  idxerN   rN   rO   r  ,  s   









r  List[Dict[str, Any]]c           
      C   s|   | \}}}t d uot|t }|rt|||||dd|d\}}	ng }	t| D ]\}}}|	t||||||d q%|	  |	S )Nr   )r  r{  r   r  r  r  r  r  )r  r{  r   r  r  r  )r   r   r  r  r  r  ry  )
r   r  r  r  r  r{  r   r  r  r  rN   rN   rO   exceptions_from_error_tuple  s:   

r  c                 C   s.   zt | W S  ty   t| dd  Y S w )Nr6   r   )rH   UnicodeDecodeErrorr]  r   rN   rN   rO   	to_string  s
   
r  eventr/   #Iterator[Annotated[Dict[str, Any]]]c                 c   s    d| v r
| d V  d| v r#| d  dpdD ]}d|v r"|d V  qd| v rA| d  dp/dD ]}t|tr@d|v r@|d V  q0d S d S )Nr  threadsvaluesrN   	exception)r   r   r   )r  threadr  rN   rN   rO   iter_event_stacktraces  s   


r  Iterator[Dict[str, Any]]c                 c   sB    t | D ]}t|tr|jpi }|dpdD ]}|V  qqd S )Nrv  rN   )r  r   r   rD   r   )r  r  r   rN   rN   rO   iter_event_frames  s   

r  in_app_excludeOptional[List[str]]in_app_includeproject_rootc                 C   s<   t | D ]}t|tr|jpi }t|d|||d q| S )Nrv  )r  r  r  )r  r   r   rD   set_in_app_in_framesr   )r  r  r  r  r  rN   rN   rO   handle_in_app  s   

r  rv  c                 C   s   | sd S | D ]B}| d}|d urq| d}t||r!d|d< qt||r+d|d< q| d}|d u r5qt|r>d|d< qt||rHd|d< qq| S )Nin_appr4  TFrY  )r   _module_in_list_is_external_source_is_in_project_root)rv  r  r  r  r   current_in_appr4  rY  rN   rN   rO   r    s0   





r  r   Union[BaseException, ExcInfo]c                 C   s   t | trt| dkr| \}}}n2t | tr;t| dd }|d ur't| }| }nt \}}}|| ur:d }| }t| }ntdt|  |||f}t	rOt
t|}|S )N   r  z,Expected Exception object to report, got %s!)r   tuplerI  BaseExceptionr  r  rh   r   r   r   r*   r0   )r   r  r{  r   r   rN   rN   rO   r     s$   


r   c                    s^   dd | D   fdd|D }| |  |r|dtnd}|dur-|t|| d }|S )zV
    Add the missing frames from full_stack to frames and return the merged list.
    c                 S   s(   h | ]}|d  |d |d |d fqS rY  rQ  r0  rl  rN   )r  r   rN   rN   rO   	<setcomp>=  s    z%merge_stack_frames.<locals>.<setcomp>c                    s0   g | ]}|d  |d |d |d f vr|qS r  rN   )r  
stackframe	frame_idsrN   rO   r@  G  s    z&merge_stack_frames.<locals>.<listcomp>max_stack_framesN)r  r   r   rI  )rv  r  r  r  r  rN   r  rO   r  5  s   


r  Tuple[Event, Dict[str, Any]]c                 C   sZ   t | } t| }|r|dtrt|d |d dd }nd }ddt| |||id|fS )	Nadd_full_stackrh  rU  )rh  rU  rv  r   r  )levelr  )r   r   r   r   rz  r  )r   r  r  hintr  rN   rN   rO   event_from_exception`  s$   r  nameitemsc                 C   s>   | d u rdS |s
dS |D ]}|| ks|  |d r dS qdS )NFr   Tr$  )r  r  itemrN   rN   rO   r  }  s   r  c                 C   s    | d u rdS t d| d u}|S )NFz [\\/](?:dist|site)-packages[\\/]r  search)rY  external_sourcerN   rN   rO   r    s
   r  c                 C   s&   | d u s|d u r
dS |  |rdS dS )NFTr  )rY  r  rN   rN   rO   r    s
   
r  string	max_bytesc                 C   s(   |  dd|d  jddd}|d S )zd
    Truncate a UTF-8-encodable string to the last full codepoint so that it fits in max_bytes.
    rV   Nr  ignore)errors...)rY   rr   )r  r  	truncatedrN   rN   rO   _truncate_by_bytes  s    r  c              	   C   s*   zt | dW S  ttfy   Y d S w )NrV   )rI  rY   UnicodeEncodeErrorr  r   rN   rN   rO   _get_size_in_bytes  s
   r  zUnion[AnnotatedValue, str]c                 C   s   | s| S |d u r
t }t| }t| }|d ur ||kr t| |}n|d ur3||kr3| d |d  d }n| S t||p:|dd|d |ggddS )Nr  r  z!limitx)rI  rem)rD   metadata)r   r  rI  r  r   )rD   r1  	byte_size	text_sizetruncated_valuerN   rN   rO   r=    s"   r=  r
  zOptional[Tuple[int, ...]]c              
   C   sp   d}t d| d t jt jB }z||  d }ttt|	ddd }W |S  t
ttfy7   Y dS w )z
    Parses a version string into a tuple of integers.
    This uses the parsing loging from PEP 440:
    https://peps.python.org/pep-0440/#appendix-b-parsing-version-strings-with-regular-expressions
    a    # noqa: N806
        v?
        (?:
            (?:(?P<epoch>[0-9]+)!)?                           # epoch
            (?P<release>[0-9]+(?:\.[0-9]+)*)                  # release segment
            (?P<pre>                                          # pre-release
                [-_\.]?
                (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
                [-_\.]?
                (?P<pre_n>[0-9]+)?
            )?
            (?P<post>                                         # post release
                (?:-(?P<post_n1>[0-9]+))
                |
                (?:
                    [-_\.]?
                    (?P<post_l>post|rev|r)
                    [-_\.]?
                    (?P<post_n2>[0-9]+)?
                )
            )?
            (?P<dev>                                          # dev release
                [-_\.]?
                (?P<dev_l>dev)
                [-_\.]?
                (?P<dev_n>[0-9]+)?
            )?
        )
        (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
    z^\s*z\s*$r   r   Nr  )r  r  VERBOSE
IGNORECASEr   	groupdictr  mapr   r_  r   r   r   )r
  VERSION_PATTERNpatternr   release_tuplerN   rN   rO   parse_version  s   

r  c                  C   s   z7ddl } ddlm} tdd td| jdd D }|dd	r6tjd
kr+|dks0|ddr3W dS W dS W n	 t	y@   Y nw z,ddl
}ddlm} t|j}|du r]td W dS |drh|dk rkW dS W dS W dS  t	yw   Y dS w )z
    Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars.
    r   N)is_object_patchedc                 S   s   g | ]}t |qS rN   )r   )r  partrN   rN   rO   r@        z*_is_contextvars_broken.<locals>.<listcomp>z	a|b|rc|\.r^  	threadinglocalr  r	  )   	   contextvars
ContextVarFT)is_monkey_patchedzYInternal error in Sentry SDK: Could not parse Greenlet version from greenlet.__version__.r  )r   r6  )geventgevent.monkeyr   r  r  r_  __version__rh   version_inforC  greenleteventlet.patcherr
  r  r   r   )r  r   version_tupler  r
  greenlet_versionrN   rN   rO   _is_contextvars_broken  sF   
	
r  r  c                    s   G  fddd}|S )Nc                       sH   e Zd Zddeddddf fddZdddd	ZdddZdddZdS )z1_make_threadlocal_contextvars.<locals>.ContextVarNr  defaultr   rF   c                    s    || _ || _  | _  | _d S r   )_name_default_local_original_local)r   r  r  r  rN   rO   r   ;  s   z:_make_threadlocal_contextvars.<locals>.ContextVar.__init__c                 S   s   t | jd|p| jS )NrD   )r  r  r  )r   r  rN   rN   rO   r   A  s   z5_make_threadlocal_contextvars.<locals>.ContextVar.getrD   c                 S   s0   t td}|  }t| j|| || j_|S )N@   )rH   randomgetrandbitsr   setattrr  r  rD   )r   rD   tokenoriginal_valuerN   rN   rO   r  D  s
   z5_make_threadlocal_contextvars.<locals>.ContextVar.setr  c                 S   s   t | j|| j_| jj|= d S r   )r  r  r  rD   r   )r   r  rN   rN   rO   resetK  s   z7_make_threadlocal_contextvars.<locals>.ContextVar.resetr   )r  r   rF   r   )rD   r   rF   r   )r  r   rF   N)r   r   r   rH   r   r   r  r   rN   r  rN   rO   r	  8  s
    
r	  rN   )r  r	  rN   r  rO   _make_threadlocal_contextvars7  s   r!  Tuple[bool, type]c                  C   s|   t  s2tjdk rzddlm}  d| fW S  ty   Y nw zddlm}  d| fW S  ty1   Y nw ddlm} dt	|fS )z
    Figure out the "right" contextvars installation to use. Returns a
    `contextvars.ContextVar`-like class with a limited API.

    See https://docs.sentry.io/platforms/python/contextvars/ for more information.
    r  r   )r	  Tr  F)
r  rh   r  aiocontextvarsr	  rC  r  r  r  r!  )r	  r  rN   rN   rO   _get_contextvarsS  s    


r$  z

With asyncio/ASGI applications, the Sentry SDK requires a functional
installation of `contextvars` to avoid leaking scope/context data across
requests.

Please refer to https://docs.sentry.io/platforms/python/contextvars/ for more information.
funcCallable[..., Any]c                 C   s   d}zd| j j| j j| jf W S  ty   Y nw d\}}t| tr0t| jdr0d\}}| j} nt| ddp;t| dd}t|t	rHd\}}|j} t| d	rQ| j
}nt| drY| j}|durut| d
rot| jtro| jd | }|| | }|S )zbReturn the qualified name of func. Works with regular function, lambda, partial and partialmethod.Nz%s.%s.%s)r   r   r   )zpartial(<function >)_partialmethod__partialmethod__)zpartialmethod(<function r'  r   r   r   )im_classr   r   r'  r   r   rB  r%  r  r   r   rH   )r%  func_qualnameprefixsuffixpartial_methodrN   rN   rO   qualname_from_function  s:   


r/  c                 C   s   t | S r   )r/  )r%  rN   rN   rO   transaction_from_function     r0  disable_capture_eventc                   @   r   )ServerlessTimeoutWarningz>Raised when a serverless method is about to reach its timeout.Nr   rN   rN   rN   rO   r3    s    r3  c                   @   sR   e Zd ZdZ		ddededdddddf
d	d
ZdddZdddZdddZ	dS )TimeoutThreadzCreates a Thread which runs (sleeps) for a time duration equal to
    waiting_time and raises a custom ServerlessTimeout exception.
    Nwaiting_timeconfigured_timeoutisolation_scopezOptional[sentry_sdk.Scope]current_scoperF   c                 C   s2   t j|  || _|| _|| _|| _t  | _d S r   )	r  Threadr   r5  r6  r7  r8  r/   _stop_event)r   r5  r6  r7  r8  rN   rN   rO   r     s   zTimeoutThread.__init__c                 C   s   | j   d S r   )r:  r  r   rN   rN   rO   stop  s   zTimeoutThread.stopr0   c                 C   s<   t  }t }t||jdddd\}}tj||d |S )Nr  Fr  )r  r  )r  )rh   r   r   r   r  optionscapture_event)r   r   r   r  r  rN   rN   rO   _capture_exception  s   
z TimeoutThread._capture_exceptionc              
   C   s   | j | j | j  rd S t| j}|| jk r|d }| jd urk| jd urktj	
| j6 tj	| j ztd| tyL   t|    Y nw W d    n1 sWw   Y  W d    n1 sfw   Y  td|)Nr6   zZWARNING : Function is expected to get timed out. Configured timeout duration = {} seconds.)r:  waitr5  is_setr   r6  r7  r8  r   scopeuse_isolation_scope	use_scoper3  r   r'  reraiser>  )r   integer_configured_timeoutrN   rN   rO   run  s6   


zTimeoutThread.runNN)rF   N)rF   r0   )
r   r   r   r   floatr   r   r;  r>  rF  rN   rN   rN   rO   r4    s$    


r4  originalc              
   C   sd   d}z|  d}t|}|d}W |S  ty1 } ztdj| d| W Y d}~|S d}~ww )zO
    Convert a string to base64, via UTF-8. Returns None on invalid input.
    NUTF-8z"Unable to encode {orig} to base64:)orig)rY   base64	b64encoderr   r'  r   warningr   )rI  base64_string
utf8_bytesbase64_byteserrrN   rN   rO   	to_base64  s   

rS  rO  c              
   C   sv   d}zt | }|sJ | d}t|}|d}W |S  ty: } ztdj	| d| W Y d}~|S d}~ww )zQ
    Convert a string from base64, via UTF-8. Returns None on invalid input.
    NrJ  z#Unable to decode {b64} from base64:)b64)
BASE64_ALPHABETr   rY   rL  	b64decoderr   r'  r   rN  r   )rO  utf8_stringonly_valid_charsrQ  rP  rR  rN   rN   rO   from_base64  s   


rY  
Components)r   r   rf   queryfragmenturlremove_authorityremove_query_valuesr_  zUnion[str, Components]c           
      C   s   t | }t|jdd}|r'|jd}t|dkr#dtt|d f }n|j}n|j}|r8ttdd |D }n|j}t	|j
|||j|jd	}	|rK|	S t|	S )
zL
    Removes the authority and query parameter values from a given URL.
    T)keep_blank_valuesr  r6   z%s:%s@%sr   c                 S   s   i | ]}|t qS rN   )r   )r  r  rN   rN   rO   
<dictcomp>F  s    z sanitize_url.<locals>.<dictcomp>r   r   r[  rf   r\  )r   r
   r[  r   r_  rI  r   r   r   rZ  r   rf   r\  r   )
r]  r^  r_  r_  
parsed_urlquery_paramsnetloc_partsr   query_string
componentsrN   rN   rO   sanitize_url)  s6   	rh  	ParsedUrlr]  r[  r\  sanitizec                 C   s>   t | d|dd}tt|j|jd|jdd}t||j|jdS )z
    Splits a URL into a url (including path), query and fragment. If sanitize is True, the query
    parameters will be sanitized to remove sensitive data. The autority (username and password)
    in the URL will always be removed.
    T)r^  r_  r_  r   rb  rj  )	rh  r   rZ  r   r   rf   ri  r[  r\  )r]  rk  rc  base_urlrN   rN   rO   	parse_url\  s"   
rm  ratec                 C   sj   t | ttfrt| rtdj|| t| d dS t	| } | dk s'| dkr3tdj|| d dS dS )	z
    Checks the given sample rate to make sure it is valid type and value (a
    boolean or a number between 0 and 1, inclusive).
    z|{source} Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got {rate} of type {type}.)rL  rn  r  Fr   r6   zW{source} Given sample rate is invalid. Sample rate must be between 0 and 1. Got {rate}.)rL  rn  T)
r   r	   r   mathisnanr   rN  r   r  rH  )rn  rL  rN   rN   rO   is_valid_sample_ratew  s    	
rq  r  
regex_listsubstring_matchingc                 C   sH   |d u rdS |D ]}|s|d dkr|d7 }t || }|r! dS qdS )NFr   $Tr  )r  rr  rs  item_matchermatchedrN   rN   rO   match_regex_list  s   rw  r   zsentry_sdk.client.BaseClientc                 C   s,   | duo| j duo| j jduo| j jj|v S )zB
    Determines whether the given URL matches the Sentry DSN.
    N)	transport
parsed_dsnr   )r   r]  rN   rN   rO   is_sentry_url  s   
rz  Iterator[Tuple[str, str]]c                  c   s    z6ddl m}  t }|  D ]%}|jdd }|d ur4t|}|jd ur4||vr4||jfV  || qW d S  tyb   zdd l	}W n tyO   Y Y d S w |j
D ]}t|j|jfV  qSY d S w )Nr   )r  Name)	importlibr  r  distributionsr   _normalize_module_namer
  r  rC  pkg_resourcesworking_setr  )r  yieldeddistr  normalized_namer  inforN   rN   rO   _generate_installed_modules  s.   

r  c                 C   s   |   S r   )rI   r  rN   rN   rO   r    r1  r  c                 C   s   t dd| S )Nz[-_.]+r   )r  subr  rN   rN   rO   1_replace_hyphens_dots_and_underscores_with_dashes  s   r  Dict[str, str]c                   C   s   t d u r	tt a t S r   )_installed_modulesr   r  rN   rN   rN   rO   _get_installed_modules  s   
r  packagec                 C   s>   t t| }dd t  D }||}|d u rd S t|S )Nc                 S   s   i | ]	\}}t ||qS rN   )r  )r  r4  vrN   rN   rO   ra    s    z#package_version.<locals>.<dictcomp>)r  r  r  r  r   r  )r  normalized_packageinstalled_packagesr
  rN   rN   rO   package_version  s   
r  tpr   r"   c                 C   s$   |d usJ |j |ur|||r   )r  with_traceback)r  rD   r   rN   rN   rO   rD    s   

rD  _a_kc                  O      dS )z.No-op function for ensure_integration_enabled.NrN   )r  r  rN   rN   rO   _no_op     r  r   )type[sentry_sdk.integrations.Integration]original_functionCallable[P, R]*Callable[[Callable[P, R]], Callable[P, R]]c                 C      d S r   rN   r   r  rN   rN   rO   ensure_integration_enabled  s   r  0Callable[[Callable[P, None]], Callable[P, None]]c                 C   r  r   rN   )r   rN   rN   rO   r    s   (Union[Callable[P, R], Callable[P, None]]c                    s*   t rttttf d fdd}|S )a  
    Ensures a given integration is enabled prior to calling a Sentry-patched function.

    The function takes as its parameters the integration that must be enabled and the original
    function that the SDK is patching. The function returns a function that takes the
    decorated (Sentry-patched) function as its parameter, and returns a function that, when
    called, checks whether the given integration is enabled. If the integration is enabled, the
    function calls the decorated, Sentry-patched function. If the integration is not enabled,
    the original function is called.

    The function also takes care of preserving the original function's signature and docstring.

    Example usage:

    ```python
    @ensure_integration_enabled(MyIntegration, my_function)
    def patch_my_function():
        with sentry_sdk.start_transaction(...):
            return my_function()
    ```
    sentry_patched_functionr  rF   c                    s2   d	 fdd}t u rt |S t|S )
NargsP.argskwargsP.kwargsrF   r5   c                     s.   t   d u r| i |S | i |S r   )r   r   get_integration)r  r  )r   r  r  rN   rO   runner-  s   z;ensure_integration_enabled.<locals>.patcher.<locals>.runner)r  r  r  r  rF   r5   )r  r   )r  r  r  )r  rO   patcher,  s   z+ensure_integration_enabled.<locals>.patcherN)r  r  rF   r  )r   r*   r   r4   r5   )r   r  r  rN   r  rO   r    s   c                   C      t  S r   )timeperf_counter_nsrN   rN   rN   rO   nanosecond_time=  r1  r  c                   C   s   t t d S )Ng    eA)r   r  perf_counterrN   rN   rN   rO   r  B     c                   C   r  r   )r  r  rN   rN   rN   rO   nowF  r1  r  )get_hubis_module_patchedOptional[Hub]c                   C   r  r   rN   rN   rN   rN   rO   get_gevent_hubP  r   r  mod_namec                 C   r  NFrN   )r  rN   rN   rO   r  S  r  r  c                   C   s   t dpt dS )Nr  _threadr  rN   rN   rN   rO   	is_geventX  r  r  r  Optional[threading.Thread]#Tuple[Optional[int], Optional[str]]c                 C   s   | durz| j }| j}|dur||fW S W n	 ty   Y nw t r9t }|dur9z|jdfW S  ty8   Y nw zt } | j }| j}|durM||fW S W n	 tyW   Y nw zt } | j }| j}|durl||fW S W dS  tyx   Y dS w )zK
    Try to get the id of the current thread, with various fall backs.
    NrG  )	identr  r   r  r  thread_identr  current_threadmain_thread)r  	thread_idthread_name
gevent_hubrN   rN   rO   get_current_thread_meta\  sP   


r  r   c                 C   s$   | t krt|dr|jdv rdS dS )Ncode)r   NFT)
SystemExitrB  r  )r   rD   rN   rN   rO   should_be_treated_as_error  s   r  Tconvert_funcCallable[[Any], T]Optional[T]c                 C   sH   z
t || r	|W S W n	 ty   Y nw z| |W S  ty#   Y dS w )z
    Attempt to convert from an unknown type to a specific type, using the
    given function. Return None if the conversion fails, i.e. if the function
    raises an exception.
    N)r   r   r'  )r  rD   rN   rN   rO   try_convert  s   

r  c                    sJ   				d	 fdd z | }t j|tdW S  ty$   t|  Y S w )
z&Safely serialize to a readable string.r  r   rF   6Union[str, dict[Any, Any], list[Any], tuple[Any, ...]]c                    s2  t | rJz3t| dd }t| dd }t| dd}|r#|r#| d| }n|r/|r/| d| }n|}d| dW S  tyI   dt| j d Y S w t| trZ fd	d
|  D S t| tt	frj fdd| D S t
| drz fdd
t|  D }dt| j d| dW S  ty   t|  Y S w | S )Nr   r   r   	anonymousr   z
<function >z
<callable c                    s   i | ]	\}}| |qS rN   rN   r  kr  serialize_itemrN   rO   ra    s    z:safe_serialize.<locals>.serialize_item.<locals>.<dictcomp>c                    s   g | ]} |qS rN   rN   )r  r  r  rN   rO   r@    r  z:safe_serialize.<locals>.serialize_item.<locals>.<listcomp>r   c                    s$   i | ]\}}| d s| |qS )r  r  r  r  rN   rO   ra    s    < )callabler  r'  r  r   r   r   r  r  r  rB  ro  r]  )r  r4  qualnamer  	full_pathattrsr  rN   rO   r    s8   



z&safe_serialize.<locals>.serialize_item)r  N)r  r   rF   r  )rW   rX   rH   r'  )rQ   
serializedrN   r  rO   safe_serialize  s   $r  r<  Optional[dict[str, Any]]c                 C   s,   | d u rdS t | ddp| d ddS )NFenable_logs_experimentsrL   r   r<  rN   rN   rO   has_logs_enabled  s   r  .Optional[Callable[[Log, Hint], Optional[Log]]]c                 C   $   | d u rd S |  dp| d  dS )Nbefore_send_logr  r   r  rN   rN   rO   get_before_send_log  
   r  c                 C   s   | d u rdS t | ddS )NFenable_metricsTr  r  rN   rN   rO   has_metrics_enabled  s   r  4Optional[Callable[[Metric, Hint], Optional[Metric]]]c                 C   r  )Nbefore_send_metricr  r  r  rN   rN   rO   get_before_send_metric  r  r  valr-   c                    s   t | ttttfr| S tdtdtdtdi}t | ttfr | s g S t | trCt| d   |v r?t fdd| D r?t	
| S t| S t | trat| d   |v rat fdd| D rat| S t| S )	a  
    Turn unsupported attribute value types into an AttributeValue.

    We do this as soon as a user-provided attribute is set, to prevent spans,
    logs, metrics and similar from having live references to various objects.

    Note: This is not the final attribute value format. Before they're sent,
    they're serialized further into the actual format the protocol expects:
    https://develop.sentry.dev/sdk/telemetry/attributes/
    zstring[]z	integer[]zdouble[]z	boolean[]r   c                 3       | ]	}t | u V  qd S r   r  r  r  r   rN   rO   r        z#format_attribute.<locals>.<genexpr>c                 3   r  r   r  r  r  rN   rO   r  !  r  )r   rL   r   rH  rH   r  r  r  allr  deepcopyr[  )r  
list_typesrN   r  rO   format_attribute  s&   


r  r.   c                    s   t | tr
| ddS t | tr| ddS t | tr| ddS t | tr(| ddS t | trR| s4g ddS t| d   ttttfv rRt fdd	| D rR| ddS t| ddS )
z2Serialize attribute value to the transport format.boolean)rD   r  integerdoubler  arrayr   c                 3   r  r   r  r  r  rN   rO   r  8  r  z&serialize_attribute.<locals>.<genexpr>)	r   rL   r   rH  rH   r  r  r  r[  )r  rN   r  rO   serialize_attribute'  s   









&
r  )rD   r   rC   rE   rF   rG   )rF   r[   r   )r   r0   rF   Nr   )r   r   rF   r   )r  r  rF   r[   )r   r   rF   r*  )NNN)r   r   rT  r2  rU  r2  rF   r5  )r4  r[   rY  r[   rF   r[   )NTTNN)TTN)NNNNNN)r  r  r{  r   r   r   r  r  r  r  r  r2  r  r2  rL  r[   r  r  rF   rk  )r   r0   rF   r  )NNr   r   NN)
r   r0   r  r  r  r  r  r  rF   r  )r  r/   rF   r  )r  r/   rF   r  )
r  r/   r  r  r  r  r  r[   rF   r/   )
rv  r   r  r  r  r  r  r[   rF   r  )r   r  rF   r0   )rv  r  r  r  r  r  rF   r  rG  )r   r  r  r  r  r  rF   r  )rF   r"  )r%  r&  rF   r[   )TTF)Tr  )rF   r{  )rF   r  )r  r   rD   r   r   r  rF   r"   )r  r   r  r   rF   N)r   r  r  r  rF   r  )r   r  rF   r  )r   r  r  r  rF   r  )rF   r  )r  r  rF   r  )r  r  rD   r   rF   r  )r<  r  rF   r  )r<  r  rF   r  )r  r   rF   r-   )r  r-   rF   r.   )rL  rW   rE  loggingro  re   r  r  r  rj   rh   r  r  collectionsr   r   r   decimalr   	functoolsr   r   r   numbersr	   urllib.parser
   r   r   r   r   r  r   rC  typingr   r   sentry_sdk._compatr   sentry_sdk._typesr   r   r   sentry_sdk.constsr   r   r   r   typesr   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   
gevent.hubr,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r   	getLoggerr   r  r  rU  	frozensetrJ   rK   r  rP   bytesrZ   rx   r   rH   r   r   r   r   r   rH  r   r   r   r   r   r   r   r   r  r  r  rL   r)  r.  r   rS  rZ  r\  r[  rg  ru  rz  r  r}  r  r  rB  r'  HAS_CHAINED_EXCEPTIONSr  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r=  r  r  r  r!  r$  HAS_REAL_CONTEXTVARSr	  CONTEXTVARS_ERROR_MESSAGEr/  r0  r2  r3  r9  r4  rS  rY  rZ  rh  ri  rm  rq  rw  rz  r  r  r  r  r  rD  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rN   rN   rN   rO   <module>   s   L$


	#O.
0
4
	

f	

h++-
	
33
%
+E
0 
-4
.
$