
    tni/              
       .   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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mZmZ d d
lmZ  ej        d          ZdZdZ G d d          Z	 d dlm Z  d dl!m"Z"m#Z#m$Z$ d dl%m&Z& dZ'dZ(dZ)dZ*dZ+ e,d  e e-e+.                                e+/                                           D                       Z0 G d de           Z1n# e2$ r dZ&Y nw xY w	 	 	 	 	 	 d%d Z3d&d$Z4dS )'    N)chainproduct)TYPE_CHECKING)Any)Callable)Dict)Optional)Self)loggerenv_to_boolcapture_internal_exceptions)Envelope	spotlightzhttp://localhost:8969/streamz(sentry_sdk.spotlight.SpotlightMiddlewarec                   2    e Zd ZdZdZdZdeddfdZdd
ZdS )SpotlightClientaY  
    A client for sending envelopes to Sentry Spotlight.

    Implements exponential backoff retry logic per the SDK spec:
    - Logs error at least once when server is unreachable
    - Does not log for every failed envelope
    - Uses exponential backoff to avoid hammering an unavailable server
    - Never blocks normal Sentry operation
    g      ?g      N@urlreturnNc                 j    || _         t          j                    | _        | j        | _        d| _        d S )N        )r   urllib3PoolManagerhttpINITIAL_RETRY_DELAY_retry_delay_last_error_time)selfr   s     Q/var/www/html/gpu-tools/venv/lib/python3.11/site-packages/sentry_sdk/spotlight.py__init__zSpotlightClient.__init__4   s2    '))	 4'*    enveloper   c                 `   | j         dk    r(t          j                    | j         z
  }|| j        k     rd S t          j                    }|                    |           	 | j                            | j        |	                                dddi          }|
                                 | j        | _        d| _         d S # t          $ rf}t          j                    | _         t          | j        dz  | j                  | _        t          j        d| j        || j                   Y d }~d S d }~ww xY w)	Nr   POSTContent-Typezapplication/x-sentry-envelope)r   bodymethodheadersr      zNFailed to send envelope to Spotlight at %s: %s. Will retry after %.1f seconds.)r   timer   ioBytesIOserialize_intor   requestr   getvaluecloser   	ExceptionminMAX_RETRY_DELAYsentry_loggerwarning)r   r    time_since_errorr$   reqes         r   capture_envelopez SpotlightClient.capture_envelope:   sQ    1$$#y{{T-BB$"333z||%%%	)##H]]__"$C	 $  C IIKKK $ 8D$'D!!! 	 	 	$(IKKD! !$D$5$94;O P PD !1!        	s   AB= =
D-AD((D-)r    r   r   N)	__name__
__module____qualname____doc__r   r1   strr   r7    r   r   r   r   %   sa          O+C +D + + + +$ $ $ $ $ $r   r   )MiddlewareMixin)HttpResponseServerErrorHttpResponseHttpRequest)settingsz/assets/main.jsz<script>window.__spotlight = {{ initOptions: {{ sidecarUrl: '{spotlight_url}', fullPage: false }} }};</script>
<script type="module" crossorigin src="{spotlight_js_url}"></script>
z<html><base href="{spotlight_url}">
<script>window.__spotlight = {{ initOptions: {{ fullPage: true, startFrom: "/errors/{event_id}" }}}};</script>
zcharset=r$   c              #   f   K   | ],}d                      d                    |                    V  -dS )z</{}> N)formatjoin).0charss     r   	<genexpr>rI   q   sL       ) ) 	rwwu~~&&) ) ) ) ) )r   c                        e Zd ZU dZded<   dZded<   d fd
Zedd            Z	 	 	 	 	 	 	 	 ddZ	ddddde
d	dfdZ xZS )SpotlightMiddlewareNOptional[str]_spotlight_script_spotlight_urlr   r
   get_responseCallable[..., HttpResponse]r   c                 *   t                                          |           dd l}|j        | _        | j                                        j        }|t          j        d           d S t          j
                            |j        d          | _        d S )Nr   zPCannot find Spotlight client from SpotlightMiddleware, disabling the middleware.z../)superr   sentry_sdk.apiapi
sentry_sdk
get_clientr   r2   r3   urllibparseurljoinr   rN   )r   rO   rU   spotlight_client	__class__s       r   r   zSpotlightMiddleware.__init__z   s    GG\***!!!!(nDO#99;;E'%f   t"(,"6"67G7KU"S"SDr   c                    | j         | j        	 t          j                            | j         t
                    }t          j                            |d          }t          j                            |           t          
                    | j         |          | _        n8# t          j        j        $ r!}t          j        d||           Y d }~nd }~ww xY w| j        S )NHEAD)r%   )spotlight_urlspotlight_js_urlzUCannot get Spotlight JS to inject at %s. SpotlightMiddleware will not be very useful.)exc_info)rN   rM   rW   rX   rY   SPOTLIGHT_JS_ENTRY_PATHr,   RequesturlopenSPOTLIGHT_JS_SNIPPET_PATTERNrE   errorURLErrorr2   debug)r   r_   r5   errs       r   spotlight_scriptz$SpotlightMiddleware.spotlight_script   s   ".43I3Q'-|';';+-D( ($ !.00(% 1  C N**3///-I-P-P&*&9)9 .Q . .D** |,   !'o(!$         ))s   BB! !C5CC_requestrA   responser@   Optional[HttpResponse]c                     t          d j                            dd                                                              d          D                       }|d         }t          |          dk    rC|d                             t                    r#|d         t          t                    d          nd| j        j	        s|dk    rt          j
                  }| j                                      }t          d	 fd
t          D             D             |          }j
        d |         |z   j
        |d          z   _
                            d          r|t          |          z   j        d<   S )Nc              3   >   K   | ]}|                                 V  d S N)strip)rG   ps     r   rI   z7SpotlightMiddleware.process_response.<locals>.<genexpr>   s>       ( ( 		( ( ( ( ( (r   r#   rD   ;r      utf-8z	text/htmlc              3   &   K   | ]}|d k    |V  dS )Nr=   )rG   idxs     r   rI   z7SpotlightMiddleware.process_response.<locals>.<genexpr>   s8         88 
 $888 r   c              3   r   K   | ]1}j                             |                                        V  2d S ro   )contentrfindencode)rG   body_variantencodingrk   s     r   rI   z7SpotlightMiddleware.process_response.<locals>.<genexpr>   sV       $ $ , %,22<3F3Fx3P3PQQ$ $ $ $ $ $r   zContent-Length)tupler&   getlowersplitlen
startswithCHARSET_PREFIXri   	streamingry   r{   nextBODY_CLOSE_TAG_POSSIBILITIES
has_header)	r   rj   rk   content_type_headercontent_typecontent_length	injectioninjection_siter}   s	     `     @r   process_responsez$SpotlightMiddleware.process_response   s    #( ( (!)--nbAAGGIIOOPSTT( ( ( # # /q1L&''!++0CA0F0Q0Q1 1+ /q1#n2E2E2G2GH" %1 * 2 K//!$X%5!6!6 188BB	!% $ $ $ $ $0L$ $ $   #
" 
" $_n_5 &~78   &&'788 Y9G#i..9XH$%56Or   	exceptionz!Optional[HttpResponseServerError]c           	         t           j        r| j        sd S 	 t          j                            | j                                                                      d          }| j        	                    |          }t          |                    dt                              | j        |                              S # t          j        j        $ r Y d S w xY w)Nrt   z<html>)r^   event_id)rB   DEBUGrN   rW   r,   rc   readdecoderU   capture_exceptionr?   replaceSPOTLIGHT_ERROR_PAGE_SNIPPETrE   re   rf   )r   rj   r   r   r   s        r   process_exceptionz%SpotlightMiddleware.process_exception   s     > )< tN**4+>??DDFFMMgVV   ?<<YGG.%% 4;;*.*= <     	 <(   tts   A	B< <CC)r   r
   rO   rP   r   N)r   r
   r   rL   )r   r
   rj   rA   rk   r@   r   rl   )r8   r9   r:   rM   __annotations__rN   r   propertyri   r   r/   r   __classcell__)r[   s   @r   rK   rK   v   s         -1?111*....	T 	T 	T 	T 	T 	T  
	* 	* 	* 
	*0,	,	$1,	=K,	%,	 ,	 ,	 ,	\		$1	>G	0	 	 	 	 	 	 	 	r   rK   spotlight_configr   r2   r   rL   c                 R   t           j                            d          }d}d}|rt          |d          }|d}|}n|}| du r|r |j        d           dS | du r|r|S t
          S t          | t                    r|r|| k    r |j        d| |           | S | |r|S |rt
          S dS )a  
    Resolve the Spotlight URL based on config and environment variable.

    Implements precedence rules per the SDK spec:
    https://develop.sentry.dev/sdk/expected-features/spotlight/

    Returns the resolved URL string, or None if Spotlight should be disabled.
    SENTRY_SPOTLIGHTNT)strictFzhSpotlight is disabled via spotlight=False config option, ignoring SENTRY_SPOTLIGHT environment variable.z`Spotlight URL from config (%s) takes precedence over SENTRY_SPOTLIGHT environment variable (%s).)osenvironr   r   r3   DEFAULT_SPOTLIGHT_URL
isinstancer<   )r   r2   spotlight_env_valuespotlight_from_envspotlight_env_urlparseds         r   _resolve_spotlight_urlr      s0    *..);<< ,0)- (0>>>>!% 3!' 5   	!M!B   t	T	!	!  	)$$((	$c	*	* ) 	#6:J#J#J!M!> #	    		! 	)$$ 	)(( 4r   optionsDict[str, Any]Optional[SpotlightClient]c                    t          |                     d          t                    }|d S t          j        t
          j                  }|                    t          j        d                     t          
                    |           t                              t          j                   || d<   t                      5  t          t          j        rt!          t"          j                            dd                    rt!          t"          j                            dd                    ret          j        }t(          |vrP t+          |          t-          |t(          f                    t          _        t                              d           d d d            n# 1 swxY w Y   t1          |          }t                              d|           |S )Nr   z' [spotlight] %(levelname)s: %(message)sSENTRY_SPOTLIGHT_ON_ERROR1SENTRY_SPOTLIGHT_MIDDLEWAREz(Enabled Spotlight integration for Djangoz%Enabled Spotlight using sidecar at %s)r   r   r2   loggingStreamHandlersysstderrsetFormatter	Formatterr   
addHandlersetLevelINFOr   rB   r   r   r   r   
MIDDLEWARE DJANGO_SPOTLIGHT_MIDDLEWARE_PATHtyper   infor   )r   r   _handler
middlewareclients        r   setup_spotlightr   +  s   
 [!9!9=
I
IC
{t $SZ00H'+,UVVWWW
h
OOGL!!! GK	$	&	& H H  !BJNN+FLLMM ! BJNN+H#NNOO !
 ",J/zAA&6d:&6&6*'G&IJJ' '# FGGGH H H H H H H H H H H H H H H S!!F
KK7===Ms   CF""F&)F&)r   r   r2   r   r   rL   )r   r   r   r   )5r)   r   r   r(   urllib.parserW   urllib.requesturllib.errorr   r   	itertoolsr   r   typingr   r   r   r   r	   r
   sentry_sdk.utilsr   r2   r   r   sentry_sdk.enveloper   	getLoggerr   r   r   django.utils.deprecationr>   django.httpr?   r@   rA   django.confrB   ra   rd   r   r   BODY_TAG_NAMEr~   zipupperr   r   rK   ImportErrorr   r   r=   r   r   <module>r      s   				  				               



 $ $ $ $ $ $ $ $                      
 ) ( ( ( ( ( 
	;	'	' 7 #M  9 9 9 9 9 9 9 9xH888888NNNNNNNNNN$$$$$$/	Q !
	{ !  NM#(5 ) )Wcc-"5"5"7"79L9L9N9NOOP) ) ) $ $ 
p p p p po p p p pd    HHH<<,1<< < < <~           s   A4C: :DD