o
    hK                     @   s  d dl m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
 d dlmZmZ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 erd 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 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& d dlm'Z'm(Z( ee) Z*zd dl+m,Z, W n e-y   d dl.m,Z, Y nw G dd de/Z0d"ddZ1G dd de0Z2G dd de0Z3d d! Z4dS )#    )print_functionN)	timedelta)defaultdict)Dsnloggercapture_internal_exceptions
json_dumps)BackgroundWorker)EnvelopeItem
PayloadRefdatetime_utcnow)TYPE_CHECKING)datetime)Any)Callable)Dict)Iterable)Optional)Tuple)Type)Union)DefaultDict)PoolManager)ProxyManager)EventEndpointType)
getproxiesc                   @   sb   e Zd ZdZdZ	dddZdd Zdd Z	dd	d
Zdd Z			dddZ
dd Zdd ZdS )	TransportzWBaseclass for all transports.

    A transport is used to send an event to sentry.
    Nc                 C   s:   || _ |r|d d ur|d rt|d | _d S d | _d S )Ndsn)optionsr   
parsed_dsn)selfr!    r$   W/var/www/html/aiguide_backend/venv/lib/python3.10/site-packages/sentry_sdk/transport.py__init__4   s   
zTransport.__init__c                 C      t  )zm
        This gets invoked with the event dictionary when an event should
        be sent to sentry.
        NotImplementedErrorr#   eventr$   r$   r%   capture_event>   s   zTransport.capture_eventc                 C   r'   )a$  
        Send an envelope to Sentry.

        Envelopes are a data container format that can hold any type of data
        submitted to Sentry. We use it for transactions and sessions, but
        regular "error" events should go through `capture_event` for backwards
        compat.
        r(   )r#   enveloper$   r$   r%   capture_envelopeH   s   zTransport.capture_envelopec                 C      dS )z=Wait `timeout` seconds for the current events to be sent out.Nr$   r#   timeoutcallbackr$   r$   r%   flushV   s   zTransport.flushc                 C   r/   )zForcefully kills the transport.Nr$   r#   r$   r$   r%   kill_   s   zTransport.killc                 C   r/   )zVThis increments a counter for event loss by reason and
        data category.
        Nr$   )r#   reasondata_categoryitemr$   r$   r%   record_lost_eventd   s   
zTransport.record_lost_eventc                 C   r/   )NTr$   r4   r$   r$   r%   
is_healthyp      zTransport.is_healthyc                 C   s$   z|    W d S  ty   Y d S w N)r5   	Exceptionr4   r$   r$   r%   __del__t   s
   zTransport.__del__r<   NN)__name__
__module____qualname____doc__r"   r&   r,   r.   r3   r5   r9   r:   r>   r$   r$   r$   r%   r   ,   s    



	
r   c              
   c   s    |d u rt  }| dD ]4}z'| dd\}}}|tt|d }|r+|dp,dD ]}||fV  q-W q ttfyA   Y qw d S )N,:   seconds;r<   )r   splitstripr   intLookupError
ValueError)headernowlimitretry_after
categories_categoryr$   r$   r%   _parse_rate_limits|   s   rV   c                   @   s   e Zd ZdZdd Z		d.ddZdd Z			d/d
dZdd Zd0ddZ	d1d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$d% Zd&d' Zd(d) Z	d2d*d+Zd,d- ZdS )3HttpTransportzThe default HTTP transport.c                 C   s  ddl m} t| | | jd usJ || _t|d d| _| jd| | _	i | _
tj | _tt| _t | _|di d}|d u rIdnt|| _|di d	}|d u r]d
nt|| _| j| j|d |d |d |d d| _ddlm} || _d S )Nr   )VERSIONtransport_queue_size)
queue_sizezsentry.python/%s_experiments transport_zlib_compression_level	   transport_num_poolsrF   
http_proxyhttps_proxyca_certsproxy_headers)r_   r`   ra   rb   )Hub)sentry_sdk.constsrX   r   r&   r"   r!   r	   _workerto_auth_auth_disabled_untilurllib3utilRetry_retryr   rL   _discarded_eventstime_last_client_report_sentget_compresslevel
_num_pools
_make_pool_pool
sentry_sdkrc   hub_cls)r#   r!   rX   compresslevel	num_poolsrc   r$   r$   r%   r&      s6   

zHttpTransport.__init__Nc                 C   sd   | j d sd S d}|d ur|j}|dkrt| pd}n|d u r%td| j||f  |7  < d S )Nsend_client_reports   
attachmentzdata category not provided)r!   r7   len	get_bytes	TypeErrorrm   )r#   r6   r7   r8   quantityr$   r$   r%   r9      s   
zHttpTransport.record_lost_eventc                 C   sl   |j d}|rtd | jt| d S |jdkr4td t t	| j
|p+dd | jd < d S d S )Nzx-sentry-rate-limitsz%Rate-limited via x-sentry-rate-limits  zRate-limited via 429<   rG   )headersrp   r   warningrh   updaterV   statusr   r   rl   get_retry_after)r#   responserO   r$   r$   r%   _update_rate_limits   s   


z!HttpTransport._update_rate_limitsstorec                    s   fdd}| tjjtj d zjjdtj|||d}W n ty;   	d |d  w zE
| |jdkrM	d	 n'|jd
ksW|jdk r{td|j|j 	d|j |d W |  d S W |  d S W |  d S |  w )Nc                    s8    d u rj | dd d S  jD ]	}j | |d qd S )Nerrorr7   r8   )r9   items)r6   r8   r-   r#   r$   r%   record_loss   s
   
z0HttpTransport._send_request.<locals>.record_loss)z
User-AgentzX-Sentry-AuthPOST)bodyr   networknetwork_errorr   
status_429i,     z%Unexpected status code: %s (body: %s)z	status_{})r   strrg   client	to_headerrt   requestget_api_urlr=   on_dropped_eventr   r   r   r   dataformatclose)r#   r   r   endpoint_typer-   r   r   r$   r   r%   _send_request   sH   	






	zHttpTransport._send_requestc                 C   s   d S r<   r$   )r#   r6   r$   r$   r%   r     r;   zHttpTransport.on_dropped_eventFr   c                 C   st   | j d sd S |s| jt | k sd S | j}tt| _t | _|s%d S ttt dd | D ddddS )Nry   c                 S   s    g | ]\\}}}|||d qS ))r6   rU   r   r$   ).0rU   r6   r   r$   r$   r%   
<listcomp>-  s    
z>HttpTransport._fetch_pending_client_report.<locals>.<listcomp>)	timestampdiscarded_events)jsonclient_report)type)	r!   ro   rn   rm   r   rL   r   r   r   )r#   forceintervalr   r$   r$   r%   _fetch_pending_client_report  s&   


z*HttpTransport._fetch_pending_client_reportc                 C   s0   | j |dd}|d ur| t|gd d S d S )Nr   )r   r   )r   )r   r.   r
   )r#   r   r   r$   r$   r%   _flush_client_reports9  s   z#HttpTransport._flush_client_reportsc                    s    fdd}||p|d S )Nc                    s    j | }|d uo|t kS r<   )rh   rp   r   )buckettsr4   r$   r%   	_disabledA  s   z0HttpTransport._check_disabled.<locals>._disabledr$   )r#   rU   r   r$   r4   r%   _check_disabled?  s   zHttpTransport._check_disabledc                 C   s   t dd | j D S )Nc                 s   s    | ]}|t  kV  qd S r<   r   )r   r   r$   r$   r%   	<genexpr>J  s    z1HttpTransport._is_rate_limited.<locals>.<genexpr>)anyrh   valuesr4   r$   r$   r%   _is_rate_limitedH  s   zHttpTransport._is_rate_limitedc                 C   s
   | j  S r<   )re   fullr4   r$   r$   r%   _is_worker_fullL  s   
zHttpTransport._is_worker_fullc                 C   s   |   p|   S r<   )r   r   r4   r$   r$   r%   r:   P  s   zHttpTransport.is_healthyc                 C   s  |  dr| d | jddd d S t }| jdkr$|t| n tj	|d| jd}|t| W d    n1 s?w   Y  | j
d usKJ td|d	pTd
|dpZd
|dp`d
| j
j| j
jf  ddi}| jdkrwd|d< | j| |d d S )Nr   self_rate_limitsratelimit_backoffr   r   wfileobjmoderw   z>Sending event, type:%s level:%s event_id:%s project:%s host:%sr   nulllevelevent_idContent-Typezapplication/jsongzipContent-Encoding)r   )r   r   r9   ioBytesIOrq   writer   r   GzipFiler"   r   debugrp   
project_idhostr   getvalue)r#   r+   r   fr   r$   r$   r%   _send_eventT  s<   



zHttpTransport._send_eventc                 C   s8  g }|j D ]}| |jr|jdv r| d | jd|d q|| qt|j|d}|j s1d S | jdd}|d urA|j | t	
 }| jdkrP|| ntj|d	| jd
}|| W d    n1 siw   Y  | jd usuJ td|j| jj| jj ddi}| jdkrd|d< | j| |d|d d S )N)transactionr   defaultr   r   r   )r   r      )r   r   r   r   z(Sending envelope [%s] project:%s host:%sr   zapplication/x-sentry-enveloper   r   r-   )r   r   r-   )r   r   r7   r   r9   appendr
   r   r   r   r   rq   serialize_intor   r   r"   r   r   descriptionr   r   r   r   )r#   r-   	new_itemsr8   client_report_itemr   r   r   r$   r$   r%   _send_envelope|  sP   




zHttpTransport._send_envelopec                 C   s   | j d|pt dS )NCERT_REQUIRED)rx   	cert_reqsra   )rr   certifiwhere)r#   ra   r$   r$   r%   _get_pool_options  s   
zHttpTransport._get_pool_optionsc                 C   sN   t  d}|s
dS |dD ]}| }|j|s!|j|r$ dS qdS )NnoFrD   T)r   rp   rJ   rK   r   endswithnetloc)r#   r"   no_proxyr   r$   r$   r%   _in_no_proxy  s   zHttpTransport._in_no_proxyc                 C   s   d }|  |}|jdkr|dkr|p| ot d}|s,|dkr,|p+| o+t d}| |}|ru|r9||d< |drld}	zddlm}
 W n tyY   d	}	t	
d
| Y nw |	rd|
|fi |S tjdi |S tj|fi |S tjdi |S )Nhttps httprb   socksTr   )SOCKSProxyManagerFzYou have configured a SOCKS proxy (%s) but support for SOCKS proxies is not installed. Disabling proxy support. Please add `PySocks` (or `urllib3` with the `[socks]` extra) to your dependencies.r$   )r   schemer   rp   r   
startswithurllib3.contrib.socksr   ImportErrorr   r   ri   r   r   )r#   r"   r_   r`   ra   rb   proxyr   optsuse_socks_proxyr   r$   r$   r%   rs     s4   	


zHttpTransport._make_poolc                    sD   j j fdd}j|s d jddd d S d S )Nc                	      r   - t       W d    n1 sw   Y  W d    d S W d    d S 1 s2w   Y  d S r<   )r   r   r   r$   r+   hubr#   r$   r%   send_event_wrapper     

"z7HttpTransport.capture_event.<locals>.send_event_wrapper
full_queuequeue_overflowr   r   )rv   currentre   submitr   r9   )r#   r+   r   r$   r   r%   r,     s   
zHttpTransport.capture_eventc                    sP   j j fdd}j|s$d  jD ]}jd|d qd S d S )Nc                	      r   r<   )r   r   r   r$   r-   r   r#   r$   r%   send_envelope_wrapper  r   z=HttpTransport.capture_envelope.<locals>.send_envelope_wrapperr   r   r   )rv   r   re   r   r   r   r9   )r#   r-   r   r8   r$   r   r%   r.     s   

zHttpTransport.capture_envelopec                    s<   t d |dkr j fdd  j|| d S d S )NzFlushing HTTP transportr   c                      s    j ddS )NT)r   )r   r$   r4   r$   r%   <lambda>(  s    z%HttpTransport.flush.<locals>.<lambda>)r   r   re   r   r3   r0   r$   r4   r%   r3     s
   
zHttpTransport.flushc                 C   s   t d | j  d S )NzKilling HTTP transport)r   r   re   r5   r4   r$   r$   r%   r5   +  s   
zHttpTransport.killr?   )r   N)Fr   )Fr<   )r@   rA   rB   rC   r&   r9   r   r   r   r   r   r   r   r   r:   r   r   r   r   rs   r,   r.   r3   r5   r$   r$   r$   r%   rW      s6    )

9

	(>/
rW   c                   @   s   e Zd Zdd Zdd ZdS )_FunctionTransportc                 C   s   t |  || _d S r<   )r   r&   _func)r#   funcr$   r$   r%   r&   2  s   

z_FunctionTransport.__init__c                 C   s   |  | d S r<   )r   r*   r$   r$   r%   r,   9  s   
z _FunctionTransport.capture_eventN)r@   rA   rB   r&   r,   r$   r$   r$   r%   r   1  s    r   c                 C   sb   | d }|d u rt }nt|tr|S t|trt|tr|}nt|r't|S | d r/|| S d S )N	transportr    )rW   
isinstancer   r   
issubclasscallabler   )r!   ref_transporttransport_clsr$   r$   r%   make_transportA  s   
r   r<   )5
__future__r   r   ri   r   r   rn   r   r   collectionsr   sentry_sdk.utilsr   r   r   r   sentry_sdk.workerr	   sentry_sdk.enveloper
   r   r   sentry_sdk._compatr   sentry_sdk._typesr   typingr   r   r   r   r   r   r   r   r   urllib3.poolmanagerr   r   r   r   r   DataCategoryurllib.requestr   r   urllibobjectr   rV   rW   r   r   r$   r$   r$   r%   <module>   sR    
P   )