o
    h_                     @   sd  d dl m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 d dlmZmZ d dlmZ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mZmZmZm Z m!Z! e	rvd dl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( d dl)m*Z+ z<d dl,Z,d dl,m-Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z<m=Z=m*Z>m?Z? W n e@y   edw zd dlAmBZB W n e@y   d dlCmBZB Y nw zd dlDZDW n e@y   dZDY nw dZEdZFG dd deZGdd ZHd:d d!ZId"d# ZJd$d% ZKd&d' ZLd(d) ZMd*d+ ZNd,d- ZOd.d/ ZPd0d1 ZQG d2d3 d3ZRd4d5 ZSd6d7 ZTd8d9 ZUdS );    )absolute_importN)deepcopy)	iteritems)TYPE_CHECKING)OP)Hub_should_send_default_pii)DidNotEnableIntegration)_is_json_content_typerequest_body_within_bounds)SentryAsgiMiddleware)SOURCE_FOR_STYLETRANSACTION_SOURCE_COMPONENTTRANSACTION_SOURCE_ROUTE)AnnotatedValuecapture_internal_exceptionsevent_from_exceptionloggerparse_versiontransaction_from_function)Any	AwaitableCallableDictOptionalTuple)Scope)__version__)	Starlette)
UploadFile)
Middleware)AuthenticationMiddleware)Request)Match)ASGIAppReceiver   SendzStarlette is not installed)ExceptionMiddlewarezgeneric Starlette request)endpointurlc                   @   s*   e Zd ZdZdZd	ddZedd ZdS )
StarletteIntegration	starlette r*   c                 C   s"   |t vrtd|t f || _d S )Nz7Invalid value for transaction_style: %s (must be in %s))TRANSACTION_STYLE_VALUES
ValueErrortransaction_style)selfr0    r2   d/var/www/html/aiguide_backend/venv/lib/python3.10/site-packages/sentry_sdk/integrations/starlette.py__init__K   s   
zStarletteIntegration.__init__c                  C   sF   t t} | d u rtdtt  t  t  | dkr!t  d S d S )Nz Unparsable Starlette version: {})r      )r   STARLETTE_VERSIONr	   formatpatch_middlewarespatch_asgi_apppatch_request_responsepatch_templates)versionr2   r2   r3   
setup_onceT   s   
zStarletteIntegration.setup_onceN)r*   )__name__
__module____qualname__
identifierr0   r4   staticmethodr=   r2   r2   r2   r3   r+   F   s    
	r+   c                    s*   | j   fdd} jdv}|r|| _ | S )Nc                    sL  t j}|t}|d ur| jj | }t| ||\}}	|d ur)|j||	d W d    n1 s3w   Y  |j	t
j dN}
|
d   fdd}tdt}|dk}|s^|n} fdd	}tdt}|d
k}|sw|n}| |||fi |I d H W  d    S 1 sw   Y  d S | |fi |I d H S )Nsourceopdescriptionstarlette.middleware_namec                     h   t j}|jtjtdtd}|d  | i |I d H W  d    S 1 s-w   Y  d S Nr@   rE   rH   )r   current
start_spanr   MIDDLEWARE_STARLETTE_RECEIVEgetattrstrset_tagargskwargshubspan)middleware_namereceiver2   r3   _sentry_receive      $zO_enable_span_for_middleware.<locals>._create_span_call.<locals>._sentry_receiver>   rX   c                     rI   rJ   )r   rK   rL   r   MIDDLEWARE_STARLETTE_SENDrN   rO   rP   rQ   )rV   sendr2   r3   _sentry_send   rY   zL_enable_span_for_middleware.<locals>._create_span_call.<locals>._sentry_sendr\   )r   rK   get_integrationr+   	__class__r>   configure_scope _get_transaction_from_middlewareset_transaction_namerL   r   MIDDLEWARE_STARLETTErP   rN   rO   )appscoperW   r[   rS   rT   integrationsentry_scopenamerD   middleware_spanrX   receive_namereceive_patchednew_receiver\   	send_namesend_patchednew_sendold_call)rV   rW   r[   r3   _create_span_callj   s<   



$&z6_enable_span_for_middleware.<locals>._create_span_call)rq   %_sentry_authenticationmiddleware_call _sentry_exceptionmiddleware_call)__call__r>   )middleware_classrq   not_yet_patchedr2   ro   r3   _enable_span_for_middlewaref   s   
8rw   Fc                 C   sR   t j}|td u rd S t| |jr|jjnd tj|dd\}}|j||d d S )N)typehandled)client_options	mechanism)hint)	r   rK   r]   r+   r   clientoptionsrA   capture_event)	exceptionry   rT   eventr|   r2   r2   r3   _capture_exception   s   

r   c                    sH   | j dtv}|r"fdd}|| _ | j  fdd}|| _dS dS )zX
    Capture all exceptions in Starlette app and
    also extract user information.
    _sentry_middleware_initc                    sJ   | g|R i | | j    fdd}| j  D ]}|| j |< qd S )Nc                    s   |d }t |dot|jto|jdk}|rt|dd d }t|jD ]}| v r0 | } nq$|d u r7d S t|rI|| g|R i |I d H S || g|R i |S )Nr   status_codei  T)ry   )hasattr
isinstancer   intr   rx   __mro___is_async_callable)r1   rR   rS   expis_http_server_errorold_handlerclsold_handlersr2   r3   !_sentry_patched_exception_handler   s(   

zfpatch_exception_middleware.<locals>._sentry_middleware_init.<locals>._sentry_patched_exception_handler)_exception_handlerscopykeys)r1   rR   rS   r   keyold_middleware_initr   r3   r      s   
z;patch_exception_middleware.<locals>._sentry_middleware_initc                    s"   t |  | |||I d H  d S N_add_user_to_sentry_scoper1   rd   rW   r[   ro   r2   r3   rs      s   zDpatch_exception_middleware.<locals>._sentry_exceptionmiddleware_callN)r4   rO   rt   )ru   rv   r   rs   r2   )rp   r   r3   patch_exception_middleware   s   %
r   c                 C   s   d| vrdS t  sdS tj}|tdu rdS | ?}i }| d }t|dd}|r1|d|j t|dd}|r@|d|j	 t|dd}|rO|d|j
 ||_W d   dS 1 s]w   Y  dS )zZ
    Extracts user information from the ASGI scope and
    adds it to Sentry's scope.
    userNusernameidemail)r   r   rK   r]   r+   r_   rN   
setdefaultr   r   r   r   )rd   rT   rf   	user_infostarlette_userr   user_idr   r2   r2   r3   r     s*   
"r   c                    s0   | j  dt v}|r fdd}|| _ dS dS )z/
    Add user information to Sentry scope.
    rr   c                    s"    | |||I d H  t | d S r   r   r   ro   r2   r3   rr   3  s   zNpatch_authentication_middleware.<locals>._sentry_authenticationmiddleware_callN)rt   rO   )ru   rv   rr   r2   ro   r3   patch_authentication_middleware(  s   
r   c                     s0   t j dt v} | r fdd}|t _dS dS )za
    Patches Starlettes `Middleware` class to record
    spans for every middleware invoked.
    r   c                    s\   |t kr | |fi |S t|} | |fi | |tkr"t| |tkr,t| d S d S r   )r   rw   r"   r   r(   r   )r1   r   r~   span_enabled_clsr   r2   r3   r   G  s   z2patch_middlewares.<locals>._sentry_middleware_initN)r!   r4   rO   )rv   r   r2   r   r3   r8   ;  s   
r8   c                     s   t j  fdd} | t _dS )zG
    Instrument Starlette ASGI app using the SentryAsgiMiddleware.
    c                    s`   t jt}|d u r |||I d H S t fddtj|jd}|j|_||||I d H S )Nc                     s    g| R i |S r   r2   )akw)old_appr1   r2   r3   <lambda>f  s    zBpatch_asgi_app.<locals>._sentry_patched_asgi_app.<locals>.<lambda>)mechanism_typer0   )	r   rK   r]   r+   r   rA   r0   
_run_asgi3rt   )r1   rd   rW   r[   re   
middlewarer   r1   r3   _sentry_patched_asgi_app_  s   z0patch_asgi_app.<locals>._sentry_patched_asgi_appN)r   rt   )r   r2   r   r3   r9   X  s   
r9   c                 C   s<   t | tjr| j} t | tjst| pt| ot| jS r   )r   	functoolspartialfuncasyncioiscoroutinefunctioncallablert   )objr2   r2   r3   r   s  s   
r   c                     s    t jj  fdd} | t j_d S )Nc                    s@   |  t  }|r fdd}|} | S  fdd}|} | S )Nc                     s   t j}|t}|d u r| i |I d H S | $}| d }t||j| t|}| I d H   fdd}W d    n1 sBw   Y  tj	|_
|||| | i |I d H S )Nr   c                        fdd}|S )Nc                    sH   |  di } rd v r d |d< d v r d |d< t|| d< | S )Nrequestcookiesdatagetr   r   r|   request_infoinfor2   r3   event_processor  s   zpatch_request_response.<locals>._sentry_request_response.<locals>._sentry_async_func.<locals>._make_request_event_processor.<locals>.event_processorr2   reqre   r   r   r2   r3   _make_request_event_processor  s   z{patch_request_response.<locals>._sentry_request_response.<locals>._sentry_async_func.<locals>._make_request_event_processor)r   rK   r]   r+   r_    _set_transaction_name_and_sourcer0   StarletteRequestExtractorextract_request_inforA   _nameadd_event_processorrR   rS   rT   re   rf   r   	extractorr   old_funcr   r3   _sentry_async_func  s&   

zTpatch_request_response.<locals>._sentry_request_response.<locals>._sentry_async_funcc                     s   t j}|t}|d u r| i |S | +}|jd ur"|j  | d }t||j| t	|}|
   fdd}W d    n1 sEw   Y  tj|_|||| | i |S )Nr   c                    r   )Nc                    s(   |  di } r |d< t|| d< | S )Nr   r   r   r   r   r2   r3   r     s
   zpatch_request_response.<locals>._sentry_request_response.<locals>._sentry_sync_func.<locals>._make_request_event_processor.<locals>.event_processorr2   r   r   r2   r3   r     s   zzpatch_request_response.<locals>._sentry_request_response.<locals>._sentry_sync_func.<locals>._make_request_event_processor)r   rK   r]   r+   r_   profileupdate_active_thread_idr   r0   r   extract_cookies_from_requestrA   r   r   r   r   r   r3   _sentry_sync_func  s(   



zSpatch_request_response.<locals>._sentry_request_response.<locals>._sentry_sync_func)r   )r   is_coroutiner   r   old_request_responser   r3   _sentry_request_response  s   *0+z8patch_request_response.<locals>._sentry_request_response)r,   routingrequest_response)r   r2   r   r3   r:   }  s   cr:   c                     sd   zddl m  W n
 ty   Y d S w ddlm}  | jdtv}|r0 fdd}|| _d S d S )Nr   Markup)Jinja2Templates_sentry_jinja2templates_initc                    sH    fdd}| dg  ||d vr|d | | g|R i |S )Nc                    s   t j} | }d|iS )Nsentry_trace_meta)r   rK   trace_propagation_meta)r   rT   
trace_metar   r2   r3   add_sentry_trace_meta  s   zTpatch_templates.<locals>._sentry_jinja2templates_init.<locals>.add_sentry_trace_metacontext_processors)r   append)r1   rR   rS   r   r   old_jinja2templates_initr2   r3   r     s
   z5patch_templates.<locals>._sentry_jinja2templates_init)
markupsafer   ImportErrorstarlette.templatingr   r4   rO   )r   rv   r   r2   r   r3   r;     s   
r;   c                   @   sT   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd ZdS )r   z
    Extracts useful information from the Starlette request
    (like form data or cookies) and adds it to the Sentry event.
    Nc                 C   s
   || _ d S r   )r   )r1   r   r2   r2   r3   r4     s   
z"StarletteRequestExtractor.__init__c                 C   s*   t jj}|d u r
d S d }t r|  }|S r   )r   rK   r}   r   r   )r1   r}   r   r2   r2   r3   r     s   z6StarletteRequestExtractor.extract_cookies_from_requestc           
         sB  t jj}|d u rd S i }t  t r|  |d< |  I d H }|s,|W  d    S |rBt||sBt	 |d< |W  d    S | 
 I d H }|rX||d< |W  d    S |  I d H }|ri }t|D ]\}}t|t}	|	st|nt ||< qg||d< |W  d    S t |d< |W  d    S 1 sw   Y  d S )Nr   r   )r   rK   r}   r   r   r   content_lengthr   r   removed_because_over_size_limitjsonformr   r   r    removed_because_raw_data)
r1   r}   r   r   r   r   	form_datar   valis_filer2   r2   r3   r   (  sL   
'$z.StarletteRequestExtractor.extract_request_infoc                    s"   d| j jv rt| j jd S d S )Nzcontent-length)r   headersr   r   r2   r2   r3   r   Z  s   z(StarletteRequestExtractor.content_lengthc                 C   s   | j jS r   )r   r   r   r2   r2   r3   r   a  s   z!StarletteRequestExtractor.cookiesc                    s.   t d u rd S | j I d H  | j I d H S r   )	multipartr   bodyr   r   r2   r2   r3   r   e  s
   zStarletteRequestExtractor.formc                 C   s   t | jjdS )Nzcontent-type)r   r   r   r   r   r2   r2   r3   is_jsonr  s   z!StarletteRequestExtractor.is_jsonc                    s   |   sd S | j I d H S r   )r   r   r   r   r2   r2   r3   r   v  s   zStarletteRequestExtractor.json)r>   r?   r@   __doc__r   r4   r   r   r   r   r   r   r   r2   r2   r2   r3   r     s    2r   c                 C   sD   |  d}|s	d S |jD ]}|| }|d tjkr|j  S qd S )Nrouterr   )r   routesmatchesr$   FULLpath)rd   r   routematchr2   r2   r3   _transaction_name_from_router~  s   



r   c                 C   st   d }t | }|dkr|jd}|rt|pd }n	|dkr"t|j}|d u r*t}t}| j||d t	d|| d S )Nr)   r*   rC   z=[Starlette] Set transaction name and source on scope: %s / %s)
r   rd   r   r   r   _DEFAULT_TRANSACTION_NAMEr   ra   r   debug)rd   r0   r   rg   rD   r)   r2   r2   r3   r     s    
r   c                 C   sF   d }d }|j dkrt| j}t}||fS |j dkrt|}t}||fS )Nr)   r*   )r0   r   r^   r   r   r   )rc   
asgi_scopere   rg   rD   r2   r2   r3   r`     s   


r`   )F)V
__future__r   r   r   r   r   sentry_sdk._compatr   sentry_sdk._typesr   sentry_sdk.constsr   sentry_sdk.hubr   r   sentry_sdk.integrationsr	   r
   $sentry_sdk.integrations._wsgi_commonr   r   sentry_sdk.integrations.asgir   sentry_sdk.tracingr   r   r   sentry_sdk.utilsr   r   r   r   r   r   typingr   r   r   r   r   r   sentry_sdk.scoper   SentryScoper,   r   r6   starlette.applicationsr   starlette.datastructuresr    starlette.middlewarer!   #starlette.middleware.authenticationr"   starlette.requestsr#   starlette.routingr$   starlette.typesr%   r&   StarletteScoper'   r   starlette.middleware.exceptionsr(   starlette.exceptionsr   r   r.   r+   rw   r   r   r   r   r8   r9   r   r:   r;   r   r   r   r`   r2   r2   r2   r3   <module>   sp     	  
HH#
j)n