o
    iik                     @   s@  d dl Z d dlZd dlmZ d dlmZ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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 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/ d dlm0Z0m1Z1m2Z2m3Z3m4Z4 d dlm5Z5 e+dZ6ndd Z,edZ7d d! Z8d"d# Z9G d$d% d%e:Z;d&d' Z<d(d) Z=d dlm Z  e rG d*d+ d+e5e;Z>nd,d-  Z>G d.d/ d/e?Z@G d0d1 d1e:ZAG d2d3 d3ee@ZBeB ZCe7DeC dS )4    N)contextmanager)datetime_utcnowwith_metaclass)INSTRUMENTERScope)Client)Profile)NoOpSpanSpanTransactionBAGGAGE_HEADER_NAMESENTRY_TRACE_HEADER_NAME)Session)has_tracing_enablednormalize_incoming_data)exc_info_from_errorevent_from_exceptionlogger
ContextVar)TYPE_CHECKING)Union)Any)Optional)Tuple)Dict)List)Callable)	Generator)Type)TypeVar)overload)ContextManager)Integration)EventHint
BreadcrumbBreadcrumbHintExcInfo)ClientConstructorTc                 C      | S N )xr-   r-   M/var/www/html/pca-backend/venv/lib/python3.10/site-packages/sentry_sdk/hub.pyr!   =      r!   sentry_current_hubc                 C   sn   |r|rt d|d ur"t| }t|r|| |S || |S |r3t| }|jdi | |S | }|S )Nzcannot provide scope and kwargsr-   )	TypeErrorcopycallableupdate_from_scopeupdate_from_kwargs)basescope_changescope_kwargsfinal_scoper-   r-   r/   _update_scopeE   s   


r;   c                  C   s   t jj} | sdS | jd S )NFsend_default_pii)Hubcurrentclientoptions)r?   r-   r-   r/   _should_send_default_piiW   s   
rA   c                   @   $   e Zd Zdd Zdd Zdd ZdS )
_InitGuardc                 C   s
   || _ d S r,   )_client)selfr?   r-   r-   r/   __init__`   s   
z_InitGuard.__init__c                 C   r+   r,   r-   rE   r-   r-   r/   	__enter__d   r0   z_InitGuard.__enter__c                 C   s   | j }|d ur|  d S d S r,   )rD   close)rE   exc_type	exc_valuetbcr-   r-   r/   __exit__h   s   z_InitGuard.__exit__N__name__
__module____qualname__rF   rH   rN   r-   r-   r-   r/   rC   _   s    rC   c                  C   sB   t jd d } | dks| dkrtddj|   td d S d S )N   )      )rT      z1sentry-sdk 2.0.0 will drop support for Python %s.z{}.{}zQPlease upgrade to the latest version to continue receiving upgrades and bugfixes.)sysversion_infor   warningformat)versionr-   r-   r/   _check_python_deprecationso   s   r\   c                  O   s,   t | i |}tj| t  t|}|S )zsInitializes the SDK and optionally integrations.

    This takes the same arguments as the client constructor.
    )r   r=   r>   bind_clientr\   rC   )argskwargsr?   rvr-   r-   r/   _init}   s
   ra   c                   @   s   e Zd ZdS )initN)rP   rQ   rR   r-   r-   r-   r/   rb      s    rb   c                   C      t S r,   )ra   r-   r-   r-   r/   <lambda>   s    rd   c                   @   s$   e Zd Zedd Zedd ZdS )HubMetac                 C   s(   t d}|du rtt}t | |S )z(Returns the current instance of the hub.N)_localgetr=   
GLOBAL_HUBset)clsr`   r-   r-   r/   r>      s
   

zHubMeta.currentc                 C   rc   )z%Returns the main instance of the hub.)rh   )rj   r-   r-   r/   main   s   zHubMeta.mainN)rP   rQ   rR   propertyr>   rk   r-   r-   r-   r/   re      s
    
	re   c                   @   rB   )_ScopeManagerc                 C   s"   || _ t|j| _|jd | _d S N)_hublen_stack_original_len_layer)rE   hubr-   r-   r/   rF      s   z_ScopeManager.__init__c                 C   s   | j d }|d usJ |S )N   )rt   )rE   scoper-   r-   r/   rH      s   
z_ScopeManager.__enter__c                 C   s   t | jj}|| jk rtd| j|  d S || jkr,td|| j | jj| jd   | jj| jd  }| jj| jd d = |d | jd krVtd|d | jd  d S |d | jd krhd}t| d S d S )Nz1Scope popped too soon. Popped %s scopes too many.zLeaked %s scopes: %srv   z2Wrong scope found. Meant to pop %s, but popped %s.r   zinit() called inside of pushed scope. This might be entirely legitimate but usually occurs when initializing the SDK inside a request handler or task/job function. Try to initialize the SDK as early as possible instead.)rq   rp   rr   rs   r   errorrY   rt   )rE   rJ   rK   rL   current_lenlayerrY   r-   r-   r/   rN      s4   

z_ScopeManager.__exit__NrO   r-   r-   r-   r/   rm      s    rm   c                   @   s  e Zd ZdZdZerdZdZ		dCddZdd Z	dd Z
d	d
 Zdd Zedd Zedd Zdd Zdd ZdCddZdCddZdCddZdd ZdCddZdejfdd Zdejfd!d"ZdDd#d$Ze	dEd%d&Zed'd& Z		(dFd)d&Zd*d+ Ze	dEd,d-Zed.d- Z		(dFd/d-Z	0dGd1d2Z d3d4 Z!d5d6 Z"d7d8 Z#		dCd9d:Z$d;d< Z%d=d> Z&dEd?d@Z'dEdAdBZ(dS )Hr=   zThe hub wraps the concurrency management of the SDK.  Each thread has
    its own hub but the hub might transfer with the flow of execution if
    context vars are available.

    If the hub is used with a with statement it's temporarily activated.
    Nc                 C   s^   t |tr|}|jd \}}|d u rt|}n|}|d u r!t }||fg| _d | _g | _d S rn   )
isinstancer=   rr   r3   r   _last_event_id	_old_hubs)rE   client_or_hubrw   ru   r?   other_scoper-   r-   r/   rF      s   


zHub.__init__c                 C   s   | j tj t|  | S r,   )r}   appendr=   r>   rf   ri   rG   r-   r-   r/   rH     s   
zHub.__enter__c                 C   s   | j  }t| d S r,   )r}   poprf   ri   )rE   rJ   rK   rL   oldr-   r-   r/   rN   
  s   
zHub.__exit__c                 C   s.   |  | W  d   S 1 sw   Y  dS )z~Runs a callback in the context of the hub.  Alternatively the
        with statement can be used on the hub directly.
        Nr-   rE   callbackr-   r-   r/   run  s   $zHub.runc                 C   sX   t |tr|}n|jdur|j}ntd| j}|dur(|j|}|dur*|S dS dS )a  Returns the integration for this hub by name or class.  If there
        is no client bound or the client does not have that integration
        then `None` is returned.

        If the return value is not `None` the hub is guaranteed to have a
        client attached.
        NzIntegration has no name)r{   str
identifier
ValueErrorr?   integrationsrg   )rE   name_or_classintegration_namer?   r`   r-   r-   r/   get_integration  s   

zHub.get_integrationc                 C      | j d d S )z&Returns the current client on the hub.ro   r   rr   rG   r-   r-   r/   r?   6     z
Hub.clientc                 C   r   )z%Returns the current scope on the hub.ro   rv   r   rG   r-   r-   r/   rw   <  r   z	Hub.scopec                 C   s   | j S )zReturns the last event ID.)r|   rG   r-   r-   r/   last_event_idB  s   zHub.last_event_idc                 C   s    | j d }||d f| j d< dS )zBinds a new client to the hub.ro   rv   Nr   )rE   newtopr-   r-   r/   r]   G  s   
zHub.bind_clientc           	      K   sX   | j d \}}t|||}|dur*|ddk}||||}|dur(|s(|| _|S dS )z
        Captures an event.

        Alias of :py:meth:`sentry_sdk.Client.capture_event`.

        :param scope_args: For supported `**scope_args` see
            :py:meth:`sentry_sdk.Scope.update_from_kwargs`.
        ro   Ntypetransaction)rr   r;   rg   capture_eventr|   )	rE   eventhintrw   
scope_argsr?   	top_scopeis_transactionr`   r-   r-   r/   r   O  s   
zHub.capture_eventc                 K   s6   | j du rdS |du rd}| j||dfd|i|S )a  
        Captures a message.

        :param message: The string to send as the message.

        :param level: If no level is provided, the default level is `info`.

        :param scope: An optional :py:class:`sentry_sdk.Scope` to use.

        :param scope_args: For supported `**scope_args` see
            :py:meth:`sentry_sdk.Scope.update_from_kwargs`.

        :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.Client.capture_event`).
        Ninfo)messagelevelrw   )r?   r   )rE   r   r   rw   r   r-   r-   r/   capture_messagec  s   
zHub.capture_messagec                 K   s|   | j }|du r	dS |durt|}nt }t||jd\}}z| j|f||d|W S  ty=   | t  Y dS w )ah  Captures an exception.

        :param error: An exception to catch. If `None`, `sys.exc_info()` will be used.

        :param scope_args: For supported `**scope_args` see
            :py:meth:`sentry_sdk.Scope.update_from_kwargs`.

        :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.Client.capture_event`).
        N)client_options)r   rw   )	r?   r   rW   exc_infor   r@   r   	Exception_capture_internal_exception)rE   rx   rw   r   r?   r   r   r   r-   r-   r/   capture_exception{  s   
zHub.capture_exceptionc                 C   s   t jd|d dS )z
        Capture an exception that is likely caused by a bug in the SDK
        itself.

        These exceptions do not end up in Sentry and are just logged instead.
        zInternal error in sentry_sdk)r   N)r   rx   )rE   r   r-   r-   r/   r     s   
zHub._capture_internal_exceptionc                 K   s   | j d \}}|du rtd dS t|pd}|| |s!dS t|p%d}|ddu r3t |d< |ddu r>d|d< |jd durN|jd ||}n|}|dur[|j	| ntd	| |jd
 }t
|j|kr{|j  t
|j|ksmdS dS )a  
        Adds a breadcrumb.

        :param crumb: Dictionary with the data as the sentry v7/v8 protocol expects.

        :param hint: An optional value that can be used by `before_breadcrumb`
            to customize the breadcrumbs that are emitted.
        ro   Nz*Dropped breadcrumb because no client boundr-   	timestampr   defaultbefore_breadcrumbz)before breadcrumb dropped breadcrumb (%s)max_breadcrumbs)rr   r   r   dictupdaterg   r   r@   _breadcrumbsr   rq   popleft)rE   crumbr   r_   r?   rw   	new_crumbr   r-   r-   r/   add_breadcrumb  s.   





zHub.add_breadcrumbc                 K   s  | j o| j jd }||krt S t|tsd|v rBd}t|tr*t| | |S d|v rBt| |d}| jdd|i|S |durOd}t| |S |	d|  | j
j}|durg|jdi |}|S d|vr|  }	|	rx|	d	d
 nd}
|
dur|
|d< tdi |S )a  
        Start a span whose parent is the currently active span or transaction, if any.

        The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
        typically used as a context manager to start and stop timing in a `with`
        block.

        Only spans contained in a transaction are sent to Sentry. Most
        integrations start a transaction at the appropriate time, for example
        for every incoming HTTP request. Use
        :py:meth:`sentry_sdk.start_transaction` to start a new transaction when
        one is not already in progress.

        For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
        instrumenterr   zcDeprecated: use start_transaction to start transactions and Transaction.start_child to start spans.nameNz]Deprecated: passing a span into `start_span` is deprecated and will be removed in the future.ru   trace_id-r   r-   )r?   r@   r
   r{   r   r   rY   start_transactionr   
setdefaultrw   spanstart_childget_traceparentsplitr   )rE   r   r   r_   configuration_instrumenterdeprecation_msgr   active_spannew_child_spantraceparentr   r-   r-   r/   
start_span  s8   





zHub.start_spanc           	      K   s   | j o| j jd }||krt S |di }|du r'|d|  tdi |}| |jd}|| |j	|d t
|| d}|j	|d |jr]| j oT| j jd d	pVd
}|j|d |S )a  
        Start and return a transaction.

        Start an existing transaction if given, otherwise create and start a new
        transaction with kwargs.

        This is the entry point to manual tracing instrumentation.

        A tree structure can be built by adding child spans to the transaction,
        and child spans to other spans. To start a new child span within the
        transaction or any span, call the respective `.start_child()` method.

        Every child span must be finished before the transaction is finished,
        otherwise the unfinished spans are discarded.

        When used as context managers, spans and transactions are automatically
        finished at the end of the `with` block. If not using context managers,
        call the `.finish()` method.

        When the transaction is finished, it will be sent to Sentry with all its
        finished child spans.

        For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
        r   custom_sampling_contextNru   )transaction_contextparent_sampled)sampling_context)ru   _experiments	max_spansi  )maxlenr-   )r?   r@   r
   r   r   r   to_jsonr   r   _set_initial_sampling_decisionr	   sampledrg   init_span_recorder)	rE   r   r   r_   r   r   r   profiler   r-   r-   r/   r     s*   
zHub.start_transactionc                 C   sL   |   }|| W d   n1 sw   Y  tjt||||d}|S )ze
        Sets the propagation context from environment or headers and returns a transaction.
        N)opr   source)configure_scopegenerate_propagation_contextr   continue_from_headersr   )rE   environ_or_headersr   r   r   rw   r   r-   r-   r/   continue_traceK  s   
zHub.continue_tracec                 C      d S r,   r-   r   r-   r-   r/   
push_scope[     zHub.push_scopec                 C   r   r,   r-   r   r-   r-   r/   r   b  r   Tc                 C   s~   |dur|   }|| W d   dS 1 sw   Y  dS | jd \}}t|}|r1|  ||f}| j| t| S )a.  
        Pushes a new layer on the scope stack.

        :param callback: If provided, this method pushes a scope, calls
            `callback`, and pops the scope again.

        :returns: If no `callback` is provided, a context manager that should
            be used to pop the scope again.
        Nro   )r   rr   r3   r   r   rm   )rE   r   r   rw   r?   	new_scope	new_layerr-   r-   r/   r   i  s   



c                 C   s   | j  }| j sJ d|S )z{
        Pops a scope layer from the stack.

        Try to use the context manager :py:meth:`push_scope` instead.
        z"stack must have at least one layer)rr   r   )rE   r`   r-   r-   r/   pop_scope_unsafe  s   
zHub.pop_scope_unsafec                 C   r   r,   r-   r   r-   r-   r/   r     r   zHub.configure_scopec                 C   r   r,   r-   r   r-   r-   r/   r     r   c                    sN   | j d \ |r  |dur dur| dS t fdd}| S )z
        Reconfigures the scope.

        :param callback: If provided, call the callback with the current scope.

        :returns: If no callback is provided, returns a context manager that returns the scope.
        ro   Nc                   3   s      d ur
V  d S t  V  d S r,   r   r-   r?   rw   r-   r/   inner  s   
z"Hub.configure_scope.<locals>.inner)rr   r   r   )rE   r   r   r   r-   r   r/   r     s   applicationc                 C   sJ   |    | jd \}}t|r|jd nd|r|jd nd|j|d|_dS )zStarts a new session.ro   releaseNenvironment)r   r   usersession_mode)end_sessionrr   r   r@   _user_session)rE   r   r?   rw   r-   r-   r/   start_session  s   zHub.start_sessionc                 C   sJ   | j d \}}|j}d| j_|dur!|  |dur#|| dS dS dS )z)Ends the current session if there is one.ro   N)rr   r   rw   rI   capture_session)rE   r?   rw   sessionr-   r-   r/   r     s   zHub.end_sessionc                 C   s    |    | jd \}}d|_dS )zStops automatic session tracking.

        This temporarily session tracking for the current scope when called.
        To resume session tracking call `resume_auto_session_tracking`.
        ro   FN)r   rr   _force_auto_session_trackingrE   r?   rw   r-   r-   r/   stop_auto_session_tracking  s   
zHub.stop_auto_session_trackingc                 C   s   | j d \}}d|_dS )zResumes automatic session tracking for the current scope if
        disabled earlier.  This requires that generally automatic session
        tracking is enabled.
        ro   N)rr   r   r   r-   r-   r/   resume_auto_session_tracking  s   
z Hub.resume_auto_session_trackingc                 C   s(   | j d \}}|dur|j||dS dS )z>
        Alias for :py:meth:`sentry_sdk.Client.flush`
        ro   N)timeoutr   )rr   flush)rE   r   r   r?   rw   r-   r-   r/   r     s   	z	Hub.flushc                 C   s8   | j durt| j jr| jjdur| jj S | j S )zX
        Returns the traceparent either from the active span or from the scope.
        N)r?   r   r@   rw   r   to_traceparentr   rG   r-   r-   r/   r     s   

zHub.get_traceparentc                 C   sN   | j durt| j jr| jjdur| jj }n| j }|dur%| S dS )zP
        Returns Baggage either from the active span or from the scope.
        N)r?   r   r@   rw   r   
to_baggageget_baggage	serialize)rE   baggager-   r-   r/   r     s   


zHub.get_baggagec                 c   sz    | j d d }|o|jd }|sdS |p| jj}|r0t|jr0|dur0| D ]}|V  q(dS | j D ]}|V  q5dS )z
        Return HTTP headers which allow propagation of trace data. Data taken
        from the span representing the request, if available, or the current
        span on the scope if not.
        ro   r   propagate_tracesN)rr   r@   rw   r   r   iter_headers)rE   r   r?   r   headerr-   r-   r/   iter_trace_propagation_headers  s   z"Hub.iter_trace_propagation_headersc                 C   sZ   |dur	t d d}|  }|dur|dt|f 7 }|  }|dur+|dt|f 7 }|S )z
        Return meta tags which should be injected into HTML templates
        to allow propagation of trace information.
        NzaThe parameter `span` in trace_propagation_meta() is deprecated and will be removed in the future. z<meta name="%s" content="%s">)r   rY   r   r   r   r   )rE   r   metasentry_tracer   r-   r-   r/   trace_propagation_meta4  s$   zHub.trace_propagation_meta)NN)NNNr,   )NT)r   ))rP   rQ   rR   __doc__rr   r   r>   rk   rF   rH   rN   r   r   rl   r?   rw   r   r]   r   r   r   r   r   r   SENTRYr   r   r   r!   r   r   r   r   r   r   r   r   r   r   r   r   r-   r-   r-   r/   r=      sr    








)C

>

 

%


r=   )Er3   rW   
contextlibr   sentry_sdk._compatr   r   sentry_sdk.constsr   sentry_sdk.scoper   sentry_sdk.clientr   sentry_sdk.profilerr	   sentry_sdk.tracingr
   r   r   r   r   sentry_sdk.sessionr   sentry_sdk.tracing_utilsr   r   sentry_sdk.utilsr   r   r   r   sentry_sdk._typesr   typingr   r   r   r   r   r   r   r   r   r    r!   r"   sentry_sdk.integrationsr#   r$   r%   r&   r'   r(   r)   r*   rf   r;   rA   objectrC   r\   ra   rb   r   re   rm   r=   rh   ri   r-   r-   r-   r/   <module>   sd    

0    v