
    tni1                     p   d Z ddlZddlZddlmZ ddlmZ ddlZddlm	Z	 ddl
mZ ddlmZmZmZ ddlmZmZ dd	lm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 ddl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(m)Z)  ed          Z*dZ+dZ,d ddde-ddfdZ.ddde/fdZ0 G d d          Z1dS )!ze
An ASGI middleware.

Based on Tom Christie's `sentry-asgi <https://github.com/encode/sentry-asgi>`.
    N)deepcopy)partial)continue_trace)OP)_get_headers_get_request_data_get_url)DEFAULT_HTTP_METHODS_TO_CAPTUREnullcontext)track_session)SOURCE_FOR_STYLETransactionSource)
ContextVarevent_from_exceptionHAS_REAL_CONTEXTVARSCONTEXTVARS_ERROR_MESSAGEloggertransaction_from_function_get_installed_modules)Transaction)TYPE_CHECKING)Any)Dict)Optional)Tuple)EventHintsentry_asgi_middleware_appliedzgeneric ASGI request)endpointurlasgiexcr   mechanism_typereturnc                     t          | t          j                    j        |dd          \  }}t          j        ||           d S )NF)typehandled)client_options	mechanism)hint)r   
sentry_sdk
get_clientoptionscapture_event)r"   r#   eventr*   s       Y/var/www/html/gpu-tools/venv/lib/python3.11/site-packages/sentry_sdk/integrations/asgi.py_capture_exceptionr1   :   sU    &!,..6)e<<  KE4
 U......    appc                     t          j        |           rt          | d          S t          j        |           rt	          j        |           S t          | dd          }t	          j        |          S )z
    Try to figure out if an application object supports ASGI3.

    This is how uvicorn figures out the application version as well.
    	__await____call__N)inspectisclasshasattr
isfunctionasyncioiscoroutinefunctiongetattr)r3   calls     r0   _looks_like_asgi3r?   C   sl     s 1sK(((		C	 	  1*3///sJ--*4000r2   c                       e Zd ZdZddddedfddd	ed
edededdddddfdZdeddfdZ	deddfdZ
d&dZd'dZdddddddeddf
dZ	 	 	 	 	 	 	 	 d(d"Zd#d d
ed ddd$fd%ZdS ))SentryAsgiMiddleware)r3   r6   transaction_styler#   span_originhttp_methods_to_captureFr   r!   manualNr3   r   unsafe_context_datarB   r#   rC   rD   zTuple[str, ...]asgi_versionzOptional[int]r$   c                    |st           st          dt          z             |t          vrt	          d|dt          d          |dk    odt                      v }|rt          j        d           || _        || _	        || _
        || _        || _        |t          |          rd	}nd
}|d	k    r| j        | _        dS |d
k    r| j        | _        dS dS )ab  
        Instrument an ASGI application with Sentry. Provides HTTP/websocket
        data to sent events and basic handling for exceptions bubbling up
        through the middleware.

        :param unsafe_context_data: Disable errors when a proper contextvars installation could not be found. We do not recommend changing this from the default.
        zRThe ASGI middleware for Sentry requires Python 3.7+ or the aiocontextvars package.z%Invalid value for transaction_style: z (must be in )r!   	starlettezThe Sentry Python SDK can now automatically support ASGI frameworks like Starlette and FastAPI. Please remove 'SentryAsgiMiddleware' from your project. See https://docs.sentry.io/platforms/python/guides/asgi/ for more information.N      )r   RuntimeErrorr   TRANSACTION_STYLE_VALUES
ValueErrorr   r   warningrB   r#   rC   r3   rD   r?   
_run_asgi3r6   
_run_asgi2)	selfr3   rF   rB   r#   rC   rD   rG   0asgi_middleware_while_using_starlette_or_fastapis	            r0   __init__zSentryAsgiMiddleware.__init__\   s7   " # 	+? 	 13LM   $<<<*$$$&>&>&>@   f$P8N8P8P)P 	9 < 	Na   "3,&'>$ %% !  1 ODMMMQ ODMMM r2   r"   c                 .    t          || j                  S )zCapture exceptions raise in application lifespan handlers.

        The separate function is needed to support overriding in derived integrations that use different catching mechanisms.
        r"   r#   r1   r#   rS   r"   s     r0   _capture_lifespan_exceptionz0SentryAsgiMiddleware._capture_lifespan_exception       
 "c$:MNNNNr2   c                 .    t          || j                  S )zCapture exceptions raised in incoming request handlers.

        The separate function is needed to support overriding in derived integrations that use different catching mechanisms.
        rW   rX   rY   s     r0   _capture_request_exceptionz/SentryAsgiMiddleware._capture_request_exception   r[   r2   scopec                      d fd}|S )Nreceiver   sendr$   c                 F   K                        | |d           d {V S )NrL   rG   _run_app)r`   ra   r^   rS   s     r0   innerz.SentryAsgiMiddleware._run_asgi2.<locals>.inner   s3      ugt!LLLLLLLLLr2   )r`   r   ra   r   r$   r    )rS   r^   rf   s   `` r0   rR   zSentryAsgiMiddleware._run_asgi2   s5    	M 	M 	M 	M 	M 	M 	M r2   r`   ra   c                 D   K   |                      |||d           d {V S )NrK   rc   rd   )rS   r^   r`   ra   s       r0   rQ   zSentryAsgiMiddleware._run_asgi3   s2      ]]5'4a]HHHHHHHHHr2   c           	      8  K   t                               d          }|d         dk    }|s|rs	 |dk    r% |                     |          |           d {V S |                     ||           d {V S # t          $ r}|                     |           |d d }~ww xY wt                               d           	 t          j                    5 }t          |d          5  |	                                 d|_
        t          | j        |	          }	|                    |	           |d         }
|                     | j        |          \  }}|                    d
d                                          }d |
dv rI|
dk    s	|| j        v r9t%          t'          |          d                    |
          ||| j                  n"t-          t.          j        ||| j                  r                    d|
           t          j        d|i          nt7                      }|5  	 	 	 	 	 dfd}|dk    rd |                     |          ||           d {V 	 cd d d            cd d d            cd d d            t                               d           S |                     |||           d {V 	 cd d d            cd d d            cd d d            t                               d           S # t          $ r}|                     |           |d d }~ww xY w# 1 swxY w Y   	 d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   t                               d           d S # t                               d           w xY w)NFr&   lifespanrL   Trequest)session_moder!   )
asgi_scopemethod )http	websocketrq   z	{}.server)opnamesourceoriginz	asgi.typerm   )custom_sampling_contextr/   Dict[str, Any]r$   r   c                    K   :|                      d          dk    od| v }|r                    | d                     |            d {V S )Nr&   zhttp.response.startstatus)getset_http_status)r/   is_http_responsera   transactions     r0   _sentry_wrapped_sendz;SentryAsgiMiddleware._run_app.<locals>._sentry_wrapped_send   sy       $/#:(-		&(9(9=R(R )>,4,= %5 (8 %U(3(C(CE(O(T(T(T-1T%[['8'8'8'8'8'8 8r2   )r/   rw   r$   r   )_asgi_middleware_appliedrz   r3   	ExceptionrZ   setr+   isolation_scoper   clear_breadcrumbs_namer   event_processoradd_event_processor _get_transaction_name_and_sourcerB   upperrD   r   r   formatrC   r   r   HTTP_SERVERset_tagstart_transactionr   r]   )rS   r^   r`   ra   rG   is_recursive_asgi_middlewareis_lifespanr"   sentry_scope	processortytransaction_nametransaction_sourcern   transaction_contextr~   r}   s      `            @r0   re   zSentryAsgiMiddleware._run_app   s      (@'C'CE'J'J$Fmz1' 		$; 		$$1$$!0%$!?!????????!%%$!?!???????? $ $ $00555t#$ 	!$$T***K	0+-- H0"<iHHH G0 G0 22444)/L& '(< O O OI 44Y???vB ==. (* #YYx44::<<F"&K222,,$:V0V0V*8 ,U 3 3#.#5#5b#9#9%5'9'+'7+ + +K '2!~!1#5#'#3	' ' ' # =#++K<<< '2	 #4'5A54I   
 )]] ( - 0 009'79!&9 9 9 9 9 9 9  ,q00-<TXXe__$+-A." ." (" (" (" (" (" (" !"#0 0 0 0 0 0 0[G0 G0 G0 G0 G0 G0 G0H0 H0 H0 H0 H0 H0 H0T %((//// .2XX$)74H." ." (" (" (" (" (" (" !"+0 0 0 0 0 0 0[G0 G0 G0 G0 G0 G0 G0H0 H0 H0 H0 H0 H0 H0T %((////	  ) 0 0 0 ;;C@@@"%4/010 0 0 0 0 0 0 0 0[G0 G0 G0 G0 G0 G0 G0 G0 G0 G0 G0 G0 G0 G0 G0H0 H0 H0 H0 H0 H0 H0 H0 H0 H0 H0 H0 H0 H0 H0T %((/////$((////s   *A8 A8 8
BBB=M= M"EL?*L',5K="L?.M:M= !K=>L?
MM= =
L$	L	L$	$L''L++L?.L+/L?3M?M	MM	M
M= MM= MM= =Nr/   r   r*   r   rm   Optional[Event]c                    |                     di           }|                    t          |                     t          |          |d<   |                     d          }|                     d          pi                      d          }|d uo/|t          k    o$|t
          j        t
          j        t
          j        fv }|s*| 	                    | j
        |          \  }}	||d<   d|	i|d<   |S )Nrk   r}   transaction_infort   )rz   updater   r   _DEFAULT_TRANSACTION_NAMEr   	COMPONENTROUTECUSTOMr   rB   )
rS   r/   r*   rm   request_datar}   r   already_setrs   rt   s
             r0   r   z$SentryAsgiMiddleware.event_processor
  s
    yyB//-j99:::#L11i ii..#ii(:;;ArFFxPPt# 88"!+!'!( 	  	;@@&
 LD& $(E- )16(:E$%r2   rS   zTuple[str, str]c                    d }t           |         }|                    d          }|dk    rP|                    d          }|rt          |          pd}nt          ||dk    rdndd           }t          j        }nY|dk    rS|                    d          }|rt          |d	d           }||}n&t          ||dk    rdndd           }t          j        }|t          }t          j        }||fS ||fS )
Nr&   r   ro   rp   ws)hostr    routepath)	r   rz   r   r	   r   URLr=   r   r   )	rS   rB   rm   rs   rt   r   r   r   r   s	            r0   r   z5SentryAsgiMiddleware._get_transaction_name_and_source-  s    !"34^^F##
**!~~j11H  /0::@b
bFllFFSWXXX*.%'' NN7++E /ufd33#D
bFllFFSWXXX*.<,D&,F<V|r2   )r^   r   r$   r   )r^   r   r`   r   ra   r   r$   r   )r/   r   r*   r   rm   r   r$   r   )__name__
__module____qualname__	__slots__r
   boolstrrU   r   rZ   r]   rR   rQ   intre   r   r   rg   r2   r0   rA   rA   R   s       I %*!+$#5T(,7, 7,7, "7, 	7,
 7, 7, "37, &7, 
7, 7, 7, 7,rOy OT O O O OOi OD O O O O   I I I I\0\0%*\027\0GJ\0	\0 \0 \0 \0|$*8=	   F#$#9<#JO#	# # # # # #r2   rA   )r!   )2__doc__r;   r7   copyr   	functoolsr   r+   sentry_sdk.apir   sentry_sdk.constsr   $sentry_sdk.integrations._asgi_commonr   r   r	   $sentry_sdk.integrations._wsgi_commonr
   r   sentry_sdk.sessionsr   sentry_sdk.tracingr   r   sentry_sdk.utilsr   r   r   r   r   r   r   r   typingr   r   r   r   r   sentry_sdk._typesr   r   r   r   rN   r   r1   r   r?   rA   rg   r2   r0   <module>r      s                      ) ) ) ) ) )                     
        . - - - - -                         + * * * * *             .-------- &:&FGG 2 . / /E /3 /D / / / /15 1T 1 1 1 1~ ~ ~ ~ ~ ~ ~ ~ ~ ~r2   