
    \j/              
           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j6                  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+j]                         e+j_                                D              Z0 G d de       Z1	 	 	 	 	 	 ddZ3ddZ4y# e2$ r dZ&Y w xY w)    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                   0    e Zd ZdZdZdZdeddfdZd	dZy)
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                 t    || _         t        j                         | _        | j                  | _        d| _        y )N        )r   urllib3PoolManagerhttpINITIAL_RETRY_DELAY_retry_delay_last_error_time)selfr   s     >/root/env/lib/python3.12/site-packages/sentry_sdk/spotlight.py__init__zSpotlightClient.__init__4   s/    '')	 44'*    c                    | j                   dkD  r1t        j                         | j                   z
  }|| j                  k  ry t        j                         }|j                  |       	 | j                  j                  | j                  |j                         dddi      }|j                          | j                  | _        d| _         y # t        $ rw}t        j                         | _         t        | j                  dz  | j                        | _        t        j                   d| j                  || j                         Y d }~y 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   envelopetime_since_errorr#   reqes         r   capture_envelopez SpotlightClient.capture_envelope:   s     1$#yy{T-B-BB$"3"33zz|%	))##HH]]_"$C	 $ C IIK $ 8 8D$'D! 	$(IIKD! !$D$5$5$94;O;O PD !!1!! 	s   'A!C	 		E	A-EE	)r3   r   r   N)	__name__
__module____qualname____doc__r   r0   strr   r7    r   r   r   r   %   s,     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              #   \   K   | ]$  }d j                  dj                  |             & yw)z</{}> N)formatjoin).0charss     r   	<genexpr>rI   q   s)      ) 	rwwu~&)s   *,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
   r   c                 $   t         |   |       dd l}|j                  | _        | j                  j                         j                  }|t        j                  d       y t        j                  j                  |j                  d      | _        y )Nr   zPCannot find Spotlight client from SpotlightMiddleware, disabling the middleware.z../)superr   sentry_sdk.apiapi
sentry_sdk
get_clientr   r1   r2   urllibparseurljoinr   rN   )r   get_responserS   spotlight_client	__class__s       r   r   zSpotlightMiddleware.__init__z   ss    G\*!(nnDO#99;EE'%%f "(,,"6"67G7K7KU"SDr   c                 &   | j                   | j                  	 t        j                  j	                  | j                   t
              }t        j                  j                  |d      }t        j                  j                  |       t        j                  | j                   |      | _        | j                  S | j                  S # t        j                  j                  $ r-}t        j                  d|       Y d }~| j                  S d }~ww xY w)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   rU   rV   rW   SPOTLIGHT_JS_ENTRY_PATHr+   RequesturlopenSPOTLIGHT_JS_SNIPPET_PATTERNrE   errorURLErrorr1   debug)r   r^   r5   errs       r   spotlight_scriptz$SpotlightMiddleware.spotlight_script   s    "".43I3I3Q'-||';';++-D($ !..00(% 1 C NN**3/-I-P-P&*&9&9)9 .Q .D* )))4))) ||,, !''o(!$  )))s   BC D#DD_requestrA   c                    t        d j                  j                  dd      j                         j	                  d      D              }|d   }t        |      dkD  r.|d   j                  t              r|d   t        t              d  nd| j                  j                  s|dk(  rt        j                        }| j                  j                        }t        d	 fd
t        D        D        |      }j                  d | |z   j                  |d  z   _
        j                  d      r|t        |      z   j                  d<   S )Nc              3   <   K   | ]  }|j                           y wN)strip)rG   ps     r   rI   z7SpotlightMiddleware.process_response.<locals>.<genexpr>   s      ( 	(s   r"   rD   ;r      utf-8z	text/htmlc              3   *   K   | ]  }|d kD  r|  yw)Nr=   )rG   idxs     r   rI   z7SpotlightMiddleware.process_response.<locals>.<genexpr>   s!       8 s   c              3   r   K   | ].  }j                   j                  |j                               0 y wrl   )contentrfindencode)rG   body_variantencodingresponses     r   rI   z7SpotlightMiddleware.process_response.<locals>.<genexpr>   s5      $ , %,,22<3F3Fx3PQ$s   47zContent-Length)tupler%   getlowersplitlen
startswithCHARSET_PREFIXrh   	streamingrv   rx   nextBODY_CLOSE_TAG_POSSIBILITIES
has_header)	r   ri   r{   content_type_headercontent_typecontent_length	injectioninjection_siterz   s	     `     @r   process_responsez$SpotlightMiddleware.process_response   se    #( (!))--nbAGGIOOPST( # /q1L&'!+0CA0F0Q0Q1 /q1#n2E2GH" %%1 ** K/!$X%5%5!6 1188B	!%$0L$ #
" $$_n5 &&~78   &&'789G#i.9XH$$%56Or   	exceptionz!Optional[HttpResponseServerError]c           	         t         j                  r| j                  sy 	 t        j                  j                  | j                        j                         j                  d      }| j                  j                  |      }t        |j                  dt        j                  | j                  |                  S # t        j                  j                  $ r Y y w xY w)Nrq   z<html>)r]   event_id)rB   DEBUGrN   rU   r+   rb   readdecoderS   capture_exceptionr?   replaceSPOTLIGHT_ERROR_PAGE_SNIPPETrE   rd   re   )r   ri   r   r   r   s        r   process_exceptionz%SpotlightMiddleware.process_exception   s     >>)<)<NN**4+>+>?DDFMMgV   ??<<YG.%% 4;;*.*=*= <  	 <<(( s   AB: :CC)r   r
   rX   zCallable[..., HttpResponse]r   N)r   r
   r   rL   )r   r
   ri   rA   r{   r@   r   zOptional[HttpResponse])r8   r9   r:   rM   __annotations__rN   r   propertyrh   r   r.   r   __classcell__)rZ   s   @r   rK   rK   v   s}    -1?1*..	T  
	* 
	*0,	,	$1,	=K,	%,	\		$1	>G	0	r   rK   c                 >   t         j                  j                  d      }d}d}|rt        |d      }|d}|}n|}| du r|r |j                  d       y| du r
|r|S t
        S t        | t              r|r|| k7  r |j                  d| |       | S | |r|S |rt
        S y)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   r2   DEFAULT_SPOTLIGHT_URL
isinstancer<   )spotlight_configr1   spotlight_env_valuespotlight_from_envspotlight_env_urlparseds         r   _resolve_spotlight_urlr      s     **..);< ,0)-0>>!% 3!' 5 !M!!B 	T	! $$((	$c	*#6:J#J!M!!> #	  		!$$(( r   c                 N   t        | j                  d      t              }|y t        j                  t
        j                        }|j                  t        j                  d             t        j                  |       t        j                  t        j                         || d<   t               5  t        t        j                  rt!        t"        j$                  j                  dd            rt!        t"        j$                  j                  dd            rVt        j&                  }t(        |vr> t+        |      t-        |t(        f            t        _        t        j/                  d       d d d        t1        |      }t        j/                  d|       |S # 1 sw Y   ,xY w)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}   r1   loggingStreamHandlersysstderrsetFormatter	Formatterr   
addHandlersetLevelINFOr   rB   r   r   r   r   
MIDDLEWARE DJANGO_SPOTLIGHT_MIDDLEWARE_PATHtyper   infor   )optionsr   _handler
middlewareclients        r   setup_spotlightr   +  s9   
 [!9=
IC
{ $$SZZ0H'++,UVW
h
OOGLL! GK	$	& H BJJNN+FLMBJJNN+H#NO!,,J/zA&6d:&6*'G&IJ'# FGH S!F
KK7=M#H Hs   1B?FF$)r   r   r1   r   r   rL   )r   zDict[str, Any]r   zOptional[SpotlightClient])5r(   r   r   r'   urllib.parserU   urllib.requesturllib.errorr   r   	itertoolsr   r   typingr   r   r   r   r	   r
   sentry_sdk.utilsr   r1   r   r   sentry_sdk.enveloper   	getLoggerr   r   r   django.utils.deprecationr>   django.httpr?   r@   rA   django.confrB   r`   rc   r   r   BODY_TAG_NAMEr|   zipupperr~   r   rK   ImportErrorr   r   r=   r   r   <module>r      s-   	  	      
 $   
 ) 
		;	' 7 #M  9 9xH8NN$/	Q !
	{ !  NM#( )c-"5"5"79L9L9NOP) $ 
po pl<<,1<<~ G  Hs   A C3 3C=<C=